tortls_openssl.c (35269B)
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 30 #include "lib/crypt_ops/crypto_cipher.h" 31 #include "lib/crypt_ops/crypto_rand.h" 32 #include "lib/crypt_ops/crypto_dh.h" 33 #include "lib/crypt_ops/crypto_util.h" 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" 61 #include "lib/tls/tortls_internal.h" 62 #include "lib/log/log.h" 63 #include "lib/log/util_bug.h" 64 #include "lib/container/smartlist.h" 65 #include "lib/string/compat_string.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 /** Set to true iff openssl bug 7712 has been detected. */ 84 static 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. */ 88 STATIC int tor_tls_object_ex_data_index = -1; 89 90 /** Helper: Allocate tor_tls_object_ex_data_index. */ 91 void 92 tor_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. */ 103 tor_tls_t * 104 tor_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. */ 113 static 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>. */ 121 void 122 tor_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>. */ 156 void 157 tor_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 */ 202 void 203 tls_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 **/ 220 const char * 221 tor_tls_get_last_error_msg(const tor_tls_t *tls) 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 */ 245 int 246 tor_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 */ 290 void 291 tor_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 */ 308 int 309 always_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 */ 318 static 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. */ 378 static 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 static 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 */ 398 MOCK_IMPL(int, 399 tor_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 423 void 424 tor_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 */ 438 tor_tls_context_t * 439 tor_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 // "/" separates tuples of groups that are "comparably secure". 565 // 566 // Note that we tell the client to send a P-256 keyshare, since until 567 // this commit, our servers didn't accept X25519. 568 // 569 // Also note that until the upstream LibreSSL bug from tor#41134 gets 570 // fixed, the order of groups common between each preference list must 571 // be the same. We can't prefer P-256 in one, and X25519 in another. 572 { 573 OPENSSL_V_SERIES(3,5,0), 574 "?*X25519MLKEM768 / ?SecP256r1MLKEM768 / *P-256:?X25519:P-224" 575 }, 576 { 0, "P-256:X25519:P-224" }, 577 { 0, "P-256:P-224" }, 578 }; 579 bool success = false; 580 long our_version = tor_OpenSSL_version_num(); 581 for (unsigned j = 0; j < ARRAY_LENGTH(group_lists); ++j) { 582 const char *list = group_lists[j].groups; 583 if (group_lists[j].min_version > our_version) { 584 log_info(LD_NET, "Not trying groups %s because of OpenSSL version.", 585 list); 586 continue; 587 } 588 int r = (int) SSL_CTX_set1_groups_list(result->ctx, list); 589 if (r == 1) { 590 static bool have_logged_already = false; 591 if (!have_logged_already) { 592 /* say it only once at startup, since the answer won't change */ 593 log_notice(LD_NET, "Set list of supported TLS groups to: %s", list); 594 have_logged_already = true; 595 } 596 success = true; 597 break; 598 } 599 log_info(LD_NET, "Group list %s wasn't accepted", list); 600 } 601 if (! success) { 602 log_warn(LD_NET, "No lists of TLS groups were supported. " 603 "Using library defaults"); 604 } 605 } 606 607 if (is_client) { 608 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER, 609 always_accept_verify_cb); 610 } else { 611 /* Don't send a certificate request at all if we're not a client. */ 612 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_NONE, NULL); 613 } 614 /* let us realloc bufs that we're writing from */ 615 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); 616 617 #ifdef SSL_OP_TLSEXT_PADDING 618 /* Adds a padding extension to ensure the ClientHello size is never between 619 * 256 and 511 bytes in length. */ 620 SSL_CTX_set_options(result->ctx, SSL_OP_TLSEXT_PADDING); 621 #endif 622 623 return result; 624 625 error: 626 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context"); 627 if (pkey) 628 EVP_PKEY_free(pkey); 629 tor_tls_context_decref(result); 630 return NULL; 631 } 632 633 /** Invoked when a TLS state changes: log the change at severity 'debug' */ 634 void 635 tor_tls_debug_state_callback(const SSL *ssl, int type, int val) 636 { 637 /* LCOV_EXCL_START since this depends on whether debug is captured or not */ 638 log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].", 639 ssl, SSL_state_string_long(ssl), type, val); 640 /* LCOV_EXCL_STOP */ 641 } 642 643 /** Create a new TLS object from a file descriptor, and a flag to 644 * determine whether it is functioning as a server. 645 */ 646 tor_tls_t * 647 tor_tls_new(tor_socket_t sock, int isServer) 648 { 649 BIO *bio = NULL; 650 tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t)); 651 tor_tls_context_t *context = tor_tls_context_get(isServer); 652 result->magic = TOR_TLS_MAGIC; 653 654 check_no_tls_errors(); 655 tor_assert(context); /* make sure somebody made it first */ 656 if (!(result->ssl = SSL_new(context->ctx))) { 657 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object"); 658 tor_free(result); 659 goto err; 660 } 661 662 #ifdef SSL_set_tlsext_host_name 663 /* Browsers use the TLS hostname extension, so we should too. */ 664 if (!isServer) { 665 char *fake_hostname = crypto_random_hostname(4,25, "www.",".com"); 666 SSL_set_tlsext_host_name(result->ssl, fake_hostname); 667 tor_free(fake_hostname); 668 } 669 #endif /* defined(SSL_set_tlsext_host_name) */ 670 671 #ifdef SSL_CTRL_SET_MAX_PROTO_VERSION 672 if (openssl_bug_7712_is_present) { 673 /* We can't actually use TLS 1.3 until this bug is fixed. */ 674 SSL_set_max_proto_version(result->ssl, TLS1_2_VERSION); 675 } 676 #endif /* defined(SSL_CTRL_SET_MAX_PROTO_VERSION) */ 677 678 /* Contrary to SSL_set_cipher_list(), TLSv1.3 SSL_set_ciphersuites() does NOT 679 * accept the final ':' so we have to strip it out. */ 680 size_t TLSv13len = strlen(CLIENT_CIPHER_LIST_TLSv13); 681 if (TLSv13len && CLIENT_CIPHER_LIST_TLSv13[TLSv13len - 1] == ':') { 682 CLIENT_CIPHER_LIST_TLSv13[TLSv13len - 1] = '\0'; 683 } 684 685 const bool tls12_ciphers_ok = SSL_set_cipher_list( 686 result->ssl, 687 isServer ? UNRESTRICTED_TLS1_2_SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST); 688 689 bool tls13_ciphers_ok = true; 690 #ifdef HAVE_SSL_SET_CIPHERSUITES 691 if (!isServer) { 692 tls13_ciphers_ok = 693 SSL_set_ciphersuites(result->ssl, CLIENT_CIPHER_LIST_TLSv13); 694 } 695 #endif 696 697 if (!tls12_ciphers_ok || !tls13_ciphers_ok) { 698 tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers"); 699 #ifdef SSL_set_tlsext_host_name 700 SSL_set_tlsext_host_name(result->ssl, NULL); 701 #endif 702 SSL_free(result->ssl); 703 tor_free(result); 704 goto err; 705 } 706 707 result->socket = sock; 708 bio = BIO_new_socket(sock, BIO_CLOSE); 709 if (! bio) { 710 tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO"); 711 #ifdef SSL_set_tlsext_host_name 712 SSL_set_tlsext_host_name(result->ssl, NULL); 713 #endif 714 SSL_free(result->ssl); 715 tor_free(result); 716 goto err; 717 } 718 { 719 int set_worked = 720 SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result); 721 if (!set_worked) { 722 log_warn(LD_BUG, 723 "Couldn't set the tls for an SSL*; connection will fail"); 724 } 725 } 726 SSL_set_bio(result->ssl, bio, bio); 727 tor_tls_context_incref(context); 728 result->context = context; 729 result->state = TOR_TLS_ST_HANDSHAKE; 730 result->isServer = isServer; 731 result->wantwrite_n = 0; 732 result->last_write_count = (unsigned long) BIO_number_written(bio); 733 result->last_read_count = (unsigned long) BIO_number_read(bio); 734 if (result->last_write_count || result->last_read_count) { 735 log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu", 736 result->last_read_count, result->last_write_count); 737 } 738 739 SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback); 740 741 goto done; 742 err: 743 result = NULL; 744 done: 745 /* Not expected to get called. */ 746 tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object"); 747 return result; 748 } 749 750 /** 751 * Tell the TLS library that the underlying socket for <b>tls</b> has been 752 * closed, and the library should not attempt to free that socket itself. 753 */ 754 void 755 tor_tls_release_socket(tor_tls_t *tls) 756 { 757 if (! tls) 758 return; 759 760 BIO *rbio, *wbio; 761 rbio = SSL_get_rbio(tls->ssl); 762 wbio = SSL_get_wbio(tls->ssl); 763 764 if (rbio) { 765 (void) BIO_set_close(rbio, BIO_NOCLOSE); 766 } 767 if (wbio && wbio != rbio) { 768 (void) BIO_set_close(wbio, BIO_NOCLOSE); 769 } 770 } 771 772 void 773 tor_tls_impl_free_(tor_tls_impl_t *ssl) 774 { 775 if (!ssl) 776 return; 777 778 #ifdef SSL_set_tlsext_host_name 779 SSL_set_tlsext_host_name(ssl, NULL); 780 #endif 781 SSL_free(ssl); 782 } 783 784 /** Underlying function for TLS reading. Reads up to <b>len</b> 785 * characters from <b>tls</b> into <b>cp</b>. On success, returns the 786 * number of characters read. On failure, returns TOR_TLS_ERROR, 787 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE. 788 */ 789 MOCK_IMPL(int, 790 tor_tls_read,(tor_tls_t *tls, char *cp, size_t len)) 791 { 792 int r, err; 793 tor_assert(tls); 794 tor_assert(tls->ssl); 795 tor_assert(tls->state == TOR_TLS_ST_OPEN); 796 tor_assert(len<INT_MAX); 797 r = SSL_read(tls->ssl, cp, (int)len); 798 if (r > 0) { 799 return r; 800 } 801 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET); 802 if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) { 803 log_debug(LD_NET,"read returned r=%d; TLS is closed",r); 804 tls->state = TOR_TLS_ST_CLOSED; 805 return TOR_TLS_CLOSE; 806 } else { 807 tor_assert(err != TOR_TLS_DONE); 808 log_debug(LD_NET,"read returned r=%d, err=%d",r,err); 809 return err; 810 } 811 } 812 813 /** Total number of bytes that we've used TLS to send. Used to track TLS 814 * overhead. */ 815 STATIC uint64_t total_bytes_written_over_tls = 0; 816 /** Total number of bytes that TLS has put on the network for us. Used to 817 * track TLS overhead. */ 818 STATIC uint64_t total_bytes_written_by_tls = 0; 819 820 /** Underlying function for TLS writing. Write up to <b>n</b> 821 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the 822 * number of characters written. On failure, returns TOR_TLS_ERROR, 823 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE. 824 */ 825 int 826 tor_tls_write(tor_tls_t *tls, const char *cp, size_t n) 827 { 828 int r, err; 829 tor_assert(tls); 830 tor_assert(tls->ssl); 831 tor_assert(tls->state == TOR_TLS_ST_OPEN); 832 tor_assert(n < INT_MAX); 833 if (n == 0) 834 return 0; 835 if (tls->wantwrite_n) { 836 /* if WANTWRITE last time, we must use the _same_ n as before */ 837 tor_assert(n >= tls->wantwrite_n); 838 log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)", 839 (int)n, (int)tls->wantwrite_n); 840 n = tls->wantwrite_n; 841 tls->wantwrite_n = 0; 842 } 843 r = SSL_write(tls->ssl, cp, (int)n); 844 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET); 845 if (err == TOR_TLS_DONE) { 846 total_bytes_written_over_tls += r; 847 return r; 848 } 849 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) { 850 tls->wantwrite_n = n; 851 } 852 return err; 853 } 854 855 /** Perform initial handshake on <b>tls</b>. When finished, returns 856 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, 857 * or TOR_TLS_WANTWRITE. 858 */ 859 int 860 tor_tls_handshake(tor_tls_t *tls) 861 { 862 int r; 863 tor_assert(tls); 864 tor_assert(tls->ssl); 865 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE); 866 867 check_no_tls_errors(); 868 869 OSSL_HANDSHAKE_STATE oldstate = SSL_get_state(tls->ssl); 870 871 if (tls->isServer) { 872 log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls, 873 SSL_state_string_long(tls->ssl)); 874 r = SSL_accept(tls->ssl); 875 } else { 876 log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls, 877 SSL_state_string_long(tls->ssl)); 878 r = SSL_connect(tls->ssl); 879 } 880 881 OSSL_HANDSHAKE_STATE newstate = SSL_get_state(tls->ssl); 882 883 if (oldstate != newstate) 884 log_debug(LD_HANDSHAKE, "After call, %p was in state %s", 885 tls, SSL_state_string_long(tls->ssl)); 886 887 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE); 888 if (ERR_peek_error() != 0) { 889 tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE, 890 "handshaking"); 891 return TOR_TLS_ERROR_MISC; 892 } 893 if (r == TOR_TLS_DONE) { 894 tls->state = TOR_TLS_ST_OPEN; 895 } 896 return r; 897 } 898 899 /** Return true iff this TLS connection is authenticated. 900 */ 901 int 902 tor_tls_peer_has_cert(tor_tls_t *tls) 903 { 904 X509 *cert; 905 cert = SSL_get_peer_certificate(tls->ssl); 906 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate"); 907 if (!cert) 908 return 0; 909 X509_free(cert); 910 return 1; 911 } 912 913 /** Return a newly allocated copy of the peer certificate, or NULL if there 914 * isn't one. */ 915 MOCK_IMPL(tor_x509_cert_t *, 916 tor_tls_get_peer_cert,(tor_tls_t *tls)) 917 { 918 X509 *cert; 919 cert = SSL_get_peer_certificate(tls->ssl); 920 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate"); 921 if (!cert) 922 return NULL; 923 return tor_x509_cert_new(cert); 924 } 925 926 /** Return a newly allocated copy of the cerficate we used on the connection, 927 * or NULL if somehow we didn't use one. */ 928 MOCK_IMPL(tor_x509_cert_t *, 929 tor_tls_get_own_cert,(tor_tls_t *tls)) 930 { 931 X509 *cert = SSL_get_certificate(tls->ssl); 932 tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, 933 "getting own-connection certificate"); 934 if (!cert) 935 return NULL; 936 /* Fun inconsistency: SSL_get_peer_certificate increments the reference 937 * count, but SSL_get_certificate does not. */ 938 X509 *duplicate = X509_dup(cert); 939 if (BUG(duplicate == NULL)) 940 return NULL; 941 return tor_x509_cert_new(duplicate); 942 } 943 944 /** Return the number of bytes available for reading from <b>tls</b>. 945 */ 946 int 947 tor_tls_get_pending_bytes(tor_tls_t *tls) 948 { 949 tor_assert(tls); 950 return SSL_pending(tls->ssl); 951 } 952 953 /** If <b>tls</b> requires that the next write be of a particular size, 954 * return that size. Otherwise, return 0. */ 955 size_t 956 tor_tls_get_forced_write_size(tor_tls_t *tls) 957 { 958 return tls->wantwrite_n; 959 } 960 961 /** Sets n_read and n_written to the number of bytes read and written, 962 * respectively, on the raw socket used by <b>tls</b> since the last time this 963 * function was called on <b>tls</b>. */ 964 void 965 tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written) 966 { 967 BIO *wbio, *tmpbio; 968 unsigned long r, w; 969 r = (unsigned long) BIO_number_read(SSL_get_rbio(tls->ssl)); 970 /* We want the number of bytes actually for real written. Unfortunately, 971 * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio, 972 * which makes the answer turn out wrong. Let's cope with that. Note 973 * that this approach will fail if we ever replace tls->ssl's BIOs with 974 * buffering bios for reasons of our own. As an alternative, we could 975 * save the original BIO for tls->ssl in the tor_tls_t structure, but 976 * that would be tempting fate. */ 977 wbio = SSL_get_wbio(tls->ssl); 978 if (BIO_method_type(wbio) == BIO_TYPE_BUFFER && 979 (tmpbio = BIO_next(wbio)) != NULL) 980 wbio = tmpbio; 981 w = (unsigned long) BIO_number_written(wbio); 982 983 /* We are ok with letting these unsigned ints go "negative" here: 984 * If we wrapped around, this should still give us the right answer, unless 985 * we wrapped around by more than ULONG_MAX since the last time we called 986 * this function. 987 */ 988 *n_read = (size_t)(r - tls->last_read_count); 989 *n_written = (size_t)(w - tls->last_write_count); 990 if (*n_read > INT_MAX || *n_written > INT_MAX) { 991 log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. " 992 "r=%lu, last_read=%lu, w=%lu, last_written=%lu", 993 r, tls->last_read_count, w, tls->last_write_count); 994 } 995 total_bytes_written_by_tls += *n_written; 996 tls->last_read_count = r; 997 tls->last_write_count = w; 998 } 999 1000 /** Return a ratio of the bytes that TLS has sent to the bytes that we've told 1001 * it to send. Used to track whether our TLS records are getting too tiny. */ 1002 MOCK_IMPL(double, 1003 tls_get_write_overhead_ratio,(void)) 1004 { 1005 if (total_bytes_written_over_tls == 0) 1006 return 1.0; 1007 1008 return ((double)total_bytes_written_by_tls) / 1009 ((double)total_bytes_written_over_tls); 1010 } 1011 1012 /** Implement check_no_tls_errors: If there are any pending OpenSSL 1013 * errors, log an error message. */ 1014 void 1015 check_no_tls_errors_(const char *fname, int line) 1016 { 1017 if (ERR_peek_error() == 0) 1018 return; 1019 log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ", 1020 tor_fix_source_file(fname), line); 1021 tls_log_errors(NULL, LOG_WARN, LD_NET, NULL); 1022 } 1023 1024 /** Using the RFC5705 key material exporting construction, and the 1025 * provided <b>context</b> (<b>context_len</b> bytes long) and 1026 * <b>label</b> (a NUL-terminated string), compute a 32-byte secret in 1027 * <b>secrets_out</b> that only the parties to this TLS session can 1028 * compute. Return 0 on success; -1 on failure; and -2 on failure 1029 * caused by OpenSSL bug 7712. 1030 */ 1031 MOCK_IMPL(int, 1032 tor_tls_export_key_material,(tor_tls_t *tls, uint8_t *secrets_out, 1033 const uint8_t *context, 1034 size_t context_len, 1035 const char *label)) 1036 { 1037 tor_assert(tls); 1038 tor_assert(tls->ssl); 1039 1040 int r = SSL_export_keying_material(tls->ssl, 1041 secrets_out, DIGEST256_LEN, 1042 label, strlen(label), 1043 context, context_len, 1); 1044 1045 if (r != 1) { 1046 int severity = openssl_bug_7712_is_present ? LOG_WARN : LOG_DEBUG; 1047 tls_log_errors(tls, severity, LD_NET, "exporting keying material"); 1048 } 1049 1050 #ifdef TLS1_3_VERSION 1051 if (r != 1 && 1052 strlen(label) > 12 && 1053 SSL_version(tls->ssl) >= TLS1_3_VERSION) { 1054 1055 if (! openssl_bug_7712_is_present) { 1056 /* We might have run into OpenSSL issue 7712, which caused OpenSSL 1057 * 1.1.1a to not handle long labels. Let's test to see if we have. 1058 */ 1059 r = SSL_export_keying_material(tls->ssl, secrets_out, DIGEST256_LEN, 1060 "short", 5, context, context_len, 1); 1061 if (r == 1) { 1062 /* A short label succeeds, but a long label fails. This was openssl 1063 * issue 7712. */ 1064 openssl_bug_7712_is_present = 1; 1065 log_warn(LD_GENERAL, "Detected OpenSSL bug 7712: disabling TLS 1.3 on " 1066 "future connections."); 1067 } 1068 } 1069 if (openssl_bug_7712_is_present) 1070 return -2; 1071 else 1072 return -1; 1073 } 1074 #endif /* defined(TLS1_3_VERSION) */ 1075 1076 return (r == 1) ? 0 : -1; 1077 } 1078 1079 /** Examine the amount of memory used and available for buffers in <b>tls</b>. 1080 * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read 1081 * buffer and *<b>rbuf_bytes</b> to the amount actually used. 1082 * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write 1083 * buffer and *<b>wbuf_bytes</b> to the amount actually used. 1084 * 1085 * Return 0 on success, -1 on failure.*/ 1086 int 1087 tor_tls_get_buffer_sizes(tor_tls_t *tls, 1088 size_t *rbuf_capacity, size_t *rbuf_bytes, 1089 size_t *wbuf_capacity, size_t *wbuf_bytes) 1090 { 1091 (void)tls; 1092 (void)rbuf_capacity; 1093 (void)rbuf_bytes; 1094 (void)wbuf_capacity; 1095 (void)wbuf_bytes; 1096 1097 return -1; 1098 } 1099 1100 /** Check whether the ECC group requested is supported by the current OpenSSL 1101 * library instance. Return 1 if the group is supported, and 0 if not. 1102 */ 1103 int 1104 evaluate_ecgroup_for_tls(const char *ecgroup) 1105 { 1106 EC_KEY *ec_key; 1107 int nid; 1108 int ret; 1109 1110 if (!ecgroup) 1111 nid = NID_tor_default_ecdhe_group; 1112 else if (!strcasecmp(ecgroup, "P256")) 1113 nid = NID_X9_62_prime256v1; 1114 else if (!strcasecmp(ecgroup, "P224")) 1115 nid = NID_secp224r1; 1116 else 1117 return 0; 1118 1119 ec_key = EC_KEY_new_by_curve_name(nid); 1120 ret = (ec_key != NULL); 1121 EC_KEY_free(ec_key); 1122 1123 return ret; 1124 }