Tor 0.4.9.2-alpha-dev
All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
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. */
40DISABLE_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
57ENABLE_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"
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/** Set to true iff openssl bug 7712 has been detected. */
84static int openssl_bug_7712_is_present = 0;
85
86/** The ex_data index in which we store a pointer to an SSL object's
87 * corresponding tor_tls_t object. */
88STATIC int tor_tls_object_ex_data_index = -1;
89
90/** Helper: Allocate tor_tls_object_ex_data_index. */
91void
92tor_tls_allocate_tor_tls_object_ex_data_index(void)
93{
94 if (tor_tls_object_ex_data_index == -1) {
95 tor_tls_object_ex_data_index =
96 SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
97 tor_assert(tor_tls_object_ex_data_index != -1);
98 }
99}
100
101/** Helper: given a SSL* pointer, return the tor_tls_t object using that
102 * pointer. */
103tor_tls_t *
104tor_tls_get_by_ssl(const SSL *ssl)
105{
106 tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
107 if (result)
108 tor_assert(result->magic == TOR_TLS_MAGIC);
109 return result;
110}
111
112/** True iff tor_tls_init() has been called. */
113static int tls_library_is_initialized = 0;
114
115/* Module-internal error codes. */
116#define TOR_TLS_SYSCALL_ (MIN_TOR_TLS_ERROR_VAL_ - 2)
117#define TOR_TLS_ZERORETURN_ (MIN_TOR_TLS_ERROR_VAL_ - 1)
118
119/** Write a description of the current state of <b>tls</b> into the
120 * <b>sz</b>-byte buffer at <b>buf</b>. */
121void
122tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
123{
124 const char *ssl_state;
125 const char *tortls_state;
126
127 if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
128 strlcpy(buf, "(No SSL object)", sz);
129 return;
130 }
131
132 ssl_state = SSL_state_string_long(tls->ssl);
133 switch (tls->state) {
134#define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
135 CASE(HANDSHAKE);
136 CASE(OPEN);
137 CASE(GOTCLOSE);
138 CASE(SENTCLOSE);
139 CASE(CLOSED);
140 CASE(RENEGOTIATE);
141#undef CASE
142 case TOR_TLS_ST_BUFFEREVENT:
143 tortls_state = "";
144 break;
145 default:
146 tortls_state = " in unknown TLS state";
147 break;
148 }
149
150 tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
151}
152
153/** Log a single error <b>err</b> as returned by ERR_get_error(), which was
154 * received while performing an operation <b>doing</b> on <b>tls</b>. Log
155 * the message at <b>severity</b>, in log domain <b>domain</b>. */
156void
157tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
158 int severity, int domain, const char *doing)
159{
160 const char *state = NULL, *addr;
161 const char *msg, *lib, *func;
162
163 state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
164
165 addr = tls ? tls->address : NULL;
166
167 /* Some errors are known-benign, meaning they are the fault of the other
168 * side of the connection. The caller doesn't know this, so override the
169 * priority for those cases. */
170 switch (ERR_GET_REASON(err)) {
171 case SSL_R_HTTP_REQUEST:
172 case SSL_R_HTTPS_PROXY_REQUEST:
173 case SSL_R_RECORD_LENGTH_MISMATCH:
174 case SSL_R_UNKNOWN_PROTOCOL:
175 case SSL_R_UNSUPPORTED_PROTOCOL:
176 severity = LOG_INFO;
177 break;
178 default:
179 break;
180 }
181
182 msg = (const char*)ERR_reason_error_string(err);
183 lib = (const char*)ERR_lib_error_string(err);
184 func = (const char*)ERR_func_error_string(err);
185 if (!msg) msg = "(null)";
186 if (!lib) lib = "(null)";
187 if (!func) func = "(null)";
188 if (doing) {
189 tor_log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
190 doing, addr?" with ":"", addr?addr:"",
191 msg, lib, func, state);
192 } else {
193 tor_log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
194 addr?" with ":"", addr?addr:"",
195 msg, lib, func, state);
196 }
197}
198
199/** Log all pending tls errors at level <b>severity</b> in log domain
200 * <b>domain</b>. Use <b>doing</b> to describe our current activities.
201 */
202void
203tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
204{
205 unsigned long err;
206
207 while ((err = ERR_get_error()) != 0) {
208 if (tls)
209 tls->last_error = err;
210 tor_tls_log_one_error(tls, err, severity, domain, doing);
211 }
212}
213
214/**
215 * Return a string representing more detail about the last error received
216 * on TLS.
217 *
218 * May return null if no error was found.
219 **/
220const char *
222{
223 IF_BUG_ONCE(!tls) {
224 return NULL;
225 }
226 if (tls->last_error == 0) {
227 return NULL;
228 }
229 return (const char*)ERR_reason_error_string(tls->last_error);
230}
231
232#define CATCH_SYSCALL 1
233#define CATCH_ZERO 2
234
235/** Given a TLS object and the result of an SSL_* call, use
236 * SSL_get_error to determine whether an error has occurred, and if so
237 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
238 * If extra&CATCH_SYSCALL is true, return TOR_TLS_SYSCALL_ instead of
239 * reporting syscall errors. If extra&CATCH_ZERO is true, return
240 * TOR_TLS_ZERORETURN_ instead of reporting zero-return errors.
241 *
242 * If an error has occurred, log it at level <b>severity</b> and describe the
243 * current action as <b>doing</b>.
244 */
245int
246tor_tls_get_error(tor_tls_t *tls, int r, int extra,
247 const char *doing, int severity, int domain)
248{
249 int err = SSL_get_error(tls->ssl, r);
250 int tor_error = TOR_TLS_ERROR_MISC;
251 switch (err) {
252 case SSL_ERROR_NONE:
253 return TOR_TLS_DONE;
254 case SSL_ERROR_WANT_READ:
255 return TOR_TLS_WANTREAD;
256 case SSL_ERROR_WANT_WRITE:
257 return TOR_TLS_WANTWRITE;
258 case SSL_ERROR_SYSCALL:
259 if (extra&CATCH_SYSCALL)
260 return TOR_TLS_SYSCALL_;
261 if (r == 0) {
262 tor_log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
263 doing, SSL_state_string_long(tls->ssl));
264 tor_error = TOR_TLS_ERROR_IO;
265 } else {
266 int e = tor_socket_errno(tls->socket);
267 tor_log(severity, LD_NET,
268 "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
269 doing, e, tor_socket_strerror(e),
270 SSL_state_string_long(tls->ssl));
271 tor_error = tor_errno_to_tls_error(e);
272 }
273 tls_log_errors(tls, severity, domain, doing);
274 return tor_error;
275 case SSL_ERROR_ZERO_RETURN:
276 if (extra&CATCH_ZERO)
277 return TOR_TLS_ZERORETURN_;
278 tor_log(severity, LD_NET, "TLS connection closed while %s in state %s",
279 doing, SSL_state_string_long(tls->ssl));
280 tls_log_errors(tls, severity, domain, doing);
281 return TOR_TLS_CLOSE;
282 default:
283 tls_log_errors(tls, severity, domain, doing);
284 return TOR_TLS_ERROR_MISC;
285 }
286}
287
288/** Initialize OpenSSL, unless it has already been initialized.
289 */
290void
291tor_tls_init(void)
292{
293 check_no_tls_errors();
294
295 if (!tls_library_is_initialized) {
296 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
297
298 tor_tls_allocate_tor_tls_object_ex_data_index();
299
300 tls_library_is_initialized = 1;
301 }
302}
303
304/** We need to give OpenSSL a callback to verify certificates. This is
305 * it: We always accept peer certs and complete the handshake. We
306 * don't validate them until later.
307 */
308int
309always_accept_verify_cb(int preverify_ok,
310 X509_STORE_CTX *x509_ctx)
311{
312 (void) preverify_ok;
313 (void) x509_ctx;
314 return 1;
315}
316
317/** List of ciphers that servers should select from when using TLS 1.2 */
318static const char UNRESTRICTED_TLS1_2_SERVER_CIPHER_LIST[] =
319 /* This list is autogenerated with the gen_server_ciphers.py script;
320 * don't hand-edit it. */
321#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
322 TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
323#endif
324#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
325 TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
326#endif
327#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384
328 TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 ":"
329#endif
330#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
331 TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
332#endif
333#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA
334 TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
335#endif
336#ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
337 TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
338#endif
339#ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384
340 TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 ":"
341#endif
342#ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256
343 TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 ":"
344#endif
345#ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_CCM
346 TLS1_TXT_DHE_RSA_WITH_AES_256_CCM ":"
347#endif
348#ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_CCM
349 TLS1_TXT_DHE_RSA_WITH_AES_128_CCM ":"
350#endif
351#ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256
352 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 ":"
353#endif
354#ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256
355 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 ":"
356#endif
357 /* Required */
358 TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
359 /* Required */
360 TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"
361#ifdef TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305
362 TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 ":"
363#endif
364#ifdef TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
365 TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
366#endif
367 ;
368
369/* Note: to set up your own private testing network with link crypto
370 * disabled, set your Tors' cipher list to
371 * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
372 * with any of the "real" Tors, though. */
373
374#define CIPHER(id, name) name ":"
375#define XCIPHER(id, name)
376/** List of ciphers that clients should advertise, omitting items that
377 * our OpenSSL doesn't know about. */
378static const char CLIENT_CIPHER_LIST[] =
379#ifndef COCCI
380#include "lib/tls/ciphers.inc"
381#endif
382 /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
383 * of any cipher we say. */
384 "!SSLv2"
385 ;
386#undef CIPHER
387#undef XCIPHER
388
389/** Return true iff the other side of <b>tls</b> has authenticated to us, and
390 * the key certified in <b>cert</b> is the same as the key they used to do it.
391 */
392MOCK_IMPL(int,
393tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
394{
395 tor_x509_cert_t *peer = tor_tls_get_peer_cert((tor_tls_t *)tls);
396 if (!peer)
397 return 0;
398
399 X509 *peercert = peer->cert;
400 EVP_PKEY *link_key = NULL, *cert_key = NULL;
401 int result;
402
403 link_key = X509_get_pubkey(peercert);
404 cert_key = X509_get_pubkey(cert->cert);
405
406 result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
407
408 tor_x509_cert_free(peer);
409 if (link_key)
410 EVP_PKEY_free(link_key);
411 if (cert_key)
412 EVP_PKEY_free(cert_key);
413
414 return result;
415}
416
417void
418tor_tls_context_impl_free_(struct ssl_ctx_st *ctx)
419{
420 if (!ctx)
421 return;
422 SSL_CTX_free(ctx);
423}
424
425/** The group we should use for ecdhe when none was selected. */
426#define NID_tor_default_ecdhe_group NID_X9_62_prime256v1
427
428/** Create a new TLS context for use with Tor TLS handshakes.
429 * <b>identity</b> should be set to the identity key used to sign the
430 * certificate.
431 */
433tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
434 unsigned flags, int is_client)
435{
436 EVP_PKEY *pkey = NULL;
437 tor_tls_context_t *result = NULL;
438
439 tor_tls_init();
440
441 result = tor_malloc_zero(sizeof(tor_tls_context_t));
442 result->refcnt = 1;
443
444 if (! is_client) {
445 if (tor_tls_context_init_certificates(result, identity, key_lifetime,
446 flags) < 0) {
447 goto error;
448 }
449 }
450
451 /* Tell OpenSSL to use TLS 1.2 or later. */
452 if (!(result->ctx = SSL_CTX_new(TLS_method())))
453 goto error;
454 if (!SSL_CTX_set_min_proto_version(result->ctx, TLS1_2_VERSION))
455 goto error;
456
457#ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
458 /* Level 1 re-enables RSA1024 and DH1024 for compatibility with old tors */
459 SSL_CTX_set_security_level(result->ctx, 1);
460#endif
461
462 /* Prefer the server's ordering of ciphers: the client's ordering has
463 * historically been chosen for fingerprinting resistance. */
464 SSL_CTX_set_options(result->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
465
466 /* Disable TLS tickets if they're supported. We never want to use them;
467 * using them can make our perfect forward secrecy a little worse, *and*
468 * create an opportunity to fingerprint us (since it's unusual to use them
469 * with TLS sessions turned off).
470 *
471 * In 0.2.4, clients advertise support for them though, to avoid a TLS
472 * distinguishability vector. This can give us worse PFS, though, if we
473 * get a server that doesn't set SSL_OP_NO_TICKET. With luck, there will
474 * be few such servers by the time 0.2.4 is more stable.
475 */
476#ifdef SSL_OP_NO_TICKET
477 if (! is_client) {
478 SSL_CTX_set_options(result->ctx, SSL_OP_NO_TICKET);
479 }
480#endif
481
482 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
483 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_ECDH_USE);
484
485#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
486 SSL_CTX_set_options(result->ctx,
487 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
488#endif
489#ifdef SSL_OP_NO_RENEGOTIATION
490 SSL_CTX_set_options(result->ctx, SSL_OP_NO_RENEGOTIATION);
491#endif
492#ifdef SSL_OP_NO_CLIENT_RENEGOTIATION
493 SSL_CTX_set_options(result->ctx, SSL_OP_NO_CLIENT_RENEGOTIATION);
494#endif
495
496 /* Don't actually allow compression; it uses RAM and time, it makes TLS
497 * vulnerable to CRIME-style attacks, and most of the data we transmit over
498 * TLS is encrypted (and therefore uncompressible) anyway. */
499#ifdef SSL_OP_NO_COMPRESSION
500 SSL_CTX_set_options(result->ctx, SSL_OP_NO_COMPRESSION);
501#endif
502
503#ifdef SSL_MODE_RELEASE_BUFFERS
504 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
505#endif
506 if (! is_client) {
507 if (result->my_link_cert &&
508 !SSL_CTX_use_certificate(result->ctx,
509 result->my_link_cert->cert)) {
510 goto error;
511 }
512 // Here we would once add my_id_cert too via X509_STORE_add_cert.
513 //
514 // We no longer do that, since we no longer send multiple certs;
515 // that was part of the obsolete v1 handshake.
516 }
517 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
518 if (!is_client) {
519 tor_assert(result->link_key);
520 if (!(pkey = crypto_pk_get_openssl_evp_pkey_(result->link_key,1)))
521 goto error;
522 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
523 goto error;
524 EVP_PKEY_free(pkey);
525 pkey = NULL;
526 if (!SSL_CTX_check_private_key(result->ctx))
527 goto error;
528 }
529
530 {
531 DH *dh = crypto_dh_new_openssl_tls();
532 tor_assert(dh);
533 SSL_CTX_set_tmp_dh(result->ctx, dh);
534 DH_free(dh);
535 }
536
537 {
538 // We'd like to say something like:
539 // "?X25519MLKEM768:P-256:P-224"
540 // to mean that we prefer X25519MLKEM768 if it is present;
541 // but we do insist on the presence of P-256 and P-224.
542 //
543 // Unfortunately, we support back to OpenSSL 3.0, which did not provide
544 // any syntax for saying "don't worry if this group isn't supported."
545 // Instead, we have to make this preference list of preference lists.
546 static const struct {
547 // Minimal version with which to try this syntax.
548 // We have to restrict, since older versions of openssl
549 // can misunderstand-but nonetheless accept!-syntaxes
550 // supported by newer versions. See #41058 for one example.
551 long min_version;
552 const char *groups;
553 } group_lists[] = {
554 // We do use the ? syntax here, since every version of OpenSSL
555 // that supports ML-KEM also supports the ? syntax.
556 // We also use the * and / syntaxes:
557 // '*' indicates that the client should send these keyshares.
558 // "/" means that we should consider a set of of groups
559 // as equivalently secure.
560 //
561 // Note that we tell the client to send a P-256 keyshare, since until
562 // this commit, our servers didn't accept X25519.
563 {
564 OPENSSL_V_SERIES(3,5,0),
565 "?*X25519MLKEM768 / ?SecP256r1MLKEM768:?X25519 / *P-256:P-224"
566 },
567 { 0, "P-256:X25519:P-224" },
568 { 0, "P-256:P-224" },
569 };
570 bool success = false;
571 long our_version = tor_OpenSSL_version_num();
572 for (unsigned j = 0; j < ARRAY_LENGTH(group_lists); ++j) {
573 const char *list = group_lists[j].groups;
574 if (group_lists[j].min_version > our_version) {
575 log_info(LD_NET, "Not trying groups %s because of OpenSSL version.",
576 list);
577 continue;
578 }
579 int r = (int) SSL_CTX_set1_groups_list(result->ctx, list);
580 if (r == 1) {
581 log_notice(LD_NET, "Set list of supported TLS groups to: %s", list);
582 success = true;
583 break;
584 }
585 log_info(LD_NET, "Group list %s wasn't accepted", list);
586 }
587 if (! success) {
588 log_warn(LD_NET, "No lists of TLS groups were supported. "
589 "Using library defaults");
590 }
591 }
592
593 if (is_client) {
594 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
595 always_accept_verify_cb);
596 } else {
597 /* Don't send a certificate request at all if we're not a client. */
598 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_NONE, NULL);
599 }
600 /* let us realloc bufs that we're writing from */
601 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
602
603#ifdef SSL_OP_TLSEXT_PADDING
604 /* Adds a padding extension to ensure the ClientHello size is never between
605 * 256 and 511 bytes in length. */
606 SSL_CTX_set_options(result->ctx, SSL_OP_TLSEXT_PADDING);
607#endif
608
609 return result;
610
611 error:
612 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
613 if (pkey)
614 EVP_PKEY_free(pkey);
616 return NULL;
617}
618
619/** Invoked when a TLS state changes: log the change at severity 'debug' */
620void
621tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
622{
623 /* LCOV_EXCL_START since this depends on whether debug is captured or not */
624 log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
625 ssl, SSL_state_string_long(ssl), type, val);
626 /* LCOV_EXCL_STOP */
627}
628
629/** Create a new TLS object from a file descriptor, and a flag to
630 * determine whether it is functioning as a server.
631 */
632tor_tls_t *
633tor_tls_new(tor_socket_t sock, int isServer)
634{
635 BIO *bio = NULL;
636 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
637 tor_tls_context_t *context = tor_tls_context_get(isServer);
638 result->magic = TOR_TLS_MAGIC;
639
640 check_no_tls_errors();
641 tor_assert(context); /* make sure somebody made it first */
642 if (!(result->ssl = SSL_new(context->ctx))) {
643 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
644 tor_free(result);
645 goto err;
646 }
647
648#ifdef SSL_set_tlsext_host_name
649 /* Browsers use the TLS hostname extension, so we should too. */
650 if (!isServer) {
651 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
652 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
653 tor_free(fake_hostname);
654 }
655#endif /* defined(SSL_set_tlsext_host_name) */
656
657#ifdef SSL_CTRL_SET_MAX_PROTO_VERSION
658 if (openssl_bug_7712_is_present) {
659 /* We can't actually use TLS 1.3 until this bug is fixed. */
660 SSL_set_max_proto_version(result->ssl, TLS1_2_VERSION);
661 }
662#endif /* defined(SSL_CTRL_SET_MAX_PROTO_VERSION) */
663
664 if (!SSL_set_cipher_list(result->ssl,
665 isServer ? UNRESTRICTED_TLS1_2_SERVER_CIPHER_LIST
666 : CLIENT_CIPHER_LIST)) {
667 tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
668#ifdef SSL_set_tlsext_host_name
669 SSL_set_tlsext_host_name(result->ssl, NULL);
670#endif
671 SSL_free(result->ssl);
672 tor_free(result);
673 goto err;
674 }
675
676 result->socket = sock;
677 bio = BIO_new_socket(sock, BIO_CLOSE);
678 if (! bio) {
679 tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
680#ifdef SSL_set_tlsext_host_name
681 SSL_set_tlsext_host_name(result->ssl, NULL);
682#endif
683 SSL_free(result->ssl);
684 tor_free(result);
685 goto err;
686 }
687 {
688 int set_worked =
689 SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
690 if (!set_worked) {
691 log_warn(LD_BUG,
692 "Couldn't set the tls for an SSL*; connection will fail");
693 }
694 }
695 SSL_set_bio(result->ssl, bio, bio);
696 tor_tls_context_incref(context);
697 result->context = context;
698 result->state = TOR_TLS_ST_HANDSHAKE;
699 result->isServer = isServer;
700 result->wantwrite_n = 0;
701 result->last_write_count = (unsigned long) BIO_number_written(bio);
702 result->last_read_count = (unsigned long) BIO_number_read(bio);
703 if (result->last_write_count || result->last_read_count) {
704 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
705 result->last_read_count, result->last_write_count);
706 }
707
708 SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
709
710 goto done;
711 err:
712 result = NULL;
713 done:
714 /* Not expected to get called. */
715 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
716 return result;
717}
718
719/**
720 * Tell the TLS library that the underlying socket for <b>tls</b> has been
721 * closed, and the library should not attempt to free that socket itself.
722 */
723void
725{
726 if (! tls)
727 return;
728
729 BIO *rbio, *wbio;
730 rbio = SSL_get_rbio(tls->ssl);
731 wbio = SSL_get_wbio(tls->ssl);
732
733 if (rbio) {
734 (void) BIO_set_close(rbio, BIO_NOCLOSE);
735 }
736 if (wbio && wbio != rbio) {
737 (void) BIO_set_close(wbio, BIO_NOCLOSE);
738 }
739}
740
741void
742tor_tls_impl_free_(tor_tls_impl_t *ssl)
743{
744 if (!ssl)
745 return;
746
747#ifdef SSL_set_tlsext_host_name
748 SSL_set_tlsext_host_name(ssl, NULL);
749#endif
750 SSL_free(ssl);
751}
752
753/** Underlying function for TLS reading. Reads up to <b>len</b>
754 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
755 * number of characters read. On failure, returns TOR_TLS_ERROR,
756 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
757 */
758MOCK_IMPL(int,
759tor_tls_read,(tor_tls_t *tls, char *cp, size_t len))
760{
761 int r, err;
762 tor_assert(tls);
763 tor_assert(tls->ssl);
764 tor_assert(tls->state == TOR_TLS_ST_OPEN);
765 tor_assert(len<INT_MAX);
766 r = SSL_read(tls->ssl, cp, (int)len);
767 if (r > 0) {
768 return r;
769 }
770 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
771 if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) {
772 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
773 tls->state = TOR_TLS_ST_CLOSED;
774 return TOR_TLS_CLOSE;
775 } else {
776 tor_assert(err != TOR_TLS_DONE);
777 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
778 return err;
779 }
780}
781
782/** Total number of bytes that we've used TLS to send. Used to track TLS
783 * overhead. */
784STATIC uint64_t total_bytes_written_over_tls = 0;
785/** Total number of bytes that TLS has put on the network for us. Used to
786 * track TLS overhead. */
787STATIC uint64_t total_bytes_written_by_tls = 0;
788
789/** Underlying function for TLS writing. Write up to <b>n</b>
790 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
791 * number of characters written. On failure, returns TOR_TLS_ERROR,
792 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
793 */
794int
795tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
796{
797 int r, err;
798 tor_assert(tls);
799 tor_assert(tls->ssl);
800 tor_assert(tls->state == TOR_TLS_ST_OPEN);
801 tor_assert(n < INT_MAX);
802 if (n == 0)
803 return 0;
804 if (tls->wantwrite_n) {
805 /* if WANTWRITE last time, we must use the _same_ n as before */
806 tor_assert(n >= tls->wantwrite_n);
807 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
808 (int)n, (int)tls->wantwrite_n);
809 n = tls->wantwrite_n;
810 tls->wantwrite_n = 0;
811 }
812 r = SSL_write(tls->ssl, cp, (int)n);
813 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
814 if (err == TOR_TLS_DONE) {
815 total_bytes_written_over_tls += r;
816 return r;
817 }
818 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
819 tls->wantwrite_n = n;
820 }
821 return err;
822}
823
824/** Perform initial handshake on <b>tls</b>. When finished, returns
825 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
826 * or TOR_TLS_WANTWRITE.
827 */
828int
830{
831 int r;
832 tor_assert(tls);
833 tor_assert(tls->ssl);
834 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
835
836 check_no_tls_errors();
837
838 OSSL_HANDSHAKE_STATE oldstate = SSL_get_state(tls->ssl);
839
840 if (tls->isServer) {
841 log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
842 SSL_state_string_long(tls->ssl));
843 r = SSL_accept(tls->ssl);
844 } else {
845 log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
846 SSL_state_string_long(tls->ssl));
847 r = SSL_connect(tls->ssl);
848 }
849
850 OSSL_HANDSHAKE_STATE newstate = SSL_get_state(tls->ssl);
851
852 if (oldstate != newstate)
853 log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
854 tls, SSL_state_string_long(tls->ssl));
855
856 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
857 if (ERR_peek_error() != 0) {
859 "handshaking");
860 return TOR_TLS_ERROR_MISC;
861 }
862 if (r == TOR_TLS_DONE) {
863 tls->state = TOR_TLS_ST_OPEN;
864 }
865 return r;
866}
867
868/** Return true iff this TLS connection is authenticated.
869 */
870int
872{
873 X509 *cert;
874 cert = SSL_get_peer_certificate(tls->ssl);
875 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
876 if (!cert)
877 return 0;
878 X509_free(cert);
879 return 1;
880}
881
882/** Return a newly allocated copy of the peer certificate, or NULL if there
883 * isn't one. */
884MOCK_IMPL(tor_x509_cert_t *,
886{
887 X509 *cert;
888 cert = SSL_get_peer_certificate(tls->ssl);
889 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
890 if (!cert)
891 return NULL;
892 return tor_x509_cert_new(cert);
893}
894
895/** Return a newly allocated copy of the cerficate we used on the connection,
896 * or NULL if somehow we didn't use one. */
897MOCK_IMPL(tor_x509_cert_t *,
899{
900 X509 *cert = SSL_get_certificate(tls->ssl);
902 "getting own-connection certificate");
903 if (!cert)
904 return NULL;
905 /* Fun inconsistency: SSL_get_peer_certificate increments the reference
906 * count, but SSL_get_certificate does not. */
907 X509 *duplicate = X509_dup(cert);
908 if (BUG(duplicate == NULL))
909 return NULL;
910 return tor_x509_cert_new(duplicate);
911}
912
913/** Return the number of bytes available for reading from <b>tls</b>.
914 */
915int
917{
918 tor_assert(tls);
919 return SSL_pending(tls->ssl);
920}
921
922/** If <b>tls</b> requires that the next write be of a particular size,
923 * return that size. Otherwise, return 0. */
924size_t
926{
927 return tls->wantwrite_n;
928}
929
930/** Sets n_read and n_written to the number of bytes read and written,
931 * respectively, on the raw socket used by <b>tls</b> since the last time this
932 * function was called on <b>tls</b>. */
933void
934tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
935{
936 BIO *wbio, *tmpbio;
937 unsigned long r, w;
938 r = (unsigned long) BIO_number_read(SSL_get_rbio(tls->ssl));
939 /* We want the number of bytes actually for real written. Unfortunately,
940 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
941 * which makes the answer turn out wrong. Let's cope with that. Note
942 * that this approach will fail if we ever replace tls->ssl's BIOs with
943 * buffering bios for reasons of our own. As an alternative, we could
944 * save the original BIO for tls->ssl in the tor_tls_t structure, but
945 * that would be tempting fate. */
946 wbio = SSL_get_wbio(tls->ssl);
947 if (BIO_method_type(wbio) == BIO_TYPE_BUFFER &&
948 (tmpbio = BIO_next(wbio)) != NULL)
949 wbio = tmpbio;
950 w = (unsigned long) BIO_number_written(wbio);
951
952 /* We are ok with letting these unsigned ints go "negative" here:
953 * If we wrapped around, this should still give us the right answer, unless
954 * we wrapped around by more than ULONG_MAX since the last time we called
955 * this function.
956 */
957 *n_read = (size_t)(r - tls->last_read_count);
958 *n_written = (size_t)(w - tls->last_write_count);
959 if (*n_read > INT_MAX || *n_written > INT_MAX) {
960 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
961 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
962 r, tls->last_read_count, w, tls->last_write_count);
963 }
964 total_bytes_written_by_tls += *n_written;
965 tls->last_read_count = r;
966 tls->last_write_count = w;
967}
968
969/** Return a ratio of the bytes that TLS has sent to the bytes that we've told
970 * it to send. Used to track whether our TLS records are getting too tiny. */
971MOCK_IMPL(double,
973{
974 if (total_bytes_written_over_tls == 0)
975 return 1.0;
976
977 return ((double)total_bytes_written_by_tls) /
978 ((double)total_bytes_written_over_tls);
979}
980
981/** Implement check_no_tls_errors: If there are any pending OpenSSL
982 * errors, log an error message. */
983void
984check_no_tls_errors_(const char *fname, int line)
985{
986 if (ERR_peek_error() == 0)
987 return;
988 log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
989 tor_fix_source_file(fname), line);
990 tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
991}
992
993/** Using the RFC5705 key material exporting construction, and the
994 * provided <b>context</b> (<b>context_len</b> bytes long) and
995 * <b>label</b> (a NUL-terminated string), compute a 32-byte secret in
996 * <b>secrets_out</b> that only the parties to this TLS session can
997 * compute. Return 0 on success; -1 on failure; and -2 on failure
998 * caused by OpenSSL bug 7712.
999 */
1000MOCK_IMPL(int,
1001tor_tls_export_key_material,(tor_tls_t *tls, uint8_t *secrets_out,
1002 const uint8_t *context,
1003 size_t context_len,
1004 const char *label))
1005{
1006 tor_assert(tls);
1007 tor_assert(tls->ssl);
1008
1009 int r = SSL_export_keying_material(tls->ssl,
1010 secrets_out, DIGEST256_LEN,
1011 label, strlen(label),
1012 context, context_len, 1);
1013
1014 if (r != 1) {
1015 int severity = openssl_bug_7712_is_present ? LOG_WARN : LOG_DEBUG;
1016 tls_log_errors(tls, severity, LD_NET, "exporting keying material");
1017 }
1018
1019#ifdef TLS1_3_VERSION
1020 if (r != 1 &&
1021 strlen(label) > 12 &&
1022 SSL_version(tls->ssl) >= TLS1_3_VERSION) {
1023
1024 if (! openssl_bug_7712_is_present) {
1025 /* We might have run into OpenSSL issue 7712, which caused OpenSSL
1026 * 1.1.1a to not handle long labels. Let's test to see if we have.
1027 */
1028 r = SSL_export_keying_material(tls->ssl, secrets_out, DIGEST256_LEN,
1029 "short", 5, context, context_len, 1);
1030 if (r == 1) {
1031 /* A short label succeeds, but a long label fails. This was openssl
1032 * issue 7712. */
1033 openssl_bug_7712_is_present = 1;
1034 log_warn(LD_GENERAL, "Detected OpenSSL bug 7712: disabling TLS 1.3 on "
1035 "future connections.");
1036 }
1037 }
1038 if (openssl_bug_7712_is_present)
1039 return -2;
1040 else
1041 return -1;
1042 }
1043#endif /* defined(TLS1_3_VERSION) */
1044
1045 return (r == 1) ? 0 : -1;
1046}
1047
1048/** Examine the amount of memory used and available for buffers in <b>tls</b>.
1049 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1050 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1051 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1052 * buffer and *<b>wbuf_bytes</b> to the amount actually used.
1053 *
1054 * Return 0 on success, -1 on failure.*/
1055int
1057 size_t *rbuf_capacity, size_t *rbuf_bytes,
1058 size_t *wbuf_capacity, size_t *wbuf_bytes)
1059{
1060 (void)tls;
1061 (void)rbuf_capacity;
1062 (void)rbuf_bytes;
1063 (void)wbuf_capacity;
1064 (void)wbuf_bytes;
1065
1066 return -1;
1067}
1068
1069/** Check whether the ECC group requested is supported by the current OpenSSL
1070 * library instance. Return 1 if the group is supported, and 0 if not.
1071 */
1072int
1073evaluate_ecgroup_for_tls(const char *ecgroup)
1074{
1075 EC_KEY *ec_key;
1076 int nid;
1077 int ret;
1078
1079 if (!ecgroup)
1080 nid = NID_tor_default_ecdhe_group;
1081 else if (!strcasecmp(ecgroup, "P256"))
1082 nid = NID_X9_62_prime256v1;
1083 else if (!strcasecmp(ecgroup, "P224"))
1084 nid = NID_secp224r1;
1085 else
1086 return 0;
1087
1088 ec_key = EC_KEY_new_by_curve_name(nid);
1089 ret = (ec_key != NULL);
1090 EC_KEY_free(ec_key);
1091
1092 return ret;
1093}
Inline functions for reading and writing multibyte values from the middle of strings,...
Macro definitions for MIN, MAX, and CLAMP.
#define ARRAY_LENGTH(x)
Header for compat_string.c.
Headers for crypto_cipher.c.
Headers for crypto_dh.c.
struct dh_st * crypto_dh_new_openssl_tls(void)
char * crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix, const char *suffix)
Definition: crypto_rand.c:554
Common functions for using (pseudo-)random number generators.
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:591
Headers for log.c.
#define LD_CRYPTO
Definition: log.h:64
#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:56
#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.
Header for smartlist.c.
Header for socket.c.
tor_tls_state_bitfield_t state
Definition: tortls_st.h:48
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:98
tor_tls_context_t * tor_tls_context_get(int is_server)
Definition: tortls.c:45
void tor_tls_context_decref(tor_tls_context_t *ctx)
Definition: tortls.c:106
int tor_errno_to_tls_error(int e)
Definition: tortls.c:53
int tor_tls_context_init_certificates(tor_tls_context_t *result, crypto_pk_t *identity, unsigned key_lifetime, unsigned flags)
Definition: tortls.c:278
int tor_tls_peer_has_cert(tor_tls_t *tls)
Definition: tortls_nss.c:497
void tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
Definition: tortls_nss.c:616
int tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
Definition: tortls_nss.c:527
double tls_get_write_overhead_ratio(void)
Definition: tortls_nss.c:651
int evaluate_ecgroup_for_tls(const char *ecgroup)
Definition: tortls_nss.c:751
int tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
Definition: tortls_nss.c:550
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:636
struct tor_x509_cert_t * tor_tls_get_peer_cert(tor_tls_t *tls)
Definition: tortls_nss.c:506
void tor_tls_init(void)
Definition: tortls_nss.c:333
int tor_tls_get_pending_bytes(tor_tls_t *tls)
Definition: tortls_nss.c:596
int tor_tls_handshake(tor_tls_t *tls)
Definition: tortls_nss.c:578
tor_tls_t * tor_tls_new(tor_socket_t sock, int is_server)
Definition: tortls_nss.c:386
const char * tor_tls_get_last_error_msg(const tor_tls_t *tls)
Definition: tortls_nss.c:374
void tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
Definition: tortls_nss.c:339
struct tor_x509_cert_t * tor_tls_get_own_cert(tor_tls_t *tls)
Definition: tortls_nss.c:516
void tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
Definition: tortls_nss.c:323
void tor_tls_release_socket(tor_tls_t *tls)
Definition: tortls_nss.c:449
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:721
size_t tor_tls_get_forced_write_size(tor_tls_t *tls)
Definition: tortls_nss.c:608
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:159
Structure declarations for internal TLS types.
Macros to manage assertions, fatal and non-fatal.
#define tor_assert(expr)
Definition: util_bug.h:103
#define IF_BUG_ONCE(cond)
Definition: util_bug.h:254
Headers for tortls.c.