1 /* $NetBSD: tls.c,v 1.10 2026/08/29 14:55:18 christos Exp $ */ 2 3 /* 4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC") 5 * 6 * SPDX-License-Identifier: MPL-2.0 7 * 8 * This Source Code Form is subject to the terms of the Mozilla Public 9 * License, v. 2.0. If a copy of the MPL was not distributed with this 10 * file, you can obtain one at https://mozilla.org/MPL/2.0/. 11 * 12 * See the COPYRIGHT file distributed with this work for additional 13 * information regarding copyright ownership. 14 */ 15 16 #include <inttypes.h> 17 #include <netinet/in.h> 18 #include <stdlib.h> 19 #include <string.h> 20 #include <sys/socket.h> 21 #if HAVE_LIBNGHTTP2 22 #include <nghttp2/nghttp2.h> 23 #endif /* HAVE_LIBNGHTTP2 */ 24 #include <arpa/inet.h> 25 26 #include <openssl/bn.h> 27 #include <openssl/conf.h> 28 #include <openssl/crypto.h> 29 #include <openssl/dh.h> 30 #if !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 31 #include <openssl/engine.h> 32 #endif /* if !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 */ 33 #include <openssl/err.h> 34 #include <openssl/evp.h> 35 #include <openssl/opensslv.h> 36 #include <openssl/rand.h> 37 #include <openssl/rsa.h> 38 #include <openssl/x509_vfy.h> 39 #include <openssl/x509v3.h> 40 41 #include <isc/atomic.h> 42 #include <isc/ht.h> 43 #include <isc/log.h> 44 #include <isc/magic.h> 45 #include <isc/mem.h> 46 #include <isc/mutex.h> 47 #include <isc/mutexblock.h> 48 #include <isc/once.h> 49 #include <isc/random.h> 50 #include <isc/refcount.h> 51 #include <isc/rwlock.h> 52 #include <isc/sockaddr.h> 53 #include <isc/thread.h> 54 #include <isc/tls.h> 55 #include <isc/util.h> 56 57 #include "openssl_shim.h" 58 59 #define COMMON_SSL_OPTIONS \ 60 (SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION) 61 62 #if OPENSSL_VERSION_NUMBER < 0x10100000L 63 static isc_mem_t *isc__tls_mctx = NULL; 64 static isc_mutex_t *locks = NULL; 65 static int nlocks; 66 67 static void 68 isc__tls_lock_callback(int mode, int type, const char *file, int line) { 69 UNUSED(file); 70 UNUSED(line); 71 if ((mode & CRYPTO_LOCK) != 0) { 72 LOCK(&locks[type]); 73 } else { 74 UNLOCK(&locks[type]); 75 } 76 } 77 78 static void 79 isc__tls_set_thread_id(CRYPTO_THREADID *id) { 80 CRYPTO_THREADID_set_numeric(id, (unsigned long)isc_thread_self()); 81 } 82 #endif 83 84 void 85 isc__tls_initialize(void) { 86 #if OPENSSL_VERSION_NUMBER >= 0x10100000L 87 uint64_t opts = OPENSSL_INIT_ENGINE_ALL_BUILTIN | 88 OPENSSL_INIT_LOAD_CONFIG; 89 #if defined(OPENSSL_INIT_NO_ATEXIT) 90 /* 91 * We call OPENSSL_cleanup() manually, in a correct order, thus disable 92 * the automatic atexit() handler. 93 */ 94 opts |= OPENSSL_INIT_NO_ATEXIT; 95 #endif 96 97 RUNTIME_CHECK(OPENSSL_init_ssl(opts, NULL) == 1); 98 #else 99 isc_mem_create(&isc__tls_mctx); 100 isc_mem_setname(isc__tls_mctx, "OpenSSL"); 101 isc_mem_setdestroycheck(isc__tls_mctx, false); 102 103 nlocks = CRYPTO_num_locks(); 104 locks = isc_mem_cget(isc__tls_mctx, nlocks, sizeof(locks[0])); 105 isc_mutexblock_init(locks, nlocks); 106 CRYPTO_set_locking_callback(isc__tls_lock_callback); 107 CRYPTO_THREADID_set_callback(isc__tls_set_thread_id); 108 109 CRYPTO_malloc_init(); 110 ERR_load_crypto_strings(); 111 SSL_load_error_strings(); 112 SSL_library_init(); 113 114 #if !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 115 ENGINE_load_builtin_engines(); 116 #endif 117 OpenSSL_add_all_algorithms(); 118 OPENSSL_load_builtin_modules(); 119 120 CONF_modules_load_file(NULL, NULL, 121 CONF_MFLAGS_DEFAULT_SECTION | 122 CONF_MFLAGS_IGNORE_MISSING_FILE); 123 #endif 124 125 /* Protect ourselves against unseeded PRNG */ 126 if (RAND_status() != 1) { 127 FATAL_ERROR("OpenSSL pseudorandom number generator " 128 "cannot be initialized (see the `PRNG not " 129 "seeded' message in the OpenSSL FAQ)"); 130 } 131 } 132 133 void 134 isc__tls_shutdown(void) { 135 #if OPENSSL_VERSION_NUMBER >= 0x10100000L 136 OPENSSL_cleanup(); 137 #else 138 CONF_modules_unload(1); 139 OBJ_cleanup(); 140 EVP_cleanup(); 141 #if !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 142 ENGINE_cleanup(); 143 #endif 144 CRYPTO_cleanup_all_ex_data(); 145 ERR_remove_thread_state(NULL); 146 RAND_cleanup(); 147 ERR_free_strings(); 148 149 CRYPTO_set_locking_callback(NULL); 150 151 if (locks != NULL) { 152 isc_mutexblock_destroy(locks, nlocks); 153 isc_mem_cput(isc__tls_mctx, locks, nlocks, sizeof(locks[0])); 154 locks = NULL; 155 } 156 157 isc_mem_destroy(&isc__tls_mctx); 158 #endif 159 } 160 161 void 162 isc__tls_setdestroycheck(bool check) { 163 #if OPENSSL_VERSION_NUMBER < 0x10100000L 164 isc_mem_setdestroycheck(isc__tls_mctx, check); 165 #else 166 UNUSED(check); 167 #endif 168 } 169 170 void 171 isc_tlsctx_free(isc_tlsctx_t **ctxp) { 172 SSL_CTX *ctx = NULL; 173 REQUIRE(ctxp != NULL && *ctxp != NULL); 174 175 ctx = *ctxp; 176 *ctxp = NULL; 177 178 SSL_CTX_free(ctx); 179 } 180 181 void 182 isc_tlsctx_attach(isc_tlsctx_t *src, isc_tlsctx_t **ptarget) { 183 REQUIRE(src != NULL); 184 REQUIRE(ptarget != NULL && *ptarget == NULL); 185 186 RUNTIME_CHECK(SSL_CTX_up_ref(src) == 1); 187 188 *ptarget = src; 189 } 190 191 #if HAVE_SSL_CTX_SET_KEYLOG_CALLBACK 192 /* 193 * Callback invoked by the SSL library whenever a new TLS pre-master secret 194 * needs to be logged. 195 */ 196 static void 197 sslkeylogfile_append(const SSL *ssl, const char *line) { 198 UNUSED(ssl); 199 200 isc_log_write(isc_lctx, ISC_LOGCATEGORY_SSLKEYLOG, ISC_LOGMODULE_NETMGR, 201 ISC_LOG_INFO, "%s", line); 202 } 203 204 /* 205 * Enable TLS pre-master secret logging if the SSLKEYLOGFILE environment 206 * variable is set. This needs to be done on a per-context basis as that is 207 * how SSL_CTX_set_keylog_callback() works. 208 */ 209 static void 210 sslkeylogfile_init(isc_tlsctx_t *ctx) { 211 if (getenv("SSLKEYLOGFILE") != NULL) { 212 SSL_CTX_set_keylog_callback(ctx, sslkeylogfile_append); 213 } 214 } 215 #else /* HAVE_SSL_CTX_SET_KEYLOG_CALLBACK */ 216 #define sslkeylogfile_init(ctx) 217 #endif /* HAVE_SSL_CTX_SET_KEYLOG_CALLBACK */ 218 219 isc_result_t 220 isc_tlsctx_createclient(isc_tlsctx_t **ctxp) { 221 unsigned long err; 222 char errbuf[256]; 223 SSL_CTX *ctx = NULL; 224 const SSL_METHOD *method = NULL; 225 226 REQUIRE(ctxp != NULL && *ctxp == NULL); 227 228 method = TLS_client_method(); 229 if (method == NULL) { 230 goto ssl_error; 231 } 232 ctx = SSL_CTX_new(method); 233 if (ctx == NULL) { 234 goto ssl_error; 235 } 236 237 SSL_CTX_set_options(ctx, COMMON_SSL_OPTIONS); 238 239 #if HAVE_SSL_CTX_SET_MIN_PROTO_VERSION 240 SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION); 241 #else 242 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | 243 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); 244 #endif 245 246 sslkeylogfile_init(ctx); 247 248 *ctxp = ctx; 249 250 return ISC_R_SUCCESS; 251 252 ssl_error: 253 err = ERR_get_error(); 254 ERR_error_string_n(err, errbuf, sizeof(errbuf)); 255 isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_NETMGR, 256 ISC_LOG_ERROR, "Error initializing TLS context: %s", 257 errbuf); 258 259 return ISC_R_TLSERROR; 260 } 261 262 isc_result_t 263 isc_tlsctx_load_certificate(isc_tlsctx_t *ctx, const char *keyfile, 264 const char *certfile) { 265 int rv; 266 REQUIRE(ctx != NULL); 267 REQUIRE(keyfile != NULL); 268 REQUIRE(certfile != NULL); 269 270 rv = SSL_CTX_use_certificate_chain_file(ctx, certfile); 271 if (rv != 1) { 272 unsigned long err = ERR_peek_last_error(); 273 char errbuf[1024] = { 0 }; 274 ERR_error_string_n(err, errbuf, sizeof(errbuf)); 275 isc_log_write( 276 isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_NETMGR, 277 ISC_LOG_ERROR, 278 "SSL_CTX_use_certificate_chain_file: '%s' failed: %s", 279 certfile, errbuf); 280 return ISC_R_TLSERROR; 281 } 282 rv = SSL_CTX_use_PrivateKey_file(ctx, keyfile, SSL_FILETYPE_PEM); 283 if (rv != 1) { 284 unsigned long err = ERR_peek_last_error(); 285 char errbuf[1024] = { 0 }; 286 ERR_error_string_n(err, errbuf, sizeof(errbuf)); 287 isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, 288 ISC_LOGMODULE_NETMGR, ISC_LOG_ERROR, 289 "SSL_CTX_use_PrivateKey_file: '%s' failed: %s", 290 keyfile, errbuf); 291 return ISC_R_TLSERROR; 292 } 293 294 return ISC_R_SUCCESS; 295 } 296 297 isc_result_t 298 isc_tlsctx_createserver(const char *keyfile, const char *certfile, 299 isc_tlsctx_t **ctxp) { 300 int rv; 301 unsigned long err; 302 bool ephemeral = (keyfile == NULL && certfile == NULL); 303 X509 *cert = NULL; 304 EVP_PKEY *pkey = NULL; 305 SSL_CTX *ctx = NULL; 306 #if OPENSSL_VERSION_NUMBER < 0x30000000L 307 EC_KEY *eckey = NULL; 308 #else 309 EVP_PKEY_CTX *pkey_ctx = NULL; 310 EVP_PKEY *params_pkey = NULL; 311 #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */ 312 char errbuf[256]; 313 const SSL_METHOD *method = NULL; 314 315 REQUIRE(ctxp != NULL && *ctxp == NULL); 316 REQUIRE((keyfile == NULL) == (certfile == NULL)); 317 318 method = TLS_server_method(); 319 if (method == NULL) { 320 goto ssl_error; 321 } 322 ctx = SSL_CTX_new(method); 323 if (ctx == NULL) { 324 goto ssl_error; 325 } 326 RUNTIME_CHECK(ctx != NULL); 327 328 SSL_CTX_set_options(ctx, COMMON_SSL_OPTIONS); 329 330 #if HAVE_SSL_CTX_SET_MIN_PROTO_VERSION 331 SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION); 332 #else 333 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | 334 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); 335 #endif 336 337 if (ephemeral) { 338 const int group_nid = NID_X9_62_prime256v1; 339 340 #if OPENSSL_VERSION_NUMBER < 0x30000000L 341 eckey = EC_KEY_new_by_curve_name(group_nid); 342 if (eckey == NULL) { 343 goto ssl_error; 344 } 345 346 /* Generate the key. */ 347 rv = EC_KEY_generate_key(eckey); 348 if (rv != 1) { 349 goto ssl_error; 350 } 351 pkey = EVP_PKEY_new(); 352 if (pkey == NULL) { 353 goto ssl_error; 354 } 355 rv = EVP_PKEY_set1_EC_KEY(pkey, eckey); 356 if (rv != 1) { 357 goto ssl_error; 358 } 359 360 /* Use a named curve and uncompressed point conversion form. */ 361 #if HAVE_EVP_PKEY_GET0_EC_KEY 362 EC_KEY_set_asn1_flag(EVP_PKEY_get0_EC_KEY(pkey), 363 OPENSSL_EC_NAMED_CURVE); 364 EC_KEY_set_conv_form(EVP_PKEY_get0_EC_KEY(pkey), 365 POINT_CONVERSION_UNCOMPRESSED); 366 #else 367 EC_KEY_set_asn1_flag(pkey->pkey.ec, OPENSSL_EC_NAMED_CURVE); 368 EC_KEY_set_conv_form(pkey->pkey.ec, 369 POINT_CONVERSION_UNCOMPRESSED); 370 #endif /* HAVE_EVP_PKEY_GET0_EC_KEY */ 371 372 #if defined(SSL_CTX_set_ecdh_auto) 373 /* 374 * Using this macro is required for older versions of OpenSSL to 375 * automatically enable ECDH support. 376 * 377 * On later versions this function is no longer needed and is 378 * deprecated. 379 */ 380 (void)SSL_CTX_set_ecdh_auto(ctx, 1); 381 #endif /* defined(SSL_CTX_set_ecdh_auto) */ 382 383 /* Cleanup */ 384 EC_KEY_free(eckey); 385 eckey = NULL; 386 #else 387 /* Generate the key's parameters. */ 388 pkey_ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL); 389 if (pkey_ctx == NULL) { 390 goto ssl_error; 391 } 392 rv = EVP_PKEY_paramgen_init(pkey_ctx); 393 if (rv != 1) { 394 goto ssl_error; 395 } 396 rv = EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pkey_ctx, 397 group_nid); 398 if (rv != 1) { 399 goto ssl_error; 400 } 401 rv = EVP_PKEY_paramgen(pkey_ctx, ¶ms_pkey); 402 if (rv != 1 || params_pkey == NULL) { 403 goto ssl_error; 404 } 405 EVP_PKEY_CTX_free(pkey_ctx); 406 407 /* Generate the key. */ 408 pkey_ctx = EVP_PKEY_CTX_new(params_pkey, NULL); 409 if (pkey_ctx == NULL) { 410 goto ssl_error; 411 } 412 rv = EVP_PKEY_keygen_init(pkey_ctx); 413 if (rv != 1) { 414 goto ssl_error; 415 } 416 rv = EVP_PKEY_keygen(pkey_ctx, &pkey); 417 if (rv != 1 || pkey == NULL) { 418 goto ssl_error; 419 } 420 421 /* Cleanup */ 422 EVP_PKEY_free(params_pkey); 423 params_pkey = NULL; 424 EVP_PKEY_CTX_free(pkey_ctx); 425 pkey_ctx = NULL; 426 #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */ 427 428 cert = X509_new(); 429 if (cert == NULL) { 430 goto ssl_error; 431 } 432 433 ASN1_INTEGER_set(X509_get_serialNumber(cert), 434 (long)isc_random32()); 435 436 /* 437 * Set the "not before" property 5 minutes into the past to 438 * accommodate with some possible clock skew across systems. 439 */ 440 #if OPENSSL_VERSION_NUMBER < 0x10101000L 441 X509_gmtime_adj(X509_get_notBefore(cert), -300); 442 #else 443 X509_gmtime_adj(X509_getm_notBefore(cert), -300); 444 #endif 445 446 /* 447 * We set the vailidy for 10 years. 448 */ 449 #if OPENSSL_VERSION_NUMBER < 0x10101000L 450 X509_gmtime_adj(X509_get_notAfter(cert), 3650 * 24 * 3600); 451 #else 452 X509_gmtime_adj(X509_getm_notAfter(cert), 3650 * 24 * 3600); 453 #endif 454 455 X509_set_pubkey(cert, pkey); 456 457 X509_NAME *name = X509_NAME_dup(X509_get_subject_name(cert)); 458 459 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, 460 (const unsigned char *)"AQ", -1, -1, 461 0); 462 X509_NAME_add_entry_by_txt( 463 name, "O", MBSTRING_ASC, 464 (const unsigned char *)"BIND9 ephemeral " 465 "certificate", 466 -1, -1, 0); 467 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, 468 (const unsigned char *)"bind9.local", 469 -1, -1, 0); 470 471 X509_set_issuer_name(cert, name); 472 473 X509_NAME_free(name); 474 475 X509_sign(cert, pkey, EVP_sha256()); 476 rv = SSL_CTX_use_certificate(ctx, cert); 477 if (rv != 1) { 478 goto ssl_error; 479 } 480 rv = SSL_CTX_use_PrivateKey(ctx, pkey); 481 if (rv != 1) { 482 goto ssl_error; 483 } 484 485 X509_free(cert); 486 EVP_PKEY_free(pkey); 487 } else { 488 isc_result_t result; 489 result = isc_tlsctx_load_certificate(ctx, keyfile, certfile); 490 if (result != ISC_R_SUCCESS) { 491 goto ssl_error; 492 } 493 } 494 495 sslkeylogfile_init(ctx); 496 497 *ctxp = ctx; 498 return ISC_R_SUCCESS; 499 500 ssl_error: 501 err = ERR_get_error(); 502 ERR_error_string_n(err, errbuf, sizeof(errbuf)); 503 isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_NETMGR, 504 ISC_LOG_ERROR, "Error initializing TLS context: %s", 505 errbuf); 506 507 if (ctx != NULL) { 508 SSL_CTX_free(ctx); 509 } 510 if (cert != NULL) { 511 X509_free(cert); 512 } 513 if (pkey != NULL) { 514 EVP_PKEY_free(pkey); 515 } 516 #if OPENSSL_VERSION_NUMBER < 0x30000000L 517 if (eckey != NULL) { 518 EC_KEY_free(eckey); 519 } 520 #else 521 if (params_pkey != NULL) { 522 EVP_PKEY_free(params_pkey); 523 } 524 if (pkey_ctx != NULL) { 525 EVP_PKEY_CTX_free(pkey_ctx); 526 } 527 #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */ 528 529 return ISC_R_TLSERROR; 530 } 531 532 static long 533 get_tls_version_disable_bit(const isc_tls_protocol_version_t tls_ver) { 534 long bit = 0; 535 536 switch (tls_ver) { 537 case ISC_TLS_PROTO_VER_1_2: 538 #ifdef SSL_OP_NO_TLSv1_2 539 bit = SSL_OP_NO_TLSv1_2; 540 #else 541 bit = 0; 542 #endif 543 break; 544 case ISC_TLS_PROTO_VER_1_3: 545 #ifdef SSL_OP_NO_TLSv1_3 546 bit = SSL_OP_NO_TLSv1_3; 547 #else 548 bit = 0; 549 #endif 550 break; 551 default: 552 UNREACHABLE(); 553 break; 554 }; 555 556 return bit; 557 } 558 559 bool 560 isc_tls_protocol_supported(const isc_tls_protocol_version_t tls_ver) { 561 return get_tls_version_disable_bit(tls_ver) != 0; 562 } 563 564 isc_tls_protocol_version_t 565 isc_tls_protocol_name_to_version(const char *name) { 566 REQUIRE(name != NULL); 567 568 if (strcasecmp(name, "TLSv1.2") == 0) { 569 return ISC_TLS_PROTO_VER_1_2; 570 } else if (strcasecmp(name, "TLSv1.3") == 0) { 571 return ISC_TLS_PROTO_VER_1_3; 572 } 573 574 return ISC_TLS_PROTO_VER_UNDEFINED; 575 } 576 577 void 578 isc_tlsctx_set_protocols(isc_tlsctx_t *ctx, const uint32_t tls_versions) { 579 REQUIRE(ctx != NULL); 580 REQUIRE(tls_versions != 0); 581 long set_options = 0; 582 long clear_options = 0; 583 uint32_t versions = tls_versions; 584 585 /* 586 * The code below might be initially hard to follow because of the 587 * double negation that OpenSSL enforces. 588 * 589 * Taking into account that OpenSSL provides bits to *disable* 590 * specific protocol versions, like SSL_OP_NO_TLSv1_2, 591 * SSL_OP_NO_TLSv1_3, etc., the code has the following logic: 592 * 593 * If a protocol version is not specified in the bitmask, get the 594 * bit that disables it and add it to the set of TLS options to 595 * set ('set_options'). Otherwise, if a protocol version is set, 596 * add the bit to the set of options to clear ('clear_options'). 597 */ 598 599 /* TLS protocol versions are defined as powers of two. */ 600 for (uint32_t tls_ver = ISC_TLS_PROTO_VER_1_2; 601 tls_ver < ISC_TLS_PROTO_VER_UNDEFINED; tls_ver <<= 1) 602 { 603 if ((tls_versions & tls_ver) == 0) { 604 set_options |= get_tls_version_disable_bit(tls_ver); 605 } else { 606 /* 607 * Only supported versions should ever be passed to the 608 * function SSL_CTX_clear_options. For example, in order 609 * to enable TLS v1.2, we have to clear 610 * SSL_OP_NO_TLSv1_2. Insist that the configuration file 611 * was verified properly, so we are not trying to enable 612 * an unsupported TLS version. 613 */ 614 INSIST(isc_tls_protocol_supported(tls_ver)); 615 clear_options |= get_tls_version_disable_bit(tls_ver); 616 } 617 versions &= ~(tls_ver); 618 } 619 620 /* All versions should be processed at this point, thus the value 621 * must equal zero. If it is not, then some garbage has been 622 * passed to the function; this situation is worth 623 * investigation. */ 624 INSIST(versions == 0); 625 626 (void)SSL_CTX_set_options(ctx, set_options); 627 (void)SSL_CTX_clear_options(ctx, clear_options); 628 } 629 630 bool 631 isc_tlsctx_load_dhparams(isc_tlsctx_t *ctx, const char *dhparams_file) { 632 REQUIRE(ctx != NULL); 633 REQUIRE(dhparams_file != NULL); 634 REQUIRE(*dhparams_file != '\0'); 635 636 #if OPENSSL_VERSION_NUMBER < 0x30000000L 637 /* OpenSSL < 3.0 */ 638 DH *dh = NULL; 639 FILE *paramfile; 640 641 paramfile = fopen(dhparams_file, "r"); 642 643 if (paramfile) { 644 int check = 0; 645 dh = PEM_read_DHparams(paramfile, NULL, NULL, NULL); 646 fclose(paramfile); 647 648 if (dh == NULL) { 649 return false; 650 } else if (DH_check(dh, &check) != 1 || check != 0) { 651 DH_free(dh); 652 return false; 653 } 654 } else { 655 return false; 656 } 657 658 if (SSL_CTX_set_tmp_dh(ctx, dh) != 1) { 659 DH_free(dh); 660 return false; 661 } 662 663 DH_free(dh); 664 #else 665 /* OpenSSL >= 3.0: low level DH APIs are deprecated in OpenSSL 3.0 */ 666 EVP_PKEY *dh = NULL; 667 BIO *bio = NULL; 668 669 bio = BIO_new_file(dhparams_file, "r"); 670 if (bio == NULL) { 671 return false; 672 } 673 674 dh = PEM_read_bio_Parameters(bio, NULL); 675 if (dh == NULL) { 676 BIO_free(bio); 677 return false; 678 } 679 680 if (SSL_CTX_set0_tmp_dh_pkey(ctx, dh) != 1) { 681 BIO_free(bio); 682 EVP_PKEY_free(dh); 683 return false; 684 } 685 686 /* No need to call EVP_PKEY_free(dh) as the "dh" is owned by the 687 * SSL context at this point. */ 688 689 BIO_free(bio); 690 #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */ 691 692 return true; 693 } 694 695 bool 696 isc_tls_cipherlist_valid(const char *cipherlist) { 697 isc_tlsctx_t *tmp_ctx = NULL; 698 const SSL_METHOD *method = NULL; 699 bool result; 700 REQUIRE(cipherlist != NULL); 701 702 if (*cipherlist == '\0') { 703 return false; 704 } 705 706 method = TLS_server_method(); 707 if (method == NULL) { 708 return false; 709 } 710 tmp_ctx = SSL_CTX_new(method); 711 if (tmp_ctx == NULL) { 712 return false; 713 } 714 715 result = SSL_CTX_set_cipher_list(tmp_ctx, cipherlist) == 1; 716 717 isc_tlsctx_free(&tmp_ctx); 718 719 return result; 720 } 721 722 void 723 isc_tlsctx_set_cipherlist(isc_tlsctx_t *ctx, const char *cipherlist) { 724 REQUIRE(ctx != NULL); 725 REQUIRE(cipherlist != NULL); 726 REQUIRE(*cipherlist != '\0'); 727 728 RUNTIME_CHECK(SSL_CTX_set_cipher_list(ctx, cipherlist) == 1); 729 } 730 731 bool 732 isc_tls_cipher_suites_valid(const char *cipher_suites) { 733 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES 734 isc_tlsctx_t *tmp_ctx = NULL; 735 const SSL_METHOD *method = NULL; 736 bool result; 737 REQUIRE(cipher_suites != NULL); 738 739 if (*cipher_suites == '\0') { 740 return false; 741 } 742 743 method = TLS_server_method(); 744 if (method == NULL) { 745 return false; 746 } 747 tmp_ctx = SSL_CTX_new(method); 748 if (tmp_ctx == NULL) { 749 return false; 750 } 751 752 result = SSL_CTX_set_ciphersuites(tmp_ctx, cipher_suites) == 1; 753 754 isc_tlsctx_free(&tmp_ctx); 755 756 return result; 757 #else 758 UNUSED(cipher_suites); 759 760 UNREACHABLE(); 761 #endif 762 } 763 764 void 765 isc_tlsctx_set_cipher_suites(isc_tlsctx_t *ctx, const char *cipher_suites) { 766 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES 767 REQUIRE(ctx != NULL); 768 REQUIRE(cipher_suites != NULL); 769 REQUIRE(*cipher_suites != '\0'); 770 771 RUNTIME_CHECK(SSL_CTX_set_ciphersuites(ctx, cipher_suites) == 1); 772 #else 773 UNUSED(ctx); 774 UNUSED(cipher_suites); 775 776 UNREACHABLE(); 777 #endif 778 } 779 780 void 781 isc_tlsctx_prefer_server_ciphers(isc_tlsctx_t *ctx, const bool prefer) { 782 REQUIRE(ctx != NULL); 783 784 if (prefer) { 785 (void)SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); 786 } else { 787 (void)SSL_CTX_clear_options(ctx, 788 SSL_OP_CIPHER_SERVER_PREFERENCE); 789 } 790 } 791 792 void 793 isc_tlsctx_session_tickets(isc_tlsctx_t *ctx, const bool use) { 794 REQUIRE(ctx != NULL); 795 796 if (!use) { 797 (void)SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET); 798 } else { 799 (void)SSL_CTX_clear_options(ctx, SSL_OP_NO_TICKET); 800 } 801 } 802 803 isc_tls_t * 804 isc_tls_create(isc_tlsctx_t *ctx) { 805 isc_tls_t *newctx = NULL; 806 807 REQUIRE(ctx != NULL); 808 809 newctx = SSL_new(ctx); 810 if (newctx == NULL) { 811 char errbuf[256]; 812 unsigned long err = ERR_get_error(); 813 814 ERR_error_string_n(err, errbuf, sizeof(errbuf)); 815 fprintf(stderr, "%s:SSL_new(%p) -> %s\n", __func__, ctx, 816 errbuf); 817 } 818 819 return newctx; 820 } 821 822 void 823 isc_tls_free(isc_tls_t **tlsp) { 824 isc_tls_t *tls = NULL; 825 REQUIRE(tlsp != NULL && *tlsp != NULL); 826 827 tls = *tlsp; 828 *tlsp = NULL; 829 SSL_free(tls); 830 } 831 832 const char * 833 isc_tls_verify_peer_result_string(isc_tls_t *tls) { 834 REQUIRE(tls != NULL); 835 836 return X509_verify_cert_error_string(SSL_get_verify_result(tls)); 837 } 838 839 #if HAVE_LIBNGHTTP2 840 #ifndef OPENSSL_NO_NEXTPROTONEG 841 /* 842 * NPN TLS extension client callback. 843 */ 844 static int 845 select_next_proto_cb(SSL *ssl, unsigned char **out, unsigned char *outlen, 846 const unsigned char *in, unsigned int inlen, void *arg) { 847 UNUSED(ssl); 848 UNUSED(arg); 849 850 if (nghttp2_select_next_protocol(out, outlen, in, inlen) <= 0) { 851 return SSL_TLSEXT_ERR_NOACK; 852 } 853 return SSL_TLSEXT_ERR_OK; 854 } 855 #endif /* !OPENSSL_NO_NEXTPROTONEG */ 856 857 void 858 isc_tlsctx_enable_http2client_alpn(isc_tlsctx_t *ctx) { 859 REQUIRE(ctx != NULL); 860 861 #ifndef OPENSSL_NO_NEXTPROTONEG 862 SSL_CTX_set_next_proto_select_cb(ctx, select_next_proto_cb, NULL); 863 #endif /* !OPENSSL_NO_NEXTPROTONEG */ 864 865 #if OPENSSL_VERSION_NUMBER >= 0x10002000L 866 SSL_CTX_set_alpn_protos(ctx, (const unsigned char *)NGHTTP2_PROTO_ALPN, 867 NGHTTP2_PROTO_ALPN_LEN); 868 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */ 869 } 870 871 #ifndef OPENSSL_NO_NEXTPROTONEG 872 static int 873 next_proto_cb(isc_tls_t *ssl, const unsigned char **data, unsigned int *len, 874 void *arg) { 875 UNUSED(ssl); 876 UNUSED(arg); 877 878 *data = (const unsigned char *)NGHTTP2_PROTO_ALPN; 879 *len = (unsigned int)NGHTTP2_PROTO_ALPN_LEN; 880 return SSL_TLSEXT_ERR_OK; 881 } 882 #endif /* !OPENSSL_NO_NEXTPROTONEG */ 883 884 #if OPENSSL_VERSION_NUMBER >= 0x10002000L 885 static int 886 alpn_select_proto_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen, 887 const unsigned char *in, unsigned int inlen, void *arg) { 888 int ret; 889 890 UNUSED(ssl); 891 UNUSED(arg); 892 893 ret = nghttp2_select_next_protocol((unsigned char **)(uintptr_t)out, 894 outlen, in, inlen); 895 896 if (ret != 1) { 897 return SSL_TLSEXT_ERR_NOACK; 898 } 899 900 return SSL_TLSEXT_ERR_OK; 901 } 902 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */ 903 904 void 905 isc_tlsctx_enable_http2server_alpn(isc_tlsctx_t *tls) { 906 REQUIRE(tls != NULL); 907 908 #ifndef OPENSSL_NO_NEXTPROTONEG 909 SSL_CTX_set_next_protos_advertised_cb(tls, next_proto_cb, NULL); 910 #endif // OPENSSL_NO_NEXTPROTONEG 911 #if OPENSSL_VERSION_NUMBER >= 0x10002000L 912 SSL_CTX_set_alpn_select_cb(tls, alpn_select_proto_cb, NULL); 913 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L 914 } 915 #endif /* HAVE_LIBNGHTTP2 */ 916 917 void 918 isc_tls_get_selected_alpn(isc_tls_t *tls, const unsigned char **alpn, 919 unsigned int *alpnlen) { 920 REQUIRE(tls != NULL); 921 REQUIRE(alpn != NULL); 922 REQUIRE(alpnlen != NULL); 923 924 #ifndef OPENSSL_NO_NEXTPROTONEG 925 SSL_get0_next_proto_negotiated(tls, alpn, alpnlen); 926 #endif 927 #if OPENSSL_VERSION_NUMBER >= 0x10002000L 928 if (*alpn == NULL) { 929 SSL_get0_alpn_selected(tls, alpn, alpnlen); 930 } 931 #endif 932 } 933 934 static bool 935 protoneg_check_protocol(const uint8_t **pout, uint8_t *pout_len, 936 const uint8_t *in, size_t in_len, const uint8_t *key, 937 size_t key_len) { 938 for (size_t i = 0; i + key_len <= in_len; i += (size_t)(in[i] + 1)) { 939 if (memcmp(&in[i], key, key_len) == 0) { 940 *pout = (const uint8_t *)(&in[i + 1]); 941 *pout_len = in[i]; 942 return true; 943 } 944 } 945 return false; 946 } 947 948 /* dot prepended by its length (3 bytes) */ 949 #define DOT_PROTO_ALPN "\x3" ISC_TLS_DOT_PROTO_ALPN_ID 950 #define DOT_PROTO_ALPN_LEN (sizeof(DOT_PROTO_ALPN) - 1) 951 952 static bool 953 dot_select_next_protocol(const uint8_t **pout, uint8_t *pout_len, 954 const uint8_t *in, size_t in_len) { 955 return protoneg_check_protocol(pout, pout_len, in, in_len, 956 (const uint8_t *)DOT_PROTO_ALPN, 957 DOT_PROTO_ALPN_LEN); 958 } 959 960 void 961 isc_tlsctx_enable_dot_client_alpn(isc_tlsctx_t *ctx) { 962 REQUIRE(ctx != NULL); 963 964 #if OPENSSL_VERSION_NUMBER >= 0x10002000L 965 SSL_CTX_set_alpn_protos(ctx, (const uint8_t *)DOT_PROTO_ALPN, 966 DOT_PROTO_ALPN_LEN); 967 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */ 968 } 969 970 #if OPENSSL_VERSION_NUMBER >= 0x10002000L 971 static int 972 dot_alpn_select_proto_cb(SSL *ssl, const unsigned char **out, 973 unsigned char *outlen, const unsigned char *in, 974 unsigned int inlen, void *arg) { 975 bool ret; 976 977 UNUSED(ssl); 978 UNUSED(arg); 979 980 ret = dot_select_next_protocol(out, outlen, in, inlen); 981 982 if (!ret) { 983 return SSL_TLSEXT_ERR_NOACK; 984 } 985 986 return SSL_TLSEXT_ERR_OK; 987 } 988 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */ 989 990 void 991 isc_tlsctx_enable_dot_server_alpn(isc_tlsctx_t *tls) { 992 REQUIRE(tls != NULL); 993 994 #if OPENSSL_VERSION_NUMBER >= 0x10002000L 995 SSL_CTX_set_alpn_select_cb(tls, dot_alpn_select_proto_cb, NULL); 996 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L 997 } 998 999 isc_result_t 1000 isc_tlsctx_enable_peer_verification(isc_tlsctx_t *tlsctx, const bool is_server, 1001 isc_tls_cert_store_t *store, 1002 const char *hostname, 1003 bool hostname_ignore_subject) { 1004 int ret = 0; 1005 REQUIRE(tlsctx != NULL); 1006 REQUIRE(store != NULL); 1007 1008 /* Set the hostname/IP address. */ 1009 if (!is_server && hostname != NULL && *hostname != '\0') { 1010 struct in6_addr sa6; 1011 struct in_addr sa; 1012 X509_VERIFY_PARAM *param = SSL_CTX_get0_param(tlsctx); 1013 unsigned int hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; 1014 1015 /* It might be an IP address. */ 1016 if (inet_pton(AF_INET6, hostname, &sa6) == 1 || 1017 inet_pton(AF_INET, hostname, &sa) == 1) 1018 { 1019 ret = X509_VERIFY_PARAM_set1_ip_asc(param, hostname); 1020 } else { 1021 /* It seems that it is a host name. Let's set it. */ 1022 ret = X509_VERIFY_PARAM_set1_host(param, hostname, 0); 1023 } 1024 if (ret != 1) { 1025 ERR_clear_error(); 1026 return ISC_R_FAILURE; 1027 } 1028 1029 #ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT 1030 /* 1031 * According to the RFC 8310, Section 8.1, Subject field MUST 1032 * NOT be inspected when verifying a hostname when using 1033 * DoT. Only SubjectAltName must be checked instead. That is 1034 * not the case for HTTPS, though. 1035 * 1036 * Unfortunately, some quite old versions of OpenSSL (< 1.1.1) 1037 * might lack the functionality to implement that. It should 1038 * have very little real-world consequences, as most of the 1039 * production-ready certificates issued by real CAs will have 1040 * SubjectAltName set. In such a case, the Subject field is 1041 * ignored. 1042 */ 1043 if (hostname_ignore_subject) { 1044 hostflags |= X509_CHECK_FLAG_NEVER_CHECK_SUBJECT; 1045 } 1046 #else 1047 UNUSED(hostname_ignore_subject); 1048 #endif 1049 X509_VERIFY_PARAM_set_hostflags(param, hostflags); 1050 } 1051 1052 /* "Attach" the cert store to the context */ 1053 SSL_CTX_set1_cert_store(tlsctx, store); 1054 1055 /* enable verification */ 1056 if (is_server) { 1057 SSL_CTX_set_verify(tlsctx, 1058 SSL_VERIFY_PEER | 1059 SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 1060 NULL); 1061 } else { 1062 SSL_CTX_set_verify(tlsctx, SSL_VERIFY_PEER, NULL); 1063 } 1064 1065 return ISC_R_SUCCESS; 1066 } 1067 1068 isc_result_t 1069 isc_tlsctx_load_client_ca_names(isc_tlsctx_t *ctx, const char *ca_bundle_file) { 1070 STACK_OF(X509_NAME) * cert_names; 1071 REQUIRE(ctx != NULL); 1072 REQUIRE(ca_bundle_file != NULL); 1073 1074 cert_names = SSL_load_client_CA_file(ca_bundle_file); 1075 if (cert_names == NULL) { 1076 ERR_clear_error(); 1077 return ISC_R_FAILURE; 1078 } 1079 1080 SSL_CTX_set_client_CA_list(ctx, cert_names); 1081 1082 return ISC_R_SUCCESS; 1083 } 1084 1085 isc_result_t 1086 isc_tls_cert_store_create(const char *ca_bundle_filename, 1087 isc_tls_cert_store_t **pstore) { 1088 int ret = 0; 1089 isc_tls_cert_store_t *store = NULL; 1090 REQUIRE(pstore != NULL && *pstore == NULL); 1091 1092 store = X509_STORE_new(); 1093 if (store == NULL) { 1094 goto error; 1095 } 1096 1097 /* Let's treat empty string as the default (system wide) store */ 1098 if (ca_bundle_filename != NULL && *ca_bundle_filename == '\0') { 1099 ca_bundle_filename = NULL; 1100 } 1101 1102 if (ca_bundle_filename == NULL) { 1103 ret = X509_STORE_set_default_paths(store); 1104 } else { 1105 ret = X509_STORE_load_locations(store, ca_bundle_filename, 1106 NULL); 1107 } 1108 1109 if (ret == 0) { 1110 goto error; 1111 } 1112 1113 *pstore = store; 1114 return ISC_R_SUCCESS; 1115 1116 error: 1117 ERR_clear_error(); 1118 if (store != NULL) { 1119 X509_STORE_free(store); 1120 } 1121 return ISC_R_FAILURE; 1122 } 1123 1124 void 1125 isc_tls_cert_store_free(isc_tls_cert_store_t **pstore) { 1126 isc_tls_cert_store_t *store; 1127 REQUIRE(pstore != NULL && *pstore != NULL); 1128 1129 store = *pstore; 1130 1131 X509_STORE_free(store); 1132 1133 *pstore = NULL; 1134 } 1135 1136 #define TLSCTX_CACHE_MAGIC ISC_MAGIC('T', 'l', 'S', 'c') 1137 #define VALID_TLSCTX_CACHE(t) ISC_MAGIC_VALID(t, TLSCTX_CACHE_MAGIC) 1138 1139 #define TLSCTX_CLIENT_SESSION_CACHE_MAGIC ISC_MAGIC('T', 'l', 'C', 'c') 1140 #define VALID_TLSCTX_CLIENT_SESSION_CACHE(t) \ 1141 ISC_MAGIC_VALID(t, TLSCTX_CLIENT_SESSION_CACHE_MAGIC) 1142 1143 typedef struct isc_tlsctx_cache_entry { 1144 /* 1145 * We need a TLS context entry for each transport on both IPv4 and 1146 * IPv6 in order to avoid cluttering a context-specific 1147 * session-resumption cache. 1148 */ 1149 isc_tlsctx_t *ctx[isc_tlsctx_cache_count - 1][2]; 1150 isc_tlsctx_client_session_cache_t 1151 *client_sess_cache[isc_tlsctx_cache_count - 1][2]; 1152 /* 1153 * One certificate store is enough for all the contexts defined 1154 * above. We need that for peer validation. 1155 */ 1156 isc_tls_cert_store_t *ca_store; 1157 } isc_tlsctx_cache_entry_t; 1158 1159 struct isc_tlsctx_cache { 1160 uint32_t magic; 1161 isc_refcount_t references; 1162 isc_mem_t *mctx; 1163 1164 isc_rwlock_t rwlock; 1165 isc_ht_t *data; 1166 }; 1167 1168 void 1169 isc_tlsctx_cache_create(isc_mem_t *mctx, isc_tlsctx_cache_t **cachep) { 1170 isc_tlsctx_cache_t *nc; 1171 1172 REQUIRE(cachep != NULL && *cachep == NULL); 1173 nc = isc_mem_get(mctx, sizeof(*nc)); 1174 1175 *nc = (isc_tlsctx_cache_t){ .magic = TLSCTX_CACHE_MAGIC }; 1176 isc_refcount_init(&nc->references, 1); 1177 isc_mem_attach(mctx, &nc->mctx); 1178 1179 isc_ht_init(&nc->data, mctx, 5, ISC_HT_CASE_SENSITIVE); 1180 isc_rwlock_init(&nc->rwlock); 1181 1182 *cachep = nc; 1183 } 1184 1185 void 1186 isc_tlsctx_cache_attach(isc_tlsctx_cache_t *source, 1187 isc_tlsctx_cache_t **targetp) { 1188 REQUIRE(VALID_TLSCTX_CACHE(source)); 1189 REQUIRE(targetp != NULL && *targetp == NULL); 1190 1191 isc_refcount_increment(&source->references); 1192 1193 *targetp = source; 1194 } 1195 1196 static void 1197 tlsctx_cache_entry_destroy(isc_mem_t *mctx, isc_tlsctx_cache_entry_t *entry) { 1198 size_t i, k; 1199 1200 for (i = 0; i < (isc_tlsctx_cache_count - 1); i++) { 1201 for (k = 0; k < 2; k++) { 1202 if (entry->ctx[i][k] != NULL) { 1203 isc_tlsctx_free(&entry->ctx[i][k]); 1204 } 1205 1206 if (entry->client_sess_cache[i][k] != NULL) { 1207 isc_tlsctx_client_session_cache_detach( 1208 &entry->client_sess_cache[i][k]); 1209 } 1210 } 1211 } 1212 if (entry->ca_store != NULL) { 1213 isc_tls_cert_store_free(&entry->ca_store); 1214 } 1215 isc_mem_put(mctx, entry, sizeof(*entry)); 1216 } 1217 1218 static void 1219 tlsctx_cache_destroy(isc_tlsctx_cache_t *cache) { 1220 isc_ht_iter_t *it = NULL; 1221 isc_result_t result; 1222 1223 cache->magic = 0; 1224 1225 isc_refcount_destroy(&cache->references); 1226 1227 isc_ht_iter_create(cache->data, &it); 1228 for (result = isc_ht_iter_first(it); result == ISC_R_SUCCESS; 1229 result = isc_ht_iter_delcurrent_next(it)) 1230 { 1231 isc_tlsctx_cache_entry_t *entry = NULL; 1232 isc_ht_iter_current(it, (void **)&entry); 1233 tlsctx_cache_entry_destroy(cache->mctx, entry); 1234 } 1235 1236 isc_ht_iter_destroy(&it); 1237 isc_ht_destroy(&cache->data); 1238 isc_rwlock_destroy(&cache->rwlock); 1239 isc_mem_putanddetach(&cache->mctx, cache, sizeof(*cache)); 1240 } 1241 1242 void 1243 isc_tlsctx_cache_detach(isc_tlsctx_cache_t **cachep) { 1244 isc_tlsctx_cache_t *cache = NULL; 1245 1246 REQUIRE(cachep != NULL); 1247 1248 cache = *cachep; 1249 *cachep = NULL; 1250 1251 REQUIRE(VALID_TLSCTX_CACHE(cache)); 1252 1253 if (isc_refcount_decrement(&cache->references) == 1) { 1254 tlsctx_cache_destroy(cache); 1255 } 1256 } 1257 1258 isc_result_t 1259 isc_tlsctx_cache_add( 1260 isc_tlsctx_cache_t *cache, const char *name, 1261 const isc_tlsctx_cache_transport_t transport, const uint16_t family, 1262 isc_tlsctx_t *ctx, isc_tls_cert_store_t *store, 1263 isc_tlsctx_client_session_cache_t *client_sess_cache, 1264 isc_tlsctx_t **pfound, isc_tls_cert_store_t **pfound_store, 1265 isc_tlsctx_client_session_cache_t **pfound_client_sess_cache) { 1266 isc_result_t result = ISC_R_FAILURE; 1267 size_t name_len, tr_offset; 1268 isc_tlsctx_cache_entry_t *entry = NULL; 1269 bool ipv6; 1270 1271 REQUIRE(VALID_TLSCTX_CACHE(cache)); 1272 REQUIRE(client_sess_cache == NULL || 1273 VALID_TLSCTX_CLIENT_SESSION_CACHE(client_sess_cache)); 1274 REQUIRE(name != NULL && *name != '\0'); 1275 REQUIRE(transport > isc_tlsctx_cache_none && 1276 transport < isc_tlsctx_cache_count); 1277 REQUIRE(family == AF_INET || family == AF_INET6); 1278 REQUIRE(ctx != NULL); 1279 1280 tr_offset = (transport - 1); 1281 ipv6 = (family == AF_INET6); 1282 1283 RWLOCK(&cache->rwlock, isc_rwlocktype_write); 1284 1285 name_len = strlen(name); 1286 result = isc_ht_find(cache->data, (const uint8_t *)name, name_len, 1287 (void **)&entry); 1288 if (result == ISC_R_SUCCESS && entry->ctx[tr_offset][ipv6] != NULL) { 1289 isc_tlsctx_client_session_cache_t *found_client_sess_cache; 1290 /* The entry exists. */ 1291 if (pfound != NULL) { 1292 INSIST(*pfound == NULL); 1293 *pfound = entry->ctx[tr_offset][ipv6]; 1294 } 1295 1296 if (pfound_store != NULL && entry->ca_store != NULL) { 1297 INSIST(*pfound_store == NULL); 1298 *pfound_store = entry->ca_store; 1299 } 1300 1301 found_client_sess_cache = 1302 entry->client_sess_cache[tr_offset][ipv6]; 1303 if (pfound_client_sess_cache != NULL && 1304 found_client_sess_cache != NULL) 1305 { 1306 INSIST(*pfound_client_sess_cache == NULL); 1307 *pfound_client_sess_cache = found_client_sess_cache; 1308 } 1309 result = ISC_R_EXISTS; 1310 } else if (result == ISC_R_SUCCESS && 1311 entry->ctx[tr_offset][ipv6] == NULL) 1312 { 1313 /* 1314 * The hash table entry exists, but is not filled for this 1315 * particular transport/IP type combination. 1316 */ 1317 entry->ctx[tr_offset][ipv6] = ctx; 1318 entry->client_sess_cache[tr_offset][ipv6] = client_sess_cache; 1319 /* 1320 * As the passed certificates store object is supposed 1321 * to be internally managed by the cache object anyway, 1322 * we might destroy the unneeded store object right now. 1323 */ 1324 if (store != NULL && store != entry->ca_store) { 1325 isc_tls_cert_store_free(&store); 1326 } 1327 result = ISC_R_SUCCESS; 1328 } else { 1329 /* 1330 * The hash table entry does not exist, let's create one. 1331 */ 1332 INSIST(result != ISC_R_SUCCESS); 1333 entry = isc_mem_get(cache->mctx, sizeof(*entry)); 1334 *entry = (isc_tlsctx_cache_entry_t){ 1335 .ca_store = store, 1336 }; 1337 1338 entry->ctx[tr_offset][ipv6] = ctx; 1339 entry->client_sess_cache[tr_offset][ipv6] = client_sess_cache; 1340 RUNTIME_CHECK(isc_ht_add(cache->data, (const uint8_t *)name, 1341 name_len, 1342 (void *)entry) == ISC_R_SUCCESS); 1343 result = ISC_R_SUCCESS; 1344 } 1345 1346 RWUNLOCK(&cache->rwlock, isc_rwlocktype_write); 1347 1348 return result; 1349 } 1350 1351 isc_result_t 1352 isc_tlsctx_cache_find( 1353 isc_tlsctx_cache_t *cache, const char *name, 1354 const isc_tlsctx_cache_transport_t transport, const uint16_t family, 1355 isc_tlsctx_t **pctx, isc_tls_cert_store_t **pstore, 1356 isc_tlsctx_client_session_cache_t **pfound_client_sess_cache) { 1357 isc_result_t result = ISC_R_FAILURE; 1358 size_t tr_offset; 1359 isc_tlsctx_cache_entry_t *entry = NULL; 1360 bool ipv6; 1361 1362 REQUIRE(VALID_TLSCTX_CACHE(cache)); 1363 REQUIRE(name != NULL && *name != '\0'); 1364 REQUIRE(transport > isc_tlsctx_cache_none && 1365 transport < isc_tlsctx_cache_count); 1366 REQUIRE(family == AF_INET || family == AF_INET6); 1367 REQUIRE(pctx != NULL && *pctx == NULL); 1368 1369 tr_offset = (transport - 1); 1370 ipv6 = (family == AF_INET6); 1371 1372 RWLOCK(&cache->rwlock, isc_rwlocktype_read); 1373 1374 result = isc_ht_find(cache->data, (const uint8_t *)name, strlen(name), 1375 (void **)&entry); 1376 1377 if (result == ISC_R_SUCCESS && pstore != NULL && 1378 entry->ca_store != NULL) 1379 { 1380 *pstore = entry->ca_store; 1381 } 1382 1383 if (result == ISC_R_SUCCESS && entry->ctx[tr_offset][ipv6] != NULL) { 1384 isc_tlsctx_client_session_cache_t *found_client_sess_cache = 1385 entry->client_sess_cache[tr_offset][ipv6]; 1386 1387 *pctx = entry->ctx[tr_offset][ipv6]; 1388 1389 if (pfound_client_sess_cache != NULL && 1390 found_client_sess_cache != NULL) 1391 { 1392 INSIST(*pfound_client_sess_cache == NULL); 1393 *pfound_client_sess_cache = found_client_sess_cache; 1394 } 1395 } else if (result == ISC_R_SUCCESS && 1396 entry->ctx[tr_offset][ipv6] == NULL) 1397 { 1398 result = ISC_R_NOTFOUND; 1399 } else { 1400 INSIST(result != ISC_R_SUCCESS); 1401 } 1402 1403 RWUNLOCK(&cache->rwlock, isc_rwlocktype_read); 1404 1405 return result; 1406 } 1407 1408 typedef struct client_session_cache_entry client_session_cache_entry_t; 1409 1410 typedef struct client_session_cache_bucket { 1411 char *bucket_key; 1412 size_t bucket_key_len; 1413 /* Cache entries within the bucket (from the oldest to the newest). */ 1414 ISC_LIST(client_session_cache_entry_t) entries; 1415 } client_session_cache_bucket_t; 1416 1417 struct client_session_cache_entry { 1418 SSL_SESSION *session; 1419 client_session_cache_bucket_t *bucket; /* "Parent" bucket pointer. */ 1420 ISC_LINK(client_session_cache_entry_t) bucket_link; 1421 ISC_LINK(client_session_cache_entry_t) cache_link; 1422 }; 1423 1424 struct isc_tlsctx_client_session_cache { 1425 uint32_t magic; 1426 isc_refcount_t references; 1427 isc_mem_t *mctx; 1428 1429 /* 1430 * We need to keep a reference to the related TLS context in order 1431 * to ensure that it remains valid while the TLS client sessions 1432 * cache object is valid, as every TLS session object 1433 * (SSL_SESSION) is "tied" to a particular context. 1434 */ 1435 isc_tlsctx_t *ctx; 1436 1437 /* 1438 * The idea is to have one bucket per remote server. Each bucket, 1439 * can maintain multiple TLS sessions to that server, as BIND 1440 * might want to establish multiple TLS connections to the remote 1441 * server at once. 1442 */ 1443 isc_ht_t *buckets; 1444 1445 /* 1446 * The list of all current entries within the cache maintained in 1447 * LRU-manner, so that the oldest entry might be efficiently 1448 * removed. 1449 */ 1450 ISC_LIST(client_session_cache_entry_t) lru_entries; 1451 /* Number of the entries within the cache. */ 1452 size_t nentries; 1453 /* Maximum number of the entries within the cache. */ 1454 size_t max_entries; 1455 1456 isc_mutex_t lock; 1457 }; 1458 1459 void 1460 isc_tlsctx_client_session_cache_create( 1461 isc_mem_t *mctx, isc_tlsctx_t *ctx, const size_t max_entries, 1462 isc_tlsctx_client_session_cache_t **cachep) { 1463 isc_tlsctx_client_session_cache_t *nc; 1464 1465 REQUIRE(ctx != NULL); 1466 REQUIRE(max_entries > 0); 1467 REQUIRE(cachep != NULL && *cachep == NULL); 1468 1469 nc = isc_mem_get(mctx, sizeof(*nc)); 1470 1471 *nc = (isc_tlsctx_client_session_cache_t){ .max_entries = max_entries }; 1472 isc_refcount_init(&nc->references, 1); 1473 isc_mem_attach(mctx, &nc->mctx); 1474 isc_tlsctx_attach(ctx, &nc->ctx); 1475 1476 isc_ht_init(&nc->buckets, mctx, 5, ISC_HT_CASE_SENSITIVE); 1477 ISC_LIST_INIT(nc->lru_entries); 1478 isc_mutex_init(&nc->lock); 1479 1480 nc->magic = TLSCTX_CLIENT_SESSION_CACHE_MAGIC; 1481 1482 *cachep = nc; 1483 } 1484 1485 void 1486 isc_tlsctx_client_session_cache_attach( 1487 isc_tlsctx_client_session_cache_t *source, 1488 isc_tlsctx_client_session_cache_t **targetp) { 1489 REQUIRE(VALID_TLSCTX_CLIENT_SESSION_CACHE(source)); 1490 REQUIRE(targetp != NULL && *targetp == NULL); 1491 1492 isc_refcount_increment(&source->references); 1493 1494 *targetp = source; 1495 } 1496 1497 static void 1498 client_cache_entry_delete(isc_tlsctx_client_session_cache_t *restrict cache, 1499 client_session_cache_entry_t *restrict entry) { 1500 client_session_cache_bucket_t *restrict bucket = entry->bucket; 1501 1502 /* Unlink and free the cache entry */ 1503 ISC_LIST_UNLINK(bucket->entries, entry, bucket_link); 1504 ISC_LIST_UNLINK(cache->lru_entries, entry, cache_link); 1505 cache->nentries--; 1506 (void)SSL_SESSION_free(entry->session); 1507 isc_mem_put(cache->mctx, entry, sizeof(*entry)); 1508 1509 /* The bucket is empty - let's remove it */ 1510 if (ISC_LIST_EMPTY(bucket->entries)) { 1511 RUNTIME_CHECK(isc_ht_delete(cache->buckets, 1512 (const uint8_t *)bucket->bucket_key, 1513 bucket->bucket_key_len) == 1514 ISC_R_SUCCESS); 1515 1516 isc_mem_free(cache->mctx, bucket->bucket_key); 1517 isc_mem_put(cache->mctx, bucket, sizeof(*bucket)); 1518 } 1519 } 1520 1521 void 1522 isc_tlsctx_client_session_cache_detach( 1523 isc_tlsctx_client_session_cache_t **cachep) { 1524 isc_tlsctx_client_session_cache_t *cache = NULL; 1525 client_session_cache_entry_t *entry = NULL, *next = NULL; 1526 1527 REQUIRE(cachep != NULL); 1528 1529 cache = *cachep; 1530 *cachep = NULL; 1531 1532 REQUIRE(VALID_TLSCTX_CLIENT_SESSION_CACHE(cache)); 1533 1534 if (isc_refcount_decrement(&cache->references) != 1) { 1535 return; 1536 } 1537 1538 cache->magic = 0; 1539 1540 isc_refcount_destroy(&cache->references); 1541 1542 entry = ISC_LIST_HEAD(cache->lru_entries); 1543 while (entry != NULL) { 1544 next = ISC_LIST_NEXT(entry, cache_link); 1545 client_cache_entry_delete(cache, entry); 1546 entry = next; 1547 } 1548 1549 RUNTIME_CHECK(isc_ht_count(cache->buckets) == 0); 1550 isc_ht_destroy(&cache->buckets); 1551 1552 isc_mutex_destroy(&cache->lock); 1553 isc_tlsctx_free(&cache->ctx); 1554 isc_mem_putanddetach(&cache->mctx, cache, sizeof(*cache)); 1555 } 1556 1557 static bool 1558 ssl_session_seems_resumable(const SSL_SESSION *sess) { 1559 #ifdef HAVE_SSL_SESSION_IS_RESUMABLE 1560 /* 1561 * If SSL_SESSION_is_resumable() is available, let's use that. It 1562 * is expected to be available on OpenSSL >= 1.1.1 and its modern 1563 * siblings. 1564 */ 1565 return SSL_SESSION_is_resumable(sess) != 0; 1566 #elif (OPENSSL_VERSION_NUMBER >= 0x10100000L) 1567 /* 1568 * Taking into consideration that OpenSSL 1.1.0 uses opaque 1569 * pointers for SSL_SESSION, we cannot implement a replacement for 1570 * SSL_SESSION_is_resumable() manually. Let's use a sensible 1571 * approximation for that, then: if there is an associated session 1572 * ticket or session ID, then, most likely, the session is 1573 * resumable. 1574 */ 1575 unsigned int session_id_len = 0; 1576 (void)SSL_SESSION_get_id(sess, &session_id_len); 1577 return SSL_SESSION_has_ticket(sess) || session_id_len > 0; 1578 #else 1579 return !sess->not_resumable && 1580 (sess->session_id_length > 0 || sess->tlsext_ticklen > 0); 1581 #endif 1582 } 1583 1584 void 1585 isc_tlsctx_client_session_cache_keep(isc_tlsctx_client_session_cache_t *cache, 1586 char *remote_peer_name, isc_tls_t *tls) { 1587 size_t name_len; 1588 isc_result_t result; 1589 SSL_SESSION *sess; 1590 client_session_cache_bucket_t *restrict bucket = NULL; 1591 client_session_cache_entry_t *restrict entry = NULL; 1592 1593 REQUIRE(VALID_TLSCTX_CLIENT_SESSION_CACHE(cache)); 1594 REQUIRE(remote_peer_name != NULL && *remote_peer_name != '\0'); 1595 REQUIRE(tls != NULL); 1596 1597 sess = SSL_get1_session(tls); 1598 if (sess == NULL) { 1599 ERR_clear_error(); 1600 return; 1601 } else if (!ssl_session_seems_resumable(sess)) { 1602 SSL_SESSION_free(sess); 1603 return; 1604 } 1605 1606 SSL_set_session(tls, NULL); 1607 1608 isc_mutex_lock(&cache->lock); 1609 1610 name_len = strlen(remote_peer_name); 1611 result = isc_ht_find(cache->buckets, (const uint8_t *)remote_peer_name, 1612 name_len, (void **)&bucket); 1613 1614 if (result != ISC_R_SUCCESS) { 1615 /* Let's create a new bucket */ 1616 INSIST(bucket == NULL); 1617 bucket = isc_mem_get(cache->mctx, sizeof(*bucket)); 1618 *bucket = (client_session_cache_bucket_t){ 1619 .bucket_key = isc_mem_strdup(cache->mctx, 1620 remote_peer_name), 1621 .bucket_key_len = name_len 1622 }; 1623 ISC_LIST_INIT(bucket->entries); 1624 RUNTIME_CHECK(isc_ht_add(cache->buckets, 1625 (const uint8_t *)remote_peer_name, 1626 name_len, 1627 (void *)bucket) == ISC_R_SUCCESS); 1628 } 1629 1630 /* Let's add a new cache entry to the new/found bucket */ 1631 entry = isc_mem_get(cache->mctx, sizeof(*entry)); 1632 *entry = (client_session_cache_entry_t){ .session = sess, 1633 .bucket = bucket }; 1634 ISC_LINK_INIT(entry, bucket_link); 1635 ISC_LINK_INIT(entry, cache_link); 1636 1637 ISC_LIST_APPEND(bucket->entries, entry, bucket_link); 1638 1639 ISC_LIST_APPEND(cache->lru_entries, entry, cache_link); 1640 cache->nentries++; 1641 1642 if (cache->nentries > cache->max_entries) { 1643 /* 1644 * Cache overrun. We need to remove the oldest entry from the 1645 * cache 1646 */ 1647 client_session_cache_entry_t *restrict oldest; 1648 INSIST((cache->nentries - 1) == cache->max_entries); 1649 1650 oldest = ISC_LIST_HEAD(cache->lru_entries); 1651 client_cache_entry_delete(cache, oldest); 1652 } 1653 1654 isc_mutex_unlock(&cache->lock); 1655 } 1656 1657 void 1658 isc_tlsctx_client_session_cache_reuse(isc_tlsctx_client_session_cache_t *cache, 1659 char *remote_peer_name, isc_tls_t *tls) { 1660 client_session_cache_bucket_t *restrict bucket = NULL; 1661 client_session_cache_entry_t *restrict entry; 1662 size_t name_len; 1663 isc_result_t result; 1664 1665 REQUIRE(VALID_TLSCTX_CLIENT_SESSION_CACHE(cache)); 1666 REQUIRE(remote_peer_name != NULL && *remote_peer_name != '\0'); 1667 REQUIRE(tls != NULL); 1668 1669 isc_mutex_lock(&cache->lock); 1670 1671 /* Let's find the bucket */ 1672 name_len = strlen(remote_peer_name); 1673 result = isc_ht_find(cache->buckets, (const uint8_t *)remote_peer_name, 1674 name_len, (void **)&bucket); 1675 1676 if (result != ISC_R_SUCCESS) { 1677 goto exit; 1678 } 1679 1680 INSIST(bucket != NULL); 1681 1682 /* 1683 * If the bucket has been found, let's use the newest session from 1684 * the bucket, as it has the highest chance to be successfully 1685 * resumed. 1686 */ 1687 INSIST(!ISC_LIST_EMPTY(bucket->entries)); 1688 entry = ISC_LIST_TAIL(bucket->entries); 1689 RUNTIME_CHECK(SSL_set_session(tls, entry->session) == 1); 1690 client_cache_entry_delete(cache, entry); 1691 1692 exit: 1693 isc_mutex_unlock(&cache->lock); 1694 } 1695 1696 void 1697 isc_tlsctx_client_session_cache_keep_sockaddr( 1698 isc_tlsctx_client_session_cache_t *cache, isc_sockaddr_t *remote_peer, 1699 isc_tls_t *tls) { 1700 char peername[ISC_SOCKADDR_FORMATSIZE] = { 0 }; 1701 1702 REQUIRE(remote_peer != NULL); 1703 1704 isc_sockaddr_format(remote_peer, peername, sizeof(peername)); 1705 1706 isc_tlsctx_client_session_cache_keep(cache, peername, tls); 1707 } 1708 1709 void 1710 isc_tlsctx_client_session_cache_reuse_sockaddr( 1711 isc_tlsctx_client_session_cache_t *cache, isc_sockaddr_t *remote_peer, 1712 isc_tls_t *tls) { 1713 char peername[ISC_SOCKADDR_FORMATSIZE] = { 0 }; 1714 1715 REQUIRE(remote_peer != NULL); 1716 1717 isc_sockaddr_format(remote_peer, peername, sizeof(peername)); 1718 1719 isc_tlsctx_client_session_cache_reuse(cache, peername, tls); 1720 } 1721 1722 const isc_tlsctx_t * 1723 isc_tlsctx_client_session_cache_getctx( 1724 isc_tlsctx_client_session_cache_t *cache) { 1725 REQUIRE(VALID_TLSCTX_CLIENT_SESSION_CACHE(cache)); 1726 return cache->ctx; 1727 } 1728 1729 void 1730 isc_tlsctx_set_random_session_id_context(isc_tlsctx_t *ctx) { 1731 uint8_t session_id_ctx[SSL_MAX_SID_CTX_LENGTH] = { 0 }; 1732 const size_t len = ISC_MIN(20, sizeof(session_id_ctx)); 1733 1734 REQUIRE(ctx != NULL); 1735 1736 RUNTIME_CHECK(RAND_bytes(session_id_ctx, len) == 1); 1737 1738 RUNTIME_CHECK( 1739 SSL_CTX_set_session_id_context(ctx, session_id_ctx, len) == 1); 1740 } 1741 1742 bool 1743 isc_tls_valid_sni_hostname(const char *hostname) { 1744 struct sockaddr_in sa_v4 = { 0 }; 1745 struct sockaddr_in6 sa_v6 = { 0 }; 1746 int ret = 0; 1747 1748 if (hostname == NULL) { 1749 return false; 1750 } 1751 1752 ret = inet_pton(AF_INET, hostname, &sa_v4.sin_addr); 1753 if (ret == 1) { 1754 return false; 1755 } 1756 1757 ret = inet_pton(AF_INET6, hostname, &sa_v6.sin6_addr); 1758 if (ret == 1) { 1759 return false; 1760 } 1761 1762 return true; 1763 } 1764