Merge branch 'maint-0.4.7' into maint-0.4.8
[tor.git] / src / lib / tls / tortls_openssl.c
blobee91715e2d7e9c60200352ba8991ee5b25827041
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 (!defined(LIBRESSL_VERSION_NUMBER) || \
346 LIBRESSL_VERSION_NUMBER < 0x3080000fL))
347 long version = tor_OpenSSL_version_num();
349 /* LCOV_EXCL_START : we can't test these lines on the same machine */
350 if (version >= OPENSSL_V_SERIES(1,0,1)) {
351 /* Warn if we could *almost* be running with much faster ECDH.
352 If we're built for a 64-bit target, using OpenSSL 1.0.1, but we
353 don't have one of the built-in __uint128-based speedups, we are
354 just one build operation away from an accelerated handshake.
356 (We could be looking at OPENSSL_NO_EC_NISTP_64_GCC_128 instead of
357 doing this test, but that gives compile-time options, not runtime
358 behavior.)
360 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
361 const EC_GROUP *g = key ? EC_KEY_get0_group(key) : NULL;
362 const EC_METHOD *m = g ? EC_GROUP_method_of(g) : NULL;
363 const int warn = (m == EC_GFp_simple_method() ||
364 m == EC_GFp_mont_method() ||
365 m == EC_GFp_nist_method());
366 EC_KEY_free(key);
368 if (warn)
369 log_notice(LD_GENERAL, "We were built to run on a 64-bit CPU, with "
370 "OpenSSL 1.0.1 or later, but with a version of OpenSSL "
371 "that apparently lacks accelerated support for the NIST "
372 "P-224 and P-256 groups. Building openssl with such "
373 "support (using the enable-ec_nistp_64_gcc_128 option "
374 "when configuring it) would make ECDH much faster.");
376 /* LCOV_EXCL_STOP */
377 #endif /* (SIZEOF_VOID_P >= 8 && ... */
379 tor_tls_allocate_tor_tls_object_ex_data_index();
381 tls_library_is_initialized = 1;
385 /** We need to give OpenSSL a callback to verify certificates. This is
386 * it: We always accept peer certs and complete the handshake. We
387 * don't validate them until later.
390 always_accept_verify_cb(int preverify_ok,
391 X509_STORE_CTX *x509_ctx)
393 (void) preverify_ok;
394 (void) x509_ctx;
395 return 1;
398 /** List of ciphers that servers should select from when the client might be
399 * claiming extra unsupported ciphers in order to avoid fingerprinting. */
400 static const char SERVER_CIPHER_LIST[] =
401 #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
402 /* This one can never actually get selected, since if the client lists it,
403 * we will assume that the client is honest, and not use this list.
404 * Nonetheless we list it if it's available, so that the server doesn't
405 * conclude that it has no valid ciphers if it's running with TLS1.3.
407 TLS1_3_TXT_AES_128_GCM_SHA256 ":"
408 #endif /* defined(TLS1_3_TXT_AES_128_GCM_SHA256) */
409 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
410 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA;
412 /** List of ciphers that servers should select from when we actually have
413 * our choice of what cipher to use. */
414 static const char UNRESTRICTED_SERVER_CIPHER_LIST[] =
415 /* Here are the TLS 1.3 ciphers we like, in the order we prefer. */
416 #ifdef TLS1_3_TXT_AES_256_GCM_SHA384
417 TLS1_3_TXT_AES_256_GCM_SHA384 ":"
418 #endif
419 #ifdef TLS1_3_TXT_CHACHA20_POLY1305_SHA256
420 TLS1_3_TXT_CHACHA20_POLY1305_SHA256 ":"
421 #endif
422 #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
423 TLS1_3_TXT_AES_128_GCM_SHA256 ":"
424 #endif
425 #ifdef TLS1_3_TXT_AES_128_CCM_SHA256
426 TLS1_3_TXT_AES_128_CCM_SHA256 ":"
427 #endif
429 /* This list is autogenerated with the gen_server_ciphers.py script;
430 * don't hand-edit it. */
431 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
432 TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
433 #endif
434 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
435 TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
436 #endif
437 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384
438 TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 ":"
439 #endif
440 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
441 TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
442 #endif
443 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA
444 TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
445 #endif
446 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
447 TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
448 #endif
449 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384
450 TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 ":"
451 #endif
452 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256
453 TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 ":"
454 #endif
455 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_CCM
456 TLS1_TXT_DHE_RSA_WITH_AES_256_CCM ":"
457 #endif
458 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_CCM
459 TLS1_TXT_DHE_RSA_WITH_AES_128_CCM ":"
460 #endif
461 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256
462 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 ":"
463 #endif
464 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256
465 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 ":"
466 #endif
467 /* Required */
468 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
469 /* Required */
470 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"
471 #ifdef TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305
472 TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 ":"
473 #endif
474 #ifdef TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
475 TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
476 #endif
479 /* Note: to set up your own private testing network with link crypto
480 * disabled, set your Tors' cipher list to
481 * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
482 * with any of the "real" Tors, though. */
484 #define CIPHER(id, name) name ":"
485 #define XCIPHER(id, name)
486 /** List of ciphers that clients should advertise, omitting items that
487 * our OpenSSL doesn't know about. */
488 static const char CLIENT_CIPHER_LIST[] =
489 #ifndef COCCI
490 #include "lib/tls/ciphers.inc"
491 #endif
492 /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
493 * of any cipher we say. */
494 "!SSLv2"
496 #undef CIPHER
497 #undef XCIPHER
499 /** Return true iff the other side of <b>tls</b> has authenticated to us, and
500 * the key certified in <b>cert</b> is the same as the key they used to do it.
502 MOCK_IMPL(int,
503 tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
505 tor_x509_cert_t *peer = tor_tls_get_peer_cert((tor_tls_t *)tls);
506 if (!peer)
507 return 0;
509 X509 *peercert = peer->cert;
510 EVP_PKEY *link_key = NULL, *cert_key = NULL;
511 int result;
513 link_key = X509_get_pubkey(peercert);
514 cert_key = X509_get_pubkey(cert->cert);
516 result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
518 tor_x509_cert_free(peer);
519 if (link_key)
520 EVP_PKEY_free(link_key);
521 if (cert_key)
522 EVP_PKEY_free(cert_key);
524 return result;
527 void
528 tor_tls_context_impl_free_(struct ssl_ctx_st *ctx)
530 if (!ctx)
531 return;
532 SSL_CTX_free(ctx);
535 /** The group we should use for ecdhe when none was selected. */
536 #define NID_tor_default_ecdhe_group NID_X9_62_prime256v1
538 /** Create a new TLS context for use with Tor TLS handshakes.
539 * <b>identity</b> should be set to the identity key used to sign the
540 * certificate.
542 tor_tls_context_t *
543 tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
544 unsigned flags, int is_client)
546 EVP_PKEY *pkey = NULL;
547 tor_tls_context_t *result = NULL;
549 tor_tls_init();
551 result = tor_malloc_zero(sizeof(tor_tls_context_t));
552 result->refcnt = 1;
554 if (! is_client) {
555 if (tor_tls_context_init_certificates(result, identity, key_lifetime,
556 flags) < 0) {
557 goto error;
561 #if 0
562 /* Tell OpenSSL to only use TLS1. This may have subtly different results
563 * from SSLv23_method() with SSLv2 and SSLv3 disabled, so we need to do some
564 * investigation before we consider adjusting it. It should be compatible
565 * with existing Tors. */
566 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
567 goto error;
568 #endif /* 0 */
570 /* Tell OpenSSL to use TLS 1.0 or later but not SSL2 or SSL3. */
571 #ifdef HAVE_TLS_METHOD
572 if (!(result->ctx = SSL_CTX_new(TLS_method())))
573 goto error;
574 #else
575 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
576 goto error;
577 #endif /* defined(HAVE_TLS_METHOD) */
579 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
580 /* Level 1 re-enables RSA1024 and DH1024 for compatibility with old tors */
581 SSL_CTX_set_security_level(result->ctx, 1);
582 #endif
584 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
585 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
587 /* Prefer the server's ordering of ciphers: the client's ordering has
588 * historically been chosen for fingerprinting resistance. */
589 SSL_CTX_set_options(result->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
591 /* Disable TLS tickets if they're supported. We never want to use them;
592 * using them can make our perfect forward secrecy a little worse, *and*
593 * create an opportunity to fingerprint us (since it's unusual to use them
594 * with TLS sessions turned off).
596 * In 0.2.4, clients advertise support for them though, to avoid a TLS
597 * distinguishability vector. This can give us worse PFS, though, if we
598 * get a server that doesn't set SSL_OP_NO_TICKET. With luck, there will
599 * be few such servers by the time 0.2.4 is more stable.
601 #ifdef SSL_OP_NO_TICKET
602 if (! is_client) {
603 SSL_CTX_set_options(result->ctx, SSL_OP_NO_TICKET);
605 #endif
607 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
608 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_ECDH_USE);
610 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
611 SSL_CTX_set_options(result->ctx,
612 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
613 #endif
614 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
615 * as authenticating any earlier-received data.
618 SSL_CTX_set_options(result->ctx,
619 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
622 /* Don't actually allow compression; it uses RAM and time, it makes TLS
623 * vulnerable to CRIME-style attacks, and most of the data we transmit over
624 * TLS is encrypted (and therefore uncompressible) anyway. */
625 #ifdef SSL_OP_NO_COMPRESSION
626 SSL_CTX_set_options(result->ctx, SSL_OP_NO_COMPRESSION);
627 #endif
628 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0)
629 #ifndef OPENSSL_NO_COMP
630 if (result->ctx->comp_methods)
631 result->ctx->comp_methods = NULL;
632 #endif
633 #endif /* OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0) */
635 #ifdef SSL_MODE_RELEASE_BUFFERS
636 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
637 #endif
638 if (! is_client) {
639 if (result->my_link_cert &&
640 !SSL_CTX_use_certificate(result->ctx,
641 result->my_link_cert->cert)) {
642 goto error;
644 if (result->my_id_cert) {
645 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
646 tor_assert(s);
647 X509_STORE_add_cert(s, result->my_id_cert->cert);
650 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
651 if (!is_client) {
652 tor_assert(result->link_key);
653 if (!(pkey = crypto_pk_get_openssl_evp_pkey_(result->link_key,1)))
654 goto error;
655 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
656 goto error;
657 EVP_PKEY_free(pkey);
658 pkey = NULL;
659 if (!SSL_CTX_check_private_key(result->ctx))
660 goto error;
664 DH *dh = crypto_dh_new_openssl_tls();
665 tor_assert(dh);
666 SSL_CTX_set_tmp_dh(result->ctx, dh);
667 DH_free(dh);
669 /* We check for this function in two ways, since it might be either a symbol
670 * or a macro. */
671 #if defined(SSL_CTX_set1_groups_list) || defined(HAVE_SSL_CTX_SET1_GROUPS_LIST)
673 const char *list;
674 if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
675 list = "P-224:P-256";
676 else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
677 list = "P-256:P-224";
678 else
679 list = "P-256:P-224";
680 int r = (int) SSL_CTX_set1_groups_list(result->ctx, list);
681 if (r < 0)
682 goto error;
684 #else /* !(defined(SSL_CTX_set1_groups_list) || defined(HAVE_SSL_CTX_SE...)) */
685 if (! is_client) {
686 int nid;
687 EC_KEY *ec_key;
688 if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
689 nid = NID_secp224r1;
690 else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
691 nid = NID_X9_62_prime256v1;
692 else
693 nid = NID_tor_default_ecdhe_group;
694 /* Use P-256 for ECDHE. */
695 ec_key = EC_KEY_new_by_curve_name(nid);
696 if (ec_key != NULL) /*XXXX Handle errors? */
697 SSL_CTX_set_tmp_ecdh(result->ctx, ec_key);
698 EC_KEY_free(ec_key);
700 #endif /* defined(SSL_CTX_set1_groups_list) || defined(HAVE_SSL_CTX_SET1...) */
701 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
702 always_accept_verify_cb);
703 /* let us realloc bufs that we're writing from */
704 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
706 #ifdef SSL_OP_TLSEXT_PADDING
707 /* Adds a padding extension to ensure the ClientHello size is never between
708 * 256 and 511 bytes in length. */
709 SSL_CTX_set_options(result->ctx, SSL_OP_TLSEXT_PADDING);
710 #endif
712 return result;
714 error:
715 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
716 if (pkey)
717 EVP_PKEY_free(pkey);
718 tor_tls_context_decref(result);
719 return NULL;
722 /** Invoked when a TLS state changes: log the change at severity 'debug' */
723 void
724 tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
726 /* LCOV_EXCL_START since this depends on whether debug is captured or not */
727 log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
728 ssl, SSL_state_string_long(ssl), type, val);
729 /* LCOV_EXCL_STOP */
732 /* Return the name of the negotiated ciphersuite in use on <b>tls</b> */
733 const char *
734 tor_tls_get_ciphersuite_name(tor_tls_t *tls)
736 return SSL_get_cipher(tls->ssl);
739 /* Here's the old V2 cipher list we sent from 0.2.1.1-alpha up to
740 * 0.2.3.17-beta. If a client is using this list, we can't believe the ciphers
741 * that it claims to support. We'll prune this list to remove the ciphers
742 * *we* don't recognize. */
743 STATIC uint16_t v2_cipher_list[] = {
744 0xc00a, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA */
745 0xc014, /* TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA */
746 0x0039, /* TLS1_TXT_DHE_RSA_WITH_AES_256_SHA */
747 0x0038, /* TLS1_TXT_DHE_DSS_WITH_AES_256_SHA */
748 0xc00f, /* TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA */
749 0xc005, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA */
750 0x0035, /* TLS1_TXT_RSA_WITH_AES_256_SHA */
751 0xc007, /* TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA */
752 0xc009, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA */
753 0xc011, /* TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA */
754 0xc013, /* TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA */
755 0x0033, /* TLS1_TXT_DHE_RSA_WITH_AES_128_SHA */
756 0x0032, /* TLS1_TXT_DHE_DSS_WITH_AES_128_SHA */
757 0xc00c, /* TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA */
758 0xc00e, /* TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA */
759 0xc002, /* TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA */
760 0xc004, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA */
761 0x0004, /* SSL3_TXT_RSA_RC4_128_MD5 */
762 0x0005, /* SSL3_TXT_RSA_RC4_128_SHA */
763 0x002f, /* TLS1_TXT_RSA_WITH_AES_128_SHA */
764 0xc008, /* TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA */
765 0xc012, /* TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA */
766 0x0016, /* SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA */
767 0x0013, /* SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA */
768 0xc00d, /* TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA */
769 0xc003, /* TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA */
770 0xfeff, /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA */
771 0x000a, /* SSL3_TXT_RSA_DES_192_CBC3_SHA */
774 /** Have we removed the unrecognized ciphers from v2_cipher_list yet? */
775 static int v2_cipher_list_pruned = 0;
777 /** Return 0 if <b>m</b> does not support the cipher with ID <b>cipher</b>;
778 * return 1 if it does support it, or if we have no way to tell. */
780 find_cipher_by_id(const SSL *ssl, const SSL_METHOD *m, uint16_t cipher)
782 const SSL_CIPHER *c;
783 #ifdef HAVE_SSL_CIPHER_FIND
784 (void) m;
786 unsigned char cipherid[3];
787 tor_assert(ssl);
788 set_uint16(cipherid, tor_htons(cipher));
789 cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
790 * with a two-byte 'cipherid', it may look for a v2
791 * cipher with the appropriate 3 bytes. */
792 c = SSL_CIPHER_find((SSL*)ssl, cipherid);
793 if (c)
794 tor_assert((SSL_CIPHER_get_id(c) & 0xffff) == cipher);
795 return c != NULL;
797 #else /* !defined(HAVE_SSL_CIPHER_FIND) */
799 # if defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR)
800 if (m && m->get_cipher_by_char) {
801 unsigned char cipherid[3];
802 set_uint16(cipherid, tor_htons(cipher));
803 cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
804 * with a two-byte 'cipherid', it may look for a v2
805 * cipher with the appropriate 3 bytes. */
806 c = m->get_cipher_by_char(cipherid);
807 if (c)
808 tor_assert((c->id & 0xffff) == cipher);
809 return c != NULL;
811 #endif /* defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR) */
812 # ifndef OPENSSL_1_1_API
813 if (m && m->get_cipher && m->num_ciphers) {
814 /* It would seem that some of the "let's-clean-up-openssl" forks have
815 * removed the get_cipher_by_char function. Okay, so now you get a
816 * quadratic search.
818 int i;
819 for (i = 0; i < m->num_ciphers(); ++i) {
820 c = m->get_cipher(i);
821 if (c && (c->id & 0xffff) == cipher) {
822 return 1;
825 return 0;
827 #endif /* !defined(OPENSSL_1_1_API) */
828 (void) ssl;
829 (void) m;
830 (void) cipher;
831 return 1; /* No way to search */
832 #endif /* defined(HAVE_SSL_CIPHER_FIND) */
835 /** Remove from v2_cipher_list every cipher that we don't support, so that
836 * comparing v2_cipher_list to a client's cipher list will give a sensible
837 * result. */
838 static void
839 prune_v2_cipher_list(const SSL *ssl)
841 uint16_t *inp, *outp;
842 #ifdef HAVE_TLS_METHOD
843 const SSL_METHOD *m = TLS_method();
844 #else
845 const SSL_METHOD *m = SSLv23_method();
846 #endif
848 inp = outp = v2_cipher_list;
849 while (*inp) {
850 if (find_cipher_by_id(ssl, m, *inp)) {
851 *outp++ = *inp++;
852 } else {
853 inp++;
856 *outp = 0;
858 v2_cipher_list_pruned = 1;
861 /** Examine the client cipher list in <b>ssl</b>, and determine what kind of
862 * client it is. Return one of CIPHERS_ERR, CIPHERS_V1, CIPHERS_V2,
863 * CIPHERS_UNRESTRICTED.
866 tor_tls_classify_client_ciphers(const SSL *ssl,
867 STACK_OF(SSL_CIPHER) *peer_ciphers)
869 int i, res;
870 tor_tls_t *tor_tls;
871 if (PREDICT_UNLIKELY(!v2_cipher_list_pruned))
872 prune_v2_cipher_list(ssl);
874 tor_tls = tor_tls_get_by_ssl(ssl);
875 if (tor_tls && tor_tls->client_cipher_list_type)
876 return tor_tls->client_cipher_list_type;
878 /* If we reached this point, we just got a client hello. See if there is
879 * a cipher list. */
880 if (!peer_ciphers) {
881 log_info(LD_NET, "No ciphers on session");
882 res = CIPHERS_ERR;
883 goto done;
885 /* Now we need to see if there are any ciphers whose presence means we're
886 * dealing with an updated Tor. */
887 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
888 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
889 const char *ciphername = SSL_CIPHER_get_name(cipher);
890 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
891 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
892 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
893 strcmp(ciphername, "(NONE)")) {
894 log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
895 // return 1;
896 goto v2_or_higher;
899 res = CIPHERS_V1;
900 goto done;
901 v2_or_higher:
903 const uint16_t *v2_cipher = v2_cipher_list;
904 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
905 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
906 uint16_t id = SSL_CIPHER_get_id(cipher) & 0xffff;
907 if (id == 0x00ff) /* extended renegotiation indicator. */
908 continue;
909 if (!id || id != *v2_cipher) {
910 res = CIPHERS_UNRESTRICTED;
911 goto dump_ciphers;
913 ++v2_cipher;
915 if (*v2_cipher != 0) {
916 res = CIPHERS_UNRESTRICTED;
917 goto dump_ciphers;
919 res = CIPHERS_V2;
922 dump_ciphers:
924 smartlist_t *elts = smartlist_new();
925 char *s;
926 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
927 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
928 const char *ciphername = SSL_CIPHER_get_name(cipher);
929 smartlist_add(elts, (char*)ciphername);
931 s = smartlist_join_strings(elts, ":", 0, NULL);
932 log_debug(LD_NET, "Got a %s V2/V3 cipher list from %s. It is: '%s'",
933 (res == CIPHERS_V2) ? "fictitious" : "real", ADDR(tor_tls), s);
934 tor_free(s);
935 smartlist_free(elts);
937 done:
938 if (tor_tls && peer_ciphers)
939 return tor_tls->client_cipher_list_type = res;
941 return res;
944 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
945 * a list that indicates that the client knows how to do the v2 TLS connection
946 * handshake. */
948 tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
950 STACK_OF(SSL_CIPHER) *ciphers;
951 #ifdef HAVE_SSL_GET_CLIENT_CIPHERS
952 ciphers = SSL_get_client_ciphers(ssl);
953 #else
954 SSL_SESSION *session;
955 if (!(session = SSL_get_session((SSL *)ssl))) {
956 log_info(LD_NET, "No session on TLS?");
957 return CIPHERS_ERR;
959 ciphers = session->ciphers;
960 #endif /* defined(HAVE_SSL_GET_CLIENT_CIPHERS) */
962 return tor_tls_classify_client_ciphers(ssl, ciphers) >= CIPHERS_V2;
965 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
966 * changes state. We use this:
967 * <ul><li>To alter the state of the handshake partway through, so we
968 * do not send or request extra certificates in v2 handshakes.</li>
969 * <li>To detect renegotiation</li></ul>
971 void
972 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
974 tor_tls_t *tls;
975 (void) val;
977 IF_BUG_ONCE(ssl == NULL) {
978 return; // LCOV_EXCL_LINE
981 tor_tls_debug_state_callback(ssl, type, val);
983 if (type != SSL_CB_ACCEPT_LOOP)
984 return;
986 OSSL_HANDSHAKE_STATE ssl_state = SSL_get_state(ssl);
987 if (! STATE_IS_SW_SERVER_HELLO(ssl_state))
988 return;
989 tls = tor_tls_get_by_ssl(ssl);
990 if (tls) {
991 /* Check whether we're watching for renegotiates. If so, this is one! */
992 if (tls->negotiated_callback)
993 tls->got_renegotiate = 1;
994 } else {
995 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
996 return;
999 /* Now check the cipher list. */
1000 if (tor_tls_client_is_using_v2_ciphers(ssl)) {
1001 if (tls->wasV2Handshake)
1002 return; /* We already turned this stuff off for the first handshake;
1003 * This is a renegotiation. */
1005 /* Yes, we're casting away the const from ssl. This is very naughty of us.
1006 * Let's hope openssl doesn't notice! */
1008 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
1009 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
1010 /* Don't send a hello request. */
1011 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
1013 if (tls) {
1014 tls->wasV2Handshake = 1;
1015 } else {
1016 /* LCOV_EXCL_START this line is not reachable */
1017 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
1018 /* LCOV_EXCL_STOP */
1023 /** Callback to get invoked on a server after we've read the list of ciphers
1024 * the client supports, but before we pick our own ciphersuite.
1026 * We can't abuse an info_cb for this, since by the time one of the
1027 * client_hello info_cbs is called, we've already picked which ciphersuite to
1028 * use.
1030 * Technically, this function is an abuse of this callback, since the point of
1031 * a session_secret_cb is to try to set up and/or verify a shared-secret for
1032 * authentication on the fly. But as long as we return 0, we won't actually be
1033 * setting up a shared secret, and all will be fine.
1036 tor_tls_session_secret_cb(SSL *ssl, void *secret, int *secret_len,
1037 STACK_OF(SSL_CIPHER) *peer_ciphers,
1038 CONST_IF_OPENSSL_1_1_API SSL_CIPHER **cipher,
1039 void *arg)
1041 (void) secret;
1042 (void) secret_len;
1043 (void) peer_ciphers;
1044 (void) cipher;
1045 (void) arg;
1047 if (tor_tls_classify_client_ciphers(ssl, peer_ciphers) ==
1048 CIPHERS_UNRESTRICTED) {
1049 SSL_set_cipher_list(ssl, UNRESTRICTED_SERVER_CIPHER_LIST);
1052 SSL_set_session_secret_cb(ssl, NULL, NULL);
1054 return 0;
1056 static void
1057 tor_tls_setup_session_secret_cb(tor_tls_t *tls)
1059 SSL_set_session_secret_cb(tls->ssl, tor_tls_session_secret_cb, NULL);
1062 /** Create a new TLS object from a file descriptor, and a flag to
1063 * determine whether it is functioning as a server.
1065 tor_tls_t *
1066 tor_tls_new(tor_socket_t sock, int isServer)
1068 BIO *bio = NULL;
1069 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
1070 tor_tls_context_t *context = tor_tls_context_get(isServer);
1071 result->magic = TOR_TLS_MAGIC;
1073 check_no_tls_errors();
1074 tor_assert(context); /* make sure somebody made it first */
1075 if (!(result->ssl = SSL_new(context->ctx))) {
1076 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
1077 tor_free(result);
1078 goto err;
1081 #ifdef SSL_set_tlsext_host_name
1082 /* Browsers use the TLS hostname extension, so we should too. */
1083 if (!isServer) {
1084 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
1085 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
1086 tor_free(fake_hostname);
1088 #endif /* defined(SSL_set_tlsext_host_name) */
1090 #ifdef SSL_CTRL_SET_MAX_PROTO_VERSION
1091 if (openssl_bug_7712_is_present) {
1092 /* We can't actually use TLS 1.3 until this bug is fixed. */
1093 SSL_set_max_proto_version(result->ssl, TLS1_2_VERSION);
1095 #endif /* defined(SSL_CTRL_SET_MAX_PROTO_VERSION) */
1097 if (!SSL_set_cipher_list(result->ssl,
1098 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
1099 tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
1100 #ifdef SSL_set_tlsext_host_name
1101 SSL_set_tlsext_host_name(result->ssl, NULL);
1102 #endif
1103 SSL_free(result->ssl);
1104 tor_free(result);
1105 goto err;
1107 result->socket = sock;
1108 bio = BIO_new_socket(sock, BIO_CLOSE);
1109 if (! bio) {
1110 tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
1111 #ifdef SSL_set_tlsext_host_name
1112 SSL_set_tlsext_host_name(result->ssl, NULL);
1113 #endif
1114 SSL_free(result->ssl);
1115 tor_free(result);
1116 goto err;
1119 int set_worked =
1120 SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
1121 if (!set_worked) {
1122 log_warn(LD_BUG,
1123 "Couldn't set the tls for an SSL*; connection will fail");
1126 SSL_set_bio(result->ssl, bio, bio);
1127 tor_tls_context_incref(context);
1128 result->context = context;
1129 result->state = TOR_TLS_ST_HANDSHAKE;
1130 result->isServer = isServer;
1131 result->wantwrite_n = 0;
1132 result->last_write_count = (unsigned long) BIO_number_written(bio);
1133 result->last_read_count = (unsigned long) BIO_number_read(bio);
1134 if (result->last_write_count || result->last_read_count) {
1135 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
1136 result->last_read_count, result->last_write_count);
1138 if (isServer) {
1139 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
1140 } else {
1141 SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
1144 if (isServer)
1145 tor_tls_setup_session_secret_cb(result);
1147 goto done;
1148 err:
1149 result = NULL;
1150 done:
1151 /* Not expected to get called. */
1152 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
1153 return result;
1156 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
1157 * next gets a client-side renegotiate in the middle of a read. Do not
1158 * invoke this function until <em>after</em> initial handshaking is done!
1160 void
1161 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
1162 void (*cb)(tor_tls_t *, void *arg),
1163 void *arg)
1165 tls->negotiated_callback = cb;
1166 tls->callback_arg = arg;
1167 tls->got_renegotiate = 0;
1168 if (cb) {
1169 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
1170 } else {
1171 SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
1175 /** If this version of openssl requires it, turn on renegotiation on
1176 * <b>tls</b>.
1178 void
1179 tor_tls_unblock_renegotiation(tor_tls_t *tls)
1181 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1182 * as authenticating any earlier-received data. */
1183 SSL_set_options(tls->ssl,
1184 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1187 /** If this version of openssl supports it, turn off renegotiation on
1188 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
1189 * to use belt-and-suspenders here.)
1191 void
1192 tor_tls_block_renegotiation(tor_tls_t *tls)
1194 #ifdef SUPPORT_UNSAFE_RENEGOTIATION_FLAG
1195 tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1196 #else
1197 (void) tls;
1198 #endif
1202 * Tell the TLS library that the underlying socket for <b>tls</b> has been
1203 * closed, and the library should not attempt to free that socket itself.
1205 void
1206 tor_tls_release_socket(tor_tls_t *tls)
1208 if (! tls)
1209 return;
1211 BIO *rbio, *wbio;
1212 rbio = SSL_get_rbio(tls->ssl);
1213 wbio = SSL_get_wbio(tls->ssl);
1215 if (rbio) {
1216 (void) BIO_set_close(rbio, BIO_NOCLOSE);
1218 if (wbio && wbio != rbio) {
1219 (void) BIO_set_close(wbio, BIO_NOCLOSE);
1223 void
1224 tor_tls_impl_free_(tor_tls_impl_t *ssl)
1226 if (!ssl)
1227 return;
1229 #ifdef SSL_set_tlsext_host_name
1230 SSL_set_tlsext_host_name(ssl, NULL);
1231 #endif
1232 SSL_free(ssl);
1235 /** Underlying function for TLS reading. Reads up to <b>len</b>
1236 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
1237 * number of characters read. On failure, returns TOR_TLS_ERROR,
1238 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1240 MOCK_IMPL(int,
1241 tor_tls_read,(tor_tls_t *tls, char *cp, size_t len))
1243 int r, err;
1244 tor_assert(tls);
1245 tor_assert(tls->ssl);
1246 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1247 tor_assert(len<INT_MAX);
1248 r = SSL_read(tls->ssl, cp, (int)len);
1249 if (r > 0) {
1250 if (tls->got_renegotiate) {
1251 /* Renegotiation happened! */
1252 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
1253 if (tls->negotiated_callback)
1254 tls->negotiated_callback(tls, tls->callback_arg);
1255 tls->got_renegotiate = 0;
1257 return r;
1259 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
1260 if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) {
1261 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
1262 tls->state = TOR_TLS_ST_CLOSED;
1263 return TOR_TLS_CLOSE;
1264 } else {
1265 tor_assert(err != TOR_TLS_DONE);
1266 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
1267 return err;
1271 /** Total number of bytes that we've used TLS to send. Used to track TLS
1272 * overhead. */
1273 STATIC uint64_t total_bytes_written_over_tls = 0;
1274 /** Total number of bytes that TLS has put on the network for us. Used to
1275 * track TLS overhead. */
1276 STATIC uint64_t total_bytes_written_by_tls = 0;
1278 /** Underlying function for TLS writing. Write up to <b>n</b>
1279 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
1280 * number of characters written. On failure, returns TOR_TLS_ERROR,
1281 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1284 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
1286 int r, err;
1287 tor_assert(tls);
1288 tor_assert(tls->ssl);
1289 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1290 tor_assert(n < INT_MAX);
1291 if (n == 0)
1292 return 0;
1293 if (tls->wantwrite_n) {
1294 /* if WANTWRITE last time, we must use the _same_ n as before */
1295 tor_assert(n >= tls->wantwrite_n);
1296 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
1297 (int)n, (int)tls->wantwrite_n);
1298 n = tls->wantwrite_n;
1299 tls->wantwrite_n = 0;
1301 r = SSL_write(tls->ssl, cp, (int)n);
1302 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
1303 if (err == TOR_TLS_DONE) {
1304 total_bytes_written_over_tls += r;
1305 return r;
1307 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
1308 tls->wantwrite_n = n;
1310 return err;
1313 /** Perform initial handshake on <b>tls</b>. When finished, returns
1314 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1315 * or TOR_TLS_WANTWRITE.
1318 tor_tls_handshake(tor_tls_t *tls)
1320 int r;
1321 tor_assert(tls);
1322 tor_assert(tls->ssl);
1323 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1325 check_no_tls_errors();
1327 OSSL_HANDSHAKE_STATE oldstate = SSL_get_state(tls->ssl);
1329 if (tls->isServer) {
1330 log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
1331 SSL_state_string_long(tls->ssl));
1332 r = SSL_accept(tls->ssl);
1333 } else {
1334 log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
1335 SSL_state_string_long(tls->ssl));
1336 r = SSL_connect(tls->ssl);
1339 OSSL_HANDSHAKE_STATE newstate = SSL_get_state(tls->ssl);
1341 if (oldstate != newstate)
1342 log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
1343 tls, SSL_state_string_long(tls->ssl));
1344 /* We need to call this here and not earlier, since OpenSSL has a penchant
1345 * for clearing its flags when you say accept or connect. */
1346 tor_tls_unblock_renegotiation(tls);
1347 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
1348 if (ERR_peek_error() != 0) {
1349 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
1350 "handshaking");
1351 return TOR_TLS_ERROR_MISC;
1353 if (r == TOR_TLS_DONE) {
1354 tls->state = TOR_TLS_ST_OPEN;
1355 return tor_tls_finish_handshake(tls);
1357 return r;
1360 /** Perform the final part of the initial TLS handshake on <b>tls</b>. This
1361 * should be called for the first handshake only: it determines whether the v1
1362 * or the v2 handshake was used, and adjusts things for the renegotiation
1363 * handshake as appropriate.
1365 * tor_tls_handshake() calls this on its own; you only need to call this if
1366 * bufferevent is doing the handshake for you.
1369 tor_tls_finish_handshake(tor_tls_t *tls)
1371 int r = TOR_TLS_DONE;
1372 check_no_tls_errors();
1373 if (tls->isServer) {
1374 SSL_set_info_callback(tls->ssl, NULL);
1375 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
1376 SSL_clear_mode(tls->ssl, SSL_MODE_NO_AUTO_CHAIN);
1377 if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
1378 /* This check is redundant, but back when we did it in the callback,
1379 * we might have not been able to look up the tor_tls_t if the code
1380 * was buggy. Fixing that. */
1381 if (!tls->wasV2Handshake) {
1382 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
1383 " get set. Fixing that.");
1385 tls->wasV2Handshake = 1;
1386 log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
1387 " for renegotiation.");
1388 } else {
1389 tls->wasV2Handshake = 0;
1391 } else {
1392 /* Client-side */
1393 tls->wasV2Handshake = 1;
1394 /* XXXX this can move, probably? -NM */
1395 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
1396 tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
1397 r = TOR_TLS_ERROR_MISC;
1400 tls_log_errors(NULL, LOG_WARN, LD_NET, "finishing the handshake");
1401 return r;
1404 /** Return true iff this TLS connection is authenticated.
1407 tor_tls_peer_has_cert(tor_tls_t *tls)
1409 X509 *cert;
1410 cert = SSL_get_peer_certificate(tls->ssl);
1411 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
1412 if (!cert)
1413 return 0;
1414 X509_free(cert);
1415 return 1;
1418 /** Return a newly allocated copy of the peer certificate, or NULL if there
1419 * isn't one. */
1420 MOCK_IMPL(tor_x509_cert_t *,
1421 tor_tls_get_peer_cert,(tor_tls_t *tls))
1423 X509 *cert;
1424 cert = SSL_get_peer_certificate(tls->ssl);
1425 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
1426 if (!cert)
1427 return NULL;
1428 return tor_x509_cert_new(cert);
1431 /** Return a newly allocated copy of the cerficate we used on the connection,
1432 * or NULL if somehow we didn't use one. */
1433 MOCK_IMPL(tor_x509_cert_t *,
1434 tor_tls_get_own_cert,(tor_tls_t *tls))
1436 X509 *cert = SSL_get_certificate(tls->ssl);
1437 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE,
1438 "getting own-connection certificate");
1439 if (!cert)
1440 return NULL;
1441 /* Fun inconsistency: SSL_get_peer_certificate increments the reference
1442 * count, but SSL_get_certificate does not. */
1443 X509 *duplicate = X509_dup(cert);
1444 if (BUG(duplicate == NULL))
1445 return NULL;
1446 return tor_x509_cert_new(duplicate);
1449 /** Helper function: try to extract a link certificate and an identity
1450 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
1451 * *<b>id_cert_out</b> respectively. Log all messages at level
1452 * <b>severity</b>.
1454 * Note that a reference is added both of the returned certificates. */
1455 MOCK_IMPL(void,
1456 try_to_extract_certs_from_tls,(int severity, tor_tls_t *tls,
1457 X509 **cert_out, X509 **id_cert_out))
1459 X509 *cert = NULL, *id_cert = NULL;
1460 STACK_OF(X509) *chain = NULL;
1461 int num_in_chain, i;
1462 *cert_out = *id_cert_out = NULL;
1463 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1464 return;
1465 *cert_out = cert;
1466 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1467 return;
1468 num_in_chain = sk_X509_num(chain);
1469 /* 1 means we're receiving (server-side), and it's just the id_cert.
1470 * 2 means we're connecting (client-side), and it's both the link
1471 * cert and the id_cert.
1473 if (num_in_chain < 1) {
1474 log_fn(severity,LD_PROTOCOL,
1475 "Unexpected number of certificates in chain (%d)",
1476 num_in_chain);
1477 return;
1479 for (i=0; i<num_in_chain; ++i) {
1480 id_cert = sk_X509_value(chain, i);
1481 if (X509_cmp(id_cert, cert) != 0)
1482 break;
1484 *id_cert_out = id_cert ? X509_dup(id_cert) : NULL;
1487 /** Return the number of bytes available for reading from <b>tls</b>.
1490 tor_tls_get_pending_bytes(tor_tls_t *tls)
1492 tor_assert(tls);
1493 return SSL_pending(tls->ssl);
1496 /** If <b>tls</b> requires that the next write be of a particular size,
1497 * return that size. Otherwise, return 0. */
1498 size_t
1499 tor_tls_get_forced_write_size(tor_tls_t *tls)
1501 return tls->wantwrite_n;
1504 /** Sets n_read and n_written to the number of bytes read and written,
1505 * respectively, on the raw socket used by <b>tls</b> since the last time this
1506 * function was called on <b>tls</b>. */
1507 void
1508 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1510 BIO *wbio, *tmpbio;
1511 unsigned long r, w;
1512 r = (unsigned long) BIO_number_read(SSL_get_rbio(tls->ssl));
1513 /* We want the number of bytes actually for real written. Unfortunately,
1514 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1515 * which makes the answer turn out wrong. Let's cope with that. Note
1516 * that this approach will fail if we ever replace tls->ssl's BIOs with
1517 * buffering bios for reasons of our own. As an alternative, we could
1518 * save the original BIO for tls->ssl in the tor_tls_t structure, but
1519 * that would be tempting fate. */
1520 wbio = SSL_get_wbio(tls->ssl);
1521 #if OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)
1522 /* BIO structure is opaque as of OpenSSL 1.1.0-pre5-dev. Again, not
1523 * supposed to use this form of the version macro, but the OpenSSL developers
1524 * introduced major API changes in the pre-release stage.
1526 if (BIO_method_type(wbio) == BIO_TYPE_BUFFER &&
1527 (tmpbio = BIO_next(wbio)) != NULL)
1528 wbio = tmpbio;
1529 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)) */
1530 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1531 wbio = tmpbio;
1532 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5) */
1533 w = (unsigned long) BIO_number_written(wbio);
1535 /* We are ok with letting these unsigned ints go "negative" here:
1536 * If we wrapped around, this should still give us the right answer, unless
1537 * we wrapped around by more than ULONG_MAX since the last time we called
1538 * this function.
1540 *n_read = (size_t)(r - tls->last_read_count);
1541 *n_written = (size_t)(w - tls->last_write_count);
1542 if (*n_read > INT_MAX || *n_written > INT_MAX) {
1543 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1544 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1545 r, tls->last_read_count, w, tls->last_write_count);
1547 total_bytes_written_by_tls += *n_written;
1548 tls->last_read_count = r;
1549 tls->last_write_count = w;
1552 /** Return a ratio of the bytes that TLS has sent to the bytes that we've told
1553 * it to send. Used to track whether our TLS records are getting too tiny. */
1554 MOCK_IMPL(double,
1555 tls_get_write_overhead_ratio,(void))
1557 if (total_bytes_written_over_tls == 0)
1558 return 1.0;
1560 return ((double)total_bytes_written_by_tls) /
1561 ((double)total_bytes_written_over_tls);
1564 /** Implement check_no_tls_errors: If there are any pending OpenSSL
1565 * errors, log an error message. */
1566 void
1567 check_no_tls_errors_(const char *fname, int line)
1569 if (ERR_peek_error() == 0)
1570 return;
1571 log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1572 tor_fix_source_file(fname), line);
1573 tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
1576 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
1577 * TLS handshake. Output is undefined if the handshake isn't finished. */
1579 tor_tls_used_v1_handshake(tor_tls_t *tls)
1581 return ! tls->wasV2Handshake;
1584 /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
1585 * request it was waiting for. */
1587 tor_tls_server_got_renegotiate(tor_tls_t *tls)
1589 return tls->got_renegotiate;
1592 #ifndef HAVE_SSL_GET_CLIENT_RANDOM
1593 static size_t
1594 SSL_get_client_random(SSL *s, uint8_t *out, size_t len)
1596 if (len == 0)
1597 return SSL3_RANDOM_SIZE;
1598 tor_assert(len == SSL3_RANDOM_SIZE);
1599 tor_assert(s->s3);
1600 memcpy(out, s->s3->client_random, len);
1601 return len;
1603 #endif /* !defined(HAVE_SSL_GET_CLIENT_RANDOM) */
1605 #ifndef HAVE_SSL_GET_SERVER_RANDOM
1606 static size_t
1607 SSL_get_server_random(SSL *s, uint8_t *out, size_t len)
1609 if (len == 0)
1610 return SSL3_RANDOM_SIZE;
1611 tor_assert(len == SSL3_RANDOM_SIZE);
1612 tor_assert(s->s3);
1613 memcpy(out, s->s3->server_random, len);
1614 return len;
1616 #endif /* !defined(HAVE_SSL_GET_SERVER_RANDOM) */
1618 #ifndef HAVE_SSL_SESSION_GET_MASTER_KEY
1619 size_t
1620 SSL_SESSION_get_master_key(SSL_SESSION *s, uint8_t *out, size_t len)
1622 tor_assert(s);
1623 if (len == 0)
1624 return s->master_key_length;
1625 tor_assert(len == (size_t)s->master_key_length);
1626 tor_assert(out);
1627 memcpy(out, s->master_key, len);
1628 return len;
1630 #endif /* !defined(HAVE_SSL_SESSION_GET_MASTER_KEY) */
1632 /** Set the DIGEST256_LEN buffer at <b>secrets_out</b> to the value used in
1633 * the v3 handshake to prove that the client knows the TLS secrets for the
1634 * connection <b>tls</b>. Return 0 on success, -1 on failure.
1636 MOCK_IMPL(int,
1637 tor_tls_get_tlssecrets,(tor_tls_t *tls, uint8_t *secrets_out))
1639 #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
1640 uint8_t buf[128];
1641 size_t len;
1642 tor_assert(tls);
1644 SSL *const ssl = tls->ssl;
1645 SSL_SESSION *const session = SSL_get_session(ssl);
1647 tor_assert(ssl);
1648 tor_assert(session);
1650 const size_t server_random_len = SSL_get_server_random(ssl, NULL, 0);
1651 const size_t client_random_len = SSL_get_client_random(ssl, NULL, 0);
1652 const size_t master_key_len = SSL_SESSION_get_master_key(session, NULL, 0);
1654 if (BUG(! server_random_len)) {
1655 log_warn(LD_NET, "Missing server randomness after handshake "
1656 "using %s (cipher: %s, server: %s) from %s",
1657 SSL_get_version(ssl),
1658 SSL_get_cipher_name(ssl),
1659 tls->isServer ? "true" : "false",
1660 ADDR(tls));
1661 return -1;
1664 if (BUG(! client_random_len)) {
1665 log_warn(LD_NET, "Missing client randomness after handshake "
1666 "using %s (cipher: %s, server: %s) from %s",
1667 SSL_get_version(ssl),
1668 SSL_get_cipher_name(ssl),
1669 tls->isServer ? "true" : "false",
1670 ADDR(tls));
1671 return -1;
1674 if (BUG(! master_key_len)) {
1675 log_warn(LD_NET, "Missing master key after handshake "
1676 "using %s (cipher: %s, server: %s) from %s",
1677 SSL_get_version(ssl),
1678 SSL_get_cipher_name(ssl),
1679 tls->isServer ? "true" : "false",
1680 ADDR(tls));
1681 return -1;
1684 len = client_random_len + server_random_len + strlen(TLSSECRET_MAGIC) + 1;
1685 tor_assert(len <= sizeof(buf));
1688 size_t r = SSL_get_client_random(ssl, buf, client_random_len);
1689 tor_assert(r == client_random_len);
1693 size_t r = SSL_get_server_random(ssl,
1694 buf+client_random_len,
1695 server_random_len);
1696 tor_assert(r == server_random_len);
1699 uint8_t *master_key = tor_malloc_zero(master_key_len);
1701 size_t r = SSL_SESSION_get_master_key(session, master_key, master_key_len);
1702 tor_assert(r == master_key_len);
1705 uint8_t *nextbuf = buf + client_random_len + server_random_len;
1706 memcpy(nextbuf, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
1709 The value is an HMAC, using the TLS master key as the HMAC key, of
1710 client_random | server_random | TLSSECRET_MAGIC
1712 crypto_hmac_sha256((char*)secrets_out,
1713 (char*)master_key,
1714 master_key_len,
1715 (char*)buf, len);
1716 memwipe(buf, 0, sizeof(buf));
1717 memwipe(master_key, 0, master_key_len);
1718 tor_free(master_key);
1720 return 0;
1723 /** Using the RFC5705 key material exporting construction, and the
1724 * provided <b>context</b> (<b>context_len</b> bytes long) and
1725 * <b>label</b> (a NUL-terminated string), compute a 32-byte secret in
1726 * <b>secrets_out</b> that only the parties to this TLS session can
1727 * compute. Return 0 on success; -1 on failure; and -2 on failure
1728 * caused by OpenSSL bug 7712.
1730 MOCK_IMPL(int,
1731 tor_tls_export_key_material,(tor_tls_t *tls, uint8_t *secrets_out,
1732 const uint8_t *context,
1733 size_t context_len,
1734 const char *label))
1736 tor_assert(tls);
1737 tor_assert(tls->ssl);
1739 int r = SSL_export_keying_material(tls->ssl,
1740 secrets_out, DIGEST256_LEN,
1741 label, strlen(label),
1742 context, context_len, 1);
1744 if (r != 1) {
1745 int severity = openssl_bug_7712_is_present ? LOG_WARN : LOG_DEBUG;
1746 tls_log_errors(tls, severity, LD_NET, "exporting keying material");
1749 #ifdef TLS1_3_VERSION
1750 if (r != 1 &&
1751 strlen(label) > 12 &&
1752 SSL_version(tls->ssl) >= TLS1_3_VERSION) {
1754 if (! openssl_bug_7712_is_present) {
1755 /* We might have run into OpenSSL issue 7712, which caused OpenSSL
1756 * 1.1.1a to not handle long labels. Let's test to see if we have.
1758 r = SSL_export_keying_material(tls->ssl, secrets_out, DIGEST256_LEN,
1759 "short", 5, context, context_len, 1);
1760 if (r == 1) {
1761 /* A short label succeeds, but a long label fails. This was openssl
1762 * issue 7712. */
1763 openssl_bug_7712_is_present = 1;
1764 log_warn(LD_GENERAL, "Detected OpenSSL bug 7712: disabling TLS 1.3 on "
1765 "future connections.");
1768 if (openssl_bug_7712_is_present)
1769 return -2;
1770 else
1771 return -1;
1773 #endif /* defined(TLS1_3_VERSION) */
1775 return (r == 1) ? 0 : -1;
1778 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
1779 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1780 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1781 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1782 * buffer and *<b>wbuf_bytes</b> to the amount actually used.
1784 * Return 0 on success, -1 on failure.*/
1786 tor_tls_get_buffer_sizes(tor_tls_t *tls,
1787 size_t *rbuf_capacity, size_t *rbuf_bytes,
1788 size_t *wbuf_capacity, size_t *wbuf_bytes)
1790 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)
1791 (void)tls;
1792 (void)rbuf_capacity;
1793 (void)rbuf_bytes;
1794 (void)wbuf_capacity;
1795 (void)wbuf_bytes;
1797 return -1;
1798 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)) */
1799 if (tls->ssl->s3->rbuf.buf)
1800 *rbuf_capacity = tls->ssl->s3->rbuf.len;
1801 else
1802 *rbuf_capacity = 0;
1803 if (tls->ssl->s3->wbuf.buf)
1804 *wbuf_capacity = tls->ssl->s3->wbuf.len;
1805 else
1806 *wbuf_capacity = 0;
1807 *rbuf_bytes = tls->ssl->s3->rbuf.left;
1808 *wbuf_bytes = tls->ssl->s3->wbuf.left;
1809 return 0;
1810 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
1813 /** Check whether the ECC group requested is supported by the current OpenSSL
1814 * library instance. Return 1 if the group is supported, and 0 if not.
1817 evaluate_ecgroup_for_tls(const char *ecgroup)
1819 EC_KEY *ec_key;
1820 int nid;
1821 int ret;
1823 if (!ecgroup)
1824 nid = NID_tor_default_ecdhe_group;
1825 else if (!strcasecmp(ecgroup, "P256"))
1826 nid = NID_X9_62_prime256v1;
1827 else if (!strcasecmp(ecgroup, "P224"))
1828 nid = NID_secp224r1;
1829 else
1830 return 0;
1832 ec_key = EC_KEY_new_by_curve_name(nid);
1833 ret = (ec_key != NULL);
1834 EC_KEY_free(ec_key);
1836 return ret;