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