Merge branch 'tor-gitlab/mr/583' into maint-0.4.7
[tor.git] / src / lib / tls / tortls_openssl.c
blob77de2d6a1112e6b765c3a04645f7490c56bfc176
1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2021, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file tortls.c
8 * \brief Wrapper functions to present a consistent interface to
9 * TLS, SSL, and X.509 functions from OpenSSL.
10 **/
12 /* (Unlike other tor functions, these
13 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
14 * functions and variables.)
17 #include "orconfig.h"
19 #define TORTLS_PRIVATE
20 #define TORTLS_OPENSSL_PRIVATE
21 #define TOR_X509_PRIVATE
23 #ifdef _WIN32
24 /* We need to include these here, or else the dtls1.h header will include
25 * <winsock.h> and mess things up, in at least some openssl versions. */
26 #include <winsock2.h>
27 #include <ws2tcpip.h>
28 #endif /* defined(_WIN32) */
30 #include "lib/crypt_ops/crypto_cipher.h"
31 #include "lib/crypt_ops/crypto_rand.h"
32 #include "lib/crypt_ops/crypto_dh.h"
33 #include "lib/crypt_ops/crypto_util.h"
34 #include "lib/crypt_ops/compat_openssl.h"
35 #include "lib/tls/x509.h"
36 #include "lib/tls/x509_internal.h"
38 /* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
39 * srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
40 DISABLE_GCC_WARNING("-Wredundant-decls")
42 #include <openssl/opensslv.h>
44 #ifdef OPENSSL_NO_EC
45 #error "We require OpenSSL with ECC support"
46 #endif
48 #include <openssl/ssl.h>
49 #include <openssl/ssl3.h>
50 #include <openssl/err.h>
51 #include <openssl/tls1.h>
52 #include <openssl/asn1.h>
53 #include <openssl/bio.h>
54 #include <openssl/bn.h>
55 #include <openssl/rsa.h>
57 ENABLE_GCC_WARNING("-Wredundant-decls")
59 #include "lib/tls/tortls.h"
60 #include "lib/tls/tortls_st.h"
61 #include "lib/tls/tortls_internal.h"
62 #include "lib/log/log.h"
63 #include "lib/log/util_bug.h"
64 #include "lib/container/smartlist.h"
65 #include "lib/string/compat_string.h"
66 #include "lib/string/printf.h"
67 #include "lib/net/socket.h"
68 #include "lib/intmath/cmp.h"
69 #include "lib/ctime/di_ops.h"
70 #include "lib/encoding/time_fmt.h"
72 #include <stdlib.h>
73 #include <string.h>
75 #include "lib/arch/bytes.h"
77 /* Copied from or.h */
78 #define LEGAL_NICKNAME_CHARACTERS \
79 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
81 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
83 #if OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f')
84 /* This is a version of OpenSSL before 1.0.0f. It does not have
85 * the CVE-2011-4576 fix, and as such it can't use RELEASE_BUFFERS and
86 * SSL3 safely at the same time.
88 #define DISABLE_SSL3_HANDSHAKE
89 #endif /* OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f') */
91 /* We redefine these so that we can run correctly even if the vendor gives us
92 * a version of OpenSSL that does not match its header files. (Apple: I am
93 * looking at you.)
95 #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
96 #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
97 #endif
98 #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
99 #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
100 #endif
102 /** Set to true iff openssl bug 7712 has been detected. */
103 static int openssl_bug_7712_is_present = 0;
105 /** Return values for tor_tls_classify_client_ciphers.
107 * @{
109 /** An error occurred when examining the client ciphers */
110 #define CIPHERS_ERR -1
111 /** The client cipher list indicates that a v1 handshake was in use. */
112 #define CIPHERS_V1 1
113 /** The client cipher list indicates that the client is using the v2 or the
114 * v3 handshake, but that it is (probably!) lying about what ciphers it
115 * supports */
116 #define CIPHERS_V2 2
117 /** The client cipher list indicates that the client is using the v2 or the
118 * v3 handshake, and that it is telling the truth about what ciphers it
119 * supports */
120 #define CIPHERS_UNRESTRICTED 3
121 /** @} */
123 /** The ex_data index in which we store a pointer to an SSL object's
124 * corresponding tor_tls_t object. */
125 STATIC int tor_tls_object_ex_data_index = -1;
127 /** Helper: Allocate tor_tls_object_ex_data_index. */
128 void
129 tor_tls_allocate_tor_tls_object_ex_data_index(void)
131 if (tor_tls_object_ex_data_index == -1) {
132 tor_tls_object_ex_data_index =
133 SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
134 tor_assert(tor_tls_object_ex_data_index != -1);
138 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
139 * pointer. */
140 tor_tls_t *
141 tor_tls_get_by_ssl(const SSL *ssl)
143 tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
144 if (result)
145 tor_assert(result->magic == TOR_TLS_MAGIC);
146 return result;
149 /** True iff tor_tls_init() has been called. */
150 static int tls_library_is_initialized = 0;
152 /* Module-internal error codes. */
153 #define TOR_TLS_SYSCALL_ (MIN_TOR_TLS_ERROR_VAL_ - 2)
154 #define TOR_TLS_ZERORETURN_ (MIN_TOR_TLS_ERROR_VAL_ - 1)
156 /** Write a description of the current state of <b>tls</b> into the
157 * <b>sz</b>-byte buffer at <b>buf</b>. */
158 void
159 tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
161 const char *ssl_state;
162 const char *tortls_state;
164 if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
165 strlcpy(buf, "(No SSL object)", sz);
166 return;
169 ssl_state = SSL_state_string_long(tls->ssl);
170 switch (tls->state) {
171 #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
172 CASE(HANDSHAKE);
173 CASE(OPEN);
174 CASE(GOTCLOSE);
175 CASE(SENTCLOSE);
176 CASE(CLOSED);
177 CASE(RENEGOTIATE);
178 #undef CASE
179 case TOR_TLS_ST_BUFFEREVENT:
180 tortls_state = "";
181 break;
182 default:
183 tortls_state = " in unknown TLS state";
184 break;
187 tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
190 /** Log a single error <b>err</b> as returned by ERR_get_error(), which was
191 * received while performing an operation <b>doing</b> on <b>tls</b>. Log
192 * the message at <b>severity</b>, in log domain <b>domain</b>. */
193 void
194 tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
195 int severity, int domain, const char *doing)
197 const char *state = NULL, *addr;
198 const char *msg, *lib, *func;
200 state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
202 addr = tls ? tls->address : NULL;
204 /* Some errors are known-benign, meaning they are the fault of the other
205 * side of the connection. The caller doesn't know this, so override the
206 * priority for those cases. */
207 switch (ERR_GET_REASON(err)) {
208 case SSL_R_HTTP_REQUEST:
209 case SSL_R_HTTPS_PROXY_REQUEST:
210 case SSL_R_RECORD_LENGTH_MISMATCH:
211 #ifndef OPENSSL_1_1_API
212 case SSL_R_RECORD_TOO_LARGE:
213 #endif
214 case SSL_R_UNKNOWN_PROTOCOL:
215 case SSL_R_UNSUPPORTED_PROTOCOL:
216 severity = LOG_INFO;
217 break;
218 default:
219 break;
222 msg = (const char*)ERR_reason_error_string(err);
223 lib = (const char*)ERR_lib_error_string(err);
224 func = (const char*)ERR_func_error_string(err);
225 if (!msg) msg = "(null)";
226 if (!lib) lib = "(null)";
227 if (!func) func = "(null)";
228 if (doing) {
229 tor_log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
230 doing, addr?" with ":"", addr?addr:"",
231 msg, lib, func, state);
232 } else {
233 tor_log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
234 addr?" with ":"", addr?addr:"",
235 msg, lib, func, state);
239 /** Log all pending tls errors at level <b>severity</b> in log domain
240 * <b>domain</b>. Use <b>doing</b> to describe our current activities.
242 void
243 tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
245 unsigned long err;
247 while ((err = ERR_get_error()) != 0) {
248 if (tls)
249 tls->last_error = err;
250 tor_tls_log_one_error(tls, err, severity, domain, doing);
255 * Return a string representing more detail about the last error received
256 * on TLS.
258 * May return null if no error was found.
260 const char *
261 tor_tls_get_last_error_msg(const tor_tls_t *tls)
263 IF_BUG_ONCE(!tls) {
264 return NULL;
266 if (tls->last_error == 0) {
267 return NULL;
269 return (const char*)ERR_reason_error_string(tls->last_error);
272 #define CATCH_SYSCALL 1
273 #define CATCH_ZERO 2
275 /** Given a TLS object and the result of an SSL_* call, use
276 * SSL_get_error to determine whether an error has occurred, and if so
277 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
278 * If extra&CATCH_SYSCALL is true, return TOR_TLS_SYSCALL_ instead of
279 * reporting syscall errors. If extra&CATCH_ZERO is true, return
280 * TOR_TLS_ZERORETURN_ instead of reporting zero-return errors.
282 * If an error has occurred, log it at level <b>severity</b> and describe the
283 * current action as <b>doing</b>.
286 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
287 const char *doing, int severity, int domain)
289 int err = SSL_get_error(tls->ssl, r);
290 int tor_error = TOR_TLS_ERROR_MISC;
291 switch (err) {
292 case SSL_ERROR_NONE:
293 return TOR_TLS_DONE;
294 case SSL_ERROR_WANT_READ:
295 return TOR_TLS_WANTREAD;
296 case SSL_ERROR_WANT_WRITE:
297 return TOR_TLS_WANTWRITE;
298 case SSL_ERROR_SYSCALL:
299 if (extra&CATCH_SYSCALL)
300 return TOR_TLS_SYSCALL_;
301 if (r == 0) {
302 tor_log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
303 doing, SSL_state_string_long(tls->ssl));
304 tor_error = TOR_TLS_ERROR_IO;
305 } else {
306 int e = tor_socket_errno(tls->socket);
307 tor_log(severity, LD_NET,
308 "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
309 doing, e, tor_socket_strerror(e),
310 SSL_state_string_long(tls->ssl));
311 tor_error = tor_errno_to_tls_error(e);
313 tls_log_errors(tls, severity, domain, doing);
314 return tor_error;
315 case SSL_ERROR_ZERO_RETURN:
316 if (extra&CATCH_ZERO)
317 return TOR_TLS_ZERORETURN_;
318 tor_log(severity, LD_NET, "TLS connection closed while %s in state %s",
319 doing, SSL_state_string_long(tls->ssl));
320 tls_log_errors(tls, severity, domain, doing);
321 return TOR_TLS_CLOSE;
322 default:
323 tls_log_errors(tls, severity, domain, doing);
324 return TOR_TLS_ERROR_MISC;
328 /** Initialize OpenSSL, unless it has already been initialized.
330 void
331 tor_tls_init(void)
333 check_no_tls_errors();
335 if (!tls_library_is_initialized) {
336 #ifdef OPENSSL_1_1_API
337 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
338 #else
339 SSL_library_init();
340 SSL_load_error_strings();
341 #endif /* defined(OPENSSL_1_1_API) */
343 #if (SIZEOF_VOID_P >= 8 && \
344 OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,1))
345 long version = tor_OpenSSL_version_num();
347 /* LCOV_EXCL_START : we can't test these lines on the same machine */
348 if (version >= OPENSSL_V_SERIES(1,0,1)) {
349 /* Warn if we could *almost* be running with much faster ECDH.
350 If we're built for a 64-bit target, using OpenSSL 1.0.1, but we
351 don't have one of the built-in __uint128-based speedups, we are
352 just one build operation away from an accelerated handshake.
354 (We could be looking at OPENSSL_NO_EC_NISTP_64_GCC_128 instead of
355 doing this test, but that gives compile-time options, not runtime
356 behavior.)
358 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
359 const EC_GROUP *g = key ? EC_KEY_get0_group(key) : NULL;
360 const EC_METHOD *m = g ? EC_GROUP_method_of(g) : NULL;
361 const int warn = (m == EC_GFp_simple_method() ||
362 m == EC_GFp_mont_method() ||
363 m == EC_GFp_nist_method());
364 EC_KEY_free(key);
366 if (warn)
367 log_notice(LD_GENERAL, "We were built to run on a 64-bit CPU, with "
368 "OpenSSL 1.0.1 or later, but with a version of OpenSSL "
369 "that apparently lacks accelerated support for the NIST "
370 "P-224 and P-256 groups. Building openssl with such "
371 "support (using the enable-ec_nistp_64_gcc_128 option "
372 "when configuring it) would make ECDH much faster.");
374 /* LCOV_EXCL_STOP */
375 #endif /* (SIZEOF_VOID_P >= 8 && ... */
377 tor_tls_allocate_tor_tls_object_ex_data_index();
379 tls_library_is_initialized = 1;
383 /** We need to give OpenSSL a callback to verify certificates. This is
384 * it: We always accept peer certs and complete the handshake. We
385 * don't validate them until later.
388 always_accept_verify_cb(int preverify_ok,
389 X509_STORE_CTX *x509_ctx)
391 (void) preverify_ok;
392 (void) x509_ctx;
393 return 1;
396 /** List of ciphers that servers should select from when the client might be
397 * claiming extra unsupported ciphers in order to avoid fingerprinting. */
398 static const char SERVER_CIPHER_LIST[] =
399 #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
400 /* This one can never actually get selected, since if the client lists it,
401 * we will assume that the client is honest, and not use this list.
402 * Nonetheless we list it if it's available, so that the server doesn't
403 * conclude that it has no valid ciphers if it's running with TLS1.3.
405 TLS1_3_TXT_AES_128_GCM_SHA256 ":"
406 #endif /* defined(TLS1_3_TXT_AES_128_GCM_SHA256) */
407 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
408 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA;
410 /** List of ciphers that servers should select from when we actually have
411 * our choice of what cipher to use. */
412 static const char UNRESTRICTED_SERVER_CIPHER_LIST[] =
413 /* Here are the TLS 1.3 ciphers we like, in the order we prefer. */
414 #ifdef TLS1_3_TXT_AES_256_GCM_SHA384
415 TLS1_3_TXT_AES_256_GCM_SHA384 ":"
416 #endif
417 #ifdef TLS1_3_TXT_CHACHA20_POLY1305_SHA256
418 TLS1_3_TXT_CHACHA20_POLY1305_SHA256 ":"
419 #endif
420 #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
421 TLS1_3_TXT_AES_128_GCM_SHA256 ":"
422 #endif
423 #ifdef TLS1_3_TXT_AES_128_CCM_SHA256
424 TLS1_3_TXT_AES_128_CCM_SHA256 ":"
425 #endif
427 /* This list is autogenerated with the gen_server_ciphers.py script;
428 * don't hand-edit it. */
429 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
430 TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
431 #endif
432 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
433 TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
434 #endif
435 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384
436 TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 ":"
437 #endif
438 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
439 TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
440 #endif
441 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA
442 TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
443 #endif
444 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
445 TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
446 #endif
447 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384
448 TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 ":"
449 #endif
450 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256
451 TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 ":"
452 #endif
453 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_CCM
454 TLS1_TXT_DHE_RSA_WITH_AES_256_CCM ":"
455 #endif
456 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_CCM
457 TLS1_TXT_DHE_RSA_WITH_AES_128_CCM ":"
458 #endif
459 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256
460 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 ":"
461 #endif
462 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256
463 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 ":"
464 #endif
465 /* Required */
466 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
467 /* Required */
468 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"
469 #ifdef TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305
470 TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 ":"
471 #endif
472 #ifdef TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
473 TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
474 #endif
477 /* Note: to set up your own private testing network with link crypto
478 * disabled, set your Tors' cipher list to
479 * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
480 * with any of the "real" Tors, though. */
482 #define CIPHER(id, name) name ":"
483 #define XCIPHER(id, name)
484 /** List of ciphers that clients should advertise, omitting items that
485 * our OpenSSL doesn't know about. */
486 static const char CLIENT_CIPHER_LIST[] =
487 #ifndef COCCI
488 #include "lib/tls/ciphers.inc"
489 #endif
490 /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
491 * of any cipher we say. */
492 "!SSLv2"
494 #undef CIPHER
495 #undef XCIPHER
497 /** Return true iff the other side of <b>tls</b> has authenticated to us, and
498 * the key certified in <b>cert</b> is the same as the key they used to do it.
500 MOCK_IMPL(int,
501 tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
503 tor_x509_cert_t *peer = tor_tls_get_peer_cert((tor_tls_t *)tls);
504 if (!peer)
505 return 0;
507 X509 *peercert = peer->cert;
508 EVP_PKEY *link_key = NULL, *cert_key = NULL;
509 int result;
511 link_key = X509_get_pubkey(peercert);
512 cert_key = X509_get_pubkey(cert->cert);
514 result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
516 tor_x509_cert_free(peer);
517 if (link_key)
518 EVP_PKEY_free(link_key);
519 if (cert_key)
520 EVP_PKEY_free(cert_key);
522 return result;
525 void
526 tor_tls_context_impl_free_(struct ssl_ctx_st *ctx)
528 if (!ctx)
529 return;
530 SSL_CTX_free(ctx);
533 /** The group we should use for ecdhe when none was selected. */
534 #define NID_tor_default_ecdhe_group NID_X9_62_prime256v1
536 /** Create a new TLS context for use with Tor TLS handshakes.
537 * <b>identity</b> should be set to the identity key used to sign the
538 * certificate.
540 tor_tls_context_t *
541 tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
542 unsigned flags, int is_client)
544 EVP_PKEY *pkey = NULL;
545 tor_tls_context_t *result = NULL;
547 tor_tls_init();
549 result = tor_malloc_zero(sizeof(tor_tls_context_t));
550 result->refcnt = 1;
552 if (! is_client) {
553 if (tor_tls_context_init_certificates(result, identity, key_lifetime,
554 flags) < 0) {
555 goto error;
559 #if 0
560 /* Tell OpenSSL to only use TLS1. This may have subtly different results
561 * from SSLv23_method() with SSLv2 and SSLv3 disabled, so we need to do some
562 * investigation before we consider adjusting it. It should be compatible
563 * with existing Tors. */
564 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
565 goto error;
566 #endif /* 0 */
568 /* Tell OpenSSL to use TLS 1.0 or later but not SSL2 or SSL3. */
569 #ifdef HAVE_TLS_METHOD
570 if (!(result->ctx = SSL_CTX_new(TLS_method())))
571 goto error;
572 #else
573 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
574 goto error;
575 #endif /* defined(HAVE_TLS_METHOD) */
577 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
578 /* Level 1 re-enables RSA1024 and DH1024 for compatibility with old tors */
579 SSL_CTX_set_security_level(result->ctx, 1);
580 #endif
582 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
583 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
585 /* Prefer the server's ordering of ciphers: the client's ordering has
586 * historically been chosen for fingerprinting resistance. */
587 SSL_CTX_set_options(result->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
589 /* Disable TLS tickets if they're supported. We never want to use them;
590 * using them can make our perfect forward secrecy a little worse, *and*
591 * create an opportunity to fingerprint us (since it's unusual to use them
592 * with TLS sessions turned off).
594 * In 0.2.4, clients advertise support for them though, to avoid a TLS
595 * distinguishability vector. This can give us worse PFS, though, if we
596 * get a server that doesn't set SSL_OP_NO_TICKET. With luck, there will
597 * be few such servers by the time 0.2.4 is more stable.
599 #ifdef SSL_OP_NO_TICKET
600 if (! is_client) {
601 SSL_CTX_set_options(result->ctx, SSL_OP_NO_TICKET);
603 #endif
605 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
606 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_ECDH_USE);
608 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
609 SSL_CTX_set_options(result->ctx,
610 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
611 #endif
612 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
613 * as authenticating any earlier-received data.
616 SSL_CTX_set_options(result->ctx,
617 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
620 /* Don't actually allow compression; it uses RAM and time, it makes TLS
621 * vulnerable to CRIME-style attacks, and most of the data we transmit over
622 * TLS is encrypted (and therefore uncompressible) anyway. */
623 #ifdef SSL_OP_NO_COMPRESSION
624 SSL_CTX_set_options(result->ctx, SSL_OP_NO_COMPRESSION);
625 #endif
626 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0)
627 #ifndef OPENSSL_NO_COMP
628 if (result->ctx->comp_methods)
629 result->ctx->comp_methods = NULL;
630 #endif
631 #endif /* OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0) */
633 #ifdef SSL_MODE_RELEASE_BUFFERS
634 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
635 #endif
636 if (! is_client) {
637 if (result->my_link_cert &&
638 !SSL_CTX_use_certificate(result->ctx,
639 result->my_link_cert->cert)) {
640 goto error;
642 if (result->my_id_cert) {
643 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
644 tor_assert(s);
645 X509_STORE_add_cert(s, result->my_id_cert->cert);
648 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
649 if (!is_client) {
650 tor_assert(result->link_key);
651 if (!(pkey = crypto_pk_get_openssl_evp_pkey_(result->link_key,1)))
652 goto error;
653 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
654 goto error;
655 EVP_PKEY_free(pkey);
656 pkey = NULL;
657 if (!SSL_CTX_check_private_key(result->ctx))
658 goto error;
662 DH *dh = crypto_dh_new_openssl_tls();
663 tor_assert(dh);
664 SSL_CTX_set_tmp_dh(result->ctx, dh);
665 DH_free(dh);
667 /* We check for this function in two ways, since it might be either a symbol
668 * or a macro. */
669 #if defined(SSL_CTX_set1_groups_list) || defined(HAVE_SSL_CTX_SET1_GROUPS_LIST)
671 const char *list;
672 if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
673 list = "P-224:P-256";
674 else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
675 list = "P-256:P-224";
676 else
677 list = "P-256:P-224";
678 int r = (int) SSL_CTX_set1_groups_list(result->ctx, list);
679 if (r < 0)
680 goto error;
682 #else /* !(defined(SSL_CTX_set1_groups_list) || defined(HAVE_SSL_CTX_SE...)) */
683 if (! is_client) {
684 int nid;
685 EC_KEY *ec_key;
686 if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
687 nid = NID_secp224r1;
688 else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
689 nid = NID_X9_62_prime256v1;
690 else
691 nid = NID_tor_default_ecdhe_group;
692 /* Use P-256 for ECDHE. */
693 ec_key = EC_KEY_new_by_curve_name(nid);
694 if (ec_key != NULL) /*XXXX Handle errors? */
695 SSL_CTX_set_tmp_ecdh(result->ctx, ec_key);
696 EC_KEY_free(ec_key);
698 #endif /* defined(SSL_CTX_set1_groups_list) || defined(HAVE_SSL_CTX_SET1...) */
699 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
700 always_accept_verify_cb);
701 /* let us realloc bufs that we're writing from */
702 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
704 #ifdef SSL_OP_TLSEXT_PADDING
705 /* Adds a padding extension to ensure the ClientHello size is never between
706 * 256 and 511 bytes in length. */
707 SSL_CTX_set_options(result->ctx, SSL_OP_TLSEXT_PADDING);
708 #endif
710 return result;
712 error:
713 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
714 if (pkey)
715 EVP_PKEY_free(pkey);
716 tor_tls_context_decref(result);
717 return NULL;
720 /** Invoked when a TLS state changes: log the change at severity 'debug' */
721 void
722 tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
724 /* LCOV_EXCL_START since this depends on whether debug is captured or not */
725 log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
726 ssl, SSL_state_string_long(ssl), type, val);
727 /* LCOV_EXCL_STOP */
730 /* Return the name of the negotiated ciphersuite in use on <b>tls</b> */
731 const char *
732 tor_tls_get_ciphersuite_name(tor_tls_t *tls)
734 return SSL_get_cipher(tls->ssl);
737 /* Here's the old V2 cipher list we sent from 0.2.1.1-alpha up to
738 * 0.2.3.17-beta. If a client is using this list, we can't believe the ciphers
739 * that it claims to support. We'll prune this list to remove the ciphers
740 * *we* don't recognize. */
741 STATIC uint16_t v2_cipher_list[] = {
742 0xc00a, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA */
743 0xc014, /* TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA */
744 0x0039, /* TLS1_TXT_DHE_RSA_WITH_AES_256_SHA */
745 0x0038, /* TLS1_TXT_DHE_DSS_WITH_AES_256_SHA */
746 0xc00f, /* TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA */
747 0xc005, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA */
748 0x0035, /* TLS1_TXT_RSA_WITH_AES_256_SHA */
749 0xc007, /* TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA */
750 0xc009, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA */
751 0xc011, /* TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA */
752 0xc013, /* TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA */
753 0x0033, /* TLS1_TXT_DHE_RSA_WITH_AES_128_SHA */
754 0x0032, /* TLS1_TXT_DHE_DSS_WITH_AES_128_SHA */
755 0xc00c, /* TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA */
756 0xc00e, /* TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA */
757 0xc002, /* TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA */
758 0xc004, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA */
759 0x0004, /* SSL3_TXT_RSA_RC4_128_MD5 */
760 0x0005, /* SSL3_TXT_RSA_RC4_128_SHA */
761 0x002f, /* TLS1_TXT_RSA_WITH_AES_128_SHA */
762 0xc008, /* TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA */
763 0xc012, /* TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA */
764 0x0016, /* SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA */
765 0x0013, /* SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA */
766 0xc00d, /* TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA */
767 0xc003, /* TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA */
768 0xfeff, /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA */
769 0x000a, /* SSL3_TXT_RSA_DES_192_CBC3_SHA */
772 /** Have we removed the unrecognized ciphers from v2_cipher_list yet? */
773 static int v2_cipher_list_pruned = 0;
775 /** Return 0 if <b>m</b> does not support the cipher with ID <b>cipher</b>;
776 * return 1 if it does support it, or if we have no way to tell. */
778 find_cipher_by_id(const SSL *ssl, const SSL_METHOD *m, uint16_t cipher)
780 const SSL_CIPHER *c;
781 #ifdef HAVE_SSL_CIPHER_FIND
782 (void) m;
784 unsigned char cipherid[3];
785 tor_assert(ssl);
786 set_uint16(cipherid, tor_htons(cipher));
787 cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
788 * with a two-byte 'cipherid', it may look for a v2
789 * cipher with the appropriate 3 bytes. */
790 c = SSL_CIPHER_find((SSL*)ssl, cipherid);
791 if (c)
792 tor_assert((SSL_CIPHER_get_id(c) & 0xffff) == cipher);
793 return c != NULL;
795 #else /* !defined(HAVE_SSL_CIPHER_FIND) */
797 # if defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR)
798 if (m && m->get_cipher_by_char) {
799 unsigned char cipherid[3];
800 set_uint16(cipherid, tor_htons(cipher));
801 cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
802 * with a two-byte 'cipherid', it may look for a v2
803 * cipher with the appropriate 3 bytes. */
804 c = m->get_cipher_by_char(cipherid);
805 if (c)
806 tor_assert((c->id & 0xffff) == cipher);
807 return c != NULL;
809 #endif /* defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR) */
810 # ifndef OPENSSL_1_1_API
811 if (m && m->get_cipher && m->num_ciphers) {
812 /* It would seem that some of the "let's-clean-up-openssl" forks have
813 * removed the get_cipher_by_char function. Okay, so now you get a
814 * quadratic search.
816 int i;
817 for (i = 0; i < m->num_ciphers(); ++i) {
818 c = m->get_cipher(i);
819 if (c && (c->id & 0xffff) == cipher) {
820 return 1;
823 return 0;
825 #endif /* !defined(OPENSSL_1_1_API) */
826 (void) ssl;
827 (void) m;
828 (void) cipher;
829 return 1; /* No way to search */
830 #endif /* defined(HAVE_SSL_CIPHER_FIND) */
833 /** Remove from v2_cipher_list every cipher that we don't support, so that
834 * comparing v2_cipher_list to a client's cipher list will give a sensible
835 * result. */
836 static void
837 prune_v2_cipher_list(const SSL *ssl)
839 uint16_t *inp, *outp;
840 #ifdef HAVE_TLS_METHOD
841 const SSL_METHOD *m = TLS_method();
842 #else
843 const SSL_METHOD *m = SSLv23_method();
844 #endif
846 inp = outp = v2_cipher_list;
847 while (*inp) {
848 if (find_cipher_by_id(ssl, m, *inp)) {
849 *outp++ = *inp++;
850 } else {
851 inp++;
854 *outp = 0;
856 v2_cipher_list_pruned = 1;
859 /** Examine the client cipher list in <b>ssl</b>, and determine what kind of
860 * client it is. Return one of CIPHERS_ERR, CIPHERS_V1, CIPHERS_V2,
861 * CIPHERS_UNRESTRICTED.
864 tor_tls_classify_client_ciphers(const SSL *ssl,
865 STACK_OF(SSL_CIPHER) *peer_ciphers)
867 int i, res;
868 tor_tls_t *tor_tls;
869 if (PREDICT_UNLIKELY(!v2_cipher_list_pruned))
870 prune_v2_cipher_list(ssl);
872 tor_tls = tor_tls_get_by_ssl(ssl);
873 if (tor_tls && tor_tls->client_cipher_list_type)
874 return tor_tls->client_cipher_list_type;
876 /* If we reached this point, we just got a client hello. See if there is
877 * a cipher list. */
878 if (!peer_ciphers) {
879 log_info(LD_NET, "No ciphers on session");
880 res = CIPHERS_ERR;
881 goto done;
883 /* Now we need to see if there are any ciphers whose presence means we're
884 * dealing with an updated Tor. */
885 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
886 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
887 const char *ciphername = SSL_CIPHER_get_name(cipher);
888 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
889 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
890 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
891 strcmp(ciphername, "(NONE)")) {
892 log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
893 // return 1;
894 goto v2_or_higher;
897 res = CIPHERS_V1;
898 goto done;
899 v2_or_higher:
901 const uint16_t *v2_cipher = v2_cipher_list;
902 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
903 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
904 uint16_t id = SSL_CIPHER_get_id(cipher) & 0xffff;
905 if (id == 0x00ff) /* extended renegotiation indicator. */
906 continue;
907 if (!id || id != *v2_cipher) {
908 res = CIPHERS_UNRESTRICTED;
909 goto dump_ciphers;
911 ++v2_cipher;
913 if (*v2_cipher != 0) {
914 res = CIPHERS_UNRESTRICTED;
915 goto dump_ciphers;
917 res = CIPHERS_V2;
920 dump_ciphers:
922 smartlist_t *elts = smartlist_new();
923 char *s;
924 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
925 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
926 const char *ciphername = SSL_CIPHER_get_name(cipher);
927 smartlist_add(elts, (char*)ciphername);
929 s = smartlist_join_strings(elts, ":", 0, NULL);
930 log_debug(LD_NET, "Got a %s V2/V3 cipher list from %s. It is: '%s'",
931 (res == CIPHERS_V2) ? "fictitious" : "real", ADDR(tor_tls), s);
932 tor_free(s);
933 smartlist_free(elts);
935 done:
936 if (tor_tls && peer_ciphers)
937 return tor_tls->client_cipher_list_type = res;
939 return res;
942 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
943 * a list that indicates that the client knows how to do the v2 TLS connection
944 * handshake. */
946 tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
948 STACK_OF(SSL_CIPHER) *ciphers;
949 #ifdef HAVE_SSL_GET_CLIENT_CIPHERS
950 ciphers = SSL_get_client_ciphers(ssl);
951 #else
952 SSL_SESSION *session;
953 if (!(session = SSL_get_session((SSL *)ssl))) {
954 log_info(LD_NET, "No session on TLS?");
955 return CIPHERS_ERR;
957 ciphers = session->ciphers;
958 #endif /* defined(HAVE_SSL_GET_CLIENT_CIPHERS) */
960 return tor_tls_classify_client_ciphers(ssl, ciphers) >= CIPHERS_V2;
963 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
964 * changes state. We use this:
965 * <ul><li>To alter the state of the handshake partway through, so we
966 * do not send or request extra certificates in v2 handshakes.</li>
967 * <li>To detect renegotiation</li></ul>
969 void
970 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
972 tor_tls_t *tls;
973 (void) val;
975 IF_BUG_ONCE(ssl == NULL) {
976 return; // LCOV_EXCL_LINE
979 tor_tls_debug_state_callback(ssl, type, val);
981 if (type != SSL_CB_ACCEPT_LOOP)
982 return;
984 OSSL_HANDSHAKE_STATE ssl_state = SSL_get_state(ssl);
985 if (! STATE_IS_SW_SERVER_HELLO(ssl_state))
986 return;
987 tls = tor_tls_get_by_ssl(ssl);
988 if (tls) {
989 /* Check whether we're watching for renegotiates. If so, this is one! */
990 if (tls->negotiated_callback)
991 tls->got_renegotiate = 1;
992 } else {
993 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
994 return;
997 /* Now check the cipher list. */
998 if (tor_tls_client_is_using_v2_ciphers(ssl)) {
999 if (tls->wasV2Handshake)
1000 return; /* We already turned this stuff off for the first handshake;
1001 * This is a renegotiation. */
1003 /* Yes, we're casting away the const from ssl. This is very naughty of us.
1004 * Let's hope openssl doesn't notice! */
1006 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
1007 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
1008 /* Don't send a hello request. */
1009 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
1011 if (tls) {
1012 tls->wasV2Handshake = 1;
1013 } else {
1014 /* LCOV_EXCL_START this line is not reachable */
1015 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
1016 /* LCOV_EXCL_STOP */
1021 /** Callback to get invoked on a server after we've read the list of ciphers
1022 * the client supports, but before we pick our own ciphersuite.
1024 * We can't abuse an info_cb for this, since by the time one of the
1025 * client_hello info_cbs is called, we've already picked which ciphersuite to
1026 * use.
1028 * Technically, this function is an abuse of this callback, since the point of
1029 * a session_secret_cb is to try to set up and/or verify a shared-secret for
1030 * authentication on the fly. But as long as we return 0, we won't actually be
1031 * setting up a shared secret, and all will be fine.
1034 tor_tls_session_secret_cb(SSL *ssl, void *secret, int *secret_len,
1035 STACK_OF(SSL_CIPHER) *peer_ciphers,
1036 CONST_IF_OPENSSL_1_1_API SSL_CIPHER **cipher,
1037 void *arg)
1039 (void) secret;
1040 (void) secret_len;
1041 (void) peer_ciphers;
1042 (void) cipher;
1043 (void) arg;
1045 if (tor_tls_classify_client_ciphers(ssl, peer_ciphers) ==
1046 CIPHERS_UNRESTRICTED) {
1047 SSL_set_cipher_list(ssl, UNRESTRICTED_SERVER_CIPHER_LIST);
1050 SSL_set_session_secret_cb(ssl, NULL, NULL);
1052 return 0;
1054 static void
1055 tor_tls_setup_session_secret_cb(tor_tls_t *tls)
1057 SSL_set_session_secret_cb(tls->ssl, tor_tls_session_secret_cb, NULL);
1060 /** Create a new TLS object from a file descriptor, and a flag to
1061 * determine whether it is functioning as a server.
1063 tor_tls_t *
1064 tor_tls_new(tor_socket_t sock, int isServer)
1066 BIO *bio = NULL;
1067 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
1068 tor_tls_context_t *context = tor_tls_context_get(isServer);
1069 result->magic = TOR_TLS_MAGIC;
1071 check_no_tls_errors();
1072 tor_assert(context); /* make sure somebody made it first */
1073 if (!(result->ssl = SSL_new(context->ctx))) {
1074 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
1075 tor_free(result);
1076 goto err;
1079 #ifdef SSL_set_tlsext_host_name
1080 /* Browsers use the TLS hostname extension, so we should too. */
1081 if (!isServer) {
1082 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
1083 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
1084 tor_free(fake_hostname);
1086 #endif /* defined(SSL_set_tlsext_host_name) */
1088 #ifdef SSL_CTRL_SET_MAX_PROTO_VERSION
1089 if (openssl_bug_7712_is_present) {
1090 /* We can't actually use TLS 1.3 until this bug is fixed. */
1091 SSL_set_max_proto_version(result->ssl, TLS1_2_VERSION);
1093 #endif /* defined(SSL_CTRL_SET_MAX_PROTO_VERSION) */
1095 if (!SSL_set_cipher_list(result->ssl,
1096 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
1097 tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
1098 #ifdef SSL_set_tlsext_host_name
1099 SSL_set_tlsext_host_name(result->ssl, NULL);
1100 #endif
1101 SSL_free(result->ssl);
1102 tor_free(result);
1103 goto err;
1105 result->socket = sock;
1106 bio = BIO_new_socket(sock, BIO_CLOSE);
1107 if (! bio) {
1108 tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
1109 #ifdef SSL_set_tlsext_host_name
1110 SSL_set_tlsext_host_name(result->ssl, NULL);
1111 #endif
1112 SSL_free(result->ssl);
1113 tor_free(result);
1114 goto err;
1117 int set_worked =
1118 SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
1119 if (!set_worked) {
1120 log_warn(LD_BUG,
1121 "Couldn't set the tls for an SSL*; connection will fail");
1124 SSL_set_bio(result->ssl, bio, bio);
1125 tor_tls_context_incref(context);
1126 result->context = context;
1127 result->state = TOR_TLS_ST_HANDSHAKE;
1128 result->isServer = isServer;
1129 result->wantwrite_n = 0;
1130 result->last_write_count = (unsigned long) BIO_number_written(bio);
1131 result->last_read_count = (unsigned long) BIO_number_read(bio);
1132 if (result->last_write_count || result->last_read_count) {
1133 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
1134 result->last_read_count, result->last_write_count);
1136 if (isServer) {
1137 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
1138 } else {
1139 SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
1142 if (isServer)
1143 tor_tls_setup_session_secret_cb(result);
1145 goto done;
1146 err:
1147 result = NULL;
1148 done:
1149 /* Not expected to get called. */
1150 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
1151 return result;
1154 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
1155 * next gets a client-side renegotiate in the middle of a read. Do not
1156 * invoke this function until <em>after</em> initial handshaking is done!
1158 void
1159 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
1160 void (*cb)(tor_tls_t *, void *arg),
1161 void *arg)
1163 tls->negotiated_callback = cb;
1164 tls->callback_arg = arg;
1165 tls->got_renegotiate = 0;
1166 if (cb) {
1167 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
1168 } else {
1169 SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
1173 /** If this version of openssl requires it, turn on renegotiation on
1174 * <b>tls</b>.
1176 void
1177 tor_tls_unblock_renegotiation(tor_tls_t *tls)
1179 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1180 * as authenticating any earlier-received data. */
1181 SSL_set_options(tls->ssl,
1182 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1185 /** If this version of openssl supports it, turn off renegotiation on
1186 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
1187 * to use belt-and-suspenders here.)
1189 void
1190 tor_tls_block_renegotiation(tor_tls_t *tls)
1192 #ifdef SUPPORT_UNSAFE_RENEGOTIATION_FLAG
1193 tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1194 #else
1195 (void) tls;
1196 #endif
1200 * Tell the TLS library that the underlying socket for <b>tls</b> has been
1201 * closed, and the library should not attempt to free that socket itself.
1203 void
1204 tor_tls_release_socket(tor_tls_t *tls)
1206 if (! tls)
1207 return;
1209 BIO *rbio, *wbio;
1210 rbio = SSL_get_rbio(tls->ssl);
1211 wbio = SSL_get_wbio(tls->ssl);
1213 if (rbio) {
1214 (void) BIO_set_close(rbio, BIO_NOCLOSE);
1216 if (wbio && wbio != rbio) {
1217 (void) BIO_set_close(wbio, BIO_NOCLOSE);
1221 void
1222 tor_tls_impl_free_(tor_tls_impl_t *ssl)
1224 if (!ssl)
1225 return;
1227 #ifdef SSL_set_tlsext_host_name
1228 SSL_set_tlsext_host_name(ssl, NULL);
1229 #endif
1230 SSL_free(ssl);
1233 /** Underlying function for TLS reading. Reads up to <b>len</b>
1234 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
1235 * number of characters read. On failure, returns TOR_TLS_ERROR,
1236 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1238 MOCK_IMPL(int,
1239 tor_tls_read,(tor_tls_t *tls, char *cp, size_t len))
1241 int r, err;
1242 tor_assert(tls);
1243 tor_assert(tls->ssl);
1244 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1245 tor_assert(len<INT_MAX);
1246 r = SSL_read(tls->ssl, cp, (int)len);
1247 if (r > 0) {
1248 if (tls->got_renegotiate) {
1249 /* Renegotiation happened! */
1250 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
1251 if (tls->negotiated_callback)
1252 tls->negotiated_callback(tls, tls->callback_arg);
1253 tls->got_renegotiate = 0;
1255 return r;
1257 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
1258 if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) {
1259 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
1260 tls->state = TOR_TLS_ST_CLOSED;
1261 return TOR_TLS_CLOSE;
1262 } else {
1263 tor_assert(err != TOR_TLS_DONE);
1264 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
1265 return err;
1269 /** Total number of bytes that we've used TLS to send. Used to track TLS
1270 * overhead. */
1271 STATIC uint64_t total_bytes_written_over_tls = 0;
1272 /** Total number of bytes that TLS has put on the network for us. Used to
1273 * track TLS overhead. */
1274 STATIC uint64_t total_bytes_written_by_tls = 0;
1276 /** Underlying function for TLS writing. Write up to <b>n</b>
1277 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
1278 * number of characters written. On failure, returns TOR_TLS_ERROR,
1279 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1282 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
1284 int r, err;
1285 tor_assert(tls);
1286 tor_assert(tls->ssl);
1287 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1288 tor_assert(n < INT_MAX);
1289 if (n == 0)
1290 return 0;
1291 if (tls->wantwrite_n) {
1292 /* if WANTWRITE last time, we must use the _same_ n as before */
1293 tor_assert(n >= tls->wantwrite_n);
1294 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
1295 (int)n, (int)tls->wantwrite_n);
1296 n = tls->wantwrite_n;
1297 tls->wantwrite_n = 0;
1299 r = SSL_write(tls->ssl, cp, (int)n);
1300 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
1301 if (err == TOR_TLS_DONE) {
1302 total_bytes_written_over_tls += r;
1303 return r;
1305 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
1306 tls->wantwrite_n = n;
1308 return err;
1311 /** Perform initial handshake on <b>tls</b>. When finished, returns
1312 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1313 * or TOR_TLS_WANTWRITE.
1316 tor_tls_handshake(tor_tls_t *tls)
1318 int r;
1319 tor_assert(tls);
1320 tor_assert(tls->ssl);
1321 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1323 check_no_tls_errors();
1325 OSSL_HANDSHAKE_STATE oldstate = SSL_get_state(tls->ssl);
1327 if (tls->isServer) {
1328 log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
1329 SSL_state_string_long(tls->ssl));
1330 r = SSL_accept(tls->ssl);
1331 } else {
1332 log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
1333 SSL_state_string_long(tls->ssl));
1334 r = SSL_connect(tls->ssl);
1337 OSSL_HANDSHAKE_STATE newstate = SSL_get_state(tls->ssl);
1339 if (oldstate != newstate)
1340 log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
1341 tls, SSL_state_string_long(tls->ssl));
1342 /* We need to call this here and not earlier, since OpenSSL has a penchant
1343 * for clearing its flags when you say accept or connect. */
1344 tor_tls_unblock_renegotiation(tls);
1345 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
1346 if (ERR_peek_error() != 0) {
1347 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
1348 "handshaking");
1349 return TOR_TLS_ERROR_MISC;
1351 if (r == TOR_TLS_DONE) {
1352 tls->state = TOR_TLS_ST_OPEN;
1353 return tor_tls_finish_handshake(tls);
1355 return r;
1358 /** Perform the final part of the initial TLS handshake on <b>tls</b>. This
1359 * should be called for the first handshake only: it determines whether the v1
1360 * or the v2 handshake was used, and adjusts things for the renegotiation
1361 * handshake as appropriate.
1363 * tor_tls_handshake() calls this on its own; you only need to call this if
1364 * bufferevent is doing the handshake for you.
1367 tor_tls_finish_handshake(tor_tls_t *tls)
1369 int r = TOR_TLS_DONE;
1370 check_no_tls_errors();
1371 if (tls->isServer) {
1372 SSL_set_info_callback(tls->ssl, NULL);
1373 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
1374 SSL_clear_mode(tls->ssl, SSL_MODE_NO_AUTO_CHAIN);
1375 if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
1376 /* This check is redundant, but back when we did it in the callback,
1377 * we might have not been able to look up the tor_tls_t if the code
1378 * was buggy. Fixing that. */
1379 if (!tls->wasV2Handshake) {
1380 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
1381 " get set. Fixing that.");
1383 tls->wasV2Handshake = 1;
1384 log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
1385 " for renegotiation.");
1386 } else {
1387 tls->wasV2Handshake = 0;
1389 } else {
1390 /* Client-side */
1391 tls->wasV2Handshake = 1;
1392 /* XXXX this can move, probably? -NM */
1393 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
1394 tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
1395 r = TOR_TLS_ERROR_MISC;
1398 tls_log_errors(NULL, LOG_WARN, LD_NET, "finishing the handshake");
1399 return r;
1402 /** Return true iff this TLS connection is authenticated.
1405 tor_tls_peer_has_cert(tor_tls_t *tls)
1407 X509 *cert;
1408 cert = SSL_get_peer_certificate(tls->ssl);
1409 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
1410 if (!cert)
1411 return 0;
1412 X509_free(cert);
1413 return 1;
1416 /** Return a newly allocated copy of the peer certificate, or NULL if there
1417 * isn't one. */
1418 MOCK_IMPL(tor_x509_cert_t *,
1419 tor_tls_get_peer_cert,(tor_tls_t *tls))
1421 X509 *cert;
1422 cert = SSL_get_peer_certificate(tls->ssl);
1423 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
1424 if (!cert)
1425 return NULL;
1426 return tor_x509_cert_new(cert);
1429 /** Return a newly allocated copy of the cerficate we used on the connection,
1430 * or NULL if somehow we didn't use one. */
1431 MOCK_IMPL(tor_x509_cert_t *,
1432 tor_tls_get_own_cert,(tor_tls_t *tls))
1434 X509 *cert = SSL_get_certificate(tls->ssl);
1435 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE,
1436 "getting own-connection certificate");
1437 if (!cert)
1438 return NULL;
1439 /* Fun inconsistency: SSL_get_peer_certificate increments the reference
1440 * count, but SSL_get_certificate does not. */
1441 X509 *duplicate = X509_dup(cert);
1442 if (BUG(duplicate == NULL))
1443 return NULL;
1444 return tor_x509_cert_new(duplicate);
1447 /** Helper function: try to extract a link certificate and an identity
1448 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1449 * *<b>id_cert_out</b> respectively. Log all messages at level
1450 * <b>severity</b>.
1452 * Note that a reference is added both of the returned certificates. */
1453 MOCK_IMPL(void,
1454 try_to_extract_certs_from_tls,(int severity, tor_tls_t *tls,
1455 X509 **cert_out, X509 **id_cert_out))
1457 X509 *cert = NULL, *id_cert = NULL;
1458 STACK_OF(X509) *chain = NULL;
1459 int num_in_chain, i;
1460 *cert_out = *id_cert_out = NULL;
1461 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1462 return;
1463 *cert_out = cert;
1464 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1465 return;
1466 num_in_chain = sk_X509_num(chain);
1467 /* 1 means we're receiving (server-side), and it's just the id_cert.
1468 * 2 means we're connecting (client-side), and it's both the link
1469 * cert and the id_cert.
1471 if (num_in_chain < 1) {
1472 log_fn(severity,LD_PROTOCOL,
1473 "Unexpected number of certificates in chain (%d)",
1474 num_in_chain);
1475 return;
1477 for (i=0; i<num_in_chain; ++i) {
1478 id_cert = sk_X509_value(chain, i);
1479 if (X509_cmp(id_cert, cert) != 0)
1480 break;
1482 *id_cert_out = id_cert ? X509_dup(id_cert) : NULL;
1485 /** Return the number of bytes available for reading from <b>tls</b>.
1488 tor_tls_get_pending_bytes(tor_tls_t *tls)
1490 tor_assert(tls);
1491 return SSL_pending(tls->ssl);
1494 /** If <b>tls</b> requires that the next write be of a particular size,
1495 * return that size. Otherwise, return 0. */
1496 size_t
1497 tor_tls_get_forced_write_size(tor_tls_t *tls)
1499 return tls->wantwrite_n;
1502 /** Sets n_read and n_written to the number of bytes read and written,
1503 * respectively, on the raw socket used by <b>tls</b> since the last time this
1504 * function was called on <b>tls</b>. */
1505 void
1506 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1508 BIO *wbio, *tmpbio;
1509 unsigned long r, w;
1510 r = (unsigned long) BIO_number_read(SSL_get_rbio(tls->ssl));
1511 /* We want the number of bytes actually for real written. Unfortunately,
1512 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1513 * which makes the answer turn out wrong. Let's cope with that. Note
1514 * that this approach will fail if we ever replace tls->ssl's BIOs with
1515 * buffering bios for reasons of our own. As an alternative, we could
1516 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1517 * that would be tempting fate. */
1518 wbio = SSL_get_wbio(tls->ssl);
1519 #if OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)
1520 /* BIO structure is opaque as of OpenSSL 1.1.0-pre5-dev. Again, not
1521 * supposed to use this form of the version macro, but the OpenSSL developers
1522 * introduced major API changes in the pre-release stage.
1524 if (BIO_method_type(wbio) == BIO_TYPE_BUFFER &&
1525 (tmpbio = BIO_next(wbio)) != NULL)
1526 wbio = tmpbio;
1527 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)) */
1528 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1529 wbio = tmpbio;
1530 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5) */
1531 w = (unsigned long) BIO_number_written(wbio);
1533 /* We are ok with letting these unsigned ints go "negative" here:
1534 * If we wrapped around, this should still give us the right answer, unless
1535 * we wrapped around by more than ULONG_MAX since the last time we called
1536 * this function.
1538 *n_read = (size_t)(r - tls->last_read_count);
1539 *n_written = (size_t)(w - tls->last_write_count);
1540 if (*n_read > INT_MAX || *n_written > INT_MAX) {
1541 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1542 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1543 r, tls->last_read_count, w, tls->last_write_count);
1545 total_bytes_written_by_tls += *n_written;
1546 tls->last_read_count = r;
1547 tls->last_write_count = w;
1550 /** Return a ratio of the bytes that TLS has sent to the bytes that we've told
1551 * it to send. Used to track whether our TLS records are getting too tiny. */
1552 MOCK_IMPL(double,
1553 tls_get_write_overhead_ratio,(void))
1555 if (total_bytes_written_over_tls == 0)
1556 return 1.0;
1558 return ((double)total_bytes_written_by_tls) /
1559 ((double)total_bytes_written_over_tls);
1562 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1563 * errors, log an error message. */
1564 void
1565 check_no_tls_errors_(const char *fname, int line)
1567 if (ERR_peek_error() == 0)
1568 return;
1569 log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1570 tor_fix_source_file(fname), line);
1571 tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
1574 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1575 * TLS handshake. Output is undefined if the handshake isn't finished. */
1577 tor_tls_used_v1_handshake(tor_tls_t *tls)
1579 return ! tls->wasV2Handshake;
1582 /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
1583 * request it was waiting for. */
1585 tor_tls_server_got_renegotiate(tor_tls_t *tls)
1587 return tls->got_renegotiate;
1590 #ifndef HAVE_SSL_GET_CLIENT_RANDOM
1591 static size_t
1592 SSL_get_client_random(SSL *s, uint8_t *out, size_t len)
1594 if (len == 0)
1595 return SSL3_RANDOM_SIZE;
1596 tor_assert(len == SSL3_RANDOM_SIZE);
1597 tor_assert(s->s3);
1598 memcpy(out, s->s3->client_random, len);
1599 return len;
1601 #endif /* !defined(HAVE_SSL_GET_CLIENT_RANDOM) */
1603 #ifndef HAVE_SSL_GET_SERVER_RANDOM
1604 static size_t
1605 SSL_get_server_random(SSL *s, uint8_t *out, size_t len)
1607 if (len == 0)
1608 return SSL3_RANDOM_SIZE;
1609 tor_assert(len == SSL3_RANDOM_SIZE);
1610 tor_assert(s->s3);
1611 memcpy(out, s->s3->server_random, len);
1612 return len;
1614 #endif /* !defined(HAVE_SSL_GET_SERVER_RANDOM) */
1616 #ifndef HAVE_SSL_SESSION_GET_MASTER_KEY
1617 size_t
1618 SSL_SESSION_get_master_key(SSL_SESSION *s, uint8_t *out, size_t len)
1620 tor_assert(s);
1621 if (len == 0)
1622 return s->master_key_length;
1623 tor_assert(len == (size_t)s->master_key_length);
1624 tor_assert(out);
1625 memcpy(out, s->master_key, len);
1626 return len;
1628 #endif /* !defined(HAVE_SSL_SESSION_GET_MASTER_KEY) */
1630 /** Set the DIGEST256_LEN buffer at <b>secrets_out</b> to the value used in
1631 * the v3 handshake to prove that the client knows the TLS secrets for the
1632 * connection <b>tls</b>. Return 0 on success, -1 on failure.
1634 MOCK_IMPL(int,
1635 tor_tls_get_tlssecrets,(tor_tls_t *tls, uint8_t *secrets_out))
1637 #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
1638 uint8_t buf[128];
1639 size_t len;
1640 tor_assert(tls);
1642 SSL *const ssl = tls->ssl;
1643 SSL_SESSION *const session = SSL_get_session(ssl);
1645 tor_assert(ssl);
1646 tor_assert(session);
1648 const size_t server_random_len = SSL_get_server_random(ssl, NULL, 0);
1649 const size_t client_random_len = SSL_get_client_random(ssl, NULL, 0);
1650 const size_t master_key_len = SSL_SESSION_get_master_key(session, NULL, 0);
1652 tor_assert(server_random_len);
1653 tor_assert(client_random_len);
1654 tor_assert(master_key_len);
1656 len = client_random_len + server_random_len + strlen(TLSSECRET_MAGIC) + 1;
1657 tor_assert(len <= sizeof(buf));
1660 size_t r = SSL_get_client_random(ssl, buf, client_random_len);
1661 tor_assert(r == client_random_len);
1665 size_t r = SSL_get_server_random(ssl,
1666 buf+client_random_len,
1667 server_random_len);
1668 tor_assert(r == server_random_len);
1671 uint8_t *master_key = tor_malloc_zero(master_key_len);
1673 size_t r = SSL_SESSION_get_master_key(session, master_key, master_key_len);
1674 tor_assert(r == master_key_len);
1677 uint8_t *nextbuf = buf + client_random_len + server_random_len;
1678 memcpy(nextbuf, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
1681 The value is an HMAC, using the TLS master key as the HMAC key, of
1682 client_random | server_random | TLSSECRET_MAGIC
1684 crypto_hmac_sha256((char*)secrets_out,
1685 (char*)master_key,
1686 master_key_len,
1687 (char*)buf, len);
1688 memwipe(buf, 0, sizeof(buf));
1689 memwipe(master_key, 0, master_key_len);
1690 tor_free(master_key);
1692 return 0;
1695 /** Using the RFC5705 key material exporting construction, and the
1696 * provided <b>context</b> (<b>context_len</b> bytes long) and
1697 * <b>label</b> (a NUL-terminated string), compute a 32-byte secret in
1698 * <b>secrets_out</b> that only the parties to this TLS session can
1699 * compute. Return 0 on success; -1 on failure; and -2 on failure
1700 * caused by OpenSSL bug 7712.
1702 MOCK_IMPL(int,
1703 tor_tls_export_key_material,(tor_tls_t *tls, uint8_t *secrets_out,
1704 const uint8_t *context,
1705 size_t context_len,
1706 const char *label))
1708 tor_assert(tls);
1709 tor_assert(tls->ssl);
1711 int r = SSL_export_keying_material(tls->ssl,
1712 secrets_out, DIGEST256_LEN,
1713 label, strlen(label),
1714 context, context_len, 1);
1716 if (r != 1) {
1717 int severity = openssl_bug_7712_is_present ? LOG_WARN : LOG_DEBUG;
1718 tls_log_errors(tls, severity, LD_NET, "exporting keying material");
1721 #ifdef TLS1_3_VERSION
1722 if (r != 1 &&
1723 strlen(label) > 12 &&
1724 SSL_version(tls->ssl) >= TLS1_3_VERSION) {
1726 if (! openssl_bug_7712_is_present) {
1727 /* We might have run into OpenSSL issue 7712, which caused OpenSSL
1728 * 1.1.1a to not handle long labels. Let's test to see if we have.
1730 r = SSL_export_keying_material(tls->ssl, secrets_out, DIGEST256_LEN,
1731 "short", 5, context, context_len, 1);
1732 if (r == 1) {
1733 /* A short label succeeds, but a long label fails. This was openssl
1734 * issue 7712. */
1735 openssl_bug_7712_is_present = 1;
1736 log_warn(LD_GENERAL, "Detected OpenSSL bug 7712: disabling TLS 1.3 on "
1737 "future connections. A fix is expected to appear in OpenSSL "
1738 "1.1.1b.");
1741 if (openssl_bug_7712_is_present)
1742 return -2;
1743 else
1744 return -1;
1746 #endif /* defined(TLS1_3_VERSION) */
1748 return (r == 1) ? 0 : -1;
1751 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1752 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1753 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1754 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1755 * buffer and *<b>wbuf_bytes</b> to the amount actually used.
1757 * Return 0 on success, -1 on failure.*/
1759 tor_tls_get_buffer_sizes(tor_tls_t *tls,
1760 size_t *rbuf_capacity, size_t *rbuf_bytes,
1761 size_t *wbuf_capacity, size_t *wbuf_bytes)
1763 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)
1764 (void)tls;
1765 (void)rbuf_capacity;
1766 (void)rbuf_bytes;
1767 (void)wbuf_capacity;
1768 (void)wbuf_bytes;
1770 return -1;
1771 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)) */
1772 if (tls->ssl->s3->rbuf.buf)
1773 *rbuf_capacity = tls->ssl->s3->rbuf.len;
1774 else
1775 *rbuf_capacity = 0;
1776 if (tls->ssl->s3->wbuf.buf)
1777 *wbuf_capacity = tls->ssl->s3->wbuf.len;
1778 else
1779 *wbuf_capacity = 0;
1780 *rbuf_bytes = tls->ssl->s3->rbuf.left;
1781 *wbuf_bytes = tls->ssl->s3->wbuf.left;
1782 return 0;
1783 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
1786 /** Check whether the ECC group requested is supported by the current OpenSSL
1787 * library instance. Return 1 if the group is supported, and 0 if not.
1790 evaluate_ecgroup_for_tls(const char *ecgroup)
1792 EC_KEY *ec_key;
1793 int nid;
1794 int ret;
1796 if (!ecgroup)
1797 nid = NID_tor_default_ecdhe_group;
1798 else if (!strcasecmp(ecgroup, "P256"))
1799 nid = NID_X9_62_prime256v1;
1800 else if (!strcasecmp(ecgroup, "P224"))
1801 nid = NID_secp224r1;
1802 else
1803 return 0;
1805 ec_key = EC_KEY_new_by_curve_name(nid);
1806 ret = (ec_key != NULL);
1807 EC_KEY_free(ec_key);
1809 return ret;