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