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