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