Tor 0.4.9.3-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 ;
386static char CLIENT_CIPHER_LIST_TLSv13[] =
387#ifndef COCCI
388#include "lib/tls/ciphers_v13.inc"
389#endif
390 ""
391 ;
392#undef CIPHER
393#undef XCIPHER
394
395/** Return true iff the other side of <b>tls</b> has authenticated to us, and
396 * the key certified in <b>cert</b> is the same as the key they used to do it.
397 */
398MOCK_IMPL(int,
399tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
400{
401 tor_x509_cert_t *peer = tor_tls_get_peer_cert((tor_tls_t *)tls);
402 if (!peer)
403 return 0;
404
405 X509 *peercert = peer->cert;
406 EVP_PKEY *link_key = NULL, *cert_key = NULL;
407 int result;
408
409 link_key = X509_get_pubkey(peercert);
410 cert_key = X509_get_pubkey(cert->cert);
411
412 result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
413
414 tor_x509_cert_free(peer);
415 if (link_key)
416 EVP_PKEY_free(link_key);
417 if (cert_key)
418 EVP_PKEY_free(cert_key);
419
420 return result;
421}
422
423void
424tor_tls_context_impl_free_(struct ssl_ctx_st *ctx)
425{
426 if (!ctx)
427 return;
428 SSL_CTX_free(ctx);
429}
430
431/** The group we should use for ecdhe when none was selected. */
432#define NID_tor_default_ecdhe_group NID_X9_62_prime256v1
433
434/** Create a new TLS context for use with Tor TLS handshakes.
435 * <b>identity</b> should be set to the identity key used to sign the
436 * certificate.
437 */
439tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
440 unsigned flags, int is_client)
441{
442 EVP_PKEY *pkey = NULL;
443 tor_tls_context_t *result = NULL;
444
445 tor_tls_init();
446
447 result = tor_malloc_zero(sizeof(tor_tls_context_t));
448 result->refcnt = 1;
449
450 if (! is_client) {
451 if (tor_tls_context_init_certificates(result, identity, key_lifetime,
452 flags) < 0) {
453 goto error;
454 }
455 }
456
457 /* Tell OpenSSL to use TLS 1.2 or later. */
458 if (!(result->ctx = SSL_CTX_new(TLS_method())))
459 goto error;
460 if (!SSL_CTX_set_min_proto_version(result->ctx, TLS1_2_VERSION))
461 goto error;
462
463#ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
464 /* Level 1 re-enables RSA1024 and DH1024 for compatibility with old tors */
465 SSL_CTX_set_security_level(result->ctx, 1);
466#endif
467
468 /* Prefer the server's ordering of ciphers: the client's ordering has
469 * historically been chosen for fingerprinting resistance. */
470 SSL_CTX_set_options(result->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
471
472 /* Disable TLS tickets if they're supported. We never want to use them;
473 * using them can make our perfect forward secrecy a little worse, *and*
474 * create an opportunity to fingerprint us (since it's unusual to use them
475 * with TLS sessions turned off).
476 *
477 * In 0.2.4, clients advertise support for them though, to avoid a TLS
478 * distinguishability vector. This can give us worse PFS, though, if we
479 * get a server that doesn't set SSL_OP_NO_TICKET. With luck, there will
480 * be few such servers by the time 0.2.4 is more stable.
481 */
482#ifdef SSL_OP_NO_TICKET
483 if (! is_client) {
484 SSL_CTX_set_options(result->ctx, SSL_OP_NO_TICKET);
485 }
486#endif
487
488 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
489 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_ECDH_USE);
490
491#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
492 SSL_CTX_set_options(result->ctx,
493 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
494#endif
495#ifdef SSL_OP_NO_RENEGOTIATION
496 SSL_CTX_set_options(result->ctx, SSL_OP_NO_RENEGOTIATION);
497#endif
498#ifdef SSL_OP_NO_CLIENT_RENEGOTIATION
499 SSL_CTX_set_options(result->ctx, SSL_OP_NO_CLIENT_RENEGOTIATION);
500#endif
501
502 /* Don't actually allow compression; it uses RAM and time, it makes TLS
503 * vulnerable to CRIME-style attacks, and most of the data we transmit over
504 * TLS is encrypted (and therefore uncompressible) anyway. */
505#ifdef SSL_OP_NO_COMPRESSION
506 SSL_CTX_set_options(result->ctx, SSL_OP_NO_COMPRESSION);
507#endif
508
509#ifdef SSL_MODE_RELEASE_BUFFERS
510 SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
511#endif
512 if (! is_client) {
513 if (result->my_link_cert &&
514 !SSL_CTX_use_certificate(result->ctx,
515 result->my_link_cert->cert)) {
516 goto error;
517 }
518 // Here we would once add my_id_cert too via X509_STORE_add_cert.
519 //
520 // We no longer do that, since we no longer send multiple certs;
521 // that was part of the obsolete v1 handshake.
522 }
523 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
524 if (!is_client) {
525 tor_assert(result->link_key);
526 if (!(pkey = crypto_pk_get_openssl_evp_pkey_(result->link_key,1)))
527 goto error;
528 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
529 goto error;
530 EVP_PKEY_free(pkey);
531 pkey = NULL;
532 if (!SSL_CTX_check_private_key(result->ctx))
533 goto error;
534 }
535
536 {
537 DH *dh = crypto_dh_new_openssl_tls();
538 tor_assert(dh);
539 SSL_CTX_set_tmp_dh(result->ctx, dh);
540 DH_free(dh);
541 }
542
543 {
544 // We'd like to say something like:
545 // "?X25519MLKEM768:P-256:P-224"
546 // to mean that we prefer X25519MLKEM768 if it is present;
547 // but we do insist on the presence of P-256 and P-224.
548 //
549 // Unfortunately, we support back to OpenSSL 3.0, which did not provide
550 // any syntax for saying "don't worry if this group isn't supported."
551 // Instead, we have to make this preference list of preference lists.
552 static const struct {
553 // Minimal version with which to try this syntax.
554 // We have to restrict, since older versions of openssl
555 // can misunderstand-but nonetheless accept!-syntaxes
556 // supported by newer versions. See #41058 for one example.
557 long min_version;
558 const char *groups;
559 } group_lists[] = {
560 // We do use the ? syntax here, since every version of OpenSSL
561 // that supports ML-KEM also supports the ? syntax.
562 // We also use the * and / syntaxes:
563 // '*' indicates that the client should send these keyshares.
564 // "/" means that we should consider a set of of groups
565 // as equivalently secure.
566 //
567 // Note that we tell the client to send a P-256 keyshare, since until
568 // this commit, our servers didn't accept X25519.
569 {
570 OPENSSL_V_SERIES(3,5,0),
571 "?*X25519MLKEM768 / ?SecP256r1MLKEM768:?X25519 / *P-256:P-224"
572 },
573 { 0, "P-256:X25519:P-224" },
574 { 0, "P-256:P-224" },
575 };
576 bool success = false;
577 long our_version = tor_OpenSSL_version_num();
578 for (unsigned j = 0; j < ARRAY_LENGTH(group_lists); ++j) {
579 const char *list = group_lists[j].groups;
580 if (group_lists[j].min_version > our_version) {
581 log_info(LD_NET, "Not trying groups %s because of OpenSSL version.",
582 list);
583 continue;
584 }
585 int r = (int) SSL_CTX_set1_groups_list(result->ctx, list);
586 if (r == 1) {
587 static bool have_logged_already = false;
588 if (!have_logged_already) {
589 /* say it only once at startup, since the answer won't change */
590 log_notice(LD_NET, "Set list of supported TLS groups to: %s", list);
591 have_logged_already = true;
592 }
593 success = true;
594 break;
595 }
596 log_info(LD_NET, "Group list %s wasn't accepted", list);
597 }
598 if (! success) {
599 log_warn(LD_NET, "No lists of TLS groups were supported. "
600 "Using library defaults");
601 }
602 }
603
604 if (is_client) {
605 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
606 always_accept_verify_cb);
607 } else {
608 /* Don't send a certificate request at all if we're not a client. */
609 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_NONE, NULL);
610 }
611 /* let us realloc bufs that we're writing from */
612 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
613
614#ifdef SSL_OP_TLSEXT_PADDING
615 /* Adds a padding extension to ensure the ClientHello size is never between
616 * 256 and 511 bytes in length. */
617 SSL_CTX_set_options(result->ctx, SSL_OP_TLSEXT_PADDING);
618#endif
619
620 return result;
621
622 error:
623 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
624 if (pkey)
625 EVP_PKEY_free(pkey);
627 return NULL;
628}
629
630/** Invoked when a TLS state changes: log the change at severity 'debug' */
631void
632tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
633{
634 /* LCOV_EXCL_START since this depends on whether debug is captured or not */
635 log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
636 ssl, SSL_state_string_long(ssl), type, val);
637 /* LCOV_EXCL_STOP */
638}
639
640/** Create a new TLS object from a file descriptor, and a flag to
641 * determine whether it is functioning as a server.
642 */
643tor_tls_t *
644tor_tls_new(tor_socket_t sock, int isServer)
645{
646 BIO *bio = NULL;
647 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
648 tor_tls_context_t *context = tor_tls_context_get(isServer);
649 result->magic = TOR_TLS_MAGIC;
650
651 check_no_tls_errors();
652 tor_assert(context); /* make sure somebody made it first */
653 if (!(result->ssl = SSL_new(context->ctx))) {
654 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
655 tor_free(result);
656 goto err;
657 }
658
659#ifdef SSL_set_tlsext_host_name
660 /* Browsers use the TLS hostname extension, so we should too. */
661 if (!isServer) {
662 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
663 SSL_set_tlsext_host_name(result->ssl, fake_hostname);
664 tor_free(fake_hostname);
665 }
666#endif /* defined(SSL_set_tlsext_host_name) */
667
668#ifdef SSL_CTRL_SET_MAX_PROTO_VERSION
669 if (openssl_bug_7712_is_present) {
670 /* We can't actually use TLS 1.3 until this bug is fixed. */
671 SSL_set_max_proto_version(result->ssl, TLS1_2_VERSION);
672 }
673#endif /* defined(SSL_CTRL_SET_MAX_PROTO_VERSION) */
674
675 /* Contrary to SSL_set_cipher_list(), TLSv1.3 SSL_set_ciphersuites() does NOT
676 * accept the final ':' so we have to strip it out. */
677 size_t TLSv13len = strlen(CLIENT_CIPHER_LIST_TLSv13);
678 if (TLSv13len && CLIENT_CIPHER_LIST_TLSv13[TLSv13len - 1] == ':') {
679 CLIENT_CIPHER_LIST_TLSv13[TLSv13len - 1] = '\0';
680 }
681
682 const bool tls12_ciphers_ok = SSL_set_cipher_list(
683 result->ssl,
684 isServer ? UNRESTRICTED_TLS1_2_SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST);
685
686 bool tls13_ciphers_ok = true;
687#ifdef HAVE_SSL_SET_CIPHERSUITES
688 if (!isServer) {
689 tls13_ciphers_ok =
690 SSL_set_ciphersuites(result->ssl, CLIENT_CIPHER_LIST_TLSv13);
691 }
692#endif
693
694 if (!tls12_ciphers_ok || !tls13_ciphers_ok) {
695 tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
696#ifdef SSL_set_tlsext_host_name
697 SSL_set_tlsext_host_name(result->ssl, NULL);
698#endif
699 SSL_free(result->ssl);
700 tor_free(result);
701 goto err;
702 }
703
704 result->socket = sock;
705 bio = BIO_new_socket(sock, BIO_CLOSE);
706 if (! bio) {
707 tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
708#ifdef SSL_set_tlsext_host_name
709 SSL_set_tlsext_host_name(result->ssl, NULL);
710#endif
711 SSL_free(result->ssl);
712 tor_free(result);
713 goto err;
714 }
715 {
716 int set_worked =
717 SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
718 if (!set_worked) {
719 log_warn(LD_BUG,
720 "Couldn't set the tls for an SSL*; connection will fail");
721 }
722 }
723 SSL_set_bio(result->ssl, bio, bio);
724 tor_tls_context_incref(context);
725 result->context = context;
726 result->state = TOR_TLS_ST_HANDSHAKE;
727 result->isServer = isServer;
728 result->wantwrite_n = 0;
729 result->last_write_count = (unsigned long) BIO_number_written(bio);
730 result->last_read_count = (unsigned long) BIO_number_read(bio);
731 if (result->last_write_count || result->last_read_count) {
732 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
733 result->last_read_count, result->last_write_count);
734 }
735
736 SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
737
738 goto done;
739 err:
740 result = NULL;
741 done:
742 /* Not expected to get called. */
743 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
744 return result;
745}
746
747/**
748 * Tell the TLS library that the underlying socket for <b>tls</b> has been
749 * closed, and the library should not attempt to free that socket itself.
750 */
751void
753{
754 if (! tls)
755 return;
756
757 BIO *rbio, *wbio;
758 rbio = SSL_get_rbio(tls->ssl);
759 wbio = SSL_get_wbio(tls->ssl);
760
761 if (rbio) {
762 (void) BIO_set_close(rbio, BIO_NOCLOSE);
763 }
764 if (wbio && wbio != rbio) {
765 (void) BIO_set_close(wbio, BIO_NOCLOSE);
766 }
767}
768
769void
770tor_tls_impl_free_(tor_tls_impl_t *ssl)
771{
772 if (!ssl)
773 return;
774
775#ifdef SSL_set_tlsext_host_name
776 SSL_set_tlsext_host_name(ssl, NULL);
777#endif
778 SSL_free(ssl);
779}
780
781/** Underlying function for TLS reading. Reads up to <b>len</b>
782 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
783 * number of characters read. On failure, returns TOR_TLS_ERROR,
784 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
785 */
786MOCK_IMPL(int,
787tor_tls_read,(tor_tls_t *tls, char *cp, size_t len))
788{
789 int r, err;
790 tor_assert(tls);
791 tor_assert(tls->ssl);
792 tor_assert(tls->state == TOR_TLS_ST_OPEN);
793 tor_assert(len<INT_MAX);
794 r = SSL_read(tls->ssl, cp, (int)len);
795 if (r > 0) {
796 return r;
797 }
798 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
799 if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) {
800 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
801 tls->state = TOR_TLS_ST_CLOSED;
802 return TOR_TLS_CLOSE;
803 } else {
804 tor_assert(err != TOR_TLS_DONE);
805 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
806 return err;
807 }
808}
809
810/** Total number of bytes that we've used TLS to send. Used to track TLS
811 * overhead. */
812STATIC uint64_t total_bytes_written_over_tls = 0;
813/** Total number of bytes that TLS has put on the network for us. Used to
814 * track TLS overhead. */
815STATIC uint64_t total_bytes_written_by_tls = 0;
816
817/** Underlying function for TLS writing. Write up to <b>n</b>
818 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
819 * number of characters written. On failure, returns TOR_TLS_ERROR,
820 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
821 */
822int
823tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
824{
825 int r, err;
826 tor_assert(tls);
827 tor_assert(tls->ssl);
828 tor_assert(tls->state == TOR_TLS_ST_OPEN);
829 tor_assert(n < INT_MAX);
830 if (n == 0)
831 return 0;
832 if (tls->wantwrite_n) {
833 /* if WANTWRITE last time, we must use the _same_ n as before */
834 tor_assert(n >= tls->wantwrite_n);
835 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
836 (int)n, (int)tls->wantwrite_n);
837 n = tls->wantwrite_n;
838 tls->wantwrite_n = 0;
839 }
840 r = SSL_write(tls->ssl, cp, (int)n);
841 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
842 if (err == TOR_TLS_DONE) {
843 total_bytes_written_over_tls += r;
844 return r;
845 }
846 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
847 tls->wantwrite_n = n;
848 }
849 return err;
850}
851
852/** Perform initial handshake on <b>tls</b>. When finished, returns
853 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
854 * or TOR_TLS_WANTWRITE.
855 */
856int
858{
859 int r;
860 tor_assert(tls);
861 tor_assert(tls->ssl);
862 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
863
864 check_no_tls_errors();
865
866 OSSL_HANDSHAKE_STATE oldstate = SSL_get_state(tls->ssl);
867
868 if (tls->isServer) {
869 log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
870 SSL_state_string_long(tls->ssl));
871 r = SSL_accept(tls->ssl);
872 } else {
873 log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
874 SSL_state_string_long(tls->ssl));
875 r = SSL_connect(tls->ssl);
876 }
877
878 OSSL_HANDSHAKE_STATE newstate = SSL_get_state(tls->ssl);
879
880 if (oldstate != newstate)
881 log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
882 tls, SSL_state_string_long(tls->ssl));
883
884 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
885 if (ERR_peek_error() != 0) {
887 "handshaking");
888 return TOR_TLS_ERROR_MISC;
889 }
890 if (r == TOR_TLS_DONE) {
891 tls->state = TOR_TLS_ST_OPEN;
892 }
893 return r;
894}
895
896/** Return true iff this TLS connection is authenticated.
897 */
898int
900{
901 X509 *cert;
902 cert = SSL_get_peer_certificate(tls->ssl);
903 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
904 if (!cert)
905 return 0;
906 X509_free(cert);
907 return 1;
908}
909
910/** Return a newly allocated copy of the peer certificate, or NULL if there
911 * isn't one. */
912MOCK_IMPL(tor_x509_cert_t *,
913tor_tls_get_peer_cert,(tor_tls_t *tls))
914{
915 X509 *cert;
916 cert = SSL_get_peer_certificate(tls->ssl);
917 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
918 if (!cert)
919 return NULL;
920 return tor_x509_cert_new(cert);
921}
922
923/** Return a newly allocated copy of the cerficate we used on the connection,
924 * or NULL if somehow we didn't use one. */
925MOCK_IMPL(tor_x509_cert_t *,
926tor_tls_get_own_cert,(tor_tls_t *tls))
927{
928 X509 *cert = SSL_get_certificate(tls->ssl);
930 "getting own-connection certificate");
931 if (!cert)
932 return NULL;
933 /* Fun inconsistency: SSL_get_peer_certificate increments the reference
934 * count, but SSL_get_certificate does not. */
935 X509 *duplicate = X509_dup(cert);
936 if (BUG(duplicate == NULL))
937 return NULL;
938 return tor_x509_cert_new(duplicate);
939}
940
941/** Return the number of bytes available for reading from <b>tls</b>.
942 */
943int
945{
946 tor_assert(tls);
947 return SSL_pending(tls->ssl);
948}
949
950/** If <b>tls</b> requires that the next write be of a particular size,
951 * return that size. Otherwise, return 0. */
952size_t
954{
955 return tls->wantwrite_n;
956}
957
958/** Sets n_read and n_written to the number of bytes read and written,
959 * respectively, on the raw socket used by <b>tls</b> since the last time this
960 * function was called on <b>tls</b>. */
961void
962tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
963{
964 BIO *wbio, *tmpbio;
965 unsigned long r, w;
966 r = (unsigned long) BIO_number_read(SSL_get_rbio(tls->ssl));
967 /* We want the number of bytes actually for real written. Unfortunately,
968 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
969 * which makes the answer turn out wrong. Let's cope with that. Note
970 * that this approach will fail if we ever replace tls->ssl's BIOs with
971 * buffering bios for reasons of our own. As an alternative, we could
972 * save the original BIO for tls->ssl in the tor_tls_t structure, but
973 * that would be tempting fate. */
974 wbio = SSL_get_wbio(tls->ssl);
975 if (BIO_method_type(wbio) == BIO_TYPE_BUFFER &&
976 (tmpbio = BIO_next(wbio)) != NULL)
977 wbio = tmpbio;
978 w = (unsigned long) BIO_number_written(wbio);
979
980 /* We are ok with letting these unsigned ints go "negative" here:
981 * If we wrapped around, this should still give us the right answer, unless
982 * we wrapped around by more than ULONG_MAX since the last time we called
983 * this function.
984 */
985 *n_read = (size_t)(r - tls->last_read_count);
986 *n_written = (size_t)(w - tls->last_write_count);
987 if (*n_read > INT_MAX || *n_written > INT_MAX) {
988 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
989 "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
990 r, tls->last_read_count, w, tls->last_write_count);
991 }
992 total_bytes_written_by_tls += *n_written;
993 tls->last_read_count = r;
994 tls->last_write_count = w;
995}
996
997/** Return a ratio of the bytes that TLS has sent to the bytes that we've told
998 * it to send. Used to track whether our TLS records are getting too tiny. */
999MOCK_IMPL(double,
1000tls_get_write_overhead_ratio,(void))
1001{
1002 if (total_bytes_written_over_tls == 0)
1003 return 1.0;
1004
1005 return ((double)total_bytes_written_by_tls) /
1006 ((double)total_bytes_written_over_tls);
1007}
1008
1009/** Implement check_no_tls_errors: If there are any pending OpenSSL
1010 * errors, log an error message. */
1011void
1012check_no_tls_errors_(const char *fname, int line)
1013{
1014 if (ERR_peek_error() == 0)
1015 return;
1016 log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
1017 tor_fix_source_file(fname), line);
1018 tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
1019}
1020
1021/** Using the RFC5705 key material exporting construction, and the
1022 * provided <b>context</b> (<b>context_len</b> bytes long) and
1023 * <b>label</b> (a NUL-terminated string), compute a 32-byte secret in
1024 * <b>secrets_out</b> that only the parties to this TLS session can
1025 * compute. Return 0 on success; -1 on failure; and -2 on failure
1026 * caused by OpenSSL bug 7712.
1027 */
1028MOCK_IMPL(int,
1029tor_tls_export_key_material,(tor_tls_t *tls, uint8_t *secrets_out,
1030 const uint8_t *context,
1031 size_t context_len,
1032 const char *label))
1033{
1034 tor_assert(tls);
1035 tor_assert(tls->ssl);
1036
1037 int r = SSL_export_keying_material(tls->ssl,
1038 secrets_out, DIGEST256_LEN,
1039 label, strlen(label),
1040 context, context_len, 1);
1041
1042 if (r != 1) {
1043 int severity = openssl_bug_7712_is_present ? LOG_WARN : LOG_DEBUG;
1044 tls_log_errors(tls, severity, LD_NET, "exporting keying material");
1045 }
1046
1047#ifdef TLS1_3_VERSION
1048 if (r != 1 &&
1049 strlen(label) > 12 &&
1050 SSL_version(tls->ssl) >= TLS1_3_VERSION) {
1051
1052 if (! openssl_bug_7712_is_present) {
1053 /* We might have run into OpenSSL issue 7712, which caused OpenSSL
1054 * 1.1.1a to not handle long labels. Let's test to see if we have.
1055 */
1056 r = SSL_export_keying_material(tls->ssl, secrets_out, DIGEST256_LEN,
1057 "short", 5, context, context_len, 1);
1058 if (r == 1) {
1059 /* A short label succeeds, but a long label fails. This was openssl
1060 * issue 7712. */
1061 openssl_bug_7712_is_present = 1;
1062 log_warn(LD_GENERAL, "Detected OpenSSL bug 7712: disabling TLS 1.3 on "
1063 "future connections.");
1064 }
1065 }
1066 if (openssl_bug_7712_is_present)
1067 return -2;
1068 else
1069 return -1;
1070 }
1071#endif /* defined(TLS1_3_VERSION) */
1072
1073 return (r == 1) ? 0 : -1;
1074}
1075
1076/** Examine the amount of memory used and available for buffers in <b>tls</b>.
1077 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
1078 * buffer and *<b>rbuf_bytes</b> to the amount actually used.
1079 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
1080 * buffer and *<b>wbuf_bytes</b> to the amount actually used.
1081 *
1082 * Return 0 on success, -1 on failure.*/
1083int
1085 size_t *rbuf_capacity, size_t *rbuf_bytes,
1086 size_t *wbuf_capacity, size_t *wbuf_bytes)
1087{
1088 (void)tls;
1089 (void)rbuf_capacity;
1090 (void)rbuf_bytes;
1091 (void)wbuf_capacity;
1092 (void)wbuf_bytes;
1093
1094 return -1;
1095}
1096
1097/** Check whether the ECC group requested is supported by the current OpenSSL
1098 * library instance. Return 1 if the group is supported, and 0 if not.
1099 */
1100int
1101evaluate_ecgroup_for_tls(const char *ecgroup)
1102{
1103 EC_KEY *ec_key;
1104 int nid;
1105 int ret;
1106
1107 if (!ecgroup)
1108 nid = NID_tor_default_ecdhe_group;
1109 else if (!strcasecmp(ecgroup, "P256"))
1110 nid = NID_X9_62_prime256v1;
1111 else if (!strcasecmp(ecgroup, "P224"))
1112 nid = NID_secp224r1;
1113 else
1114 return 0;
1115
1116 ec_key = EC_KEY_new_by_curve_name(nid);
1117 ret = (ec_key != NULL);
1118 EC_KEY_free(ec_key);
1119
1120 return ret;
1121}
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)
Common functions for using (pseudo-)random number generators.
Common functions for cryptographic routines.
Headers for di_ops.c.
#define DIGEST256_LEN
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)
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 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
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
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.