1 /*
2  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
7  *
8  * See the COPYRIGHT file distributed with this work for additional
9  * information regarding copyright ownership.
10  */
11 
12 #include <inttypes.h>
13 #include <string.h>
14 #if HAVE_LIBNGHTTP2
15 #include <nghttp2/nghttp2.h>
16 #endif /* HAVE_LIBNGHTTP2 */
17 
18 #include <openssl/bn.h>
19 #include <openssl/conf.h>
20 #include <openssl/dh.h>
21 #include <openssl/err.h>
22 #include <openssl/opensslv.h>
23 #include <openssl/rand.h>
24 #include <openssl/rsa.h>
25 
26 #include <isc/atomic.h>
27 #include <isc/log.h>
28 #include <isc/mutex.h>
29 #include <isc/mutexblock.h>
30 #include <isc/once.h>
31 #include <isc/thread.h>
32 #include <isc/tls.h>
33 #include <isc/util.h>
34 
35 #include "openssl_shim.h"
36 #include "tls_p.h"
37 
38 #define COMMON_SSL_OPTIONS \
39 	(SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)
40 
41 static isc_once_t init_once = ISC_ONCE_INIT;
42 static isc_once_t shut_once = ISC_ONCE_INIT;
43 static atomic_bool init_done = ATOMIC_VAR_INIT(false);
44 static atomic_bool shut_done = ATOMIC_VAR_INIT(false);
45 
46 #if OPENSSL_VERSION_NUMBER < 0x10100000L
47 static isc_mutex_t *locks = NULL;
48 static int nlocks;
49 
50 static void
isc__tls_lock_callback(int mode,int type,const char * file,int line)51 isc__tls_lock_callback(int mode, int type, const char *file, int line) {
52 	UNUSED(file);
53 	UNUSED(line);
54 	if ((mode & CRYPTO_LOCK) != 0) {
55 		LOCK(&locks[type]);
56 	} else {
57 		UNLOCK(&locks[type]);
58 	}
59 }
60 
61 static void
isc__tls_set_thread_id(CRYPTO_THREADID * id)62 isc__tls_set_thread_id(CRYPTO_THREADID *id) {
63 	CRYPTO_THREADID_set_numeric(id, (unsigned long)isc_thread_self());
64 }
65 #endif
66 
67 static void
tls_initialize(void)68 tls_initialize(void) {
69 	REQUIRE(!atomic_load(&init_done));
70 
71 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
72 	RUNTIME_CHECK(OPENSSL_init_ssl(OPENSSL_INIT_ENGINE_ALL_BUILTIN |
73 					       OPENSSL_INIT_LOAD_CONFIG,
74 				       NULL) == 1);
75 #else
76 	nlocks = CRYPTO_num_locks();
77 	/*
78 	 * We can't use isc_mem API here, because it's called too
79 	 * early and when the isc_mem_debugging flags are changed
80 	 * later.
81 	 *
82 	 * Actually, since this is a single allocation at library load
83 	 * and deallocation at library unload, using the standard
84 	 * allocator without the tracking is fine for this purpose.
85 	 */
86 	locks = calloc(nlocks, sizeof(locks[0]));
87 	isc_mutexblock_init(locks, nlocks);
88 	CRYPTO_set_locking_callback(isc__tls_lock_callback);
89 	CRYPTO_THREADID_set_callback(isc__tls_set_thread_id);
90 
91 	CRYPTO_malloc_init();
92 	ERR_load_crypto_strings();
93 	SSL_load_error_strings();
94 	SSL_library_init();
95 
96 #if !defined(OPENSSL_NO_ENGINE)
97 	ENGINE_load_builtin_engines();
98 #endif
99 	OpenSSL_add_all_algorithms();
100 	OPENSSL_load_builtin_modules();
101 
102 	CONF_modules_load_file(NULL, NULL,
103 			       CONF_MFLAGS_DEFAULT_SECTION |
104 				       CONF_MFLAGS_IGNORE_MISSING_FILE);
105 #endif
106 
107 	/* Protect ourselves against unseeded PRNG */
108 	if (RAND_status() != 1) {
109 		FATAL_ERROR(__FILE__, __LINE__,
110 			    "OpenSSL pseudorandom number generator "
111 			    "cannot be initialized (see the `PRNG not "
112 			    "seeded' message in the OpenSSL FAQ)");
113 	}
114 
115 	REQUIRE(atomic_compare_exchange_strong(&init_done, &(bool){ false },
116 					       true));
117 }
118 
119 void
isc__tls_initialize(void)120 isc__tls_initialize(void) {
121 	isc_result_t result = isc_once_do(&init_once, tls_initialize);
122 	REQUIRE(result == ISC_R_SUCCESS);
123 	REQUIRE(atomic_load(&init_done));
124 }
125 
126 static void
tls_shutdown(void)127 tls_shutdown(void) {
128 	REQUIRE(atomic_load(&init_done));
129 	REQUIRE(!atomic_load(&shut_done));
130 
131 #if OPENSSL_VERSION_NUMBER < 0x10100000L
132 
133 	CONF_modules_unload(1);
134 	OBJ_cleanup();
135 	EVP_cleanup();
136 #if !defined(OPENSSL_NO_ENGINE)
137 	ENGINE_cleanup();
138 #endif
139 	CRYPTO_cleanup_all_ex_data();
140 	ERR_remove_thread_state(NULL);
141 	RAND_cleanup();
142 	ERR_free_strings();
143 
144 	CRYPTO_set_locking_callback(NULL);
145 
146 	if (locks != NULL) {
147 		isc_mutexblock_destroy(locks, nlocks);
148 		free(locks);
149 		locks = NULL;
150 	}
151 #endif
152 
153 	REQUIRE(atomic_compare_exchange_strong(&shut_done, &(bool){ false },
154 					       true));
155 }
156 
157 void
isc__tls_shutdown(void)158 isc__tls_shutdown(void) {
159 	isc_result_t result = isc_once_do(&shut_once, tls_shutdown);
160 	REQUIRE(result == ISC_R_SUCCESS);
161 	REQUIRE(atomic_load(&shut_done));
162 }
163 
164 void
isc_tlsctx_free(isc_tlsctx_t ** ctxp)165 isc_tlsctx_free(isc_tlsctx_t **ctxp) {
166 	SSL_CTX *ctx = NULL;
167 	REQUIRE(ctxp != NULL && *ctxp != NULL);
168 
169 	ctx = *ctxp;
170 	*ctxp = NULL;
171 
172 	SSL_CTX_free(ctx);
173 }
174 
175 isc_result_t
isc_tlsctx_createclient(isc_tlsctx_t ** ctxp)176 isc_tlsctx_createclient(isc_tlsctx_t **ctxp) {
177 	unsigned long err;
178 	char errbuf[256];
179 	SSL_CTX *ctx = NULL;
180 	const SSL_METHOD *method = NULL;
181 
182 	REQUIRE(ctxp != NULL && *ctxp == NULL);
183 
184 	method = TLS_client_method();
185 	if (method == NULL) {
186 		goto ssl_error;
187 	}
188 	ctx = SSL_CTX_new(method);
189 	if (ctx == NULL) {
190 		goto ssl_error;
191 	}
192 
193 	SSL_CTX_set_options(ctx, COMMON_SSL_OPTIONS);
194 
195 #if HAVE_SSL_CTX_SET_MIN_PROTO_VERSION
196 	SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
197 #else
198 	SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
199 					 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);
200 #endif
201 
202 	*ctxp = ctx;
203 
204 	return (ISC_R_SUCCESS);
205 
206 ssl_error:
207 	err = ERR_get_error();
208 	ERR_error_string_n(err, errbuf, sizeof(errbuf));
209 	isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_NETMGR,
210 		      ISC_LOG_ERROR, "Error initializing TLS context: %s",
211 		      errbuf);
212 
213 	return (ISC_R_TLSERROR);
214 }
215 
216 isc_result_t
isc_tlsctx_createserver(const char * keyfile,const char * certfile,isc_tlsctx_t ** ctxp)217 isc_tlsctx_createserver(const char *keyfile, const char *certfile,
218 			isc_tlsctx_t **ctxp) {
219 	int rv;
220 	unsigned long err;
221 	bool ephemeral = (keyfile == NULL && certfile == NULL);
222 	X509 *cert = NULL;
223 	EVP_PKEY *pkey = NULL;
224 	BIGNUM *bn = NULL;
225 	SSL_CTX *ctx = NULL;
226 	RSA *rsa = NULL;
227 	char errbuf[256];
228 	const SSL_METHOD *method = NULL;
229 
230 	REQUIRE(ctxp != NULL && *ctxp == NULL);
231 	REQUIRE((keyfile == NULL) == (certfile == NULL));
232 
233 	method = TLS_server_method();
234 	if (method == NULL) {
235 		goto ssl_error;
236 	}
237 	ctx = SSL_CTX_new(method);
238 	if (ctx == NULL) {
239 		goto ssl_error;
240 	}
241 	RUNTIME_CHECK(ctx != NULL);
242 
243 	SSL_CTX_set_options(ctx, COMMON_SSL_OPTIONS);
244 
245 #if HAVE_SSL_CTX_SET_MIN_PROTO_VERSION
246 	SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
247 #else
248 	SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
249 					 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);
250 #endif
251 
252 	if (ephemeral) {
253 		rsa = RSA_new();
254 		if (rsa == NULL) {
255 			goto ssl_error;
256 		}
257 		bn = BN_new();
258 		if (bn == NULL) {
259 			goto ssl_error;
260 		}
261 		BN_set_word(bn, RSA_F4);
262 		rv = RSA_generate_key_ex(rsa, 4096, bn, NULL);
263 		if (rv != 1) {
264 			goto ssl_error;
265 		}
266 		cert = X509_new();
267 		if (cert == NULL) {
268 			goto ssl_error;
269 		}
270 		pkey = EVP_PKEY_new();
271 		if (pkey == NULL) {
272 			goto ssl_error;
273 		}
274 
275 		/*
276 		 * EVP_PKEY_assign_*() set the referenced key to key
277 		 * however these use the supplied key internally and so
278 		 * key will be freed when the parent pkey is freed.
279 		 */
280 		EVP_PKEY_assign(pkey, EVP_PKEY_RSA, rsa);
281 		rsa = NULL;
282 		ASN1_INTEGER_set(X509_get_serialNumber(cert), 1);
283 
284 #if OPENSSL_VERSION_NUMBER < 0x10101000L
285 		X509_gmtime_adj(X509_get_notBefore(cert), 0);
286 #else
287 		X509_gmtime_adj(X509_getm_notBefore(cert), 0);
288 #endif
289 		/*
290 		 * We set the vailidy for 10 years.
291 		 */
292 #if OPENSSL_VERSION_NUMBER < 0x10101000L
293 		X509_gmtime_adj(X509_get_notAfter(cert), 3650 * 24 * 3600);
294 #else
295 		X509_gmtime_adj(X509_getm_notAfter(cert), 3650 * 24 * 3600);
296 #endif
297 
298 		X509_set_pubkey(cert, pkey);
299 
300 		X509_NAME *name = X509_get_subject_name(cert);
301 
302 		X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
303 					   (const unsigned char *)"AQ", -1, -1,
304 					   0);
305 		X509_NAME_add_entry_by_txt(
306 			name, "O", MBSTRING_ASC,
307 			(const unsigned char *)"BIND9 ephemeral "
308 					       "certificate",
309 			-1, -1, 0);
310 		X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
311 					   (const unsigned char *)"bind9.local",
312 					   -1, -1, 0);
313 
314 		X509_set_issuer_name(cert, name);
315 		X509_sign(cert, pkey, EVP_sha256());
316 		rv = SSL_CTX_use_certificate(ctx, cert);
317 		if (rv != 1) {
318 			goto ssl_error;
319 		}
320 		rv = SSL_CTX_use_PrivateKey(ctx, pkey);
321 		if (rv != 1) {
322 			goto ssl_error;
323 		}
324 
325 		X509_free(cert);
326 		EVP_PKEY_free(pkey);
327 		BN_free(bn);
328 	} else {
329 		rv = SSL_CTX_use_certificate_chain_file(ctx, certfile);
330 		if (rv != 1) {
331 			goto ssl_error;
332 		}
333 		rv = SSL_CTX_use_PrivateKey_file(ctx, keyfile,
334 						 SSL_FILETYPE_PEM);
335 		if (rv != 1) {
336 			goto ssl_error;
337 		}
338 	}
339 
340 	*ctxp = ctx;
341 	return (ISC_R_SUCCESS);
342 
343 ssl_error:
344 	err = ERR_get_error();
345 	ERR_error_string_n(err, errbuf, sizeof(errbuf));
346 	isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_NETMGR,
347 		      ISC_LOG_ERROR, "Error initializing TLS context: %s",
348 		      errbuf);
349 
350 	if (ctx != NULL) {
351 		SSL_CTX_free(ctx);
352 	}
353 	if (cert != NULL) {
354 		X509_free(cert);
355 	}
356 	if (pkey != NULL) {
357 		EVP_PKEY_free(pkey);
358 	}
359 	if (bn != NULL) {
360 		BN_free(bn);
361 	}
362 	if (rsa != NULL) {
363 		RSA_free(rsa);
364 	}
365 
366 	return (ISC_R_TLSERROR);
367 }
368 
369 static long
get_tls_version_disable_bit(const isc_tls_protocol_version_t tls_ver)370 get_tls_version_disable_bit(const isc_tls_protocol_version_t tls_ver) {
371 	long bit = 0;
372 
373 	switch (tls_ver) {
374 	case ISC_TLS_PROTO_VER_1_2:
375 #ifdef SSL_OP_NO_TLSv1_2
376 		bit = SSL_OP_NO_TLSv1_2;
377 #else
378 		bit = 0;
379 #endif
380 		break;
381 	case ISC_TLS_PROTO_VER_1_3:
382 #ifdef SSL_OP_NO_TLSv1_3
383 		bit = SSL_OP_NO_TLSv1_3;
384 #else
385 		bit = 0;
386 #endif
387 		break;
388 	default:
389 		INSIST(0);
390 		ISC_UNREACHABLE();
391 		break;
392 	};
393 
394 	return (bit);
395 }
396 
397 bool
isc_tls_protocol_supported(const isc_tls_protocol_version_t tls_ver)398 isc_tls_protocol_supported(const isc_tls_protocol_version_t tls_ver) {
399 	return (get_tls_version_disable_bit(tls_ver) != 0);
400 }
401 
402 isc_tls_protocol_version_t
isc_tls_protocol_name_to_version(const char * name)403 isc_tls_protocol_name_to_version(const char *name) {
404 	REQUIRE(name != NULL);
405 
406 	if (strcasecmp(name, "TLSv1.2") == 0) {
407 		return (ISC_TLS_PROTO_VER_1_2);
408 	} else if (strcasecmp(name, "TLSv1.3") == 0) {
409 		return (ISC_TLS_PROTO_VER_1_3);
410 	}
411 
412 	return (ISC_TLS_PROTO_VER_UNDEFINED);
413 }
414 
415 void
isc_tlsctx_set_protocols(isc_tlsctx_t * ctx,const uint32_t tls_versions)416 isc_tlsctx_set_protocols(isc_tlsctx_t *ctx, const uint32_t tls_versions) {
417 	REQUIRE(ctx != NULL);
418 	REQUIRE(tls_versions != 0);
419 	long set_options = 0;
420 	long clear_options = 0;
421 	uint32_t versions = tls_versions;
422 
423 	/*
424 	 * The code below might be initially hard to follow because of the
425 	 * double negation that OpenSSL enforces.
426 	 *
427 	 * Taking into account that OpenSSL provides bits to *disable*
428 	 * specific protocol versions, like SSL_OP_NO_TLSv1_2,
429 	 * SSL_OP_NO_TLSv1_3, etc., the code has the following logic:
430 	 *
431 	 * If a protocol version is not specified in the bitmask, get the
432 	 * bit that disables it and add it to the set of TLS options to
433 	 * set ('set_options'). Otherwise, if a protocol version is set,
434 	 * add the bit to the set of options to clear ('clear_options').
435 	 */
436 
437 	/* TLS protocol versions are defined as powers of two. */
438 	for (uint32_t tls_ver = ISC_TLS_PROTO_VER_1_2;
439 	     tls_ver < ISC_TLS_PROTO_VER_UNDEFINED; tls_ver <<= 1)
440 	{
441 		/* Only supported versions should ever be passed to the
442 		 * function. The configuration file was not verified
443 		 * properly, if we are trying to enable an unsupported
444 		 * TLS version */
445 		INSIST(isc_tls_protocol_supported(tls_ver));
446 		if ((tls_versions & tls_ver) == 0) {
447 			set_options |= get_tls_version_disable_bit(tls_ver);
448 		} else {
449 			clear_options |= get_tls_version_disable_bit(tls_ver);
450 		}
451 		versions &= ~(tls_ver);
452 	}
453 
454 	/* All versions should be processed at this point, thus the value
455 	 * must equal zero. If it is not, then some garbage has been
456 	 * passed to the function; this situation is worth
457 	 * investigation. */
458 	INSIST(versions == 0);
459 
460 	(void)SSL_CTX_set_options(ctx, set_options);
461 	(void)SSL_CTX_clear_options(ctx, clear_options);
462 }
463 
464 bool
isc_tlsctx_load_dhparams(isc_tlsctx_t * ctx,const char * dhparams_file)465 isc_tlsctx_load_dhparams(isc_tlsctx_t *ctx, const char *dhparams_file) {
466 	REQUIRE(ctx != NULL);
467 	REQUIRE(dhparams_file != NULL);
468 	REQUIRE(*dhparams_file != '\0');
469 
470 #ifdef SSL_CTX_set_tmp_dh
471 	/* OpenSSL < 3.0 */
472 	DH *dh = NULL;
473 	FILE *paramfile;
474 
475 	paramfile = fopen(dhparams_file, "r");
476 
477 	if (paramfile) {
478 		int check = 0;
479 		dh = PEM_read_DHparams(paramfile, NULL, NULL, NULL);
480 		fclose(paramfile);
481 
482 		if (dh == NULL) {
483 			return (false);
484 		} else if (DH_check(dh, &check) != 1 || check != 0) {
485 			DH_free(dh);
486 			return (false);
487 		}
488 	} else {
489 		return (false);
490 	}
491 
492 	if (SSL_CTX_set_tmp_dh(ctx, dh) != 1) {
493 		DH_free(dh);
494 		return (false);
495 	}
496 
497 	DH_free(dh);
498 #else
499 	/* OpenSSL >= 3.0: SSL_CTX_set_tmp_dh() is deprecated in OpenSSL 3.0 */
500 	EVP_PKEY *dh = NULL;
501 	BIO *bio = NULL;
502 
503 	bio = BIO_new_file(dhparams_file, "r");
504 	if (bio == NULL) {
505 		return (false);
506 	}
507 
508 	dh = PEM_read_bio_Parameters(bio, NULL);
509 	if (dh == NULL) {
510 		BIO_free(bio);
511 		return (false);
512 	}
513 
514 	if (SSL_CTX_set0_tmp_dh_pkey(ctx, dh) != 1) {
515 		BIO_free(bio);
516 		EVP_PKEY_free(dh);
517 		return (false);
518 	}
519 
520 	/* No need to call EVP_PKEY_free(dh) as the "dh" is owned by the
521 	 * SSL context at this point. */
522 
523 	BIO_free(bio);
524 #endif
525 
526 	return (true);
527 }
528 
529 bool
isc_tls_cipherlist_valid(const char * cipherlist)530 isc_tls_cipherlist_valid(const char *cipherlist) {
531 	isc_tlsctx_t *tmp_ctx = NULL;
532 	const SSL_METHOD *method = NULL;
533 	bool result;
534 	REQUIRE(cipherlist != NULL);
535 
536 	if (*cipherlist == '\0') {
537 		return (false);
538 	}
539 
540 	method = TLS_server_method();
541 	if (method == NULL) {
542 		return (false);
543 	}
544 	tmp_ctx = SSL_CTX_new(method);
545 	if (tmp_ctx == NULL) {
546 		return (false);
547 	}
548 
549 	result = SSL_CTX_set_cipher_list(tmp_ctx, cipherlist) == 1;
550 
551 	isc_tlsctx_free(&tmp_ctx);
552 
553 	return (result);
554 }
555 
556 void
isc_tlsctx_set_cipherlist(isc_tlsctx_t * ctx,const char * cipherlist)557 isc_tlsctx_set_cipherlist(isc_tlsctx_t *ctx, const char *cipherlist) {
558 	REQUIRE(ctx != NULL);
559 	REQUIRE(cipherlist != NULL);
560 	REQUIRE(*cipherlist != '\0');
561 
562 	RUNTIME_CHECK(SSL_CTX_set_cipher_list(ctx, cipherlist) == 1);
563 }
564 
565 void
isc_tlsctx_prefer_server_ciphers(isc_tlsctx_t * ctx,const bool prefer)566 isc_tlsctx_prefer_server_ciphers(isc_tlsctx_t *ctx, const bool prefer) {
567 	REQUIRE(ctx != NULL);
568 
569 	if (prefer) {
570 		(void)SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
571 	} else {
572 		(void)SSL_CTX_clear_options(ctx,
573 					    SSL_OP_CIPHER_SERVER_PREFERENCE);
574 	}
575 }
576 
577 void
isc_tlsctx_session_tickets(isc_tlsctx_t * ctx,const bool use)578 isc_tlsctx_session_tickets(isc_tlsctx_t *ctx, const bool use) {
579 	REQUIRE(ctx != NULL);
580 
581 	if (!use) {
582 		(void)SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
583 	} else {
584 		(void)SSL_CTX_clear_options(ctx, SSL_OP_NO_TICKET);
585 	}
586 }
587 
588 isc_tls_t *
isc_tls_create(isc_tlsctx_t * ctx)589 isc_tls_create(isc_tlsctx_t *ctx) {
590 	isc_tls_t *newctx = NULL;
591 
592 	REQUIRE(ctx != NULL);
593 
594 	newctx = SSL_new(ctx);
595 	if (newctx == NULL) {
596 		char errbuf[256];
597 		unsigned long err = ERR_get_error();
598 
599 		ERR_error_string_n(err, errbuf, sizeof(errbuf));
600 		fprintf(stderr, "%s:SSL_new(%p) -> %s\n", __func__, ctx,
601 			errbuf);
602 	}
603 
604 	return (newctx);
605 }
606 
607 void
isc_tls_free(isc_tls_t ** tlsp)608 isc_tls_free(isc_tls_t **tlsp) {
609 	REQUIRE(tlsp != NULL && *tlsp != NULL);
610 
611 	SSL_free(*tlsp);
612 	*tlsp = NULL;
613 }
614 
615 #if HAVE_LIBNGHTTP2
616 #ifndef OPENSSL_NO_NEXTPROTONEG
617 /*
618  * NPN TLS extension client callback.
619  */
620 static int
select_next_proto_cb(SSL * ssl,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)621 select_next_proto_cb(SSL *ssl, unsigned char **out, unsigned char *outlen,
622 		     const unsigned char *in, unsigned int inlen, void *arg) {
623 	UNUSED(ssl);
624 	UNUSED(arg);
625 
626 	if (nghttp2_select_next_protocol(out, outlen, in, inlen) <= 0) {
627 		return (SSL_TLSEXT_ERR_NOACK);
628 	}
629 	return (SSL_TLSEXT_ERR_OK);
630 }
631 #endif /* !OPENSSL_NO_NEXTPROTONEG */
632 
633 void
isc_tlsctx_enable_http2client_alpn(isc_tlsctx_t * ctx)634 isc_tlsctx_enable_http2client_alpn(isc_tlsctx_t *ctx) {
635 	REQUIRE(ctx != NULL);
636 
637 #ifndef OPENSSL_NO_NEXTPROTONEG
638 	SSL_CTX_set_next_proto_select_cb(ctx, select_next_proto_cb, NULL);
639 #endif /* !OPENSSL_NO_NEXTPROTONEG */
640 
641 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
642 	SSL_CTX_set_alpn_protos(ctx, (const unsigned char *)NGHTTP2_PROTO_ALPN,
643 				NGHTTP2_PROTO_ALPN_LEN);
644 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
645 }
646 
647 #ifndef OPENSSL_NO_NEXTPROTONEG
648 static int
next_proto_cb(isc_tls_t * ssl,const unsigned char ** data,unsigned int * len,void * arg)649 next_proto_cb(isc_tls_t *ssl, const unsigned char **data, unsigned int *len,
650 	      void *arg) {
651 	UNUSED(ssl);
652 	UNUSED(arg);
653 
654 	*data = (const unsigned char *)NGHTTP2_PROTO_ALPN;
655 	*len = (unsigned int)NGHTTP2_PROTO_ALPN_LEN;
656 	return (SSL_TLSEXT_ERR_OK);
657 }
658 #endif /* !OPENSSL_NO_NEXTPROTONEG */
659 
660 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
661 static int
alpn_select_proto_cb(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)662 alpn_select_proto_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen,
663 		     const unsigned char *in, unsigned int inlen, void *arg) {
664 	int ret;
665 
666 	UNUSED(ssl);
667 	UNUSED(arg);
668 
669 	ret = nghttp2_select_next_protocol((unsigned char **)(uintptr_t)out,
670 					   outlen, in, inlen);
671 
672 	if (ret != 1) {
673 		return (SSL_TLSEXT_ERR_NOACK);
674 	}
675 
676 	return (SSL_TLSEXT_ERR_OK);
677 }
678 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
679 
680 void
isc_tlsctx_enable_http2server_alpn(isc_tlsctx_t * tls)681 isc_tlsctx_enable_http2server_alpn(isc_tlsctx_t *tls) {
682 	REQUIRE(tls != NULL);
683 
684 #ifndef OPENSSL_NO_NEXTPROTONEG
685 	SSL_CTX_set_next_protos_advertised_cb(tls, next_proto_cb, NULL);
686 #endif // OPENSSL_NO_NEXTPROTONEG
687 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
688 	SSL_CTX_set_alpn_select_cb(tls, alpn_select_proto_cb, NULL);
689 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
690 }
691 #endif /* HAVE_LIBNGHTTP2 */
692 
693 void
isc_tls_get_selected_alpn(isc_tls_t * tls,const unsigned char ** alpn,unsigned int * alpnlen)694 isc_tls_get_selected_alpn(isc_tls_t *tls, const unsigned char **alpn,
695 			  unsigned int *alpnlen) {
696 	REQUIRE(tls != NULL);
697 	REQUIRE(alpn != NULL);
698 	REQUIRE(alpnlen != NULL);
699 
700 #ifndef OPENSSL_NO_NEXTPROTONEG
701 	SSL_get0_next_proto_negotiated(tls, alpn, alpnlen);
702 #endif
703 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
704 	if (*alpn == NULL) {
705 		SSL_get0_alpn_selected(tls, alpn, alpnlen);
706 	}
707 #endif
708 }
709 
710 static bool
protoneg_check_protocol(const uint8_t ** pout,uint8_t * pout_len,const uint8_t * in,size_t in_len,const uint8_t * key,size_t key_len)711 protoneg_check_protocol(const uint8_t **pout, uint8_t *pout_len,
712 			const uint8_t *in, size_t in_len, const uint8_t *key,
713 			size_t key_len) {
714 	for (size_t i = 0; i + key_len <= in_len; i += (size_t)(in[i] + 1)) {
715 		if (memcmp(&in[i], key, key_len) == 0) {
716 			*pout = (const uint8_t *)(&in[i + 1]);
717 			*pout_len = in[i];
718 			return (true);
719 		}
720 	}
721 	return (false);
722 }
723 
724 /* dot prepended by its length (3 bytes) */
725 #define DOT_PROTO_ALPN	   "\x3" ISC_TLS_DOT_PROTO_ALPN_ID
726 #define DOT_PROTO_ALPN_LEN (sizeof(DOT_PROTO_ALPN) - 1)
727 
728 static bool
dot_select_next_protocol(const uint8_t ** pout,uint8_t * pout_len,const uint8_t * in,size_t in_len)729 dot_select_next_protocol(const uint8_t **pout, uint8_t *pout_len,
730 			 const uint8_t *in, size_t in_len) {
731 	return (protoneg_check_protocol(pout, pout_len, in, in_len,
732 					(const uint8_t *)DOT_PROTO_ALPN,
733 					DOT_PROTO_ALPN_LEN));
734 }
735 
736 void
isc_tlsctx_enable_dot_client_alpn(isc_tlsctx_t * ctx)737 isc_tlsctx_enable_dot_client_alpn(isc_tlsctx_t *ctx) {
738 	REQUIRE(ctx != NULL);
739 
740 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
741 	SSL_CTX_set_alpn_protos(ctx, (const uint8_t *)DOT_PROTO_ALPN,
742 				DOT_PROTO_ALPN_LEN);
743 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
744 }
745 
746 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
747 static int
dot_alpn_select_proto_cb(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)748 dot_alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
749 			 unsigned char *outlen, const unsigned char *in,
750 			 unsigned int inlen, void *arg) {
751 	bool ret;
752 
753 	UNUSED(ssl);
754 	UNUSED(arg);
755 
756 	ret = dot_select_next_protocol(out, outlen, in, inlen);
757 
758 	if (!ret) {
759 		return (SSL_TLSEXT_ERR_NOACK);
760 	}
761 
762 	return (SSL_TLSEXT_ERR_OK);
763 }
764 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
765 
766 void
isc_tlsctx_enable_dot_server_alpn(isc_tlsctx_t * tls)767 isc_tlsctx_enable_dot_server_alpn(isc_tlsctx_t *tls) {
768 	REQUIRE(tls != NULL);
769 
770 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
771 	SSL_CTX_set_alpn_select_cb(tls, dot_alpn_select_proto_cb, NULL);
772 #endif // OPENSSL_VERSION_NUMBER >= 0x10002000L
773 }
774