Merge branch 'maint-0.3.3' into maint-0.3.4
[tor.git] / src / common / tortls.c
blob653bd66de5d5918514234ea09378ebd3b8367a0c
1 /* Copyright (c) 2003, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2017, 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
22 #include <assert.h>
23 #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
24 #include <winsock2.h>
25 #include <ws2tcpip.h>
26 #endif
28 #include "crypto.h"
29 #include "crypto_rand.h"
30 #include "crypto_util.h"
31 #include "compat.h"
33 /* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
34 * srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
35 DISABLE_GCC_WARNING(redundant-decls)
37 #include <openssl/opensslv.h>
39 #ifdef OPENSSL_NO_EC
40 #error "We require OpenSSL with ECC support"
41 #endif
43 #include <openssl/ssl.h>
44 #include <openssl/ssl3.h>
45 #include <openssl/err.h>
46 #include <openssl/tls1.h>
47 #include <openssl/asn1.h>
48 #include <openssl/bio.h>
49 #include <openssl/bn.h>
50 #include <openssl/rsa.h>
52 ENABLE_GCC_WARNING(redundant-decls)
54 #define TORTLS_PRIVATE
55 #include "tortls.h"
56 #include "util.h"
57 #include "torlog.h"
58 #include "container.h"
59 #include <string.h>
61 #ifdef OPENSSL_1_1_API
62 #define X509_get_notBefore_const(cert) \
63 X509_get0_notBefore(cert)
64 #define X509_get_notAfter_const(cert) \
65 X509_get0_notAfter(cert)
66 #ifndef X509_get_notBefore
67 #define X509_get_notBefore(cert) \
68 X509_getm_notBefore(cert)
69 #endif
70 #ifndef X509_get_notAfter
71 #define X509_get_notAfter(cert) \
72 X509_getm_notAfter(cert)
73 #endif
74 #else /* ! OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
75 #define X509_get_notBefore_const(cert) \
76 ((const ASN1_TIME*) X509_get_notBefore((X509 *)cert))
77 #define X509_get_notAfter_const(cert) \
78 ((const ASN1_TIME*) X509_get_notAfter((X509 *)cert))
79 #endif
81 /* Copied from or.h */
82 #define LEGAL_NICKNAME_CHARACTERS \
83 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
85 /** How long do identity certificates live? (sec) */
86 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
88 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
90 #if OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f')
91 /* This is a version of OpenSSL before 1.0.0f. It does not have
92 * the CVE-2011-4576 fix, and as such it can't use RELEASE_BUFFERS and
93 * SSL3 safely at the same time.
95 #define DISABLE_SSL3_HANDSHAKE
96 #endif /* OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f') */
98 /* We redefine these so that we can run correctly even if the vendor gives us
99 * a version of OpenSSL that does not match its header files. (Apple: I am
100 * looking at you.)
102 #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
103 #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
104 #endif
105 #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
106 #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
107 #endif
109 /** Return values for tor_tls_classify_client_ciphers.
111 * @{
113 /** An error occurred when examining the client ciphers */
114 #define CIPHERS_ERR -1
115 /** The client cipher list indicates that a v1 handshake was in use. */
116 #define CIPHERS_V1 1
117 /** The client cipher list indicates that the client is using the v2 or the
118 * v3 handshake, but that it is (probably!) lying about what ciphers it
119 * supports */
120 #define CIPHERS_V2 2
121 /** The client cipher list indicates that the client is using the v2 or the
122 * v3 handshake, and that it is telling the truth about what ciphers it
123 * supports */
124 #define CIPHERS_UNRESTRICTED 3
125 /** @} */
127 /** The ex_data index in which we store a pointer to an SSL object's
128 * corresponding tor_tls_t object. */
129 STATIC int tor_tls_object_ex_data_index = -1;
131 /** Helper: Allocate tor_tls_object_ex_data_index. */
132 STATIC void
133 tor_tls_allocate_tor_tls_object_ex_data_index(void)
135 if (tor_tls_object_ex_data_index == -1) {
136 tor_tls_object_ex_data_index =
137 SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
138 tor_assert(tor_tls_object_ex_data_index != -1);
142 /** Helper: given a SSL* pointer, return the tor_tls_t object using that
143 * pointer. */
144 STATIC tor_tls_t *
145 tor_tls_get_by_ssl(const SSL *ssl)
147 tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
148 if (result)
149 tor_assert(result->magic == TOR_TLS_MAGIC);
150 return result;
153 static void tor_tls_context_decref(tor_tls_context_t *ctx);
154 static void tor_tls_context_incref(tor_tls_context_t *ctx);
156 static int check_cert_lifetime_internal(int severity, const X509 *cert,
157 time_t now,
158 int past_tolerance, int future_tolerance);
160 /** Global TLS contexts. We keep them here because nobody else needs
161 * to touch them.
163 * @{ */
164 STATIC tor_tls_context_t *server_tls_context = NULL;
165 STATIC tor_tls_context_t *client_tls_context = NULL;
166 /**@}*/
168 /** True iff tor_tls_init() has been called. */
169 static int tls_library_is_initialized = 0;
171 /* Module-internal error codes. */
172 #define TOR_TLS_SYSCALL_ (MIN_TOR_TLS_ERROR_VAL_ - 2)
173 #define TOR_TLS_ZERORETURN_ (MIN_TOR_TLS_ERROR_VAL_ - 1)
175 /** Write a description of the current state of <b>tls</b> into the
176 * <b>sz</b>-byte buffer at <b>buf</b>. */
177 void
178 tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
180 const char *ssl_state;
181 const char *tortls_state;
183 if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
184 strlcpy(buf, "(No SSL object)", sz);
185 return;
188 ssl_state = SSL_state_string_long(tls->ssl);
189 switch (tls->state) {
190 #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
191 CASE(HANDSHAKE);
192 CASE(OPEN);
193 CASE(GOTCLOSE);
194 CASE(SENTCLOSE);
195 CASE(CLOSED);
196 CASE(RENEGOTIATE);
197 #undef CASE
198 case TOR_TLS_ST_BUFFEREVENT:
199 tortls_state = "";
200 break;
201 default:
202 tortls_state = " in unknown TLS state";
203 break;
206 tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
209 /** Log a single error <b>err</b> as returned by ERR_get_error(), which was
210 * received while performing an operation <b>doing</b> on <b>tls</b>. Log
211 * the message at <b>severity</b>, in log domain <b>domain</b>. */
212 void
213 tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
214 int severity, int domain, const char *doing)
216 const char *state = NULL, *addr;
217 const char *msg, *lib, *func;
219 state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
221 addr = tls ? tls->address : NULL;
223 /* Some errors are known-benign, meaning they are the fault of the other
224 * side of the connection. The caller doesn't know this, so override the
225 * priority for those cases. */
226 switch (ERR_GET_REASON(err)) {
227 case SSL_R_HTTP_REQUEST:
228 case SSL_R_HTTPS_PROXY_REQUEST:
229 case SSL_R_RECORD_LENGTH_MISMATCH:
230 #ifndef OPENSSL_1_1_API
231 case SSL_R_RECORD_TOO_LARGE:
232 #endif
233 case SSL_R_UNKNOWN_PROTOCOL:
234 case SSL_R_UNSUPPORTED_PROTOCOL:
235 severity = LOG_INFO;
236 break;
237 default:
238 break;
241 msg = (const char*)ERR_reason_error_string(err);
242 lib = (const char*)ERR_lib_error_string(err);
243 func = (const char*)ERR_func_error_string(err);
244 if (!msg) msg = "(null)";
245 if (!lib) lib = "(null)";
246 if (!func) func = "(null)";
247 if (doing) {
248 tor_log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
249 doing, addr?" with ":"", addr?addr:"",
250 msg, lib, func, state);
251 } else {
252 tor_log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
253 addr?" with ":"", addr?addr:"",
254 msg, lib, func, state);
258 /** Log all pending tls errors at level <b>severity</b> in log domain
259 * <b>domain</b>. Use <b>doing</b> to describe our current activities.
261 STATIC void
262 tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
264 unsigned long err;
266 while ((err = ERR_get_error()) != 0) {
267 tor_tls_log_one_error(tls, err, severity, domain, doing);
271 /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
272 * code. */
273 STATIC int
274 tor_errno_to_tls_error(int e)
276 switch (e) {
277 case SOCK_ERRNO(ECONNRESET): // most common
278 return TOR_TLS_ERROR_CONNRESET;
279 case SOCK_ERRNO(ETIMEDOUT):
280 return TOR_TLS_ERROR_TIMEOUT;
281 case SOCK_ERRNO(EHOSTUNREACH):
282 case SOCK_ERRNO(ENETUNREACH):
283 return TOR_TLS_ERROR_NO_ROUTE;
284 case SOCK_ERRNO(ECONNREFUSED):
285 return TOR_TLS_ERROR_CONNREFUSED; // least common
286 default:
287 return TOR_TLS_ERROR_MISC;
291 /** Given a TOR_TLS_* error code, return a string equivalent. */
292 const char *
293 tor_tls_err_to_string(int err)
295 if (err >= 0)
296 return "[Not an error.]";
297 switch (err) {
298 case TOR_TLS_ERROR_MISC: return "misc error";
299 case TOR_TLS_ERROR_IO: return "unexpected close";
300 case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
301 case TOR_TLS_ERROR_CONNRESET: return "connection reset";
302 case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
303 case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
304 case TOR_TLS_CLOSE: return "closed";
305 case TOR_TLS_WANTREAD: return "want to read";
306 case TOR_TLS_WANTWRITE: return "want to write";
307 default: return "(unknown error code)";
311 #define CATCH_SYSCALL 1
312 #define CATCH_ZERO 2
314 /** Given a TLS object and the result of an SSL_* call, use
315 * SSL_get_error to determine whether an error has occurred, and if so
316 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
317 * If extra&CATCH_SYSCALL is true, return TOR_TLS_SYSCALL_ instead of
318 * reporting syscall errors. If extra&CATCH_ZERO is true, return
319 * TOR_TLS_ZERORETURN_ instead of reporting zero-return errors.
321 * If an error has occurred, log it at level <b>severity</b> and describe the
322 * current action as <b>doing</b>.
324 STATIC int
325 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
326 const char *doing, int severity, int domain)
328 int err = SSL_get_error(tls->ssl, r);
329 int tor_error = TOR_TLS_ERROR_MISC;
330 switch (err) {
331 case SSL_ERROR_NONE:
332 return TOR_TLS_DONE;
333 case SSL_ERROR_WANT_READ:
334 return TOR_TLS_WANTREAD;
335 case SSL_ERROR_WANT_WRITE:
336 return TOR_TLS_WANTWRITE;
337 case SSL_ERROR_SYSCALL:
338 if (extra&CATCH_SYSCALL)
339 return TOR_TLS_SYSCALL_;
340 if (r == 0) {
341 tor_log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
342 doing, SSL_state_string_long(tls->ssl));
343 tor_error = TOR_TLS_ERROR_IO;
344 } else {
345 int e = tor_socket_errno(tls->socket);
346 tor_log(severity, LD_NET,
347 "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
348 doing, e, tor_socket_strerror(e),
349 SSL_state_string_long(tls->ssl));
350 tor_error = tor_errno_to_tls_error(e);
352 tls_log_errors(tls, severity, domain, doing);
353 return tor_error;
354 case SSL_ERROR_ZERO_RETURN:
355 if (extra&CATCH_ZERO)
356 return TOR_TLS_ZERORETURN_;
357 tor_log(severity, LD_NET, "TLS connection closed while %s in state %s",
358 doing, SSL_state_string_long(tls->ssl));
359 tls_log_errors(tls, severity, domain, doing);
360 return TOR_TLS_CLOSE;
361 default:
362 tls_log_errors(tls, severity, domain, doing);
363 return TOR_TLS_ERROR_MISC;
367 /** Initialize OpenSSL, unless it has already been initialized.
369 static void
370 tor_tls_init(void)
372 check_no_tls_errors();
374 if (!tls_library_is_initialized) {
375 #ifdef OPENSSL_1_1_API
376 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
377 #else
378 SSL_library_init();
379 SSL_load_error_strings();
380 #endif
382 #if (SIZEOF_VOID_P >= 8 && \
383 OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,1))
384 long version = OpenSSL_version_num();
386 /* LCOV_EXCL_START : we can't test these lines on the same machine */
387 if (version >= OPENSSL_V_SERIES(1,0,1)) {
388 /* Warn if we could *almost* be running with much faster ECDH.
389 If we're built for a 64-bit target, using OpenSSL 1.0.1, but we
390 don't have one of the built-in __uint128-based speedups, we are
391 just one build operation away from an accelerated handshake.
393 (We could be looking at OPENSSL_NO_EC_NISTP_64_GCC_128 instead of
394 doing this test, but that gives compile-time options, not runtime
395 behavior.)
397 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
398 const EC_GROUP *g = key ? EC_KEY_get0_group(key) : NULL;
399 const EC_METHOD *m = g ? EC_GROUP_method_of(g) : NULL;
400 const int warn = (m == EC_GFp_simple_method() ||
401 m == EC_GFp_mont_method() ||
402 m == EC_GFp_nist_method());
403 EC_KEY_free(key);
405 if (warn)
406 log_notice(LD_GENERAL, "We were built to run on a 64-bit CPU, with "
407 "OpenSSL 1.0.1 or later, but with a version of OpenSSL "
408 "that apparently lacks accelerated support for the NIST "
409 "P-224 and P-256 groups. Building openssl with such "
410 "support (using the enable-ec_nistp_64_gcc_128 option "
411 "when configuring it) would make ECDH much faster.");
413 /* LCOV_EXCL_STOP */
414 #endif /* (SIZEOF_VOID_P >= 8 && ... */
416 tor_tls_allocate_tor_tls_object_ex_data_index();
418 tls_library_is_initialized = 1;
422 /** Free all global TLS structures. */
423 void
424 tor_tls_free_all(void)
426 check_no_tls_errors();
428 if (server_tls_context) {
429 tor_tls_context_t *ctx = server_tls_context;
430 server_tls_context = NULL;
431 tor_tls_context_decref(ctx);
433 if (client_tls_context) {
434 tor_tls_context_t *ctx = client_tls_context;
435 client_tls_context = NULL;
436 tor_tls_context_decref(ctx);
440 /** We need to give OpenSSL a callback to verify certificates. This is
441 * it: We always accept peer certs and complete the handshake. We
442 * don't validate them until later.
444 STATIC int
445 always_accept_verify_cb(int preverify_ok,
446 X509_STORE_CTX *x509_ctx)
448 (void) preverify_ok;
449 (void) x509_ctx;
450 return 1;
453 /** Return a newly allocated X509 name with commonName <b>cname</b>. */
454 static X509_NAME *
455 tor_x509_name_new(const char *cname)
457 int nid;
458 X509_NAME *name;
459 /* LCOV_EXCL_BR_START : these branches will only fail on OOM errors */
460 if (!(name = X509_NAME_new()))
461 return NULL;
462 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
463 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
464 (unsigned char*)cname, -1, -1, 0)))
465 goto error;
466 /* LCOV_EXCL_BR_STOP */
467 return name;
469 /* LCOV_EXCL_START : these lines will only execute on out of memory errors*/
470 error:
471 X509_NAME_free(name);
472 return NULL;
473 /* LCOV_EXCL_STOP */
476 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
477 * signed by the private key <b>rsa_sign</b>. The commonName of the
478 * certificate will be <b>cname</b>; the commonName of the issuer will be
479 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b>
480 * seconds, starting from some time in the past.
482 * Return a certificate on success, NULL on failure.
484 MOCK_IMPL(STATIC X509 *,
485 tor_tls_create_certificate,(crypto_pk_t *rsa,
486 crypto_pk_t *rsa_sign,
487 const char *cname,
488 const char *cname_sign,
489 unsigned int cert_lifetime))
491 /* OpenSSL generates self-signed certificates with random 64-bit serial
492 * numbers, so let's do that too. */
493 #define SERIAL_NUMBER_SIZE 8
495 time_t start_time, end_time;
496 BIGNUM *serial_number = NULL;
497 unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
498 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
499 X509 *x509 = NULL;
500 X509_NAME *name = NULL, *name_issuer=NULL;
502 tor_tls_init();
504 /* Make sure we're part-way through the certificate lifetime, rather
505 * than having it start right now. Don't choose quite uniformly, since
506 * then we might pick a time where we're about to expire. Lastly, be
507 * sure to start on a day boundary. */
508 time_t now = time(NULL);
509 /* Our certificate lifetime will be cert_lifetime no matter what, but if we
510 * start cert_lifetime in the past, we'll have 0 real lifetime. instead we
511 * start up to (cert_lifetime - min_real_lifetime - start_granularity) in
512 * the past. */
513 const time_t min_real_lifetime = 24*3600;
514 const time_t start_granularity = 24*3600;
515 time_t earliest_start_time;
516 /* Don't actually start in the future! */
517 if (cert_lifetime <= min_real_lifetime + start_granularity) {
518 earliest_start_time = now - 1;
519 } else {
520 earliest_start_time = now + min_real_lifetime + start_granularity
521 - cert_lifetime;
523 start_time = crypto_rand_time_range(earliest_start_time, now);
524 /* Round the start time back to the start of a day. */
525 start_time -= start_time % start_granularity;
527 end_time = start_time + cert_lifetime;
529 tor_assert(rsa);
530 tor_assert(cname);
531 tor_assert(rsa_sign);
532 tor_assert(cname_sign);
533 if (!(sign_pkey = crypto_pk_get_evp_pkey_(rsa_sign,1)))
534 goto error;
535 if (!(pkey = crypto_pk_get_evp_pkey_(rsa,0)))
536 goto error;
537 if (!(x509 = X509_new()))
538 goto error;
539 if (!(X509_set_version(x509, 2)))
540 goto error;
542 { /* our serial number is 8 random bytes. */
543 crypto_rand((char *)serial_tmp, sizeof(serial_tmp));
544 if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
545 goto error;
546 if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
547 goto error;
550 if (!(name = tor_x509_name_new(cname)))
551 goto error;
552 if (!(X509_set_subject_name(x509, name)))
553 goto error;
554 if (!(name_issuer = tor_x509_name_new(cname_sign)))
555 goto error;
556 if (!(X509_set_issuer_name(x509, name_issuer)))
557 goto error;
559 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
560 goto error;
561 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
562 goto error;
563 if (!X509_set_pubkey(x509, pkey))
564 goto error;
566 if (!X509_sign(x509, sign_pkey, EVP_sha256()))
567 goto error;
569 goto done;
570 error:
571 if (x509) {
572 X509_free(x509);
573 x509 = NULL;
575 done:
576 tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
577 if (sign_pkey)
578 EVP_PKEY_free(sign_pkey);
579 if (pkey)
580 EVP_PKEY_free(pkey);
581 if (serial_number)
582 BN_clear_free(serial_number);
583 if (name)
584 X509_NAME_free(name);
585 if (name_issuer)
586 X509_NAME_free(name_issuer);
587 return x509;
589 #undef SERIAL_NUMBER_SIZE
592 /** List of ciphers that servers should select from when the client might be
593 * claiming extra unsupported ciphers in order to avoid fingerprinting. */
594 static const char SERVER_CIPHER_LIST[] =
595 #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
596 /* This one can never actually get selected, since if the client lists it,
597 * we will assume that the client is honest, and not use this list.
598 * Nonetheless we list it if it's available, so that the server doesn't
599 * conclude that it has no valid ciphers if it's running with TLS1.3.
601 TLS1_3_TXT_AES_128_GCM_SHA256 ":"
602 #endif
603 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
604 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA;
606 /** List of ciphers that servers should select from when we actually have
607 * our choice of what cipher to use. */
608 static const char UNRESTRICTED_SERVER_CIPHER_LIST[] =
609 /* Here are the TLS 1.3 ciphers we like, in the order we prefer. */
610 #ifdef TLS1_3_TXT_AES_256_GCM_SHA384
611 TLS1_3_TXT_AES_256_GCM_SHA384 ":"
612 #endif
613 #ifdef TLS1_3_TXT_CHACHA20_POLY1305_SHA256
614 TLS1_3_TXT_CHACHA20_POLY1305_SHA256 ":"
615 #endif
616 #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
617 TLS1_3_TXT_AES_128_GCM_SHA256 ":"
618 #endif
619 #ifdef TLS1_3_TXT_AES_128_CCM_SHA256
620 TLS1_3_TXT_AES_128_CCM_SHA256 ":"
621 #endif
623 /* This list is autogenerated with the gen_server_ciphers.py script;
624 * don't hand-edit it. */
625 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
626 TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
627 #endif
628 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
629 TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
630 #endif
631 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384
632 TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 ":"
633 #endif
634 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
635 TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
636 #endif
637 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA
638 TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
639 #endif
640 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
641 TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
642 #endif
643 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384
644 TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 ":"
645 #endif
646 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256
647 TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 ":"
648 #endif
649 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_CCM
650 TLS1_TXT_DHE_RSA_WITH_AES_256_CCM ":"
651 #endif
652 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_CCM
653 TLS1_TXT_DHE_RSA_WITH_AES_128_CCM ":"
654 #endif
655 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256
656 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 ":"
657 #endif
658 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256
659 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 ":"
660 #endif
661 /* Required */
662 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
663 /* Required */
664 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"
665 #ifdef TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305
666 TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 ":"
667 #endif
668 #ifdef TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
669 TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
670 #endif
673 /* Note: to set up your own private testing network with link crypto
674 * disabled, set your Tors' cipher list to
675 * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
676 * with any of the "real" Tors, though. */
678 #define CIPHER(id, name) name ":"
679 #define XCIPHER(id, name)
680 /** List of ciphers that clients should advertise, omitting items that
681 * our OpenSSL doesn't know about. */
682 static const char CLIENT_CIPHER_LIST[] =
683 #include "ciphers.inc"
684 /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
685 * of any cipher we say. */
686 "!SSLv2"
688 #undef CIPHER
689 #undef XCIPHER
691 /** Free all storage held in <b>cert</b> */
692 void
693 tor_x509_cert_free_(tor_x509_cert_t *cert)
695 if (! cert)
696 return;
697 if (cert->cert)
698 X509_free(cert->cert);
699 tor_free(cert->encoded);
700 memwipe(cert, 0x03, sizeof(*cert));
701 /* LCOV_EXCL_BR_START since cert will never be NULL here */
702 tor_free(cert);
703 /* LCOV_EXCL_BR_STOP */
707 * Allocate a new tor_x509_cert_t to hold the certificate "x509_cert".
709 * Steals a reference to x509_cert.
711 MOCK_IMPL(STATIC tor_x509_cert_t *,
712 tor_x509_cert_new,(X509 *x509_cert))
714 tor_x509_cert_t *cert;
715 EVP_PKEY *pkey;
716 RSA *rsa;
717 int length;
718 unsigned char *buf = NULL;
720 if (!x509_cert)
721 return NULL;
723 length = i2d_X509(x509_cert, &buf);
724 cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
725 if (length <= 0 || buf == NULL) {
726 goto err;
728 cert->encoded_len = (size_t) length;
729 cert->encoded = tor_malloc(length);
730 memcpy(cert->encoded, buf, length);
731 OPENSSL_free(buf);
733 cert->cert = x509_cert;
735 crypto_common_digests(&cert->cert_digests,
736 (char*)cert->encoded, cert->encoded_len);
738 if ((pkey = X509_get_pubkey(x509_cert)) &&
739 (rsa = EVP_PKEY_get1_RSA(pkey))) {
740 crypto_pk_t *pk = crypto_new_pk_from_rsa_(rsa);
741 if (crypto_pk_get_common_digests(pk, &cert->pkey_digests) < 0) {
742 crypto_pk_free(pk);
743 EVP_PKEY_free(pkey);
744 goto err;
747 cert->pkey_digests_set = 1;
748 crypto_pk_free(pk);
749 EVP_PKEY_free(pkey);
752 return cert;
753 err:
754 /* LCOV_EXCL_START for the same reason as the exclusion above */
755 tor_free(cert);
756 log_err(LD_CRYPTO, "Couldn't wrap encoded X509 certificate.");
757 X509_free(x509_cert);
758 return NULL;
759 /* LCOV_EXCL_STOP */
762 /** Return a new copy of <b>cert</b>. */
763 tor_x509_cert_t *
764 tor_x509_cert_dup(const tor_x509_cert_t *cert)
766 tor_assert(cert);
767 X509 *x509 = cert->cert;
768 return tor_x509_cert_new(X509_dup(x509));
771 /** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
772 * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on
773 * success and NULL on failure. */
774 tor_x509_cert_t *
775 tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
777 X509 *x509;
778 const unsigned char *cp = (const unsigned char *)certificate;
779 tor_x509_cert_t *newcert;
780 tor_assert(certificate);
781 check_no_tls_errors();
783 if (certificate_len > INT_MAX)
784 goto err;
786 x509 = d2i_X509(NULL, &cp, (int)certificate_len);
788 if (!x509)
789 goto err; /* Couldn't decode */
790 if (cp - certificate != (int)certificate_len) {
791 X509_free(x509);
792 goto err; /* Didn't use all the bytes */
794 newcert = tor_x509_cert_new(x509);
795 if (!newcert) {
796 goto err;
798 if (newcert->encoded_len != certificate_len ||
799 fast_memneq(newcert->encoded, certificate, certificate_len)) {
800 /* Cert wasn't in DER */
801 tor_x509_cert_free(newcert);
802 goto err;
804 return newcert;
805 err:
806 tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "decoding a certificate");
807 return NULL;
810 /** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
811 * representation and length, respectively. */
812 void
813 tor_x509_cert_get_der(const tor_x509_cert_t *cert,
814 const uint8_t **encoded_out, size_t *size_out)
816 tor_assert(cert);
817 tor_assert(encoded_out);
818 tor_assert(size_out);
819 *encoded_out = cert->encoded;
820 *size_out = cert->encoded_len;
823 /** Return a set of digests for the public key in <b>cert</b>, or NULL if this
824 * cert's public key is not one we know how to take the digest of. */
825 const common_digests_t *
826 tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert)
828 if (cert->pkey_digests_set)
829 return &cert->pkey_digests;
830 else
831 return NULL;
834 /** Return a set of digests for the public key in <b>cert</b>. */
835 const common_digests_t *
836 tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
838 return &cert->cert_digests;
841 /** Remove a reference to <b>ctx</b>, and free it if it has no more
842 * references. */
843 static void
844 tor_tls_context_decref(tor_tls_context_t *ctx)
846 tor_assert(ctx);
847 if (--ctx->refcnt == 0) {
848 SSL_CTX_free(ctx->ctx);
849 tor_x509_cert_free(ctx->my_link_cert);
850 tor_x509_cert_free(ctx->my_id_cert);
851 tor_x509_cert_free(ctx->my_auth_cert);
852 crypto_pk_free(ctx->link_key);
853 crypto_pk_free(ctx->auth_key);
854 /* LCOV_EXCL_BR_START since ctx will never be NULL here */
855 tor_free(ctx);
856 /* LCOV_EXCL_BR_STOP */
860 /** Set *<b>link_cert_out</b> and *<b>id_cert_out</b> to the link certificate
861 * and ID certificate that we're currently using for our V3 in-protocol
862 * handshake's certificate chain. If <b>server</b> is true, provide the certs
863 * that we use in server mode (auth, ID); otherwise, provide the certs that we
864 * use in client mode. (link, ID) */
866 tor_tls_get_my_certs(int server,
867 const tor_x509_cert_t **link_cert_out,
868 const tor_x509_cert_t **id_cert_out)
870 tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
871 if (! ctx)
872 return -1;
873 if (link_cert_out)
874 *link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
875 if (id_cert_out)
876 *id_cert_out = ctx->my_id_cert;
877 return 0;
881 * Return the authentication key that we use to authenticate ourselves as a
882 * client in the V3 in-protocol handshake.
884 crypto_pk_t *
885 tor_tls_get_my_client_auth_key(void)
887 if (! client_tls_context)
888 return NULL;
889 return client_tls_context->auth_key;
893 * Return a newly allocated copy of the public key that a certificate
894 * certifies. Watch out! This returns NULL if the cert's key is not RSA.
896 crypto_pk_t *
897 tor_tls_cert_get_key(tor_x509_cert_t *cert)
899 crypto_pk_t *result = NULL;
900 EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
901 RSA *rsa;
902 if (!pkey)
903 return NULL;
904 rsa = EVP_PKEY_get1_RSA(pkey);
905 if (!rsa) {
906 EVP_PKEY_free(pkey);
907 return NULL;
909 result = crypto_new_pk_from_rsa_(rsa);
910 EVP_PKEY_free(pkey);
911 return result;
914 /** Return true iff the other side of <b>tls</b> has authenticated to us, and
915 * the key certified in <b>cert</b> is the same as the key they used to do it.
917 MOCK_IMPL(int,
918 tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
920 tor_x509_cert_t *peer = tor_tls_get_peer_cert((tor_tls_t *)tls);
921 if (!peer)
922 return 0;
924 X509 *peercert = peer->cert;
925 EVP_PKEY *link_key = NULL, *cert_key = NULL;
926 int result;
928 link_key = X509_get_pubkey(peercert);
929 cert_key = X509_get_pubkey(cert->cert);
931 result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
933 tor_x509_cert_free(peer);
934 if (link_key)
935 EVP_PKEY_free(link_key);
936 if (cert_key)
937 EVP_PKEY_free(cert_key);
939 return result;
942 /** Check whether <b>cert</b> is well-formed, currently live, and correctly
943 * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
944 * make sure that it has an RSA key with 1024 bits; otherwise, just check that
945 * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
946 * we couldn't check it. */
948 tor_tls_cert_is_valid(int severity,
949 const tor_x509_cert_t *cert,
950 const tor_x509_cert_t *signing_cert,
951 time_t now,
952 int check_rsa_1024)
954 check_no_tls_errors();
955 EVP_PKEY *cert_key;
956 int r, key_ok = 0;
958 if (!signing_cert || !cert)
959 goto bad;
961 EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
962 if (!signing_key)
963 goto bad;
964 r = X509_verify(cert->cert, signing_key);
965 EVP_PKEY_free(signing_key);
966 if (r <= 0)
967 goto bad;
969 /* okay, the signature checked out right. Now let's check the check the
970 * lifetime. */
971 if (check_cert_lifetime_internal(severity, cert->cert, now,
972 48*60*60, 30*24*60*60) < 0)
973 goto bad;
975 cert_key = X509_get_pubkey(cert->cert);
976 if (check_rsa_1024 && cert_key) {
977 RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
978 #ifdef OPENSSL_1_1_API
979 if (rsa && RSA_bits(rsa) == 1024)
980 #else
981 if (rsa && BN_num_bits(rsa->n) == 1024)
982 #endif
983 key_ok = 1;
984 if (rsa)
985 RSA_free(rsa);
986 } else if (cert_key) {
987 int min_bits = 1024;
988 #ifdef EVP_PKEY_EC
989 if (EVP_PKEY_base_id(cert_key) == EVP_PKEY_EC)
990 min_bits = 128;
991 #endif
992 if (EVP_PKEY_bits(cert_key) >= min_bits)
993 key_ok = 1;
995 EVP_PKEY_free(cert_key);
996 if (!key_ok)
997 goto bad;
999 /* XXXX compare DNs or anything? */
1001 return 1;
1002 bad:
1003 tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "checking a certificate");
1004 return 0;
1007 /** Increase the reference count of <b>ctx</b>. */
1008 static void
1009 tor_tls_context_incref(tor_tls_context_t *ctx)
1011 ++ctx->refcnt;
1014 /** Create new global client and server TLS contexts.
1016 * If <b>server_identity</b> is NULL, this will not generate a server
1017 * TLS context. If TOR_TLS_CTX_IS_PUBLIC_SERVER is set in <b>flags</b>, use
1018 * the same TLS context for incoming and outgoing connections, and
1019 * ignore <b>client_identity</b>. If one of TOR_TLS_CTX_USE_ECDHE_P{224,256}
1020 * is set in <b>flags</b>, use that ECDHE group if possible; otherwise use
1021 * the default ECDHE group. */
1023 tor_tls_context_init(unsigned flags,
1024 crypto_pk_t *client_identity,
1025 crypto_pk_t *server_identity,
1026 unsigned int key_lifetime)
1028 int rv1 = 0;
1029 int rv2 = 0;
1030 const int is_public_server = flags & TOR_TLS_CTX_IS_PUBLIC_SERVER;
1031 check_no_tls_errors();
1033 if (is_public_server) {
1034 tor_tls_context_t *new_ctx;
1035 tor_tls_context_t *old_ctx;
1037 tor_assert(server_identity != NULL);
1039 rv1 = tor_tls_context_init_one(&server_tls_context,
1040 server_identity,
1041 key_lifetime, flags, 0);
1043 if (rv1 >= 0) {
1044 new_ctx = server_tls_context;
1045 tor_tls_context_incref(new_ctx);
1046 old_ctx = client_tls_context;
1047 client_tls_context = new_ctx;
1049 if (old_ctx != NULL) {
1050 tor_tls_context_decref(old_ctx);
1053 } else {
1054 if (server_identity != NULL) {
1055 rv1 = tor_tls_context_init_one(&server_tls_context,
1056 server_identity,
1057 key_lifetime,
1058 flags,
1060 } else {
1061 tor_tls_context_t *old_ctx = server_tls_context;
1062 server_tls_context = NULL;
1064 if (old_ctx != NULL) {
1065 tor_tls_context_decref(old_ctx);
1069 rv2 = tor_tls_context_init_one(&client_tls_context,
1070 client_identity,
1071 key_lifetime,
1072 flags,
1076 tls_log_errors(NULL, LOG_WARN, LD_CRYPTO, "constructing a TLS context");
1077 return MIN(rv1, rv2);
1080 /** Create a new global TLS context.
1082 * You can call this function multiple times. Each time you call it,
1083 * it generates new certificates; all new connections will use
1084 * the new SSL context.
1086 STATIC int
1087 tor_tls_context_init_one(tor_tls_context_t **ppcontext,
1088 crypto_pk_t *identity,
1089 unsigned int key_lifetime,
1090 unsigned int flags,
1091 int is_client)
1093 tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
1094 key_lifetime,
1095 flags,
1096 is_client);
1097 tor_tls_context_t *old_ctx = *ppcontext;
1099 if (new_ctx != NULL) {
1100 *ppcontext = new_ctx;
1102 /* Free the old context if one existed. */
1103 if (old_ctx != NULL) {
1104 /* This is safe even if there are open connections: we reference-
1105 * count tor_tls_context_t objects. */
1106 tor_tls_context_decref(old_ctx);
1110 return ((new_ctx != NULL) ? 0 : -1);
1113 /** The group we should use for ecdhe when none was selected. */
1114 #define NID_tor_default_ecdhe_group NID_X9_62_prime256v1
1116 #define RSA_LINK_KEY_BITS 2048
1118 /** Create a new TLS context for use with Tor TLS handshakes.
1119 * <b>identity</b> should be set to the identity key used to sign the
1120 * certificate.
1122 STATIC tor_tls_context_t *
1123 tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
1124 unsigned flags, int is_client)
1126 crypto_pk_t *rsa = NULL, *rsa_auth = NULL;
1127 EVP_PKEY *pkey = NULL;
1128 tor_tls_context_t *result = NULL;
1129 X509 *cert = NULL, *idcert = NULL, *authcert = NULL;
1130 char *nickname = NULL, *nn2 = NULL;
1132 tor_tls_init();
1133 nickname = crypto_random_hostname(8, 20, "www.", ".net");
1134 #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
1135 nn2 = crypto_random_hostname(8, 20, "www.", ".net");
1136 #else
1137 nn2 = crypto_random_hostname(8, 20, "www.", ".com");
1138 #endif
1140 /* Generate short-term RSA key for use with TLS. */
1141 if (!(rsa = crypto_pk_new()))
1142 goto error;
1143 if (crypto_pk_generate_key_with_bits(rsa, RSA_LINK_KEY_BITS)<0)
1144 goto error;
1145 if (!is_client) {
1146 /* Generate short-term RSA key for use in the in-protocol ("v3")
1147 * authentication handshake. */
1148 if (!(rsa_auth = crypto_pk_new()))
1149 goto error;
1150 if (crypto_pk_generate_key(rsa_auth)<0)
1151 goto error;
1152 /* Create a link certificate signed by identity key. */
1153 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
1154 key_lifetime);
1155 /* Create self-signed certificate for identity key. */
1156 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
1157 IDENTITY_CERT_LIFETIME);
1158 /* Create an authentication certificate signed by identity key. */
1159 authcert = tor_tls_create_certificate(rsa_auth, identity, nickname, nn2,
1160 key_lifetime);
1161 if (!cert || !idcert || !authcert) {
1162 log_warn(LD_CRYPTO, "Error creating certificate");
1163 goto error;
1167 result = tor_malloc_zero(sizeof(tor_tls_context_t));
1168 result->refcnt = 1;
1169 if (!is_client) {
1170 result->my_link_cert = tor_x509_cert_new(X509_dup(cert));
1171 result->my_id_cert = tor_x509_cert_new(X509_dup(idcert));
1172 result->my_auth_cert = tor_x509_cert_new(X509_dup(authcert));
1173 if (!result->my_link_cert || !result->my_id_cert || !result->my_auth_cert)
1174 goto error;
1175 result->link_key = crypto_pk_dup_key(rsa);
1176 result->auth_key = crypto_pk_dup_key(rsa_auth);
1179 #if 0
1180 /* Tell OpenSSL to only use TLS1. This may have subtly different results
1181 * from SSLv23_method() with SSLv2 and SSLv3 disabled, so we need to do some
1182 * investigation before we consider adjusting it. It should be compatible
1183 * with existing Tors. */
1184 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
1185 goto error;
1186 #endif /* 0 */
1188 /* Tell OpenSSL to use TLS 1.0 or later but not SSL2 or SSL3. */
1189 #ifdef HAVE_TLS_METHOD
1190 if (!(result->ctx = SSL_CTX_new(TLS_method())))
1191 goto error;
1192 #else
1193 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
1194 goto error;
1195 #endif /* defined(HAVE_TLS_METHOD) */
1197 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
1198 /* Level 1 re-enables RSA1024 and DH1024 for compatibility with old tors */
1199 SSL_CTX_set_security_level(result->ctx, 1);
1200 #endif
1202 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
1203 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
1205 /* Prefer the server's ordering of ciphers: the client's ordering has
1206 * historically been chosen for fingerprinting resistance. */
1207 SSL_CTX_set_options(result->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1209 /* Disable TLS tickets if they're supported. We never want to use them;
1210 * using them can make our perfect forward secrecy a little worse, *and*
1211 * create an opportunity to fingerprint us (since it's unusual to use them
1212 * with TLS sessions turned off).
1214 * In 0.2.4, clients advertise support for them though, to avoid a TLS
1215 * distinguishability vector. This can give us worse PFS, though, if we
1216 * get a server that doesn't set SSL_OP_NO_TICKET. With luck, there will
1217 * be few such servers by the time 0.2.4 is more stable.
1219 #ifdef SSL_OP_NO_TICKET
1220 if (! is_client) {
1221 SSL_CTX_set_options(result->ctx, SSL_OP_NO_TICKET);
1223 #endif
1225 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
1226 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_ECDH_USE);
1228 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1229 SSL_CTX_set_options(result->ctx,
1230 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
1231 #endif
1232 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1233 * as authenticating any earlier-received data.
1236 SSL_CTX_set_options(result->ctx,
1237 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1240 /* Don't actually allow compression; it uses RAM and time, it makes TLS
1241 * vulnerable to CRIME-style attacks, and most of the data we transmit over
1242 * TLS is encrypted (and therefore uncompressible) anyway. */
1243 #ifdef SSL_OP_NO_COMPRESSION
1244 SSL_CTX_set_options(result->ctx, SSL_OP_NO_COMPRESSION);
1245 #endif
1246 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0)
1247 #ifndef OPENSSL_NO_COMP
1248 if (result->ctx->comp_methods)
1249 result->ctx->comp_methods = NULL;
1250 #endif
1251 #endif /* OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0) */
1253 #ifdef SSL_MODE_RELEASE_BUFFERS
1254 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
1255 #endif
1256 if (! is_client) {
1257 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
1258 goto error;
1259 X509_free(cert); /* We just added a reference to cert. */
1260 cert=NULL;
1261 if (idcert) {
1262 X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
1263 tor_assert(s);
1264 X509_STORE_add_cert(s, idcert);
1265 X509_free(idcert); /* The context now owns the reference to idcert */
1266 idcert = NULL;
1269 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
1270 if (!is_client) {
1271 tor_assert(rsa);
1272 if (!(pkey = crypto_pk_get_evp_pkey_(rsa,1)))
1273 goto error;
1274 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
1275 goto error;
1276 EVP_PKEY_free(pkey);
1277 pkey = NULL;
1278 if (!SSL_CTX_check_private_key(result->ctx))
1279 goto error;
1282 crypto_dh_t *dh = crypto_dh_new(DH_TYPE_TLS);
1283 tor_assert(dh);
1284 SSL_CTX_set_tmp_dh(result->ctx, crypto_dh_get_dh_(dh));
1285 crypto_dh_free(dh);
1287 /* We check for this function in two ways, since it might be either a symbol
1288 * or a macro. */
1289 #if defined(SSL_CTX_set1_groups_list) || defined(HAVE_SSL_CTX_SET1_GROUPS_LIST)
1291 const char *list;
1292 if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
1293 list = "P-224:P-256";
1294 else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
1295 list = "P-256:P-224";
1296 else
1297 list = "P-256:P-224";
1298 int r = SSL_CTX_set1_groups_list(result->ctx, list);
1299 if (r < 0)
1300 goto error;
1302 #else
1303 if (! is_client) {
1304 int nid;
1305 EC_KEY *ec_key;
1306 if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
1307 nid = NID_secp224r1;
1308 else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
1309 nid = NID_X9_62_prime256v1;
1310 else
1311 nid = NID_tor_default_ecdhe_group;
1312 /* Use P-256 for ECDHE. */
1313 ec_key = EC_KEY_new_by_curve_name(nid);
1314 if (ec_key != NULL) /*XXXX Handle errors? */
1315 SSL_CTX_set_tmp_ecdh(result->ctx, ec_key);
1316 EC_KEY_free(ec_key);
1318 #endif
1319 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
1320 always_accept_verify_cb);
1321 /* let us realloc bufs that we're writing from */
1322 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1324 if (rsa)
1325 crypto_pk_free(rsa);
1326 if (rsa_auth)
1327 crypto_pk_free(rsa_auth);
1328 X509_free(authcert);
1329 tor_free(nickname);
1330 tor_free(nn2);
1331 return result;
1333 error:
1334 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
1335 tor_free(nickname);
1336 tor_free(nn2);
1337 if (pkey)
1338 EVP_PKEY_free(pkey);
1339 if (rsa)
1340 crypto_pk_free(rsa);
1341 if (rsa_auth)
1342 crypto_pk_free(rsa_auth);
1343 if (result)
1344 tor_tls_context_decref(result);
1345 if (cert)
1346 X509_free(cert);
1347 if (idcert)
1348 X509_free(idcert);
1349 if (authcert)
1350 X509_free(authcert);
1351 return NULL;
1354 /** Invoked when a TLS state changes: log the change at severity 'debug' */
1355 STATIC void
1356 tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
1358 /* LCOV_EXCL_START since this depends on whether debug is captured or not */
1359 log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
1360 ssl, SSL_state_string_long(ssl), type, val);
1361 /* LCOV_EXCL_STOP */
1364 /* Return the name of the negotiated ciphersuite in use on <b>tls</b> */
1365 const char *
1366 tor_tls_get_ciphersuite_name(tor_tls_t *tls)
1368 return SSL_get_cipher(tls->ssl);
1371 /* Here's the old V2 cipher list we sent from 0.2.1.1-alpha up to
1372 * 0.2.3.17-beta. If a client is using this list, we can't believe the ciphers
1373 * that it claims to support. We'll prune this list to remove the ciphers
1374 * *we* don't recognize. */
1375 STATIC uint16_t v2_cipher_list[] = {
1376 0xc00a, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA */
1377 0xc014, /* TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA */
1378 0x0039, /* TLS1_TXT_DHE_RSA_WITH_AES_256_SHA */
1379 0x0038, /* TLS1_TXT_DHE_DSS_WITH_AES_256_SHA */
1380 0xc00f, /* TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA */
1381 0xc005, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA */
1382 0x0035, /* TLS1_TXT_RSA_WITH_AES_256_SHA */
1383 0xc007, /* TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA */
1384 0xc009, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA */
1385 0xc011, /* TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA */
1386 0xc013, /* TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA */
1387 0x0033, /* TLS1_TXT_DHE_RSA_WITH_AES_128_SHA */
1388 0x0032, /* TLS1_TXT_DHE_DSS_WITH_AES_128_SHA */
1389 0xc00c, /* TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA */
1390 0xc00e, /* TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA */
1391 0xc002, /* TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA */
1392 0xc004, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA */
1393 0x0004, /* SSL3_TXT_RSA_RC4_128_MD5 */
1394 0x0005, /* SSL3_TXT_RSA_RC4_128_SHA */
1395 0x002f, /* TLS1_TXT_RSA_WITH_AES_128_SHA */
1396 0xc008, /* TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA */
1397 0xc012, /* TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA */
1398 0x0016, /* SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA */
1399 0x0013, /* SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA */
1400 0xc00d, /* TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA */
1401 0xc003, /* TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA */
1402 0xfeff, /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA */
1403 0x000a, /* SSL3_TXT_RSA_DES_192_CBC3_SHA */
1406 /** Have we removed the unrecognized ciphers from v2_cipher_list yet? */
1407 static int v2_cipher_list_pruned = 0;
1409 /** Return 0 if <b>m</b> does not support the cipher with ID <b>cipher</b>;
1410 * return 1 if it does support it, or if we have no way to tell. */
1411 STATIC int
1412 find_cipher_by_id(const SSL *ssl, const SSL_METHOD *m, uint16_t cipher)
1414 const SSL_CIPHER *c;
1415 #ifdef HAVE_SSL_CIPHER_FIND
1416 (void) m;
1418 unsigned char cipherid[3];
1419 tor_assert(ssl);
1420 set_uint16(cipherid, htons(cipher));
1421 cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
1422 * with a two-byte 'cipherid', it may look for a v2
1423 * cipher with the appropriate 3 bytes. */
1424 c = SSL_CIPHER_find((SSL*)ssl, cipherid);
1425 if (c)
1426 tor_assert((SSL_CIPHER_get_id(c) & 0xffff) == cipher);
1427 return c != NULL;
1429 #else /* !(defined(HAVE_SSL_CIPHER_FIND)) */
1431 # if defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR)
1432 if (m && m->get_cipher_by_char) {
1433 unsigned char cipherid[3];
1434 set_uint16(cipherid, htons(cipher));
1435 cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
1436 * with a two-byte 'cipherid', it may look for a v2
1437 * cipher with the appropriate 3 bytes. */
1438 c = m->get_cipher_by_char(cipherid);
1439 if (c)
1440 tor_assert((c->id & 0xffff) == cipher);
1441 return c != NULL;
1443 #endif /* defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR) */
1444 # ifndef OPENSSL_1_1_API
1445 if (m && m->get_cipher && m->num_ciphers) {
1446 /* It would seem that some of the "let's-clean-up-openssl" forks have
1447 * removed the get_cipher_by_char function. Okay, so now you get a
1448 * quadratic search.
1450 int i;
1451 for (i = 0; i < m->num_ciphers(); ++i) {
1452 c = m->get_cipher(i);
1453 if (c && (c->id & 0xffff) == cipher) {
1454 return 1;
1457 return 0;
1459 #endif /* !defined(OPENSSL_1_1_API) */
1460 (void) ssl;
1461 (void) m;
1462 (void) cipher;
1463 return 1; /* No way to search */
1464 #endif /* defined(HAVE_SSL_CIPHER_FIND) */
1467 /** Remove from v2_cipher_list every cipher that we don't support, so that
1468 * comparing v2_cipher_list to a client's cipher list will give a sensible
1469 * result. */
1470 static void
1471 prune_v2_cipher_list(const SSL *ssl)
1473 uint16_t *inp, *outp;
1474 #ifdef HAVE_TLS_METHOD
1475 const SSL_METHOD *m = TLS_method();
1476 #else
1477 const SSL_METHOD *m = SSLv23_method();
1478 #endif
1480 inp = outp = v2_cipher_list;
1481 while (*inp) {
1482 if (find_cipher_by_id(ssl, m, *inp)) {
1483 *outp++ = *inp++;
1484 } else {
1485 inp++;
1488 *outp = 0;
1490 v2_cipher_list_pruned = 1;
1493 /** Examine the client cipher list in <b>ssl</b>, and determine what kind of
1494 * client it is. Return one of CIPHERS_ERR, CIPHERS_V1, CIPHERS_V2,
1495 * CIPHERS_UNRESTRICTED.
1497 STATIC int
1498 tor_tls_classify_client_ciphers(const SSL *ssl,
1499 STACK_OF(SSL_CIPHER) *peer_ciphers)
1501 int i, res;
1502 tor_tls_t *tor_tls;
1503 if (PREDICT_UNLIKELY(!v2_cipher_list_pruned))
1504 prune_v2_cipher_list(ssl);
1506 tor_tls = tor_tls_get_by_ssl(ssl);
1507 if (tor_tls && tor_tls->client_cipher_list_type)
1508 return tor_tls->client_cipher_list_type;
1510 /* If we reached this point, we just got a client hello. See if there is
1511 * a cipher list. */
1512 if (!peer_ciphers) {
1513 log_info(LD_NET, "No ciphers on session");
1514 res = CIPHERS_ERR;
1515 goto done;
1517 /* Now we need to see if there are any ciphers whose presence means we're
1518 * dealing with an updated Tor. */
1519 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
1520 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
1521 const char *ciphername = SSL_CIPHER_get_name(cipher);
1522 if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
1523 strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
1524 strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
1525 strcmp(ciphername, "(NONE)")) {
1526 log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
1527 // return 1;
1528 goto v2_or_higher;
1531 res = CIPHERS_V1;
1532 goto done;
1533 v2_or_higher:
1535 const uint16_t *v2_cipher = v2_cipher_list;
1536 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
1537 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
1538 uint16_t id = SSL_CIPHER_get_id(cipher) & 0xffff;
1539 if (id == 0x00ff) /* extended renegotiation indicator. */
1540 continue;
1541 if (!id || id != *v2_cipher) {
1542 res = CIPHERS_UNRESTRICTED;
1543 goto dump_ciphers;
1545 ++v2_cipher;
1547 if (*v2_cipher != 0) {
1548 res = CIPHERS_UNRESTRICTED;
1549 goto dump_ciphers;
1551 res = CIPHERS_V2;
1554 dump_ciphers:
1556 smartlist_t *elts = smartlist_new();
1557 char *s;
1558 for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
1559 const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
1560 const char *ciphername = SSL_CIPHER_get_name(cipher);
1561 smartlist_add(elts, (char*)ciphername);
1563 s = smartlist_join_strings(elts, ":", 0, NULL);
1564 log_debug(LD_NET, "Got a %s V2/V3 cipher list from %s. It is: '%s'",
1565 (res == CIPHERS_V2) ? "fictitious" : "real", ADDR(tor_tls), s);
1566 tor_free(s);
1567 smartlist_free(elts);
1569 done:
1570 if (tor_tls)
1571 return tor_tls->client_cipher_list_type = res;
1573 return res;
1576 /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
1577 * a list that indicates that the client knows how to do the v2 TLS connection
1578 * handshake. */
1579 STATIC int
1580 tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
1582 STACK_OF(SSL_CIPHER) *ciphers;
1583 #ifdef HAVE_SSL_GET_CLIENT_CIPHERS
1584 ciphers = SSL_get_client_ciphers(ssl);
1585 #else
1586 SSL_SESSION *session;
1587 if (!(session = SSL_get_session((SSL *)ssl))) {
1588 log_info(LD_NET, "No session on TLS?");
1589 return CIPHERS_ERR;
1591 ciphers = session->ciphers;
1592 #endif /* defined(HAVE_SSL_GET_CLIENT_CIPHERS) */
1594 return tor_tls_classify_client_ciphers(ssl, ciphers) >= CIPHERS_V2;
1597 /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
1598 * changes state. We use this:
1599 * <ul><li>To alter the state of the handshake partway through, so we
1600 * do not send or request extra certificates in v2 handshakes.</li>
1601 * <li>To detect renegotiation</li></ul>
1603 STATIC void
1604 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
1606 tor_tls_t *tls;
1607 (void) val;
1609 IF_BUG_ONCE(ssl == NULL) {
1610 return; // LCOV_EXCL_LINE
1613 tor_tls_debug_state_callback(ssl, type, val);
1615 if (type != SSL_CB_ACCEPT_LOOP)
1616 return;
1618 OSSL_HANDSHAKE_STATE ssl_state = SSL_get_state(ssl);
1619 if (! STATE_IS_SW_SERVER_HELLO(ssl_state))
1620 return;
1621 tls = tor_tls_get_by_ssl(ssl);
1622 if (tls) {
1623 /* Check whether we're watching for renegotiates. If so, this is one! */
1624 if (tls->negotiated_callback)
1625 tls->got_renegotiate = 1;
1626 if (tls->server_handshake_count < 127) /*avoid any overflow possibility*/
1627 ++tls->server_handshake_count;
1628 } else {
1629 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
1630 return;
1633 /* Now check the cipher list. */
1634 if (tor_tls_client_is_using_v2_ciphers(ssl)) {
1635 if (tls->wasV2Handshake)
1636 return; /* We already turned this stuff off for the first handshake;
1637 * This is a renegotiation. */
1639 /* Yes, we're casting away the const from ssl. This is very naughty of us.
1640 * Let's hope openssl doesn't notice! */
1642 /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
1643 SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
1644 /* Don't send a hello request. */
1645 SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
1647 if (tls) {
1648 tls->wasV2Handshake = 1;
1649 } else {
1650 /* LCOV_EXCL_START this line is not reachable */
1651 log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
1652 /* LCOV_EXCL_STOP */
1657 /** Callback to get invoked on a server after we've read the list of ciphers
1658 * the client supports, but before we pick our own ciphersuite.
1660 * We can't abuse an info_cb for this, since by the time one of the
1661 * client_hello info_cbs is called, we've already picked which ciphersuite to
1662 * use.
1664 * Technically, this function is an abuse of this callback, since the point of
1665 * a session_secret_cb is to try to set up and/or verify a shared-secret for
1666 * authentication on the fly. But as long as we return 0, we won't actually be
1667 * setting up a shared secret, and all will be fine.
1669 STATIC int
1670 tor_tls_session_secret_cb(SSL *ssl, void *secret, int *secret_len,
1671 STACK_OF(SSL_CIPHER) *peer_ciphers,
1672 CONST_IF_OPENSSL_1_1_API SSL_CIPHER **cipher,
1673 void *arg)
1675 (void) secret;
1676 (void) secret_len;
1677 (void) peer_ciphers;
1678 (void) cipher;
1679 (void) arg;
1681 if (tor_tls_classify_client_ciphers(ssl, peer_ciphers) ==
1682 CIPHERS_UNRESTRICTED) {
1683 SSL_set_cipher_list(ssl, UNRESTRICTED_SERVER_CIPHER_LIST);
1686 SSL_set_session_secret_cb(ssl, NULL, NULL);
1688 return 0;
1690 static void
1691 tor_tls_setup_session_secret_cb(tor_tls_t *tls)
1693 SSL_set_session_secret_cb(tls->ssl, tor_tls_session_secret_cb, NULL);
1696 /** Create a new TLS object from a file descriptor, and a flag to
1697 * determine whether it is functioning as a server.
1699 tor_tls_t *
1700 tor_tls_new(int sock, int isServer)
1702 BIO *bio = NULL;
1703 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
1704 tor_tls_context_t *context = isServer ? server_tls_context :
1705 client_tls_context;
1706 result->magic = TOR_TLS_MAGIC;
1708 check_no_tls_errors();
1709 tor_assert(context); /* make sure somebody made it first */
1710 if (!(result->ssl = SSL_new(context->ctx))) {
1711 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
1712 tor_free(result);
1713 goto err;
1716 #ifdef SSL_set_tlsext_host_name
1717 /* Browsers use the TLS hostname extension, so we should too. */
1718 if (!isServer) {
1719 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
1720 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
1721 tor_free(fake_hostname);
1723 #endif /* defined(SSL_set_tlsext_host_name) */
1725 if (!SSL_set_cipher_list(result->ssl,
1726 isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
1727 tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
1728 #ifdef SSL_set_tlsext_host_name
1729 SSL_set_tlsext_host_name(result->ssl, NULL);
1730 #endif
1731 SSL_free(result->ssl);
1732 tor_free(result);
1733 goto err;
1735 result->socket = sock;
1736 bio = BIO_new_socket(sock, BIO_NOCLOSE);
1737 if (! bio) {
1738 tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
1739 #ifdef SSL_set_tlsext_host_name
1740 SSL_set_tlsext_host_name(result->ssl, NULL);
1741 #endif
1742 SSL_free(result->ssl);
1743 tor_free(result);
1744 goto err;
1747 int set_worked =
1748 SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
1749 if (!set_worked) {
1750 log_warn(LD_BUG,
1751 "Couldn't set the tls for an SSL*; connection will fail");
1754 SSL_set_bio(result->ssl, bio, bio);
1755 tor_tls_context_incref(context);
1756 result->context = context;
1757 result->state = TOR_TLS_ST_HANDSHAKE;
1758 result->isServer = isServer;
1759 result->wantwrite_n = 0;
1760 result->last_write_count = (unsigned long) BIO_number_written(bio);
1761 result->last_read_count = (unsigned long) BIO_number_read(bio);
1762 if (result->last_write_count || result->last_read_count) {
1763 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
1764 result->last_read_count, result->last_write_count);
1766 if (isServer) {
1767 SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
1768 } else {
1769 SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
1772 if (isServer)
1773 tor_tls_setup_session_secret_cb(result);
1775 goto done;
1776 err:
1777 result = NULL;
1778 done:
1779 /* Not expected to get called. */
1780 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
1781 return result;
1784 /** Make future log messages about <b>tls</b> display the address
1785 * <b>address</b>.
1787 void
1788 tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
1790 tor_assert(tls);
1791 tor_free(tls->address);
1792 tls->address = tor_strdup(address);
1795 /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
1796 * next gets a client-side renegotiate in the middle of a read. Do not
1797 * invoke this function until <em>after</em> initial handshaking is done!
1799 void
1800 tor_tls_set_renegotiate_callback(tor_tls_t *tls,
1801 void (*cb)(tor_tls_t *, void *arg),
1802 void *arg)
1804 tls->negotiated_callback = cb;
1805 tls->callback_arg = arg;
1806 tls->got_renegotiate = 0;
1807 if (cb) {
1808 SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
1809 } else {
1810 SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
1814 /** If this version of openssl requires it, turn on renegotiation on
1815 * <b>tls</b>.
1817 void
1818 tor_tls_unblock_renegotiation(tor_tls_t *tls)
1820 /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1821 * as authenticating any earlier-received data. */
1822 SSL_set_options(tls->ssl,
1823 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1826 /** If this version of openssl supports it, turn off renegotiation on
1827 * <b>tls</b>. (Our protocol never requires this for security, but it's nice
1828 * to use belt-and-suspenders here.)
1830 void
1831 tor_tls_block_renegotiation(tor_tls_t *tls)
1833 #ifdef SUPPORT_UNSAFE_RENEGOTIATION_FLAG
1834 tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1835 #else
1836 (void) tls;
1837 #endif
1840 /** Assert that the flags that allow legacy renegotiation are still set */
1841 void
1842 tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
1844 #if defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) && \
1845 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION != 0
1846 long options = SSL_get_options(tls->ssl);
1847 tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
1848 #else
1849 (void) tls;
1850 #endif /* defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) && ... */
1853 /** Return whether this tls initiated the connect (client) or
1854 * received it (server). */
1856 tor_tls_is_server(tor_tls_t *tls)
1858 tor_assert(tls);
1859 return tls->isServer;
1862 /** Release resources associated with a TLS object. Does not close the
1863 * underlying file descriptor.
1865 void
1866 tor_tls_free_(tor_tls_t *tls)
1868 if (!tls)
1869 return;
1870 tor_assert(tls->ssl);
1872 size_t r,w;
1873 tor_tls_get_n_raw_bytes(tls,&r,&w); /* ensure written_by_tls is updated */
1875 #ifdef SSL_set_tlsext_host_name
1876 SSL_set_tlsext_host_name(tls->ssl, NULL);
1877 #endif
1878 SSL_free(tls->ssl);
1879 tls->ssl = NULL;
1880 tls->negotiated_callback = NULL;
1881 if (tls->context)
1882 tor_tls_context_decref(tls->context);
1883 tor_free(tls->address);
1884 tls->magic = 0x99999999;
1885 tor_free(tls);
1888 /** Underlying function for TLS reading. Reads up to <b>len</b>
1889 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
1890 * number of characters read. On failure, returns TOR_TLS_ERROR,
1891 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1893 MOCK_IMPL(int,
1894 tor_tls_read,(tor_tls_t *tls, char *cp, size_t len))
1896 int r, err;
1897 tor_assert(tls);
1898 tor_assert(tls->ssl);
1899 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1900 tor_assert(len<INT_MAX);
1901 r = SSL_read(tls->ssl, cp, (int)len);
1902 if (r > 0) {
1903 if (tls->got_renegotiate) {
1904 /* Renegotiation happened! */
1905 log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
1906 if (tls->negotiated_callback)
1907 tls->negotiated_callback(tls, tls->callback_arg);
1908 tls->got_renegotiate = 0;
1910 return r;
1912 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
1913 if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) {
1914 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
1915 tls->state = TOR_TLS_ST_CLOSED;
1916 return TOR_TLS_CLOSE;
1917 } else {
1918 tor_assert(err != TOR_TLS_DONE);
1919 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
1920 return err;
1924 /** Total number of bytes that we've used TLS to send. Used to track TLS
1925 * overhead. */
1926 STATIC uint64_t total_bytes_written_over_tls = 0;
1927 /** Total number of bytes that TLS has put on the network for us. Used to
1928 * track TLS overhead. */
1929 STATIC uint64_t total_bytes_written_by_tls = 0;
1931 /** Underlying function for TLS writing. Write up to <b>n</b>
1932 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
1933 * number of characters written. On failure, returns TOR_TLS_ERROR,
1934 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
1937 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
1939 int r, err;
1940 tor_assert(tls);
1941 tor_assert(tls->ssl);
1942 tor_assert(tls->state == TOR_TLS_ST_OPEN);
1943 tor_assert(n < INT_MAX);
1944 if (n == 0)
1945 return 0;
1946 if (tls->wantwrite_n) {
1947 /* if WANTWRITE last time, we must use the _same_ n as before */
1948 tor_assert(n >= tls->wantwrite_n);
1949 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
1950 (int)n, (int)tls->wantwrite_n);
1951 n = tls->wantwrite_n;
1952 tls->wantwrite_n = 0;
1954 r = SSL_write(tls->ssl, cp, (int)n);
1955 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
1956 if (err == TOR_TLS_DONE) {
1957 total_bytes_written_over_tls += r;
1958 return r;
1960 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
1961 tls->wantwrite_n = n;
1963 return err;
1966 /** Perform initial handshake on <b>tls</b>. When finished, returns
1967 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
1968 * or TOR_TLS_WANTWRITE.
1971 tor_tls_handshake(tor_tls_t *tls)
1973 int r;
1974 tor_assert(tls);
1975 tor_assert(tls->ssl);
1976 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1978 check_no_tls_errors();
1980 OSSL_HANDSHAKE_STATE oldstate = SSL_get_state(tls->ssl);
1982 if (tls->isServer) {
1983 log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
1984 SSL_state_string_long(tls->ssl));
1985 r = SSL_accept(tls->ssl);
1986 } else {
1987 log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
1988 SSL_state_string_long(tls->ssl));
1989 r = SSL_connect(tls->ssl);
1992 OSSL_HANDSHAKE_STATE newstate = SSL_get_state(tls->ssl);
1994 if (oldstate != newstate)
1995 log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
1996 tls, SSL_state_string_long(tls->ssl));
1997 /* We need to call this here and not earlier, since OpenSSL has a penchant
1998 * for clearing its flags when you say accept or connect. */
1999 tor_tls_unblock_renegotiation(tls);
2000 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
2001 if (ERR_peek_error() != 0) {
2002 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
2003 "handshaking");
2004 return TOR_TLS_ERROR_MISC;
2006 if (r == TOR_TLS_DONE) {
2007 tls->state = TOR_TLS_ST_OPEN;
2008 return tor_tls_finish_handshake(tls);
2010 return r;
2013 /** Perform the final part of the initial TLS handshake on <b>tls</b>. This
2014 * should be called for the first handshake only: it determines whether the v1
2015 * or the v2 handshake was used, and adjusts things for the renegotiation
2016 * handshake as appropriate.
2018 * tor_tls_handshake() calls this on its own; you only need to call this if
2019 * bufferevent is doing the handshake for you.
2022 tor_tls_finish_handshake(tor_tls_t *tls)
2024 int r = TOR_TLS_DONE;
2025 check_no_tls_errors();
2026 if (tls->isServer) {
2027 SSL_set_info_callback(tls->ssl, NULL);
2028 SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
2029 SSL_clear_mode(tls->ssl, SSL_MODE_NO_AUTO_CHAIN);
2030 if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
2031 /* This check is redundant, but back when we did it in the callback,
2032 * we might have not been able to look up the tor_tls_t if the code
2033 * was buggy. Fixing that. */
2034 if (!tls->wasV2Handshake) {
2035 log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
2036 " get set. Fixing that.");
2038 tls->wasV2Handshake = 1;
2039 log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
2040 " for renegotiation.");
2041 } else {
2042 tls->wasV2Handshake = 0;
2044 } else {
2045 /* Client-side */
2046 tls->wasV2Handshake = 1;
2047 /* XXXX this can move, probably? -NM */
2048 if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
2049 tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
2050 r = TOR_TLS_ERROR_MISC;
2053 tls_log_errors(NULL, LOG_WARN, LD_NET, "finishing the handshake");
2054 return r;
2057 /** Shut down an open tls connection <b>tls</b>. When finished, returns
2058 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
2059 * or TOR_TLS_WANTWRITE.
2062 tor_tls_shutdown(tor_tls_t *tls)
2064 int r, err;
2065 char buf[128];
2066 tor_assert(tls);
2067 tor_assert(tls->ssl);
2068 check_no_tls_errors();
2070 while (1) {
2071 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
2072 /* If we've already called shutdown once to send a close message,
2073 * we read until the other side has closed too.
2075 do {
2076 r = SSL_read(tls->ssl, buf, 128);
2077 } while (r>0);
2078 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
2079 LOG_INFO, LD_NET);
2080 if (err == TOR_TLS_ZERORETURN_) {
2081 tls->state = TOR_TLS_ST_GOTCLOSE;
2082 /* fall through... */
2083 } else {
2084 return err;
2088 r = SSL_shutdown(tls->ssl);
2089 if (r == 1) {
2090 /* If shutdown returns 1, the connection is entirely closed. */
2091 tls->state = TOR_TLS_ST_CLOSED;
2092 return TOR_TLS_DONE;
2094 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
2095 LOG_INFO, LD_NET);
2096 if (err == TOR_TLS_SYSCALL_) {
2097 /* The underlying TCP connection closed while we were shutting down. */
2098 tls->state = TOR_TLS_ST_CLOSED;
2099 return TOR_TLS_DONE;
2100 } else if (err == TOR_TLS_ZERORETURN_) {
2101 /* The TLS connection says that it sent a shutdown record, but
2102 * isn't done shutting down yet. Make sure that this hasn't
2103 * happened before, then go back to the start of the function
2104 * and try to read.
2106 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
2107 tls->state == TOR_TLS_ST_SENTCLOSE) {
2108 log_warn(LD_NET,
2109 "TLS returned \"half-closed\" value while already half-closed");
2110 return TOR_TLS_ERROR_MISC;
2112 tls->state = TOR_TLS_ST_SENTCLOSE;
2113 /* fall through ... */
2114 } else {
2115 return err;
2117 } /* end loop */
2120 /** Return true iff this TLS connection is authenticated.
2123 tor_tls_peer_has_cert(tor_tls_t *tls)
2125 X509 *cert;
2126 cert = SSL_get_peer_certificate(tls->ssl);
2127 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
2128 if (!cert)
2129 return 0;
2130 X509_free(cert);
2131 return 1;
2134 /** Return a newly allocated copy of the peer certificate, or NULL if there
2135 * isn't one. */
2136 MOCK_IMPL(tor_x509_cert_t *,
2137 tor_tls_get_peer_cert,(tor_tls_t *tls))
2139 X509 *cert;
2140 cert = SSL_get_peer_certificate(tls->ssl);
2141 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
2142 if (!cert)
2143 return NULL;
2144 return tor_x509_cert_new(cert);
2147 /** Return a newly allocated copy of the cerficate we used on the connection,
2148 * or NULL if somehow we didn't use one. */
2149 MOCK_IMPL(tor_x509_cert_t *,
2150 tor_tls_get_own_cert,(tor_tls_t *tls))
2152 X509 *cert = SSL_get_certificate(tls->ssl);
2153 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE,
2154 "getting own-connection certificate");
2155 if (!cert)
2156 return NULL;
2157 /* Fun inconsistency: SSL_get_peer_certificate increments the reference
2158 * count, but SSL_get_certificate does not. */
2159 X509 *duplicate = X509_dup(cert);
2160 if (BUG(duplicate == NULL))
2161 return NULL;
2162 return tor_x509_cert_new(duplicate);
2165 /** Warn that a certificate lifetime extends through a certain range. */
2166 static void
2167 log_cert_lifetime(int severity, const X509 *cert, const char *problem,
2168 time_t now)
2170 BIO *bio = NULL;
2171 BUF_MEM *buf;
2172 char *s1=NULL, *s2=NULL;
2173 char mytime[33];
2174 struct tm tm;
2175 size_t n;
2177 if (problem)
2178 tor_log(severity, LD_GENERAL,
2179 "Certificate %s. Either their clock is set wrong, or your clock "
2180 "is wrong.",
2181 problem);
2183 if (!(bio = BIO_new(BIO_s_mem()))) {
2184 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
2186 if (!(ASN1_TIME_print(bio, X509_get_notBefore_const(cert)))) {
2187 tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
2188 goto end;
2190 BIO_get_mem_ptr(bio, &buf);
2191 s1 = tor_strndup(buf->data, buf->length);
2193 (void)BIO_reset(bio);
2194 if (!(ASN1_TIME_print(bio, X509_get_notAfter_const(cert)))) {
2195 tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
2196 goto end;
2198 BIO_get_mem_ptr(bio, &buf);
2199 s2 = tor_strndup(buf->data, buf->length);
2201 n = strftime(mytime, 32, "%b %d %H:%M:%S %Y UTC", tor_gmtime_r(&now, &tm));
2202 if (n > 0) {
2203 tor_log(severity, LD_GENERAL,
2204 "(certificate lifetime runs from %s through %s. Your time is %s.)",
2205 s1,s2,mytime);
2206 } else {
2207 tor_log(severity, LD_GENERAL,
2208 "(certificate lifetime runs from %s through %s. "
2209 "Couldn't get your time.)",
2210 s1, s2);
2213 end:
2214 /* Not expected to get invoked */
2215 tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
2216 if (bio)
2217 BIO_free(bio);
2218 tor_free(s1);
2219 tor_free(s2);
2222 /** Helper function: try to extract a link certificate and an identity
2223 * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
2224 * *<b>id_cert_out</b> respectively. Log all messages at level
2225 * <b>severity</b>.
2227 * Note that a reference is added to cert_out, so it needs to be
2228 * freed. id_cert_out doesn't. */
2229 MOCK_IMPL(STATIC void,
2230 try_to_extract_certs_from_tls,(int severity, tor_tls_t *tls,
2231 X509 **cert_out, X509 **id_cert_out))
2233 X509 *cert = NULL, *id_cert = NULL;
2234 STACK_OF(X509) *chain = NULL;
2235 int num_in_chain, i;
2236 *cert_out = *id_cert_out = NULL;
2237 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
2238 return;
2239 *cert_out = cert;
2240 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
2241 return;
2242 num_in_chain = sk_X509_num(chain);
2243 /* 1 means we're receiving (server-side), and it's just the id_cert.
2244 * 2 means we're connecting (client-side), and it's both the link
2245 * cert and the id_cert.
2247 if (num_in_chain < 1) {
2248 log_fn(severity,LD_PROTOCOL,
2249 "Unexpected number of certificates in chain (%d)",
2250 num_in_chain);
2251 return;
2253 for (i=0; i<num_in_chain; ++i) {
2254 id_cert = sk_X509_value(chain, i);
2255 if (X509_cmp(id_cert, cert) != 0)
2256 break;
2258 *id_cert_out = id_cert;
2261 /** If the provided tls connection is authenticated and has a
2262 * certificate chain that is currently valid and signed, then set
2263 * *<b>identity_key</b> to the identity certificate's key and return
2264 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
2267 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity_key)
2269 X509 *cert = NULL, *id_cert = NULL;
2270 EVP_PKEY *id_pkey = NULL;
2271 RSA *rsa;
2272 int r = -1;
2274 check_no_tls_errors();
2275 *identity_key = NULL;
2277 try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
2278 if (!cert)
2279 goto done;
2280 if (!id_cert) {
2281 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
2282 goto done;
2284 tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
2286 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
2287 X509_verify(cert, id_pkey) <= 0) {
2288 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
2289 tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
2290 goto done;
2293 rsa = EVP_PKEY_get1_RSA(id_pkey);
2294 if (!rsa)
2295 goto done;
2296 *identity_key = crypto_new_pk_from_rsa_(rsa);
2298 r = 0;
2300 done:
2301 if (cert)
2302 X509_free(cert);
2303 if (id_pkey)
2304 EVP_PKEY_free(id_pkey);
2306 /* This should never get invoked, but let's make sure in case OpenSSL
2307 * acts unexpectedly. */
2308 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
2310 return r;
2313 /** Check whether the certificate set on the connection <b>tls</b> is expired
2314 * give or take <b>past_tolerance</b> seconds, or not-yet-valid give or take
2315 * <b>future_tolerance</b> seconds. Return 0 for valid, -1 for failure.
2317 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
2320 tor_tls_check_lifetime(int severity, tor_tls_t *tls,
2321 time_t now,
2322 int past_tolerance, int future_tolerance)
2324 X509 *cert;
2325 int r = -1;
2327 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
2328 goto done;
2330 if (check_cert_lifetime_internal(severity, cert, now,
2331 past_tolerance, future_tolerance) < 0)
2332 goto done;
2334 r = 0;
2335 done:
2336 if (cert)
2337 X509_free(cert);
2338 /* Not expected to get invoked */
2339 tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
2341 return r;
2344 /** Helper: check whether <b>cert</b> is expired give or take
2345 * <b>past_tolerance</b> seconds, or not-yet-valid give or take
2346 * <b>future_tolerance</b> seconds. (Relative to the current time
2347 * <b>now</b>.) If it is live, return 0. If it is not live, log a message
2348 * and return -1. */
2349 static int
2350 check_cert_lifetime_internal(int severity, const X509 *cert,
2351 time_t now,
2352 int past_tolerance, int future_tolerance)
2354 time_t t;
2356 t = now + future_tolerance;
2357 if (X509_cmp_time(X509_get_notBefore_const(cert), &t) > 0) {
2358 log_cert_lifetime(severity, cert, "not yet valid", now);
2359 return -1;
2361 t = now - past_tolerance;
2362 if (X509_cmp_time(X509_get_notAfter_const(cert), &t) < 0) {
2363 log_cert_lifetime(severity, cert, "already expired", now);
2364 return -1;
2367 return 0;
2370 #ifdef TOR_UNIT_TESTS
2371 /* Testing only: return a new x509 cert with the same contents as <b>inp</b>,
2372 but with the expiration time <b>new_expiration_time</b>, signed with
2373 <b>signing_key</b>. */
2374 STATIC tor_x509_cert_t *
2375 tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
2376 time_t new_expiration_time,
2377 crypto_pk_t *signing_key)
2379 X509 *newc = X509_dup(inp->cert);
2380 X509_time_adj(X509_get_notAfter(newc), 0, &new_expiration_time);
2381 EVP_PKEY *pk = crypto_pk_get_evp_pkey_(signing_key, 1);
2382 tor_assert(X509_sign(newc, pk, EVP_sha256()));
2383 EVP_PKEY_free(pk);
2384 return tor_x509_cert_new(newc);
2386 #endif /* defined(TOR_UNIT_TESTS) */
2388 /** Return the number of bytes available for reading from <b>tls</b>.
2391 tor_tls_get_pending_bytes(tor_tls_t *tls)
2393 tor_assert(tls);
2394 return SSL_pending(tls->ssl);
2397 /** If <b>tls</b> requires that the next write be of a particular size,
2398 * return that size. Otherwise, return 0. */
2399 size_t
2400 tor_tls_get_forced_write_size(tor_tls_t *tls)
2402 return tls->wantwrite_n;
2405 /** Sets n_read and n_written to the number of bytes read and written,
2406 * respectively, on the raw socket used by <b>tls</b> since the last time this
2407 * function was called on <b>tls</b>. */
2408 void
2409 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
2411 BIO *wbio, *tmpbio;
2412 unsigned long r, w;
2413 r = (unsigned long) BIO_number_read(SSL_get_rbio(tls->ssl));
2414 /* We want the number of bytes actually for real written. Unfortunately,
2415 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
2416 * which makes the answer turn out wrong. Let's cope with that. Note
2417 * that this approach will fail if we ever replace tls->ssl's BIOs with
2418 * buffering bios for reasons of our own. As an alternative, we could
2419 * save the original BIO for tls->ssl in the tor_tls_t structure, but
2420 * that would be tempting fate. */
2421 wbio = SSL_get_wbio(tls->ssl);
2422 #if OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)
2423 /* BIO structure is opaque as of OpenSSL 1.1.0-pre5-dev. Again, not
2424 * supposed to use this form of the version macro, but the OpenSSL developers
2425 * introduced major API changes in the pre-release stage.
2427 if (BIO_method_type(wbio) == BIO_TYPE_BUFFER &&
2428 (tmpbio = BIO_next(wbio)) != NULL)
2429 wbio = tmpbio;
2430 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)) */
2431 if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
2432 wbio = tmpbio;
2433 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5) */
2434 w = (unsigned long) BIO_number_written(wbio);
2436 /* We are ok with letting these unsigned ints go "negative" here:
2437 * If we wrapped around, this should still give us the right answer, unless
2438 * we wrapped around by more than ULONG_MAX since the last time we called
2439 * this function.
2441 *n_read = (size_t)(r - tls->last_read_count);
2442 *n_written = (size_t)(w - tls->last_write_count);
2443 if (*n_read > INT_MAX || *n_written > INT_MAX) {
2444 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
2445 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
2446 r, tls->last_read_count, w, tls->last_write_count);
2448 total_bytes_written_by_tls += *n_written;
2449 tls->last_read_count = r;
2450 tls->last_write_count = w;
2453 /** Return a ratio of the bytes that TLS has sent to the bytes that we've told
2454 * it to send. Used to track whether our TLS records are getting too tiny. */
2455 MOCK_IMPL(double,
2456 tls_get_write_overhead_ratio,(void))
2458 if (total_bytes_written_over_tls == 0)
2459 return 1.0;
2461 return U64_TO_DBL(total_bytes_written_by_tls) /
2462 U64_TO_DBL(total_bytes_written_over_tls);
2465 /** Implement check_no_tls_errors: If there are any pending OpenSSL
2466 * errors, log an error message. */
2467 void
2468 check_no_tls_errors_(const char *fname, int line)
2470 if (ERR_peek_error() == 0)
2471 return;
2472 log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
2473 tor_fix_source_file(fname), line);
2474 tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
2477 /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
2478 * TLS handshake. Output is undefined if the handshake isn't finished. */
2480 tor_tls_used_v1_handshake(tor_tls_t *tls)
2482 return ! tls->wasV2Handshake;
2485 /** Return the number of server handshakes that we've noticed doing on
2486 * <b>tls</b>. */
2488 tor_tls_get_num_server_handshakes(tor_tls_t *tls)
2490 return tls->server_handshake_count;
2493 /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
2494 * request it was waiting for. */
2496 tor_tls_server_got_renegotiate(tor_tls_t *tls)
2498 return tls->got_renegotiate;
2501 #ifndef HAVE_SSL_GET_CLIENT_RANDOM
2502 static size_t
2503 SSL_get_client_random(SSL *s, uint8_t *out, size_t len)
2505 if (len == 0)
2506 return SSL3_RANDOM_SIZE;
2507 tor_assert(len == SSL3_RANDOM_SIZE);
2508 tor_assert(s->s3);
2509 memcpy(out, s->s3->client_random, len);
2510 return len;
2512 #endif /* !defined(HAVE_SSL_GET_CLIENT_RANDOM) */
2514 #ifndef HAVE_SSL_GET_SERVER_RANDOM
2515 static size_t
2516 SSL_get_server_random(SSL *s, uint8_t *out, size_t len)
2518 if (len == 0)
2519 return SSL3_RANDOM_SIZE;
2520 tor_assert(len == SSL3_RANDOM_SIZE);
2521 tor_assert(s->s3);
2522 memcpy(out, s->s3->server_random, len);
2523 return len;
2525 #endif /* !defined(HAVE_SSL_GET_SERVER_RANDOM) */
2527 #ifndef HAVE_SSL_SESSION_GET_MASTER_KEY
2528 STATIC size_t
2529 SSL_SESSION_get_master_key(SSL_SESSION *s, uint8_t *out, size_t len)
2531 tor_assert(s);
2532 if (len == 0)
2533 return s->master_key_length;
2534 tor_assert(len == (size_t)s->master_key_length);
2535 tor_assert(out);
2536 memcpy(out, s->master_key, len);
2537 return len;
2539 #endif /* !defined(HAVE_SSL_SESSION_GET_MASTER_KEY) */
2541 /** Set the DIGEST256_LEN buffer at <b>secrets_out</b> to the value used in
2542 * the v3 handshake to prove that the client knows the TLS secrets for the
2543 * connection <b>tls</b>. Return 0 on success, -1 on failure.
2545 MOCK_IMPL(int,
2546 tor_tls_get_tlssecrets,(tor_tls_t *tls, uint8_t *secrets_out))
2548 #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
2549 uint8_t buf[128];
2550 size_t len;
2551 tor_assert(tls);
2553 SSL *const ssl = tls->ssl;
2554 SSL_SESSION *const session = SSL_get_session(ssl);
2556 tor_assert(ssl);
2557 tor_assert(session);
2559 const size_t server_random_len = SSL_get_server_random(ssl, NULL, 0);
2560 const size_t client_random_len = SSL_get_client_random(ssl, NULL, 0);
2561 const size_t master_key_len = SSL_SESSION_get_master_key(session, NULL, 0);
2563 tor_assert(server_random_len);
2564 tor_assert(client_random_len);
2565 tor_assert(master_key_len);
2567 len = client_random_len + server_random_len + strlen(TLSSECRET_MAGIC) + 1;
2568 tor_assert(len <= sizeof(buf));
2571 size_t r = SSL_get_client_random(ssl, buf, client_random_len);
2572 tor_assert(r == client_random_len);
2576 size_t r = SSL_get_server_random(ssl,
2577 buf+client_random_len,
2578 server_random_len);
2579 tor_assert(r == server_random_len);
2582 uint8_t *master_key = tor_malloc_zero(master_key_len);
2584 size_t r = SSL_SESSION_get_master_key(session, master_key, master_key_len);
2585 tor_assert(r == master_key_len);
2588 uint8_t *nextbuf = buf + client_random_len + server_random_len;
2589 memcpy(nextbuf, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
2592 The value is an HMAC, using the TLS master key as the HMAC key, of
2593 client_random | server_random | TLSSECRET_MAGIC
2595 crypto_hmac_sha256((char*)secrets_out,
2596 (char*)master_key,
2597 master_key_len,
2598 (char*)buf, len);
2599 memwipe(buf, 0, sizeof(buf));
2600 memwipe(master_key, 0, master_key_len);
2601 tor_free(master_key);
2603 return 0;
2606 /** Using the RFC5705 key material exporting construction, and the
2607 * provided <b>context</b> (<b>context_len</b> bytes long) and
2608 * <b>label</b> (a NUL-terminated string), compute a 32-byte secret in
2609 * <b>secrets_out</b> that only the parties to this TLS session can
2610 * compute. Return 0 on success and -1 on failure.
2612 MOCK_IMPL(int,
2613 tor_tls_export_key_material,(tor_tls_t *tls, uint8_t *secrets_out,
2614 const uint8_t *context,
2615 size_t context_len,
2616 const char *label))
2618 tor_assert(tls);
2619 tor_assert(tls->ssl);
2621 int r = SSL_export_keying_material(tls->ssl,
2622 secrets_out, DIGEST256_LEN,
2623 label, strlen(label),
2624 context, context_len, 1);
2625 return (r == 1) ? 0 : -1;
2628 /** Examine the amount of memory used and available for buffers in <b>tls</b>.
2629 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
2630 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
2631 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
2632 * buffer and *<b>wbuf_bytes</b> to the amount actually used.
2634 * Return 0 on success, -1 on failure.*/
2636 tor_tls_get_buffer_sizes(tor_tls_t *tls,
2637 size_t *rbuf_capacity, size_t *rbuf_bytes,
2638 size_t *wbuf_capacity, size_t *wbuf_bytes)
2640 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)
2641 (void)tls;
2642 (void)rbuf_capacity;
2643 (void)rbuf_bytes;
2644 (void)wbuf_capacity;
2645 (void)wbuf_bytes;
2647 return -1;
2648 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)) */
2649 if (tls->ssl->s3->rbuf.buf)
2650 *rbuf_capacity = tls->ssl->s3->rbuf.len;
2651 else
2652 *rbuf_capacity = 0;
2653 if (tls->ssl->s3->wbuf.buf)
2654 *wbuf_capacity = tls->ssl->s3->wbuf.len;
2655 else
2656 *wbuf_capacity = 0;
2657 *rbuf_bytes = tls->ssl->s3->rbuf.left;
2658 *wbuf_bytes = tls->ssl->s3->wbuf.left;
2659 return 0;
2660 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
2663 /** Check whether the ECC group requested is supported by the current OpenSSL
2664 * library instance. Return 1 if the group is supported, and 0 if not.
2667 evaluate_ecgroup_for_tls(const char *ecgroup)
2669 EC_KEY *ec_key;
2670 int nid;
2671 int ret;
2673 if (!ecgroup)
2674 nid = NID_tor_default_ecdhe_group;
2675 else if (!strcasecmp(ecgroup, "P256"))
2676 nid = NID_X9_62_prime256v1;
2677 else if (!strcasecmp(ecgroup, "P224"))
2678 nid = NID_secp224r1;
2679 else
2680 return 0;
2682 ec_key = EC_KEY_new_by_curve_name(nid);
2683 ret = (ec_key != NULL);
2684 EC_KEY_free(ec_key);
2686 return ret;