tor  0.4.1.0-alpha-dev
tortls_openssl.c
1 /* Copyright (c) 2003, Roger Dingledine.
2  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3  * Copyright (c) 2007-2019, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 
12 /* (Unlike other tor functions, these
13  * are prefixed with tor_ in order to avoid conflicting with OpenSSL
14  * functions and variables.)
15  */
16 
17 #include "orconfig.h"
18 
19 #define TORTLS_PRIVATE
20 #define TORTLS_OPENSSL_PRIVATE
21 #define TOR_X509_PRIVATE
22 
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
29 
34 #include "lib/crypt_ops/compat_openssl.h"
35 #include "lib/tls/x509.h"
36 #include "lib/tls/x509_internal.h"
37 
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(redundant-decls)
41 
42 #include <openssl/opensslv.h>
43 
44 #ifdef OPENSSL_NO_EC
45 #error "We require OpenSSL with ECC support"
46 #endif
47 
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>
56 
57 ENABLE_GCC_WARNING(redundant-decls)
58 
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"
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"
71 
72 #include <stdlib.h>
73 #include <string.h>
74 
75 #include "lib/arch/bytes.h"
76 
77 /* Copied from or.h */
78 #define LEGAL_NICKNAME_CHARACTERS \
79  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
80 
81 #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
82 
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.
87  */
88 #define DISABLE_SSL3_HANDSHAKE
89 #endif /* OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f') */
90 
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.)
94  */
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
101 
103 static int openssl_bug_7712_is_present = 0;
104 
110 #define CIPHERS_ERR -1
111 
112 #define CIPHERS_V1 1
113 
116 #define CIPHERS_V2 2
117 
120 #define CIPHERS_UNRESTRICTED 3
121 
125 STATIC int tor_tls_object_ex_data_index = -1;
126 
128 void
129 tor_tls_allocate_tor_tls_object_ex_data_index(void)
130 {
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);
135  }
136 }
137 
140 tor_tls_t *
141 tor_tls_get_by_ssl(const SSL *ssl)
142 {
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;
147 }
148 
150 static int tls_library_is_initialized = 0;
151 
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)
155 
158 void
159 tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
160 {
161  const char *ssl_state;
162  const char *tortls_state;
163 
164  if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
165  strlcpy(buf, "(No SSL object)", sz);
166  return;
167  }
168 
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;
185  }
186 
187  tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
188 }
189 
193 void
194 tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
195  int severity, int domain, const char *doing)
196 {
197  const char *state = NULL, *addr;
198  const char *msg, *lib, *func;
199 
200  state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
201 
202  addr = tls ? tls->address : NULL;
203 
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;
220  }
221 
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);
236  }
237 }
238 
242 void
243 tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
244 {
245  unsigned long err;
246 
247  while ((err = ERR_get_error()) != 0) {
248  tor_tls_log_one_error(tls, err, severity, domain, doing);
249  }
250 }
251 
252 #define CATCH_SYSCALL 1
253 #define CATCH_ZERO 2
254 
265 int
266 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
267  const char *doing, int severity, int domain)
268 {
269  int err = SSL_get_error(tls->ssl, r);
270  int tor_error = TOR_TLS_ERROR_MISC;
271  switch (err) {
272  case SSL_ERROR_NONE:
273  return TOR_TLS_DONE;
274  case SSL_ERROR_WANT_READ:
275  return TOR_TLS_WANTREAD;
276  case SSL_ERROR_WANT_WRITE:
277  return TOR_TLS_WANTWRITE;
278  case SSL_ERROR_SYSCALL:
279  if (extra&CATCH_SYSCALL)
280  return TOR_TLS_SYSCALL_;
281  if (r == 0) {
282  tor_log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
283  doing, SSL_state_string_long(tls->ssl));
284  tor_error = TOR_TLS_ERROR_IO;
285  } else {
286  int e = tor_socket_errno(tls->socket);
287  tor_log(severity, LD_NET,
288  "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
289  doing, e, tor_socket_strerror(e),
290  SSL_state_string_long(tls->ssl));
291  tor_error = tor_errno_to_tls_error(e);
292  }
293  tls_log_errors(tls, severity, domain, doing);
294  return tor_error;
295  case SSL_ERROR_ZERO_RETURN:
296  if (extra&CATCH_ZERO)
297  return TOR_TLS_ZERORETURN_;
298  tor_log(severity, LD_NET, "TLS connection closed while %s in state %s",
299  doing, SSL_state_string_long(tls->ssl));
300  tls_log_errors(tls, severity, domain, doing);
301  return TOR_TLS_CLOSE;
302  default:
303  tls_log_errors(tls, severity, domain, doing);
304  return TOR_TLS_ERROR_MISC;
305  }
306 }
307 
310 void
311 tor_tls_init(void)
312 {
313  check_no_tls_errors();
314 
315  if (!tls_library_is_initialized) {
316 #ifdef OPENSSL_1_1_API
317  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
318 #else
319  SSL_library_init();
320  SSL_load_error_strings();
321 #endif
322 
323 #if (SIZEOF_VOID_P >= 8 && \
324  OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,1))
325  long version = OpenSSL_version_num();
326 
327  /* LCOV_EXCL_START : we can't test these lines on the same machine */
328  if (version >= OPENSSL_V_SERIES(1,0,1)) {
329  /* Warn if we could *almost* be running with much faster ECDH.
330  If we're built for a 64-bit target, using OpenSSL 1.0.1, but we
331  don't have one of the built-in __uint128-based speedups, we are
332  just one build operation away from an accelerated handshake.
333 
334  (We could be looking at OPENSSL_NO_EC_NISTP_64_GCC_128 instead of
335  doing this test, but that gives compile-time options, not runtime
336  behavior.)
337  */
338  EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
339  const EC_GROUP *g = key ? EC_KEY_get0_group(key) : NULL;
340  const EC_METHOD *m = g ? EC_GROUP_method_of(g) : NULL;
341  const int warn = (m == EC_GFp_simple_method() ||
342  m == EC_GFp_mont_method() ||
343  m == EC_GFp_nist_method());
344  EC_KEY_free(key);
345 
346  if (warn)
347  log_notice(LD_GENERAL, "We were built to run on a 64-bit CPU, with "
348  "OpenSSL 1.0.1 or later, but with a version of OpenSSL "
349  "that apparently lacks accelerated support for the NIST "
350  "P-224 and P-256 groups. Building openssl with such "
351  "support (using the enable-ec_nistp_64_gcc_128 option "
352  "when configuring it) would make ECDH much faster.");
353  }
354  /* LCOV_EXCL_STOP */
355 #endif /* (SIZEOF_VOID_P >= 8 && ... */
356 
357  tor_tls_allocate_tor_tls_object_ex_data_index();
358 
359  tls_library_is_initialized = 1;
360  }
361 }
362 
367 int
368 always_accept_verify_cb(int preverify_ok,
369  X509_STORE_CTX *x509_ctx)
370 {
371  (void) preverify_ok;
372  (void) x509_ctx;
373  return 1;
374 }
375 
378 static const char SERVER_CIPHER_LIST[] =
379 #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
380  /* This one can never actually get selected, since if the client lists it,
381  * we will assume that the client is honest, and not use this list.
382  * Nonetheless we list it if it's available, so that the server doesn't
383  * conclude that it has no valid ciphers if it's running with TLS1.3.
384  */
385  TLS1_3_TXT_AES_128_GCM_SHA256 ":"
386 #endif
387  TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
388  TLS1_TXT_DHE_RSA_WITH_AES_128_SHA;
389 
392 static const char UNRESTRICTED_SERVER_CIPHER_LIST[] =
393  /* Here are the TLS 1.3 ciphers we like, in the order we prefer. */
394 #ifdef TLS1_3_TXT_AES_256_GCM_SHA384
395  TLS1_3_TXT_AES_256_GCM_SHA384 ":"
396 #endif
397 #ifdef TLS1_3_TXT_CHACHA20_POLY1305_SHA256
398  TLS1_3_TXT_CHACHA20_POLY1305_SHA256 ":"
399 #endif
400 #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
401  TLS1_3_TXT_AES_128_GCM_SHA256 ":"
402 #endif
403 #ifdef TLS1_3_TXT_AES_128_CCM_SHA256
404  TLS1_3_TXT_AES_128_CCM_SHA256 ":"
405 #endif
406 
407  /* This list is autogenerated with the gen_server_ciphers.py script;
408  * don't hand-edit it. */
409 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
410  TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
411 #endif
412 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
413  TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
414 #endif
415 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384
416  TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 ":"
417 #endif
418 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
419  TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
420 #endif
421 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA
422  TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
423 #endif
424 #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
425  TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
426 #endif
427 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384
428  TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 ":"
429 #endif
430 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256
431  TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 ":"
432 #endif
433 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_CCM
434  TLS1_TXT_DHE_RSA_WITH_AES_256_CCM ":"
435 #endif
436 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_CCM
437  TLS1_TXT_DHE_RSA_WITH_AES_128_CCM ":"
438 #endif
439 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256
440  TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 ":"
441 #endif
442 #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256
443  TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 ":"
444 #endif
445  /* Required */
446  TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
447  /* Required */
448  TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"
449 #ifdef TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305
450  TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 ":"
451 #endif
452 #ifdef TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
453  TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
454 #endif
455  ;
456 
457 /* Note: to set up your own private testing network with link crypto
458  * disabled, set your Tors' cipher list to
459  * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
460  * with any of the "real" Tors, though. */
461 
462 #define CIPHER(id, name) name ":"
463 #define XCIPHER(id, name)
464 
466 static const char CLIENT_CIPHER_LIST[] =
467 #include "lib/tls/ciphers.inc"
468  /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
469  * of any cipher we say. */
470  "!SSLv2"
471  ;
472 #undef CIPHER
473 #undef XCIPHER
474 
478 MOCK_IMPL(int,
479 tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
480 {
481  tor_x509_cert_t *peer = tor_tls_get_peer_cert((tor_tls_t *)tls);
482  if (!peer)
483  return 0;
484 
485  X509 *peercert = peer->cert;
486  EVP_PKEY *link_key = NULL, *cert_key = NULL;
487  int result;
488 
489  link_key = X509_get_pubkey(peercert);
490  cert_key = X509_get_pubkey(cert->cert);
491 
492  result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
493 
494  tor_x509_cert_free(peer);
495  if (link_key)
496  EVP_PKEY_free(link_key);
497  if (cert_key)
498  EVP_PKEY_free(cert_key);
499 
500  return result;
501 }
502 
503 void
504 tor_tls_context_impl_free_(struct ssl_ctx_st *ctx)
505 {
506  if (!ctx)
507  return;
508  SSL_CTX_free(ctx);
509 }
510 
512 #define NID_tor_default_ecdhe_group NID_X9_62_prime256v1
513 
519 tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
520  unsigned flags, int is_client)
521 {
522  EVP_PKEY *pkey = NULL;
523  tor_tls_context_t *result = NULL;
524 
525  tor_tls_init();
526 
527  result = tor_malloc_zero(sizeof(tor_tls_context_t));
528  result->refcnt = 1;
529 
530  if (! is_client) {
531  if (tor_tls_context_init_certificates(result, identity, key_lifetime,
532  flags) < 0) {
533  goto error;
534  }
535  }
536 
537 #if 0
538  /* Tell OpenSSL to only use TLS1. This may have subtly different results
539  * from SSLv23_method() with SSLv2 and SSLv3 disabled, so we need to do some
540  * investigation before we consider adjusting it. It should be compatible
541  * with existing Tors. */
542  if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
543  goto error;
544 #endif /* 0 */
545 
546  /* Tell OpenSSL to use TLS 1.0 or later but not SSL2 or SSL3. */
547 #ifdef HAVE_TLS_METHOD
548  if (!(result->ctx = SSL_CTX_new(TLS_method())))
549  goto error;
550 #else
551  if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
552  goto error;
553 #endif /* defined(HAVE_TLS_METHOD) */
554 
555 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
556  /* Level 1 re-enables RSA1024 and DH1024 for compatibility with old tors */
557  SSL_CTX_set_security_level(result->ctx, 1);
558 #endif
559 
560  SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
561  SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
562 
563  /* Prefer the server's ordering of ciphers: the client's ordering has
564  * historically been chosen for fingerprinting resistance. */
565  SSL_CTX_set_options(result->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
566 
567  /* Disable TLS tickets if they're supported. We never want to use them;
568  * using them can make our perfect forward secrecy a little worse, *and*
569  * create an opportunity to fingerprint us (since it's unusual to use them
570  * with TLS sessions turned off).
571  *
572  * In 0.2.4, clients advertise support for them though, to avoid a TLS
573  * distinguishability vector. This can give us worse PFS, though, if we
574  * get a server that doesn't set SSL_OP_NO_TICKET. With luck, there will
575  * be few such servers by the time 0.2.4 is more stable.
576  */
577 #ifdef SSL_OP_NO_TICKET
578  if (! is_client) {
579  SSL_CTX_set_options(result->ctx, SSL_OP_NO_TICKET);
580  }
581 #endif
582 
583  SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
584  SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_ECDH_USE);
585 
586 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
587  SSL_CTX_set_options(result->ctx,
588  SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
589 #endif
590  /* Yes, we know what we are doing here. No, we do not treat a renegotiation
591  * as authenticating any earlier-received data.
592  */
593  {
594  SSL_CTX_set_options(result->ctx,
595  SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
596  }
597 
598  /* Don't actually allow compression; it uses RAM and time, it makes TLS
599  * vulnerable to CRIME-style attacks, and most of the data we transmit over
600  * TLS is encrypted (and therefore uncompressible) anyway. */
601 #ifdef SSL_OP_NO_COMPRESSION
602  SSL_CTX_set_options(result->ctx, SSL_OP_NO_COMPRESSION);
603 #endif
604 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0)
605 #ifndef OPENSSL_NO_COMP
606  if (result->ctx->comp_methods)
607  result->ctx->comp_methods = NULL;
608 #endif
609 #endif /* OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0) */
610 
611 #ifdef SSL_MODE_RELEASE_BUFFERS
612  SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
613 #endif
614  if (! is_client) {
615  if (result->my_link_cert &&
616  !SSL_CTX_use_certificate(result->ctx,
617  result->my_link_cert->cert)) {
618  goto error;
619  }
620  if (result->my_id_cert) {
621  X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
622  tor_assert(s);
623  X509_STORE_add_cert(s, result->my_id_cert->cert);
624  }
625  }
626  SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
627  if (!is_client) {
628  tor_assert(result->link_key);
629  if (!(pkey = crypto_pk_get_openssl_evp_pkey_(result->link_key,1)))
630  goto error;
631  if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
632  goto error;
633  EVP_PKEY_free(pkey);
634  pkey = NULL;
635  if (!SSL_CTX_check_private_key(result->ctx))
636  goto error;
637  }
638 
639  {
640  DH *dh = crypto_dh_new_openssl_tls();
641  tor_assert(dh);
642  SSL_CTX_set_tmp_dh(result->ctx, dh);
643  DH_free(dh);
644  }
645 /* We check for this function in two ways, since it might be either a symbol
646  * or a macro. */
647 #if defined(SSL_CTX_set1_groups_list) || defined(HAVE_SSL_CTX_SET1_GROUPS_LIST)
648  {
649  const char *list;
650  if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
651  list = "P-224:P-256";
652  else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
653  list = "P-256:P-224";
654  else
655  list = "P-256:P-224";
656  int r = (int) SSL_CTX_set1_groups_list(result->ctx, list);
657  if (r < 0)
658  goto error;
659  }
660 #else
661  if (! is_client) {
662  int nid;
663  EC_KEY *ec_key;
664  if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
665  nid = NID_secp224r1;
666  else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
667  nid = NID_X9_62_prime256v1;
668  else
669  nid = NID_tor_default_ecdhe_group;
670  /* Use P-256 for ECDHE. */
671  ec_key = EC_KEY_new_by_curve_name(nid);
672  if (ec_key != NULL) /*XXXX Handle errors? */
673  SSL_CTX_set_tmp_ecdh(result->ctx, ec_key);
674  EC_KEY_free(ec_key);
675  }
676 #endif
677  SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
678  always_accept_verify_cb);
679  /* let us realloc bufs that we're writing from */
680  SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
681 
682  return result;
683 
684  error:
685  tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
686  if (pkey)
687  EVP_PKEY_free(pkey);
688  tor_tls_context_decref(result);
689  return NULL;
690 }
691 
693 void
694 tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
695 {
696  /* LCOV_EXCL_START since this depends on whether debug is captured or not */
697  log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
698  ssl, SSL_state_string_long(ssl), type, val);
699  /* LCOV_EXCL_STOP */
700 }
701 
702 /* Return the name of the negotiated ciphersuite in use on <b>tls</b> */
703 const char *
704 tor_tls_get_ciphersuite_name(tor_tls_t *tls)
705 {
706  return SSL_get_cipher(tls->ssl);
707 }
708 
709 /* Here's the old V2 cipher list we sent from 0.2.1.1-alpha up to
710  * 0.2.3.17-beta. If a client is using this list, we can't believe the ciphers
711  * that it claims to support. We'll prune this list to remove the ciphers
712  * *we* don't recognize. */
713 STATIC uint16_t v2_cipher_list[] = {
714  0xc00a, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA */
715  0xc014, /* TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA */
716  0x0039, /* TLS1_TXT_DHE_RSA_WITH_AES_256_SHA */
717  0x0038, /* TLS1_TXT_DHE_DSS_WITH_AES_256_SHA */
718  0xc00f, /* TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA */
719  0xc005, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA */
720  0x0035, /* TLS1_TXT_RSA_WITH_AES_256_SHA */
721  0xc007, /* TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA */
722  0xc009, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA */
723  0xc011, /* TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA */
724  0xc013, /* TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA */
725  0x0033, /* TLS1_TXT_DHE_RSA_WITH_AES_128_SHA */
726  0x0032, /* TLS1_TXT_DHE_DSS_WITH_AES_128_SHA */
727  0xc00c, /* TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA */
728  0xc00e, /* TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA */
729  0xc002, /* TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA */
730  0xc004, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA */
731  0x0004, /* SSL3_TXT_RSA_RC4_128_MD5 */
732  0x0005, /* SSL3_TXT_RSA_RC4_128_SHA */
733  0x002f, /* TLS1_TXT_RSA_WITH_AES_128_SHA */
734  0xc008, /* TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA */
735  0xc012, /* TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA */
736  0x0016, /* SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA */
737  0x0013, /* SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA */
738  0xc00d, /* TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA */
739  0xc003, /* TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA */
740  0xfeff, /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA */
741  0x000a, /* SSL3_TXT_RSA_DES_192_CBC3_SHA */
742  0
743 };
745 static int v2_cipher_list_pruned = 0;
746 
749 int
750 find_cipher_by_id(const SSL *ssl, const SSL_METHOD *m, uint16_t cipher)
751 {
752  const SSL_CIPHER *c;
753 #ifdef HAVE_SSL_CIPHER_FIND
754  (void) m;
755  {
756  unsigned char cipherid[3];
757  tor_assert(ssl);
758  set_uint16(cipherid, tor_htons(cipher));
759  cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
760  * with a two-byte 'cipherid', it may look for a v2
761  * cipher with the appropriate 3 bytes. */
762  c = SSL_CIPHER_find((SSL*)ssl, cipherid);
763  if (c)
764  tor_assert((SSL_CIPHER_get_id(c) & 0xffff) == cipher);
765  return c != NULL;
766  }
767 #else /* !(defined(HAVE_SSL_CIPHER_FIND)) */
768 
769 # if defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR)
770  if (m && m->get_cipher_by_char) {
771  unsigned char cipherid[3];
772  set_uint16(cipherid, tor_htons(cipher));
773  cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
774  * with a two-byte 'cipherid', it may look for a v2
775  * cipher with the appropriate 3 bytes. */
776  c = m->get_cipher_by_char(cipherid);
777  if (c)
778  tor_assert((c->id & 0xffff) == cipher);
779  return c != NULL;
780  }
781 #endif /* defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR) */
782 # ifndef OPENSSL_1_1_API
783  if (m && m->get_cipher && m->num_ciphers) {
784  /* It would seem that some of the "let's-clean-up-openssl" forks have
785  * removed the get_cipher_by_char function. Okay, so now you get a
786  * quadratic search.
787  */
788  int i;
789  for (i = 0; i < m->num_ciphers(); ++i) {
790  c = m->get_cipher(i);
791  if (c && (c->id & 0xffff) == cipher) {
792  return 1;
793  }
794  }
795  return 0;
796  }
797 #endif /* !defined(OPENSSL_1_1_API) */
798  (void) ssl;
799  (void) m;
800  (void) cipher;
801  return 1; /* No way to search */
802 #endif /* defined(HAVE_SSL_CIPHER_FIND) */
803 }
804 
808 static void
809 prune_v2_cipher_list(const SSL *ssl)
810 {
811  uint16_t *inp, *outp;
812 #ifdef HAVE_TLS_METHOD
813  const SSL_METHOD *m = TLS_method();
814 #else
815  const SSL_METHOD *m = SSLv23_method();
816 #endif
817 
818  inp = outp = v2_cipher_list;
819  while (*inp) {
820  if (find_cipher_by_id(ssl, m, *inp)) {
821  *outp++ = *inp++;
822  } else {
823  inp++;
824  }
825  }
826  *outp = 0;
827 
828  v2_cipher_list_pruned = 1;
829 }
830 
835 int
836 tor_tls_classify_client_ciphers(const SSL *ssl,
837  STACK_OF(SSL_CIPHER) *peer_ciphers)
838 {
839  int i, res;
840  tor_tls_t *tor_tls;
841  if (PREDICT_UNLIKELY(!v2_cipher_list_pruned))
842  prune_v2_cipher_list(ssl);
843 
844  tor_tls = tor_tls_get_by_ssl(ssl);
845  if (tor_tls && tor_tls->client_cipher_list_type)
846  return tor_tls->client_cipher_list_type;
847 
848  /* If we reached this point, we just got a client hello. See if there is
849  * a cipher list. */
850  if (!peer_ciphers) {
851  log_info(LD_NET, "No ciphers on session");
852  res = CIPHERS_ERR;
853  goto done;
854  }
855  /* Now we need to see if there are any ciphers whose presence means we're
856  * dealing with an updated Tor. */
857  for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
858  const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
859  const char *ciphername = SSL_CIPHER_get_name(cipher);
860  if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
861  strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
862  strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
863  strcmp(ciphername, "(NONE)")) {
864  log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
865  // return 1;
866  goto v2_or_higher;
867  }
868  }
869  res = CIPHERS_V1;
870  goto done;
871  v2_or_higher:
872  {
873  const uint16_t *v2_cipher = v2_cipher_list;
874  for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
875  const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
876  uint16_t id = SSL_CIPHER_get_id(cipher) & 0xffff;
877  if (id == 0x00ff) /* extended renegotiation indicator. */
878  continue;
879  if (!id || id != *v2_cipher) {
880  res = CIPHERS_UNRESTRICTED;
881  goto dump_ciphers;
882  }
883  ++v2_cipher;
884  }
885  if (*v2_cipher != 0) {
886  res = CIPHERS_UNRESTRICTED;
887  goto dump_ciphers;
888  }
889  res = CIPHERS_V2;
890  }
891 
892  dump_ciphers:
893  {
894  smartlist_t *elts = smartlist_new();
895  char *s;
896  for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
897  const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
898  const char *ciphername = SSL_CIPHER_get_name(cipher);
899  smartlist_add(elts, (char*)ciphername);
900  }
901  s = smartlist_join_strings(elts, ":", 0, NULL);
902  log_debug(LD_NET, "Got a %s V2/V3 cipher list from %s. It is: '%s'",
903  (res == CIPHERS_V2) ? "fictitious" : "real", ADDR(tor_tls), s);
904  tor_free(s);
905  smartlist_free(elts);
906  }
907  done:
908  if (tor_tls)
909  return tor_tls->client_cipher_list_type = res;
910 
911  return res;
912 }
913 
917 int
918 tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
919 {
920  STACK_OF(SSL_CIPHER) *ciphers;
921 #ifdef HAVE_SSL_GET_CLIENT_CIPHERS
922  ciphers = SSL_get_client_ciphers(ssl);
923 #else
924  SSL_SESSION *session;
925  if (!(session = SSL_get_session((SSL *)ssl))) {
926  log_info(LD_NET, "No session on TLS?");
927  return CIPHERS_ERR;
928  }
929  ciphers = session->ciphers;
930 #endif /* defined(HAVE_SSL_GET_CLIENT_CIPHERS) */
931 
932  return tor_tls_classify_client_ciphers(ssl, ciphers) >= CIPHERS_V2;
933 }
934 
941 void
942 tor_tls_server_info_callback(const SSL *ssl, int type, int val)
943 {
944  tor_tls_t *tls;
945  (void) val;
946 
947  IF_BUG_ONCE(ssl == NULL) {
948  return; // LCOV_EXCL_LINE
949  }
950 
951  tor_tls_debug_state_callback(ssl, type, val);
952 
953  if (type != SSL_CB_ACCEPT_LOOP)
954  return;
955 
956  OSSL_HANDSHAKE_STATE ssl_state = SSL_get_state(ssl);
957  if (! STATE_IS_SW_SERVER_HELLO(ssl_state))
958  return;
959  tls = tor_tls_get_by_ssl(ssl);
960  if (tls) {
961  /* Check whether we're watching for renegotiates. If so, this is one! */
962  if (tls->negotiated_callback)
963  tls->got_renegotiate = 1;
964  } else {
965  log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
966  return;
967  }
968 
969  /* Now check the cipher list. */
970  if (tor_tls_client_is_using_v2_ciphers(ssl)) {
971  if (tls->wasV2Handshake)
972  return; /* We already turned this stuff off for the first handshake;
973  * This is a renegotiation. */
974 
975  /* Yes, we're casting away the const from ssl. This is very naughty of us.
976  * Let's hope openssl doesn't notice! */
977 
978  /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
979  SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
980  /* Don't send a hello request. */
981  SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
982 
983  if (tls) {
984  tls->wasV2Handshake = 1;
985  } else {
986  /* LCOV_EXCL_START this line is not reachable */
987  log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
988  /* LCOV_EXCL_STOP */
989  }
990  }
991 }
992 
1005 int
1006 tor_tls_session_secret_cb(SSL *ssl, void *secret, int *secret_len,
1007  STACK_OF(SSL_CIPHER) *peer_ciphers,
1008  CONST_IF_OPENSSL_1_1_API SSL_CIPHER **cipher,
1009  void *arg)
1010 {
1011  (void) secret;
1012  (void) secret_len;
1013  (void) peer_ciphers;
1014  (void) cipher;
1015  (void) arg;
1016 
1017  if (tor_tls_classify_client_ciphers(ssl, peer_ciphers) ==
1018  CIPHERS_UNRESTRICTED) {
1019  SSL_set_cipher_list(ssl, UNRESTRICTED_SERVER_CIPHER_LIST);
1020  }
1021 
1022  SSL_set_session_secret_cb(ssl, NULL, NULL);
1023 
1024  return 0;
1025 }
1026 static void
1027 tor_tls_setup_session_secret_cb(tor_tls_t *tls)
1028 {
1029  SSL_set_session_secret_cb(tls->ssl, tor_tls_session_secret_cb, NULL);
1030 }
1031 
1035 tor_tls_t *
1036 tor_tls_new(tor_socket_t sock, int isServer)
1037 {
1038  BIO *bio = NULL;
1039  tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
1040  tor_tls_context_t *context = tor_tls_context_get(isServer);
1041  result->magic = TOR_TLS_MAGIC;
1042 
1043  check_no_tls_errors();
1044  tor_assert(context); /* make sure somebody made it first */
1045  if (!(result->ssl = SSL_new(context->ctx))) {
1046  tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
1047  tor_free(result);
1048  goto err;
1049  }
1050 
1051 #ifdef SSL_set_tlsext_host_name
1052  /* Browsers use the TLS hostname extension, so we should too. */
1053  if (!isServer) {
1054  char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
1055  SSL_set_tlsext_host_name(result->ssl, fake_hostname);
1056  tor_free(fake_hostname);
1057  }
1058 #endif /* defined(SSL_set_tlsext_host_name) */
1059 
1060 #ifdef SSL_CTRL_SET_MAX_PROTO_VERSION
1061  if (openssl_bug_7712_is_present) {
1062  /* We can't actually use TLS 1.3 until this bug is fixed. */
1063  SSL_set_max_proto_version(result->ssl, TLS1_2_VERSION);
1064  }
1065 #endif
1066 
1067  if (!SSL_set_cipher_list(result->ssl,
1068  isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
1069  tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
1070 #ifdef SSL_set_tlsext_host_name
1071  SSL_set_tlsext_host_name(result->ssl, NULL);
1072 #endif
1073  SSL_free(result->ssl);
1074  tor_free(result);
1075  goto err;
1076  }
1077  result->socket = sock;
1078  bio = BIO_new_socket(sock, BIO_CLOSE);
1079  if (! bio) {
1080  tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
1081 #ifdef SSL_set_tlsext_host_name
1082  SSL_set_tlsext_host_name(result->ssl, NULL);
1083 #endif
1084  SSL_free(result->ssl);
1085  tor_free(result);
1086  goto err;
1087  }
1088  {
1089  int set_worked =
1090  SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
1091  if (!set_worked) {
1092  log_warn(LD_BUG,
1093  "Couldn't set the tls for an SSL*; connection will fail");
1094  }
1095  }
1096  SSL_set_bio(result->ssl, bio, bio);
1097  tor_tls_context_incref(context);
1098  result->context = context;
1099  result->state = TOR_TLS_ST_HANDSHAKE;
1100  result->isServer = isServer;
1101  result->wantwrite_n = 0;
1102  result->last_write_count = (unsigned long) BIO_number_written(bio);
1103  result->last_read_count = (unsigned long) BIO_number_read(bio);
1104  if (result->last_write_count || result->last_read_count) {
1105  log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
1106  result->last_read_count, result->last_write_count);
1107  }
1108  if (isServer) {
1109  SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
1110  } else {
1111  SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
1112  }
1113 
1114  if (isServer)
1115  tor_tls_setup_session_secret_cb(result);
1116 
1117  goto done;
1118  err:
1119  result = NULL;
1120  done:
1121  /* Not expected to get called. */
1122  tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
1123  return result;
1124 }
1125 
1130 void
1132  void (*cb)(tor_tls_t *, void *arg),
1133  void *arg)
1134 {
1135  tls->negotiated_callback = cb;
1136  tls->callback_arg = arg;
1137  tls->got_renegotiate = 0;
1138  if (cb) {
1139  SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
1140  } else {
1141  SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
1142  }
1143 }
1144 
1148 void
1150 {
1151  /* Yes, we know what we are doing here. No, we do not treat a renegotiation
1152  * as authenticating any earlier-received data. */
1153  SSL_set_options(tls->ssl,
1154  SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
1155 }
1156 
1161 void
1163 {
1164 #ifdef SUPPORT_UNSAFE_RENEGOTIATION_FLAG
1165  tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
1166 #else
1167  (void) tls;
1168 #endif
1169 }
1170 
1172 void
1174 {
1175 #if defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) && \
1176  SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION != 0
1177  long options = SSL_get_options(tls->ssl);
1178  tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
1179 #else
1180  (void) tls;
1181 #endif /* defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) && ... */
1182 }
1183 
1188 void
1190 {
1191  if (! tls)
1192  return;
1193 
1194  BIO *rbio, *wbio;
1195  rbio = SSL_get_rbio(tls->ssl);
1196  wbio = SSL_get_wbio(tls->ssl);
1197 
1198  if (rbio) {
1199  (void) BIO_set_close(rbio, BIO_NOCLOSE);
1200  }
1201  if (wbio && wbio != rbio) {
1202  (void) BIO_set_close(wbio, BIO_NOCLOSE);
1203  }
1204 }
1205 
1206 void
1207 tor_tls_impl_free_(tor_tls_impl_t *ssl)
1208 {
1209  if (!ssl)
1210  return;
1211 
1212 #ifdef SSL_set_tlsext_host_name
1213  SSL_set_tlsext_host_name(ssl, NULL);
1214 #endif
1215  SSL_free(ssl);
1216 }
1217 
1223 MOCK_IMPL(int,
1224 tor_tls_read,(tor_tls_t *tls, char *cp, size_t len))
1225 {
1226  int r, err;
1227  tor_assert(tls);
1228  tor_assert(tls->ssl);
1229  tor_assert(tls->state == TOR_TLS_ST_OPEN);
1230  tor_assert(len<INT_MAX);
1231  r = SSL_read(tls->ssl, cp, (int)len);
1232  if (r > 0) {
1233  if (tls->got_renegotiate) {
1234  /* Renegotiation happened! */
1235  log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
1236  if (tls->negotiated_callback)
1237  tls->negotiated_callback(tls, tls->callback_arg);
1238  tls->got_renegotiate = 0;
1239  }
1240  return r;
1241  }
1242  err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
1243  if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) {
1244  log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
1245  tls->state = TOR_TLS_ST_CLOSED;
1246  return TOR_TLS_CLOSE;
1247  } else {
1248  tor_assert(err != TOR_TLS_DONE);
1249  log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
1250  return err;
1251  }
1252 }
1253 
1256 STATIC uint64_t total_bytes_written_over_tls = 0;
1259 STATIC uint64_t total_bytes_written_by_tls = 0;
1260 
1266 int
1267 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
1268 {
1269  int r, err;
1270  tor_assert(tls);
1271  tor_assert(tls->ssl);
1272  tor_assert(tls->state == TOR_TLS_ST_OPEN);
1273  tor_assert(n < INT_MAX);
1274  if (n == 0)
1275  return 0;
1276  if (tls->wantwrite_n) {
1277  /* if WANTWRITE last time, we must use the _same_ n as before */
1278  tor_assert(n >= tls->wantwrite_n);
1279  log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
1280  (int)n, (int)tls->wantwrite_n);
1281  n = tls->wantwrite_n;
1282  tls->wantwrite_n = 0;
1283  }
1284  r = SSL_write(tls->ssl, cp, (int)n);
1285  err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
1286  if (err == TOR_TLS_DONE) {
1287  total_bytes_written_over_tls += r;
1288  return r;
1289  }
1290  if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
1291  tls->wantwrite_n = n;
1292  }
1293  return err;
1294 }
1295 
1300 int
1302 {
1303  int r;
1304  tor_assert(tls);
1305  tor_assert(tls->ssl);
1306  tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
1307 
1308  check_no_tls_errors();
1309 
1310  OSSL_HANDSHAKE_STATE oldstate = SSL_get_state(tls->ssl);
1311 
1312  if (tls->isServer) {
1313  log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
1314  SSL_state_string_long(tls->ssl));
1315  r = SSL_accept(tls->ssl);
1316  } else {
1317  log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
1318  SSL_state_string_long(tls->ssl));
1319  r = SSL_connect(tls->ssl);
1320  }
1321 
1322  OSSL_HANDSHAKE_STATE newstate = SSL_get_state(tls->ssl);
1323 
1324  if (oldstate != newstate)
1325  log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
1326  tls, SSL_state_string_long(tls->ssl));
1327  /* We need to call this here and not earlier, since OpenSSL has a penchant
1328  * for clearing its flags when you say accept or connect. */
1330  r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
1331  if (ERR_peek_error() != 0) {
1333  "handshaking");
1334  return TOR_TLS_ERROR_MISC;
1335  }
1336  if (r == TOR_TLS_DONE) {
1337  tls->state = TOR_TLS_ST_OPEN;
1338  return tor_tls_finish_handshake(tls);
1339  }
1340  return r;
1341 }
1342 
1351 int
1353 {
1354  int r = TOR_TLS_DONE;
1355  check_no_tls_errors();
1356  if (tls->isServer) {
1357  SSL_set_info_callback(tls->ssl, NULL);
1358  SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
1359  SSL_clear_mode(tls->ssl, SSL_MODE_NO_AUTO_CHAIN);
1360  if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
1361  /* This check is redundant, but back when we did it in the callback,
1362  * we might have not been able to look up the tor_tls_t if the code
1363  * was buggy. Fixing that. */
1364  if (!tls->wasV2Handshake) {
1365  log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
1366  " get set. Fixing that.");
1367  }
1368  tls->wasV2Handshake = 1;
1369  log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
1370  " for renegotiation.");
1371  } else {
1372  tls->wasV2Handshake = 0;
1373  }
1374  } else {
1375  /* Client-side */
1376  tls->wasV2Handshake = 1;
1377  /* XXXX this can move, probably? -NM */
1378  if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
1379  tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
1380  r = TOR_TLS_ERROR_MISC;
1381  }
1382  }
1383  tls_log_errors(NULL, LOG_WARN, LD_NET, "finishing the handshake");
1384  return r;
1385 }
1386 
1389 int
1391 {
1392  X509 *cert;
1393  cert = SSL_get_peer_certificate(tls->ssl);
1394  tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
1395  if (!cert)
1396  return 0;
1397  X509_free(cert);
1398  return 1;
1399 }
1400 
1403 MOCK_IMPL(tor_x509_cert_t *,
1404 tor_tls_get_peer_cert,(tor_tls_t *tls))
1405 {
1406  X509 *cert;
1407  cert = SSL_get_peer_certificate(tls->ssl);
1408  tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
1409  if (!cert)
1410  return NULL;
1411  return tor_x509_cert_new(cert);
1412 }
1413 
1416 MOCK_IMPL(tor_x509_cert_t *,
1417 tor_tls_get_own_cert,(tor_tls_t *tls))
1418 {
1419  X509 *cert = SSL_get_certificate(tls->ssl);
1421  "getting own-connection certificate");
1422  if (!cert)
1423  return NULL;
1424  /* Fun inconsistency: SSL_get_peer_certificate increments the reference
1425  * count, but SSL_get_certificate does not. */
1426  X509 *duplicate = X509_dup(cert);
1427  if (BUG(duplicate == NULL))
1428  return NULL;
1429  return tor_x509_cert_new(duplicate);
1430 }
1431 
1438 MOCK_IMPL(void,
1439 try_to_extract_certs_from_tls,(int severity, tor_tls_t *tls,
1440  X509 **cert_out, X509 **id_cert_out))
1441 {
1442  X509 *cert = NULL, *id_cert = NULL;
1443  STACK_OF(X509) *chain = NULL;
1444  int num_in_chain, i;
1445  *cert_out = *id_cert_out = NULL;
1446  if (!(cert = SSL_get_peer_certificate(tls->ssl)))
1447  return;
1448  *cert_out = cert;
1449  if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
1450  return;
1451  num_in_chain = sk_X509_num(chain);
1452  /* 1 means we're receiving (server-side), and it's just the id_cert.
1453  * 2 means we're connecting (client-side), and it's both the link
1454  * cert and the id_cert.
1455  */
1456  if (num_in_chain < 1) {
1457  log_fn(severity,LD_PROTOCOL,
1458  "Unexpected number of certificates in chain (%d)",
1459  num_in_chain);
1460  return;
1461  }
1462  for (i=0; i<num_in_chain; ++i) {
1463  id_cert = sk_X509_value(chain, i);
1464  if (X509_cmp(id_cert, cert) != 0)
1465  break;
1466  }
1467  *id_cert_out = id_cert ? X509_dup(id_cert) : NULL;
1468 }
1469 
1472 int
1474 {
1475  tor_assert(tls);
1476  return SSL_pending(tls->ssl);
1477 }
1478 
1481 size_t
1483 {
1484  return tls->wantwrite_n;
1485 }
1486 
1490 void
1491 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
1492 {
1493  BIO *wbio, *tmpbio;
1494  unsigned long r, w;
1495  r = (unsigned long) BIO_number_read(SSL_get_rbio(tls->ssl));
1496  /* We want the number of bytes actually for real written. Unfortunately,
1497  * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
1498  * which makes the answer turn out wrong. Let's cope with that. Note
1499  * that this approach will fail if we ever replace tls->ssl's BIOs with
1500  * buffering bios for reasons of our own. As an alternative, we could
1501  * save the original BIO for tls->ssl in the tor_tls_t structure, but
1502  * that would be tempting fate. */
1503  wbio = SSL_get_wbio(tls->ssl);
1504 #if OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)
1505  /* BIO structure is opaque as of OpenSSL 1.1.0-pre5-dev. Again, not
1506  * supposed to use this form of the version macro, but the OpenSSL developers
1507  * introduced major API changes in the pre-release stage.
1508  */
1509  if (BIO_method_type(wbio) == BIO_TYPE_BUFFER &&
1510  (tmpbio = BIO_next(wbio)) != NULL)
1511  wbio = tmpbio;
1512 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)) */
1513  if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
1514  wbio = tmpbio;
1515 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5) */
1516  w = (unsigned long) BIO_number_written(wbio);
1517 
1518  /* We are ok with letting these unsigned ints go "negative" here:
1519  * If we wrapped around, this should still give us the right answer, unless
1520  * we wrapped around by more than ULONG_MAX since the last time we called
1521  * this function.
1522  */
1523  *n_read = (size_t)(r - tls->last_read_count);
1524  *n_written = (size_t)(w - tls->last_write_count);
1525  if (*n_read > INT_MAX || *n_written > INT_MAX) {
1526  log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
1527  "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
1528  r, tls->last_read_count, w, tls->last_write_count);
1529  }
1530  total_bytes_written_by_tls += *n_written;
1531  tls->last_read_count = r;
1532  tls->last_write_count = w;
1533 }
1534 
1537 MOCK_IMPL(double,
1538 tls_get_write_overhead_ratio,(void))
1539 {
1540  if (total_bytes_written_over_tls == 0)
1541  return 1.0;
1542 
1543  return ((double)total_bytes_written_by_tls) /
1544  ((double)total_bytes_written_over_tls);
1545 }
1546 
1549 void
1550 check_no_tls_errors_(const char *fname, int line)
1551 {
1552  if (ERR_peek_error() == 0)
1553  return;
1554  log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1555  tor_fix_source_file(fname), line);
1556  tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
1557 }
1558 
1561 int
1563 {
1564  return ! tls->wasV2Handshake;
1565 }
1566 
1569 int
1571 {
1572  return tls->got_renegotiate;
1573 }
1574 
1575 #ifndef HAVE_SSL_GET_CLIENT_RANDOM
1576 static size_t
1577 SSL_get_client_random(SSL *s, uint8_t *out, size_t len)
1578 {
1579  if (len == 0)
1580  return SSL3_RANDOM_SIZE;
1581  tor_assert(len == SSL3_RANDOM_SIZE);
1582  tor_assert(s->s3);
1583  memcpy(out, s->s3->client_random, len);
1584  return len;
1585 }
1586 #endif /* !defined(HAVE_SSL_GET_CLIENT_RANDOM) */
1587 
1588 #ifndef HAVE_SSL_GET_SERVER_RANDOM
1589 static size_t
1590 SSL_get_server_random(SSL *s, uint8_t *out, size_t len)
1591 {
1592  if (len == 0)
1593  return SSL3_RANDOM_SIZE;
1594  tor_assert(len == SSL3_RANDOM_SIZE);
1595  tor_assert(s->s3);
1596  memcpy(out, s->s3->server_random, len);
1597  return len;
1598 }
1599 #endif /* !defined(HAVE_SSL_GET_SERVER_RANDOM) */
1600 
1601 #ifndef HAVE_SSL_SESSION_GET_MASTER_KEY
1602 size_t
1603 SSL_SESSION_get_master_key(SSL_SESSION *s, uint8_t *out, size_t len)
1604 {
1605  tor_assert(s);
1606  if (len == 0)
1607  return s->master_key_length;
1608  tor_assert(len == (size_t)s->master_key_length);
1609  tor_assert(out);
1610  memcpy(out, s->master_key, len);
1611  return len;
1612 }
1613 #endif /* !defined(HAVE_SSL_SESSION_GET_MASTER_KEY) */
1614 
1619 MOCK_IMPL(int,
1620 tor_tls_get_tlssecrets,(tor_tls_t *tls, uint8_t *secrets_out))
1621 {
1622 #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
1623  uint8_t buf[128];
1624  size_t len;
1625  tor_assert(tls);
1626 
1627  SSL *const ssl = tls->ssl;
1628  SSL_SESSION *const session = SSL_get_session(ssl);
1629 
1630  tor_assert(ssl);
1631  tor_assert(session);
1632 
1633  const size_t server_random_len = SSL_get_server_random(ssl, NULL, 0);
1634  const size_t client_random_len = SSL_get_client_random(ssl, NULL, 0);
1635  const size_t master_key_len = SSL_SESSION_get_master_key(session, NULL, 0);
1636 
1637  tor_assert(server_random_len);
1638  tor_assert(client_random_len);
1639  tor_assert(master_key_len);
1640 
1641  len = client_random_len + server_random_len + strlen(TLSSECRET_MAGIC) + 1;
1642  tor_assert(len <= sizeof(buf));
1643 
1644  {
1645  size_t r = SSL_get_client_random(ssl, buf, client_random_len);
1646  tor_assert(r == client_random_len);
1647  }
1648 
1649  {
1650  size_t r = SSL_get_server_random(ssl,
1651  buf+client_random_len,
1652  server_random_len);
1653  tor_assert(r == server_random_len);
1654  }
1655 
1656  uint8_t *master_key = tor_malloc_zero(master_key_len);
1657  {
1658  size_t r = SSL_SESSION_get_master_key(session, master_key, master_key_len);
1659  tor_assert(r == master_key_len);
1660  }
1661 
1662  uint8_t *nextbuf = buf + client_random_len + server_random_len;
1663  memcpy(nextbuf, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
1664 
1665  /*
1666  The value is an HMAC, using the TLS master key as the HMAC key, of
1667  client_random | server_random | TLSSECRET_MAGIC
1668  */
1669  crypto_hmac_sha256((char*)secrets_out,
1670  (char*)master_key,
1671  master_key_len,
1672  (char*)buf, len);
1673  memwipe(buf, 0, sizeof(buf));
1674  memwipe(master_key, 0, master_key_len);
1675  tor_free(master_key);
1676 
1677  return 0;
1678 }
1679 
1687 MOCK_IMPL(int,
1688 tor_tls_export_key_material,(tor_tls_t *tls, uint8_t *secrets_out,
1689  const uint8_t *context,
1690  size_t context_len,
1691  const char *label))
1692 {
1693  tor_assert(tls);
1694  tor_assert(tls->ssl);
1695 
1696  int r = SSL_export_keying_material(tls->ssl,
1697  secrets_out, DIGEST256_LEN,
1698  label, strlen(label),
1699  context, context_len, 1);
1700 
1701  if (r != 1) {
1702  int severity = openssl_bug_7712_is_present ? LOG_WARN : LOG_DEBUG;
1703  tls_log_errors(tls, severity, LD_NET, "exporting keying material");
1704  }
1705 
1706 #ifdef TLS1_3_VERSION
1707  if (r != 1 &&
1708  strlen(label) > 12 &&
1709  SSL_version(tls->ssl) >= TLS1_3_VERSION) {
1710 
1711  if (! openssl_bug_7712_is_present) {
1712  /* We might have run into OpenSSL issue 7712, which caused OpenSSL
1713  * 1.1.1a to not handle long labels. Let's test to see if we have.
1714  */
1715  r = SSL_export_keying_material(tls->ssl, secrets_out, DIGEST256_LEN,
1716  "short", 5, context, context_len, 1);
1717  if (r == 1) {
1718  /* A short label succeeds, but a long label fails. This was openssl
1719  * issue 7712. */
1720  openssl_bug_7712_is_present = 1;
1721  log_warn(LD_GENERAL, "Detected OpenSSL bug 7712: disabling TLS 1.3 on "
1722  "future connections. A fix is expected to appear in OpenSSL "
1723  "1.1.1b.");
1724  }
1725  }
1726  if (openssl_bug_7712_is_present)
1727  return -2;
1728  else
1729  return -1;
1730  }
1731 #endif
1732 
1733  return (r == 1) ? 0 : -1;
1734 }
1735 
1743 int
1745  size_t *rbuf_capacity, size_t *rbuf_bytes,
1746  size_t *wbuf_capacity, size_t *wbuf_bytes)
1747 {
1748 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)
1749  (void)tls;
1750  (void)rbuf_capacity;
1751  (void)rbuf_bytes;
1752  (void)wbuf_capacity;
1753  (void)wbuf_bytes;
1754 
1755  return -1;
1756 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)) */
1757  if (tls->ssl->s3->rbuf.buf)
1758  *rbuf_capacity = tls->ssl->s3->rbuf.len;
1759  else
1760  *rbuf_capacity = 0;
1761  if (tls->ssl->s3->wbuf.buf)
1762  *wbuf_capacity = tls->ssl->s3->wbuf.len;
1763  else
1764  *wbuf_capacity = 0;
1765  *rbuf_bytes = tls->ssl->s3->rbuf.left;
1766  *wbuf_bytes = tls->ssl->s3->wbuf.left;
1767  return 0;
1768 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
1769 }
1770 
1774 int
1775 evaluate_ecgroup_for_tls(const char *ecgroup)
1776 {
1777  EC_KEY *ec_key;
1778  int nid;
1779  int ret;
1780 
1781  if (!ecgroup)
1782  nid = NID_tor_default_ecdhe_group;
1783  else if (!strcasecmp(ecgroup, "P256"))
1784  nid = NID_X9_62_prime256v1;
1785  else if (!strcasecmp(ecgroup, "P224"))
1786  nid = NID_secp224r1;
1787  else
1788  return 0;
1789 
1790  ec_key = EC_KEY_new_by_curve_name(nid);
1791  ret = (ec_key != NULL);
1792  EC_KEY_free(ec_key);
1793 
1794  return ret;
1795 }
char * address
Definition: tortls_st.h:39
void tor_tls_block_renegotiation(tor_tls_t *tls)
Definition: tortls_nss.c:588
tor_socket_t socket
Definition: tortls_st.h:37
tor_tls_context_t * tor_tls_context_get(int is_server)
Definition: tortls.c:40
unsigned int got_renegotiate
Definition: tortls_st.h:50
Common functions for using (pseudo-)random number generators.
Header for printf.c.
Headers for crypto_dh.c.
Header for smartlist.c.
Headers for di_ops.c.
unsigned int wasV2Handshake
Definition: tortls_st.h:44
int evaluate_ecgroup_for_tls(const char *ecgroup)
Definition: tortls_nss.c:765
Headers for crypto_cipher.c.
static void set_uint16(void *cp, uint16_t v)
Definition: bytes.h:73
#define LD_GENERAL
Definition: log.h:58
Macro definitions for MIN, MAX, and CLAMP.
struct dh_st * crypto_dh_new_openssl_tls(void)
#define LOG_INFO
Definition: log.h:41
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:631
void tor_tls_init(void)
Definition: tortls_nss.c:324
void smartlist_add(smartlist_t *sl, void *element)
int tor_tls_get_buffer_sizes(tor_tls_t *tls, size_t *rbuf_capacity, size_t *rbuf_bytes, size_t *wbuf_capacity, size_t *wbuf_bytes)
Definition: tortls_nss.c:642
tor_tls_t * tor_tls_new(tor_socket_t sock, int is_server)
Definition: tortls_nss.c:364
Header for time_fmt.c.
#define tor_free(p)
Definition: malloc.h:52
void tor_tls_context_decref(tor_tls_context_t *ctx)
Definition: tortls.c:114
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:57
void crypto_hmac_sha256(char *hmac_out, const char *key, size_t key_len, const char *msg, size_t msg_len)
int tor_errno_to_tls_error(int e)
Definition: tortls.c:48
unsigned int isServer
Definition: tortls_st.h:43
int tor_tls_server_got_renegotiate(tor_tls_t *tls)
Definition: tortls_nss.c:674
#define DIGEST256_LEN
Definition: digest_sizes.h:23
void tor_tls_release_socket(tor_tls_t *tls)
Definition: tortls_nss.c:429
Common functions for cryptographic routines.
tor_assert(buffer)
void tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
Definition: tortls_nss.c:595
void tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
Definition: tortls_nss.c:314
int tor_tls_used_v1_handshake(tor_tls_t *tls)
Definition: tortls_nss.c:665
void tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
Definition: tortls_nss.c:330
int tor_tls_context_init_certificates(tor_tls_context_t *result, crypto_pk_t *identity, unsigned key_lifetime, unsigned flags)
Definition: tortls.c:287
#define LD_HANDSHAKE
Definition: log.h:97
#define LOG_WARN
Definition: log.h:49
#define tor_socket_t
Definition: nettypes.h:36
Headers for tortls.c.
void tor_tls_unblock_renegotiation(tor_tls_t *tls)
Definition: tortls_nss.c:581
void tor_tls_set_renegotiate_callback(tor_tls_t *tls, void(*cb)(tor_tls_t *, void *arg), void *arg)
Definition: tortls_nss.c:413
int tor_tls_handshake(tor_tls_t *tls)
Definition: tortls_nss.c:554
int tor_tls_finish_handshake(tor_tls_t *tls)
Definition: tortls_nss.c:572
tor_tls_impl_t * ssl
Definition: tortls_st.h:36
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
#define IF_BUG_ONCE(cond)
Definition: util_bug.h:214
Inline functions for reading and writing multibyte values from the middle of strings, and for manipulating byte order.
tor_tls_state_bitfield_t state
Definition: tortls_st.h:40
int tor_tls_peer_has_cert(tor_tls_t *tls)
Definition: tortls_nss.c:477
#define log_fn(severity, domain, args,...)
Definition: log.h:255
Header for compat_string.c.
size_t tor_tls_get_forced_write_size(tor_tls_t *tls)
Definition: tortls_nss.c:614
int tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
Definition: tortls_nss.c:530
#define LOG_DEBUG
Definition: log.h:38
void tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
Definition: tortls_nss.c:622
#define LD_NET
Definition: log.h:62
Headers for log.c.
Header for socket.c.
int tor_tls_get_pending_bytes(tor_tls_t *tls)
Definition: tortls_nss.c:602
void tor_tls_context_incref(tor_tls_context_t *ctx)
Definition: tortls.c:106
#define LD_CRYPTO
Definition: log.h:60
Macros to manage assertions, fatal and non-fatal.
#define LD_PROTOCOL
Definition: log.h:68
char * crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix, const char *suffix)
Definition: crypto_rand.c:551
#define LD_BUG
Definition: log.h:82