xref: /netbsd-src/external/mpl/bind/dist/lib/isc/netmgr/tlsstream.c (revision bcda20f65a8566e103791ec395f7f499ef322704)
1 /*	$NetBSD: tlsstream.c,v 1.4 2025/01/26 16:25:43 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 <errno.h>
17 #include <libgen.h>
18 #include <unistd.h>
19 
20 #include <openssl/err.h>
21 #include <openssl/ssl.h>
22 
23 #include <isc/async.h>
24 #include <isc/atomic.h>
25 #include <isc/buffer.h>
26 #include <isc/condition.h>
27 #include <isc/log.h>
28 #include <isc/magic.h>
29 #include <isc/mem.h>
30 #include <isc/netmgr.h>
31 #include <isc/once.h>
32 #include <isc/quota.h>
33 #include <isc/random.h>
34 #include <isc/refcount.h>
35 #include <isc/region.h>
36 #include <isc/result.h>
37 #include <isc/sockaddr.h>
38 #include <isc/stdtime.h>
39 #include <isc/thread.h>
40 #include <isc/util.h>
41 #include <isc/uv.h>
42 
43 #include "../openssl_shim.h"
44 #include "netmgr-int.h"
45 
46 #define TLS_BUF_SIZE (UINT16_MAX)
47 
48 #define TLS_MAX_SEND_BUF_SIZE (UINT16_MAX + UINT16_MAX / 2)
49 
50 #define MAX_DNS_MESSAGE_SIZE (UINT16_MAX)
51 
52 #ifdef ISC_NETMGR_TRACE
53 ISC_ATTR_UNUSED static const char *
54 tls_status2str(int tls_status) {
55 	switch (tls_status) {
56 	case SSL_ERROR_NONE:
57 		return "SSL_ERROR_NONE";
58 	case SSL_ERROR_ZERO_RETURN:
59 		return "SSL_ERROR_ZERO_RETURN";
60 	case SSL_ERROR_WANT_WRITE:
61 		return "SSL_ERROR_WANT_WRITE";
62 	case SSL_ERROR_WANT_READ:
63 		return "SSL_ERROR_WANT_READ";
64 	case SSL_ERROR_SSL:
65 		return "SSL_ERROR_SSL";
66 	default:
67 		UNREACHABLE();
68 	}
69 }
70 
71 ISC_ATTR_UNUSED static const char *
72 state2str(int state) {
73 	switch (state) {
74 	case TLS_INIT:
75 		return "TLS_INIT";
76 	case TLS_HANDSHAKE:
77 		return "TLS_HANDSHAKE";
78 	case TLS_IO:
79 		return "TLS_IO";
80 	case TLS_CLOSED:
81 		return "TLS_CLOSED";
82 	default:
83 		UNREACHABLE();
84 	}
85 }
86 #endif /* ISC_NETMGR_TRACE */
87 
88 static isc_result_t
89 tls_error_to_result(const int tls_err, const int tls_state, isc_tls_t *tls) {
90 	switch (tls_err) {
91 	case SSL_ERROR_ZERO_RETURN:
92 		return ISC_R_EOF;
93 	case SSL_ERROR_SSL:
94 		if (tls != NULL && tls_state < TLS_IO &&
95 		    SSL_get_verify_result(tls) != X509_V_OK)
96 		{
97 			return ISC_R_TLSBADPEERCERT;
98 		}
99 		return ISC_R_TLSERROR;
100 	default:
101 		return ISC_R_UNEXPECTED;
102 	}
103 }
104 
105 static void
106 tls_read_start(isc_nmsocket_t *restrict sock);
107 
108 static void
109 tls_read_stop(isc_nmsocket_t *sock);
110 
111 static void
112 tls_failed_read_cb(isc_nmsocket_t *sock, const isc_result_t result);
113 
114 static void
115 tls_do_bio(isc_nmsocket_t *sock, isc_region_t *received_data,
116 	   isc__nm_uvreq_t *send_data, bool finish);
117 
118 static void
119 tls_readcb(isc_nmhandle_t *handle, isc_result_t result, isc_region_t *region,
120 	   void *cbarg);
121 
122 static void
123 async_tls_do_bio(isc_nmsocket_t *sock);
124 
125 static void
126 tls_init_listener_tlsctx(isc_nmsocket_t *listener, isc_tlsctx_t *ctx);
127 
128 static void
129 tls_cleanup_listener_tlsctx(isc_nmsocket_t *listener);
130 
131 static isc_tlsctx_t *
132 tls_get_listener_tlsctx(isc_nmsocket_t *listener, const int tid);
133 
134 static void
135 tls_keep_client_tls_session(isc_nmsocket_t *sock);
136 
137 static void
138 tls_try_shutdown(isc_tls_t *tls, const bool quite);
139 
140 static void
141 tls_try_to_enable_tcp_nodelay(isc_nmsocket_t *tlssock);
142 
143 /*
144  * The socket is closing, outerhandle has been detached, listener is
145  * inactive, or the netmgr is closing: any operation on it should abort
146  * with ISC_R_CANCELED.
147  */
148 static bool
149 inactive(isc_nmsocket_t *sock) {
150 	return !isc__nmsocket_active(sock) || sock->closing ||
151 	       sock->outerhandle == NULL ||
152 	       !isc__nmsocket_active(sock->outerhandle->sock) ||
153 	       sock->outerhandle->sock->closing ||
154 	       isc__nm_closing(sock->worker);
155 }
156 
157 static void
158 tls_call_connect_cb(isc_nmsocket_t *sock, isc_nmhandle_t *handle,
159 		    const isc_result_t result) {
160 	INSIST(sock->connect_cb != NULL);
161 	sock->connect_cb(handle, result, sock->connect_cbarg);
162 	if (result != ISC_R_SUCCESS) {
163 		isc__nmsocket_clearcb(handle->sock);
164 	}
165 }
166 
167 static void
168 tls_senddone(isc_nmhandle_t *handle, isc_result_t eresult, void *cbarg) {
169 	isc_nmsocket_tls_send_req_t *send_req =
170 		(isc_nmsocket_tls_send_req_t *)cbarg;
171 	isc_nmsocket_t *tlssock = NULL;
172 	bool finish = send_req->finish;
173 	isc_nm_cb_t send_cb = NULL;
174 	void *send_cbarg = NULL;
175 	isc_nmhandle_t *send_handle = NULL;
176 
177 	REQUIRE(VALID_NMHANDLE(handle));
178 	REQUIRE(VALID_NMSOCK(handle->sock));
179 	REQUIRE(VALID_NMSOCK(send_req->tlssock));
180 
181 	tlssock = send_req->tlssock;
182 	send_req->tlssock = NULL;
183 	send_cb = send_req->cb;
184 	send_req->cb = NULL;
185 	send_cbarg = send_req->cbarg;
186 	send_req->cbarg = NULL;
187 	send_handle = send_req->handle;
188 	send_req->handle = NULL;
189 
190 	if (finish) {
191 		tls_try_shutdown(tlssock->tlsstream.tls, true);
192 	}
193 
194 	/* Try to keep the object to be reused later - to avoid an allocation */
195 	if (tlssock->tlsstream.send_req == NULL) {
196 		tlssock->tlsstream.send_req = send_req;
197 		/*
198 		 * We need to ensure that the buffer is not going to grow too
199 		 * large uncontrollably. We try to keep its size to be no more
200 		 * than TLS_MAX_SEND_BUF_SIZE. The constant should be larger
201 		 * than 64 KB for this to work efficiently when combined with
202 		 * DNS transports.
203 		 */
204 		if (isc_buffer_length(&send_req->data) > TLS_MAX_SEND_BUF_SIZE)
205 		{
206 			/* free the underlying buffer */
207 			isc_buffer_clearmctx(&send_req->data);
208 			isc_buffer_invalidate(&send_req->data);
209 			isc_buffer_init(&send_req->data, send_req->smallbuf,
210 					sizeof(send_req->smallbuf));
211 			isc_buffer_setmctx(&send_req->data,
212 					   handle->sock->worker->mctx);
213 		} else {
214 			isc_buffer_clear(&send_req->data);
215 		}
216 	} else {
217 		isc_buffer_clearmctx(&send_req->data);
218 		isc_buffer_invalidate(&send_req->data);
219 		isc_mem_put(handle->sock->worker->mctx, send_req,
220 			    sizeof(*send_req));
221 	}
222 	tlssock->tlsstream.nsending--;
223 
224 	if (send_cb != NULL) {
225 		INSIST(VALID_NMHANDLE(tlssock->statichandle));
226 		send_cb(send_handle, eresult, send_cbarg);
227 		isc_nmhandle_detach(&send_handle);
228 		/* The last handle has been just detached: close the underlying
229 		 * socket. */
230 		if (tlssock->statichandle == NULL) {
231 			finish = true;
232 		}
233 	}
234 
235 	if (finish) {
236 		/*
237 		 * If wrapping up, call tls_failed_read() - it will care of
238 		 * socket de-initialisation and calling the read callback, if
239 		 * necessary.
240 		 */
241 		tls_failed_read_cb(tlssock, ISC_R_EOF);
242 	} else if (eresult == ISC_R_SUCCESS) {
243 		tls_do_bio(tlssock, NULL, NULL, false);
244 	} else if (eresult != ISC_R_SUCCESS &&
245 		   tlssock->tlsstream.state <= TLS_HANDSHAKE &&
246 		   !tlssock->tlsstream.server)
247 	{
248 		/*
249 		 * We are still waiting for the handshake to complete, but
250 		 * it isn't going to happen. Call the connect callback,
251 		 * passing the error code there.
252 		 *
253 		 * (Note: tls_failed_read_cb() calls the connect
254 		 * rather than the read callback in this case.
255 		 * XXX: clarify?)
256 		 */
257 		tls_failed_read_cb(tlssock, eresult);
258 	}
259 
260 	isc__nmsocket_detach(&tlssock);
261 }
262 
263 static void
264 tls_failed_read_cb(isc_nmsocket_t *sock, isc_result_t result) {
265 	REQUIRE(VALID_NMSOCK(sock));
266 	REQUIRE(result != ISC_R_SUCCESS);
267 
268 	/* This is TLS counterpart of isc__nm_failed_connect_cb() */
269 	if (!sock->tlsstream.server &&
270 	    (sock->tlsstream.state == TLS_INIT ||
271 	     sock->tlsstream.state == TLS_HANDSHAKE) &&
272 	    sock->connect_cb != NULL)
273 	{
274 		isc_nmhandle_t *handle = NULL;
275 		INSIST(sock->statichandle == NULL);
276 		handle = isc__nmhandle_get(sock, &sock->peer, &sock->iface);
277 		tls_call_connect_cb(sock, handle, result);
278 		isc__nmsocket_clearcb(sock);
279 		isc_nmhandle_detach(&handle);
280 		goto destroy;
281 	}
282 
283 	isc__nmsocket_timer_stop(sock);
284 
285 	/* Nobody is reading from the socket yet */
286 	if (sock->statichandle == NULL) {
287 		goto destroy;
288 	}
289 
290 	/* This is TLS counterpart of isc__nmsocket_readtimeout_cb() */
291 	if (sock->client && result == ISC_R_TIMEDOUT) {
292 		INSIST(sock->statichandle != NULL);
293 
294 		if (sock->recv_cb != NULL) {
295 			isc__nm_uvreq_t *req = isc__nm_get_read_req(sock, NULL);
296 			isc__nm_readcb(sock, req, ISC_R_TIMEDOUT, false);
297 		}
298 
299 		if (isc__nmsocket_timer_running(sock)) {
300 			/* Timer was restarted, bail-out */
301 			return;
302 		}
303 
304 		isc__nmsocket_clearcb(sock);
305 
306 		goto destroy;
307 	}
308 
309 	/*
310 	 * We don't need to check for .nsending, as the callbacks will be
311 	 * cleared at the time the tls_senddone() tries to call it for the
312 	 * second time.
313 	 */
314 
315 	if (sock->recv_cb != NULL) {
316 		isc__nm_uvreq_t *req = isc__nm_get_read_req(sock, NULL);
317 		isc__nmsocket_clearcb(sock);
318 		isc__nm_readcb(sock, req, result, false);
319 	}
320 
321 destroy:
322 	isc__nmsocket_prep_destroy(sock);
323 }
324 
325 void
326 isc__nm_tls_failed_read_cb(isc_nmsocket_t *sock, isc_result_t result,
327 			   bool async ISC_ATTR_UNUSED) {
328 	if (!inactive(sock) && sock->tlsstream.state == TLS_IO) {
329 		tls_do_bio(sock, NULL, NULL, true);
330 		return;
331 	}
332 
333 	tls_failed_read_cb(sock, result);
334 }
335 
336 static void
337 tls_do_bio_cb(void *arg) {
338 	isc_nmsocket_t *sock = arg;
339 
340 	REQUIRE(VALID_NMSOCK(sock));
341 
342 	tls_do_bio(sock, NULL, NULL, false);
343 
344 	isc__nmsocket_detach(&sock);
345 }
346 
347 static void
348 async_tls_do_bio(isc_nmsocket_t *sock) {
349 	isc__nmsocket_attach(sock, &(isc_nmsocket_t *){ NULL });
350 	isc_async_run(sock->worker->loop, tls_do_bio_cb, sock);
351 }
352 
353 static int
354 tls_send_outgoing(isc_nmsocket_t *sock, bool finish, isc_nmhandle_t *tlshandle,
355 		  isc_nm_cb_t cb, void *cbarg) {
356 	isc_nmsocket_tls_send_req_t *send_req = NULL;
357 	int pending;
358 	int rv;
359 	size_t len = 0;
360 	bool new_send_req = false;
361 	isc_region_t used_region = { 0 };
362 	bool shutting_down = isc__nm_closing(sock->worker);
363 
364 	if (shutting_down || inactive(sock)) {
365 		if (cb != NULL) {
366 			isc_result_t result = shutting_down ? ISC_R_SHUTTINGDOWN
367 							    : ISC_R_CANCELED;
368 			INSIST(VALID_NMHANDLE(tlshandle));
369 			cb(tlshandle, result, cbarg);
370 		}
371 		return 0;
372 	}
373 
374 	if (finish) {
375 		tls_try_shutdown(sock->tlsstream.tls, false);
376 		tls_keep_client_tls_session(sock);
377 	}
378 
379 	pending = BIO_pending(sock->tlsstream.bio_out);
380 	if (pending <= 0) {
381 		return pending;
382 	}
383 
384 	/* Try to reuse previously allocated object */
385 	if (sock->tlsstream.send_req != NULL) {
386 		send_req = sock->tlsstream.send_req;
387 		send_req->finish = finish;
388 		sock->tlsstream.send_req = NULL;
389 	} else {
390 		send_req = isc_mem_get(sock->worker->mctx, sizeof(*send_req));
391 		*send_req = (isc_nmsocket_tls_send_req_t){ .finish = finish };
392 		new_send_req = true;
393 	}
394 
395 	if (new_send_req) {
396 		isc_buffer_init(&send_req->data, &send_req->smallbuf,
397 				sizeof(send_req->smallbuf));
398 		isc_buffer_setmctx(&send_req->data, sock->worker->mctx);
399 	}
400 	INSIST(isc_buffer_remaininglength(&send_req->data) == 0);
401 
402 	isc__nmsocket_attach(sock, &send_req->tlssock);
403 	if (cb != NULL) {
404 		send_req->cb = cb;
405 		send_req->cbarg = cbarg;
406 		isc_nmhandle_attach(tlshandle, &send_req->handle);
407 	}
408 
409 	RUNTIME_CHECK(isc_buffer_reserve(&send_req->data, pending) ==
410 		      ISC_R_SUCCESS);
411 	isc_buffer_add(&send_req->data, pending);
412 	rv = BIO_read_ex(sock->tlsstream.bio_out,
413 			 isc_buffer_base(&send_req->data), pending, &len);
414 	/* There's something pending, read must succeed */
415 	RUNTIME_CHECK(rv == 1 && len == (size_t)pending);
416 
417 	INSIST(VALID_NMHANDLE(sock->outerhandle));
418 
419 	sock->tlsstream.nsending++;
420 	isc_buffer_remainingregion(&send_req->data, &used_region);
421 	isc_nm_send(sock->outerhandle, &used_region, tls_senddone, send_req);
422 
423 	return pending;
424 }
425 
426 static int
427 tls_process_outgoing(isc_nmsocket_t *sock, bool finish,
428 		     isc__nm_uvreq_t *send_data) {
429 	int pending;
430 
431 	bool received_shutdown = ((SSL_get_shutdown(sock->tlsstream.tls) &
432 				   SSL_RECEIVED_SHUTDOWN) != 0);
433 	bool sent_shutdown = ((SSL_get_shutdown(sock->tlsstream.tls) &
434 			       SSL_SENT_SHUTDOWN) != 0);
435 
436 	if (received_shutdown && !sent_shutdown) {
437 		finish = true;
438 	}
439 
440 	/* Data from TLS to network */
441 	if (send_data != NULL) {
442 		pending = tls_send_outgoing(sock, finish, send_data->handle,
443 					    send_data->cb.send,
444 					    send_data->cbarg);
445 	} else {
446 		pending = tls_send_outgoing(sock, finish, NULL, NULL, NULL);
447 	}
448 
449 	return pending;
450 }
451 
452 static int
453 tls_try_handshake(isc_nmsocket_t *sock, isc_result_t *presult) {
454 	REQUIRE(sock->tlsstream.state == TLS_HANDSHAKE);
455 
456 	if (SSL_is_init_finished(sock->tlsstream.tls) == 1) {
457 		return 0;
458 	}
459 
460 	int rv = SSL_do_handshake(sock->tlsstream.tls);
461 	if (rv == 1) {
462 		isc_nmhandle_t *tlshandle = NULL;
463 		isc_result_t result = ISC_R_SUCCESS;
464 
465 		REQUIRE(sock->statichandle == NULL);
466 		INSIST(SSL_is_init_finished(sock->tlsstream.tls) == 1);
467 
468 		isc__nmsocket_log_tls_session_reuse(sock, sock->tlsstream.tls);
469 		tlshandle = isc__nmhandle_get(sock, &sock->peer, &sock->iface);
470 		tls_read_stop(sock);
471 
472 		if (isc__nm_closing(sock->worker)) {
473 			result = ISC_R_SHUTTINGDOWN;
474 		}
475 
476 		if (sock->tlsstream.server) {
477 			/*
478 			 * The listening sockets are now closed from outer
479 			 * to inner order, which means that this function
480 			 * will never be called when the outer socket has
481 			 * stopped listening.
482 			 *
483 			 * Also see 'isc__nmsocket_stop()' - the function used
484 			 * to shut down the listening TLS socket - for more
485 			 * details.
486 			 */
487 			if (result == ISC_R_SUCCESS) {
488 				result = sock->accept_cb(tlshandle, result,
489 							 sock->accept_cbarg);
490 			}
491 		} else {
492 			tls_call_connect_cb(sock, tlshandle, result);
493 		}
494 		isc_nmhandle_detach(&tlshandle);
495 		sock->tlsstream.state = TLS_IO;
496 
497 		if (presult != NULL) {
498 			*presult = result;
499 		}
500 	}
501 
502 	return rv;
503 }
504 
505 static bool
506 tls_try_to_close_unused_socket(isc_nmsocket_t *sock) {
507 	if (sock->tlsstream.state > TLS_HANDSHAKE &&
508 	    sock->statichandle == NULL && sock->tlsstream.nsending == 0)
509 	{
510 		/*
511 		 * It seems that no action on the socket has been
512 		 * scheduled on some point after the handshake, let's
513 		 * close the connection.
514 		 */
515 		isc__nmsocket_prep_destroy(sock);
516 		return true;
517 	}
518 
519 	return false;
520 }
521 
522 static void
523 tls_do_bio(isc_nmsocket_t *sock, isc_region_t *received_data,
524 	   isc__nm_uvreq_t *send_data, bool finish) {
525 	isc_result_t result = ISC_R_SUCCESS;
526 	int pending, tls_status = SSL_ERROR_NONE;
527 	int rv = 0;
528 	size_t len = 0;
529 	int saved_errno = 0;
530 
531 	REQUIRE(VALID_NMSOCK(sock));
532 	REQUIRE(sock->tid == isc_tid());
533 
534 	/*
535 	 * Clear the TLS error queue so that SSL_get_error() and SSL I/O
536 	 * routine calls will not get affected by prior error statuses.
537 	 *
538 	 * See here:
539 	 * https://www.openssl.org/docs/man3.0/man3/SSL_get_error.html
540 	 *
541 	 * In particular, it mentions the following:
542 	 *
543 	 * The current thread's error queue must be empty before the
544 	 * TLS/SSL I/O operation is attempted, or SSL_get_error() will not
545 	 * work reliably.
546 	 *
547 	 * As we use the result of SSL_get_error() to decide on I/O
548 	 * operations, we need to ensure that it works reliably by
549 	 * cleaning the error queue.
550 	 *
551 	 * The sum of details: https://stackoverflow.com/a/37980911
552 	 */
553 	ERR_clear_error();
554 
555 	if (sock->tlsstream.state == TLS_INIT) {
556 		INSIST(received_data == NULL && send_data == NULL);
557 		if (sock->tlsstream.server) {
558 			SSL_set_accept_state(sock->tlsstream.tls);
559 		} else {
560 			SSL_set_connect_state(sock->tlsstream.tls);
561 		}
562 		sock->tlsstream.state = TLS_HANDSHAKE;
563 		rv = tls_try_handshake(sock, NULL);
564 		INSIST(SSL_is_init_finished(sock->tlsstream.tls) == 0);
565 		isc__nmsocket_timer_restart(sock);
566 	} else if (sock->tlsstream.state == TLS_CLOSED) {
567 		return;
568 	} else { /* initialised and doing I/O */
569 		if (received_data != NULL) {
570 			INSIST(send_data == NULL);
571 			rv = BIO_write_ex(sock->tlsstream.bio_in,
572 					  received_data->base,
573 					  received_data->length, &len);
574 			if (rv <= 0 || len != received_data->length) {
575 				result = ISC_R_TLSERROR;
576 #if ISC_NETMGR_TRACE
577 				saved_errno = errno;
578 #endif
579 				goto error;
580 			}
581 
582 			/*
583 			 * Only after doing the IO we can check whether SSL
584 			 * handshake is done.
585 			 */
586 			if (sock->tlsstream.state == TLS_HANDSHAKE) {
587 				isc_result_t hs_result = ISC_R_UNSET;
588 				rv = tls_try_handshake(sock, &hs_result);
589 				if (sock->tlsstream.state == TLS_IO &&
590 				    hs_result != ISC_R_SUCCESS)
591 				{
592 					/*
593 					 * The accept/connect callback has been
594 					 * called unsuccessfully. Let's try to
595 					 * shut down the TLS connection
596 					 * gracefully.
597 					 */
598 					INSIST(SSL_is_init_finished(
599 						       sock->tlsstream.tls) ==
600 					       1);
601 					finish = true;
602 				}
603 			}
604 		} else if (send_data != NULL) {
605 			INSIST(received_data == NULL);
606 			INSIST(sock->tlsstream.state > TLS_HANDSHAKE);
607 			bool received_shutdown =
608 				((SSL_get_shutdown(sock->tlsstream.tls) &
609 				  SSL_RECEIVED_SHUTDOWN) != 0);
610 			bool sent_shutdown =
611 				((SSL_get_shutdown(sock->tlsstream.tls) &
612 				  SSL_SENT_SHUTDOWN) != 0);
613 			bool write_failed = false;
614 			if (*(uint16_t *)send_data->tcplen != 0) {
615 				size_t sendlen = 0;
616 				uint8_t sendbuf[MAX_DNS_MESSAGE_SIZE +
617 						sizeof(uint16_t)];
618 				/*
619 				 * There is a DNS message length to write - do
620 				 * it.
621 				 */
622 
623 				/*
624 				 * There's no SSL_writev(), so we need to use a
625 				 * local buffer to assemble the whole message
626 				 */
627 				INSIST(send_data->uvbuf.len <=
628 				       MAX_DNS_MESSAGE_SIZE);
629 
630 				sendlen = send_data->uvbuf.len +
631 					  sizeof(uint16_t);
632 				memmove(sendbuf, send_data->tcplen,
633 					sizeof(uint16_t));
634 				memmove(sendbuf + sizeof(uint16_t),
635 					send_data->uvbuf.base,
636 					send_data->uvbuf.len);
637 
638 				/* Write data */
639 				rv = SSL_write_ex(sock->tlsstream.tls, sendbuf,
640 						  sendlen, &len);
641 				if (rv != 1 || len != sendlen) {
642 					write_failed = true;
643 				}
644 			} else {
645 				/* Write data only */
646 				rv = SSL_write_ex(sock->tlsstream.tls,
647 						  send_data->uvbuf.base,
648 						  send_data->uvbuf.len, &len);
649 				if (rv != 1 || len != send_data->uvbuf.len) {
650 					write_failed = true;
651 				}
652 			}
653 
654 			if (write_failed) {
655 				result = received_shutdown || sent_shutdown
656 						 ? ISC_R_CANCELED
657 						 : ISC_R_TLSERROR;
658 				send_data->cb.send(send_data->handle, result,
659 						   send_data->cbarg);
660 				send_data = NULL;
661 				return;
662 			}
663 		}
664 
665 		/* Decrypt and pass data from network to client */
666 		if (sock->tlsstream.state >= TLS_IO && sock->recv_cb != NULL &&
667 		    sock->statichandle != NULL && sock->reading && !finish)
668 		{
669 			bool was_new_data = false;
670 			uint8_t recv_buf[TLS_BUF_SIZE];
671 			INSIST(sock->tlsstream.state > TLS_HANDSHAKE);
672 			while ((rv = SSL_read_ex(sock->tlsstream.tls, recv_buf,
673 						 TLS_BUF_SIZE, &len)) == 1)
674 			{
675 				isc_region_t region;
676 				region = (isc_region_t){ .base = &recv_buf[0],
677 							 .length = len };
678 
679 				was_new_data = true;
680 				INSIST(VALID_NMHANDLE(sock->statichandle));
681 				sock->recv_cb(sock->statichandle, ISC_R_SUCCESS,
682 					      &region, sock->recv_cbarg);
683 				/* The handle could have been detached in
684 				 * sock->recv_cb, making the sock->statichandle
685 				 * nullified (it happens in netmgr.c). If it is
686 				 * the case, then it means that we are not
687 				 * interested in keeping the connection alive
688 				 * anymore. Let's shut down the SSL session,
689 				 * send what we have in the SSL buffers,
690 				 * and close the connection.
691 				 */
692 				if (sock->statichandle == NULL) {
693 					finish = true;
694 					break;
695 				} else if (sock->recv_cb == NULL) {
696 					/*
697 					 * The 'sock->recv_cb' might have been
698 					 * nullified during the call to
699 					 * 'sock->recv_cb'. That could happen,
700 					 * e.g. by an indirect call to
701 					 * 'isc_nmhandle_close()' from within
702 					 * the callback when wrapping up.
703 					 *
704 					 * In this case, let's close the TLS
705 					 * connection.
706 					 */
707 					finish = true;
708 					break;
709 				} else if (!sock->reading) {
710 					/*
711 					 * Reading has been paused from withing
712 					 * the context of read callback - stop
713 					 * processing incoming data.
714 					 */
715 					break;
716 				}
717 			}
718 
719 			if (was_new_data && !sock->manual_read_timer) {
720 				/*
721 				 * Some data has been decrypted, it is the right
722 				 * time to stop the read timer as it will be
723 				 * restarted on the next read attempt.
724 				 */
725 				isc__nmsocket_timer_stop(sock);
726 			}
727 		}
728 	}
729 
730 	/*
731 	 * Setting 'finish' to 'true' means that we are about to close the
732 	 * TLS stream (we intend to send TLS shutdown message to the
733 	 * remote side). After that no new data can be received, so we
734 	 * should stop the timer regardless of the
735 	 * 'sock->manual_read_timer' value.
736 	 */
737 	if (finish) {
738 		isc__nmsocket_timer_stop(sock);
739 	}
740 
741 	errno = 0;
742 	tls_status = SSL_get_error(sock->tlsstream.tls, rv);
743 	saved_errno = errno;
744 
745 	/* See "BUGS" section at:
746 	 * https://www.openssl.org/docs/man1.1.1/man3/SSL_get_error.html
747 	 *
748 	 * It is mentioned there that when TLS status equals
749 	 * SSL_ERROR_SYSCALL AND errno == 0 it means that underlying
750 	 * transport layer returned EOF prematurely.  However, we are
751 	 * managing the transport ourselves, so we should just resume
752 	 * reading from the TCP socket.
753 	 *
754 	 * It seems that this case has been handled properly on modern
755 	 * versions of OpenSSL. That being said, the situation goes in
756 	 * line with the manual: it is briefly mentioned there that
757 	 * SSL_ERROR_SYSCALL might be returned not only in a case of
758 	 * low-level errors (like system call failures).
759 	 */
760 	if (tls_status == SSL_ERROR_SYSCALL && saved_errno == 0 &&
761 	    received_data == NULL && send_data == NULL && finish == false)
762 	{
763 		tls_status = SSL_ERROR_WANT_READ;
764 	}
765 
766 	pending = tls_process_outgoing(sock, finish, send_data);
767 	if (pending > 0 && tls_status != SSL_ERROR_SSL) {
768 		return;
769 	}
770 
771 	switch (tls_status) {
772 	case SSL_ERROR_NONE:
773 	case SSL_ERROR_ZERO_RETURN:
774 		(void)tls_try_to_close_unused_socket(sock);
775 		return;
776 	case SSL_ERROR_WANT_WRITE:
777 		if (sock->tlsstream.nsending == 0) {
778 			/*
779 			 * Launch tls_do_bio asynchronously. If we're sending
780 			 * already the send callback will call it.
781 			 */
782 			async_tls_do_bio(sock);
783 		}
784 		return;
785 	case SSL_ERROR_WANT_READ:
786 		if (tls_try_to_close_unused_socket(sock) ||
787 		    sock->outerhandle == NULL)
788 		{
789 			return;
790 		} else if (sock->reading == false &&
791 			   sock->tlsstream.state == TLS_HANDSHAKE)
792 		{
793 			/*
794 			 * We need to read data when doing handshake even if
795 			 * 'sock->reading == false'. It will be stopped when
796 			 * handshake is completed.
797 			 */
798 			tls_read_start(sock);
799 			return;
800 		} else if (sock->reading == false) {
801 			return;
802 		}
803 
804 		tls_read_start(sock);
805 		return;
806 	default:
807 		result = tls_error_to_result(tls_status, sock->tlsstream.state,
808 					     sock->tlsstream.tls);
809 		break;
810 	}
811 
812 error:
813 #if ISC_NETMGR_TRACE
814 	isc__nmsocket_log(sock, ISC_LOG_NOTICE,
815 			  "SSL error in BIO: %d %s (errno: %d). Arguments: "
816 			  "received_data: %p, "
817 			  "send_data: %p, finish: %s",
818 			  tls_status, isc_result_totext(result), saved_errno,
819 			  received_data, send_data, finish ? "true" : "false");
820 #endif
821 	tls_failed_read_cb(sock, result);
822 }
823 
824 static void
825 tls_readcb(isc_nmhandle_t *handle, isc_result_t result, isc_region_t *region,
826 	   void *cbarg) {
827 	isc_nmsocket_t *tlssock = (isc_nmsocket_t *)cbarg;
828 
829 	REQUIRE(VALID_NMSOCK(tlssock));
830 	REQUIRE(VALID_NMHANDLE(handle));
831 	REQUIRE(tlssock->tid == isc_tid());
832 
833 	if (result != ISC_R_SUCCESS) {
834 		tls_failed_read_cb(tlssock, result);
835 		return;
836 	} else if (isc__nmsocket_closing(handle->sock)) {
837 		tls_failed_read_cb(tlssock, ISC_R_CANCELED);
838 		return;
839 	}
840 
841 	REQUIRE(handle == tlssock->outerhandle);
842 	tls_do_bio(tlssock, region, NULL, false);
843 }
844 
845 static isc_result_t
846 initialize_tls(isc_nmsocket_t *sock, bool server) {
847 	REQUIRE(sock->tid == isc_tid());
848 
849 	sock->tlsstream.bio_in = BIO_new(BIO_s_mem());
850 	if (sock->tlsstream.bio_in == NULL) {
851 		isc_tls_free(&sock->tlsstream.tls);
852 		return ISC_R_TLSERROR;
853 	}
854 	sock->tlsstream.bio_out = BIO_new(BIO_s_mem());
855 	if (sock->tlsstream.bio_out == NULL) {
856 		BIO_free_all(sock->tlsstream.bio_in);
857 		sock->tlsstream.bio_in = NULL;
858 		isc_tls_free(&sock->tlsstream.tls);
859 		return ISC_R_TLSERROR;
860 	}
861 
862 	if (BIO_set_mem_eof_return(sock->tlsstream.bio_in, EOF) != 1 ||
863 	    BIO_set_mem_eof_return(sock->tlsstream.bio_out, EOF) != 1)
864 	{
865 		goto error;
866 	}
867 
868 	SSL_set_bio(sock->tlsstream.tls, sock->tlsstream.bio_in,
869 		    sock->tlsstream.bio_out);
870 	sock->tlsstream.server = server;
871 	sock->tlsstream.nsending = 0;
872 	sock->tlsstream.state = TLS_INIT;
873 	return ISC_R_SUCCESS;
874 error:
875 	isc_tls_free(&sock->tlsstream.tls);
876 	sock->tlsstream.bio_out = sock->tlsstream.bio_in = NULL;
877 	return ISC_R_TLSERROR;
878 }
879 
880 static void
881 tls_try_to_enable_tcp_nodelay(isc_nmsocket_t *tlssock) {
882 	/*
883 	 * Try to enable TCP_NODELAY for TLS connections by default to speed up
884 	 * the handshakes, just like other software (e.g. NGINX) does.
885 	 */
886 	isc_result_t result = isc_nmhandle_set_tcp_nodelay(tlssock->outerhandle,
887 							   true);
888 	tlssock->tlsstream.tcp_nodelay_value = (result == ISC_R_SUCCESS);
889 }
890 
891 static isc_result_t
892 tlslisten_acceptcb(isc_nmhandle_t *handle, isc_result_t result, void *cbarg) {
893 	isc_nmsocket_t *tlslistensock = (isc_nmsocket_t *)cbarg;
894 	isc_nmsocket_t *tlssock = NULL;
895 	isc_tlsctx_t *tlsctx = NULL;
896 	isc_sockaddr_t local;
897 
898 	/* If accept() was unsuccessful we can't do anything */
899 	if (result != ISC_R_SUCCESS) {
900 		return result;
901 	}
902 
903 	REQUIRE(VALID_NMHANDLE(handle));
904 	REQUIRE(VALID_NMSOCK(handle->sock));
905 	REQUIRE(VALID_NMSOCK(tlslistensock));
906 	REQUIRE(tlslistensock->type == isc_nm_tlslistener);
907 
908 	if (isc__nm_closing(handle->sock->worker)) {
909 		return ISC_R_SHUTTINGDOWN;
910 	} else if (isc__nmsocket_closing(handle->sock)) {
911 		return ISC_R_CANCELED;
912 	}
913 
914 	local = isc_nmhandle_localaddr(handle);
915 	/*
916 	 * We need to create a 'wrapper' tlssocket for this connection.
917 	 */
918 	tlssock = isc_mempool_get(handle->sock->worker->nmsocket_pool);
919 	isc__nmsocket_init(tlssock, handle->sock->worker, isc_nm_tlssocket,
920 			   &local, NULL);
921 	isc__nmsocket_attach(tlslistensock, &tlssock->server);
922 
923 	/* We need to initialize SSL now to reference SSL_CTX properly */
924 	tlsctx = tls_get_listener_tlsctx(tlslistensock, isc_tid());
925 	RUNTIME_CHECK(tlsctx != NULL);
926 	isc_tlsctx_attach(tlsctx, &tlssock->tlsstream.ctx);
927 	tlssock->tlsstream.tls = isc_tls_create(tlssock->tlsstream.ctx);
928 	if (tlssock->tlsstream.tls == NULL) {
929 		tlssock->closed = true;
930 		isc_tlsctx_free(&tlssock->tlsstream.ctx);
931 		isc__nmsocket_detach(&tlssock);
932 		return ISC_R_TLSERROR;
933 	}
934 
935 	tlssock->accept_cb = tlslistensock->accept_cb;
936 	tlssock->accept_cbarg = tlslistensock->accept_cbarg;
937 	isc__nmsocket_attach(handle->sock, &tlssock->listener);
938 	isc_nmhandle_attach(handle, &tlssock->outerhandle);
939 	tlssock->peer = isc_nmhandle_peeraddr(handle);
940 	tlssock->read_timeout =
941 		atomic_load_relaxed(&handle->sock->worker->netmgr->init);
942 
943 	/*
944 	 * Hold a reference to tlssock in the TCP socket: it will
945 	 * detached in isc__nm_tls_cleanup_data().
946 	 */
947 	handle->sock->tlsstream.tlssocket = tlssock;
948 
949 	result = initialize_tls(tlssock, true);
950 	RUNTIME_CHECK(result == ISC_R_SUCCESS);
951 	/* TODO: catch failure code, detach tlssock, and log the error */
952 
953 	tls_try_to_enable_tcp_nodelay(tlssock);
954 
955 	isc__nmhandle_set_manual_timer(tlssock->outerhandle, true);
956 	tls_do_bio(tlssock, NULL, NULL, false);
957 	return result;
958 }
959 
960 isc_result_t
961 isc_nm_listentls(isc_nm_t *mgr, uint32_t workers, isc_sockaddr_t *iface,
962 		 isc_nm_accept_cb_t accept_cb, void *accept_cbarg, int backlog,
963 		 isc_quota_t *quota, SSL_CTX *sslctx, bool proxy,
964 		 isc_nmsocket_t **sockp) {
965 	isc_result_t result;
966 	isc_nmsocket_t *tlssock = NULL;
967 	isc_nmsocket_t *tsock = NULL;
968 	isc__networker_t *worker = NULL;
969 
970 	REQUIRE(VALID_NM(mgr));
971 	REQUIRE(isc_tid() == 0);
972 
973 	worker = &mgr->workers[isc_tid()];
974 
975 	if (isc__nm_closing(worker)) {
976 		return ISC_R_SHUTTINGDOWN;
977 	}
978 
979 	if (workers == 0) {
980 		workers = mgr->nloops;
981 	}
982 	REQUIRE(workers <= mgr->nloops);
983 
984 	tlssock = isc_mempool_get(worker->nmsocket_pool);
985 	isc__nmsocket_init(tlssock, worker, isc_nm_tlslistener, iface, NULL);
986 	tlssock->accept_cb = accept_cb;
987 	tlssock->accept_cbarg = accept_cbarg;
988 	tls_init_listener_tlsctx(tlssock, sslctx);
989 	tlssock->tlsstream.tls = NULL;
990 
991 	/*
992 	 * tlssock will be a TLS 'wrapper' around an unencrypted stream.
993 	 * We set tlssock->outer to a socket listening for a TCP connection.
994 	 */
995 	if (proxy) {
996 		result = isc_nm_listenproxystream(
997 			mgr, workers, iface, tlslisten_acceptcb, tlssock,
998 			backlog, quota, NULL, &tlssock->outer);
999 	} else {
1000 		result = isc_nm_listentcp(mgr, workers, iface,
1001 					  tlslisten_acceptcb, tlssock, backlog,
1002 					  quota, &tlssock->outer);
1003 	}
1004 	if (result != ISC_R_SUCCESS) {
1005 		tlssock->closed = true;
1006 		isc__nmsocket_detach(&tlssock);
1007 		return result;
1008 	}
1009 
1010 	/* copy the actual port we're listening on into sock->iface */
1011 	if (isc_sockaddr_getport(iface) == 0) {
1012 		tlssock->iface = tlssock->outer->iface;
1013 	}
1014 
1015 	/* wait for listen result */
1016 	isc__nmsocket_attach(tlssock->outer, &tsock);
1017 	tlssock->result = result;
1018 	tlssock->active = true;
1019 	INSIST(tlssock->outer->tlsstream.tlslistener == NULL);
1020 	isc__nmsocket_attach(tlssock, &tlssock->outer->tlsstream.tlslistener);
1021 	isc__nmsocket_detach(&tsock);
1022 	INSIST(result != ISC_R_UNSET);
1023 	tlssock->nchildren = tlssock->outer->nchildren;
1024 
1025 	if (result == ISC_R_SUCCESS) {
1026 		*sockp = tlssock;
1027 	}
1028 
1029 	return result;
1030 }
1031 
1032 static void
1033 tls_send_direct(void *arg) {
1034 	isc__nm_uvreq_t *req = arg;
1035 
1036 	REQUIRE(VALID_UVREQ(req));
1037 
1038 	isc_nmsocket_t *sock = req->sock;
1039 
1040 	REQUIRE(VALID_NMSOCK(sock));
1041 	REQUIRE(sock->tid == isc_tid());
1042 
1043 	if (isc__nm_closing(sock->worker)) {
1044 		req->cb.send(req->handle, ISC_R_SHUTTINGDOWN, req->cbarg);
1045 		goto done;
1046 	} else if (inactive(sock)) {
1047 		req->cb.send(req->handle, ISC_R_CANCELED, req->cbarg);
1048 		goto done;
1049 	}
1050 
1051 	tls_do_bio(sock, NULL, req, false);
1052 done:
1053 	isc__nm_uvreq_put(&req);
1054 	return;
1055 }
1056 
1057 static void
1058 tls_send(isc_nmhandle_t *handle, const isc_region_t *region, isc_nm_cb_t cb,
1059 	 void *cbarg, const bool dnsmsg) {
1060 	isc__nm_uvreq_t *uvreq = NULL;
1061 	isc_nmsocket_t *sock = NULL;
1062 
1063 	REQUIRE(VALID_NMHANDLE(handle));
1064 	REQUIRE(VALID_NMSOCK(handle->sock));
1065 
1066 	sock = handle->sock;
1067 
1068 	REQUIRE(sock->type == isc_nm_tlssocket);
1069 
1070 	uvreq = isc__nm_uvreq_get(sock);
1071 	isc_nmhandle_attach(handle, &uvreq->handle);
1072 	uvreq->cb.send = cb;
1073 	uvreq->cbarg = cbarg;
1074 	uvreq->uvbuf.base = (char *)region->base;
1075 	uvreq->uvbuf.len = region->length;
1076 	if (dnsmsg) {
1077 		*(uint16_t *)uvreq->tcplen = htons(region->length);
1078 	}
1079 
1080 	isc_job_run(sock->worker->loop, &uvreq->job, tls_send_direct, uvreq);
1081 }
1082 
1083 void
1084 isc__nm_tls_send(isc_nmhandle_t *handle, const isc_region_t *region,
1085 		 isc_nm_cb_t cb, void *cbarg) {
1086 	tls_send(handle, region, cb, cbarg, false);
1087 }
1088 
1089 void
1090 isc__nm_tls_senddns(isc_nmhandle_t *handle, const isc_region_t *region,
1091 		    isc_nm_cb_t cb, void *cbarg) {
1092 	tls_send(handle, region, cb, cbarg, true);
1093 }
1094 
1095 void
1096 isc__nm_tls_read(isc_nmhandle_t *handle, isc_nm_recv_cb_t cb, void *cbarg) {
1097 	isc_nmsocket_t *sock = NULL;
1098 
1099 	REQUIRE(VALID_NMHANDLE(handle));
1100 
1101 	sock = handle->sock;
1102 	REQUIRE(VALID_NMSOCK(sock));
1103 	REQUIRE(sock->statichandle == handle);
1104 	REQUIRE(sock->tid == isc_tid());
1105 
1106 	if (isc__nm_closing(sock->worker)) {
1107 		cb(handle, ISC_R_SHUTTINGDOWN, NULL, cbarg);
1108 		return;
1109 	} else if (inactive(sock)) {
1110 		cb(handle, ISC_R_CANCELED, NULL, cbarg);
1111 		return;
1112 	}
1113 
1114 	sock->recv_cb = cb;
1115 	sock->recv_cbarg = cbarg;
1116 	sock->reading = true;
1117 
1118 	async_tls_do_bio(sock);
1119 }
1120 
1121 static void
1122 tls_read_start(isc_nmsocket_t *restrict sock) {
1123 	if (sock->tlsstream.reading) {
1124 		return;
1125 	}
1126 	sock->tlsstream.reading = true;
1127 
1128 	INSIST(VALID_NMHANDLE(sock->outerhandle));
1129 
1130 	isc_nm_read(sock->outerhandle, tls_readcb, sock);
1131 	if (!sock->manual_read_timer) {
1132 		isc__nmsocket_timer_start(sock);
1133 	}
1134 }
1135 
1136 static void
1137 tls_read_stop(isc_nmsocket_t *sock) {
1138 	sock->tlsstream.reading = false;
1139 	if (sock->outerhandle != NULL) {
1140 		isc_nm_read_stop(sock->outerhandle);
1141 	}
1142 }
1143 
1144 void
1145 isc__nm_tls_read_stop(isc_nmhandle_t *handle) {
1146 	REQUIRE(VALID_NMHANDLE(handle));
1147 	REQUIRE(VALID_NMSOCK(handle->sock));
1148 
1149 	handle->sock->reading = false;
1150 
1151 	tls_read_stop(handle->sock);
1152 }
1153 
1154 void
1155 isc__nm_tls_close(isc_nmsocket_t *sock) {
1156 	REQUIRE(VALID_NMSOCK(sock));
1157 	REQUIRE(sock->type == isc_nm_tlssocket);
1158 	REQUIRE(!sock->closing);
1159 	REQUIRE(sock->tid == isc_tid());
1160 	REQUIRE(!sock->closed);
1161 	REQUIRE(!sock->closing);
1162 
1163 	sock->closing = true;
1164 
1165 	/*
1166 	 * At this point we're certain that there are no
1167 	 * external references, we can close everything.
1168 	 */
1169 	tls_read_stop(sock);
1170 	if (sock->outerhandle != NULL) {
1171 		isc_nm_read_stop(sock->outerhandle);
1172 		isc_nmhandle_close(sock->outerhandle);
1173 		isc_nmhandle_detach(&sock->outerhandle);
1174 	}
1175 
1176 	if (sock->listener != NULL) {
1177 		isc__nmsocket_detach(&sock->listener);
1178 	}
1179 
1180 	if (sock->server != NULL) {
1181 		isc__nmsocket_detach(&sock->server);
1182 	}
1183 
1184 	/* Further cleanup performed in isc__nm_tls_cleanup_data() */
1185 	sock->closed = true;
1186 	sock->active = false;
1187 	sock->tlsstream.state = TLS_CLOSED;
1188 }
1189 
1190 void
1191 isc__nm_tls_stoplistening(isc_nmsocket_t *sock) {
1192 	REQUIRE(VALID_NMSOCK(sock));
1193 	REQUIRE(sock->type == isc_nm_tlslistener);
1194 	REQUIRE(sock->tlsstream.tls == NULL);
1195 	REQUIRE(sock->tlsstream.ctx == NULL);
1196 
1197 	isc__nmsocket_stop(sock);
1198 }
1199 
1200 static void
1201 tcp_connected(isc_nmhandle_t *handle, isc_result_t result, void *cbarg);
1202 
1203 void
1204 isc_nm_tlsconnect(isc_nm_t *mgr, isc_sockaddr_t *local, isc_sockaddr_t *peer,
1205 		  isc_nm_cb_t connect_cb, void *connect_cbarg,
1206 		  isc_tlsctx_t *ctx,
1207 		  isc_tlsctx_client_session_cache_t *client_sess_cache,
1208 		  unsigned int timeout, bool proxy,
1209 		  isc_nm_proxyheader_info_t *proxy_info) {
1210 	isc_nmsocket_t *sock = NULL;
1211 	isc__networker_t *worker = NULL;
1212 
1213 	REQUIRE(VALID_NM(mgr));
1214 
1215 	worker = &mgr->workers[isc_tid()];
1216 
1217 	if (isc__nm_closing(worker)) {
1218 		connect_cb(NULL, ISC_R_SHUTTINGDOWN, connect_cbarg);
1219 		return;
1220 	}
1221 
1222 	sock = isc_mempool_get(worker->nmsocket_pool);
1223 	isc__nmsocket_init(sock, worker, isc_nm_tlssocket, local, NULL);
1224 	sock->connect_cb = connect_cb;
1225 	sock->connect_cbarg = connect_cbarg;
1226 	sock->connect_timeout = timeout;
1227 	isc_tlsctx_attach(ctx, &sock->tlsstream.ctx);
1228 	sock->client = true;
1229 	if (client_sess_cache != NULL) {
1230 		INSIST(isc_tlsctx_client_session_cache_getctx(
1231 			       client_sess_cache) == ctx);
1232 		isc_tlsctx_client_session_cache_attach(
1233 			client_sess_cache, &sock->tlsstream.client_sess_cache);
1234 	}
1235 
1236 	if (proxy) {
1237 		isc_nm_proxystreamconnect(mgr, local, peer, tcp_connected, sock,
1238 					  sock->connect_timeout, NULL, NULL,
1239 					  proxy_info);
1240 	} else {
1241 		isc_nm_tcpconnect(mgr, local, peer, tcp_connected, sock,
1242 				  sock->connect_timeout);
1243 	}
1244 }
1245 
1246 static void
1247 tcp_connected(isc_nmhandle_t *handle, isc_result_t result, void *cbarg) {
1248 	isc_nmsocket_t *tlssock = (isc_nmsocket_t *)cbarg;
1249 	isc_nmhandle_t *tlshandle = NULL;
1250 	isc__networker_t *worker = NULL;
1251 
1252 	REQUIRE(VALID_NMSOCK(tlssock));
1253 
1254 	worker = tlssock->worker;
1255 
1256 	if (result != ISC_R_SUCCESS) {
1257 		goto error;
1258 	}
1259 
1260 	INSIST(VALID_NMHANDLE(handle));
1261 
1262 	tlssock->iface = isc_nmhandle_localaddr(handle);
1263 	tlssock->peer = isc_nmhandle_peeraddr(handle);
1264 	if (isc__nm_closing(worker)) {
1265 		result = ISC_R_SHUTTINGDOWN;
1266 		goto error;
1267 	} else if (isc__nmsocket_closing(handle->sock)) {
1268 		result = ISC_R_CANCELED;
1269 		goto error;
1270 	}
1271 
1272 	/*
1273 	 * We need to initialize SSL now to reference SSL_CTX properly.
1274 	 */
1275 	tlssock->tlsstream.tls = isc_tls_create(tlssock->tlsstream.ctx);
1276 	if (tlssock->tlsstream.tls == NULL) {
1277 		result = ISC_R_TLSERROR;
1278 		goto error;
1279 	}
1280 
1281 	result = initialize_tls(tlssock, false);
1282 	if (result != ISC_R_SUCCESS) {
1283 		goto error;
1284 	}
1285 	tlssock->peer = isc_nmhandle_peeraddr(handle);
1286 	isc_nmhandle_attach(handle, &tlssock->outerhandle);
1287 	tlssock->active = true;
1288 
1289 	if (tlssock->tlsstream.client_sess_cache != NULL) {
1290 		isc_tlsctx_client_session_cache_reuse_sockaddr(
1291 			tlssock->tlsstream.client_sess_cache, &tlssock->peer,
1292 			tlssock->tlsstream.tls);
1293 	}
1294 
1295 	/*
1296 	 * Hold a reference to tlssock in the TCP socket: it will
1297 	 * detached in isc__nm_tls_cleanup_data().
1298 	 */
1299 	handle->sock->tlsstream.tlssocket = tlssock;
1300 
1301 	tls_try_to_enable_tcp_nodelay(tlssock);
1302 
1303 	isc__nmhandle_set_manual_timer(tlssock->outerhandle, true);
1304 	tls_do_bio(tlssock, NULL, NULL, false);
1305 	return;
1306 error:
1307 	tlshandle = isc__nmhandle_get(tlssock, NULL, NULL);
1308 	tlssock->closed = true;
1309 	tls_call_connect_cb(tlssock, tlshandle, result);
1310 	isc_nmhandle_detach(&tlshandle);
1311 	isc__nmsocket_detach(&tlssock);
1312 }
1313 
1314 void
1315 isc__nm_tls_cleanup_data(isc_nmsocket_t *sock) {
1316 	if ((sock->type == isc_nm_tcplistener ||
1317 	     sock->type == isc_nm_proxystreamlistener) &&
1318 	    sock->tlsstream.tlslistener != NULL)
1319 	{
1320 		isc__nmsocket_detach(&sock->tlsstream.tlslistener);
1321 	} else if (sock->type == isc_nm_tlslistener) {
1322 		tls_cleanup_listener_tlsctx(sock);
1323 	} else if (sock->type == isc_nm_tlssocket) {
1324 		if (sock->tlsstream.tls != NULL) {
1325 			/*
1326 			 * Let's shut down the TLS session properly so that
1327 			 * the session will remain resumable, if required.
1328 			 */
1329 			tls_try_shutdown(sock->tlsstream.tls, true);
1330 			tls_keep_client_tls_session(sock);
1331 			isc_tls_free(&sock->tlsstream.tls);
1332 			/* These are destroyed when we free SSL */
1333 			sock->tlsstream.bio_out = NULL;
1334 			sock->tlsstream.bio_in = NULL;
1335 		}
1336 		if (sock->tlsstream.ctx != NULL) {
1337 			isc_tlsctx_free(&sock->tlsstream.ctx);
1338 		}
1339 		if (sock->tlsstream.client_sess_cache != NULL) {
1340 			INSIST(sock->client);
1341 			isc_tlsctx_client_session_cache_detach(
1342 				&sock->tlsstream.client_sess_cache);
1343 		}
1344 
1345 		if (sock->tlsstream.send_req != NULL) {
1346 			isc_buffer_clearmctx(&sock->tlsstream.send_req->data);
1347 			isc_buffer_invalidate(&sock->tlsstream.send_req->data);
1348 			isc_mem_put(sock->worker->mctx,
1349 				    sock->tlsstream.send_req,
1350 				    sizeof(*sock->tlsstream.send_req));
1351 		}
1352 	} else if ((sock->type == isc_nm_tcpsocket ||
1353 		    sock->type == isc_nm_proxystreamsocket) &&
1354 		   sock->tlsstream.tlssocket != NULL)
1355 	{
1356 		/*
1357 		 * The TLS socket can't be destroyed until its underlying TCP
1358 		 * socket is, to avoid possible use-after-free errors.
1359 		 */
1360 		isc__nmsocket_detach(&sock->tlsstream.tlssocket);
1361 	}
1362 }
1363 
1364 void
1365 isc__nm_tls_cleartimeout(isc_nmhandle_t *handle) {
1366 	isc_nmsocket_t *sock = NULL;
1367 
1368 	REQUIRE(VALID_NMHANDLE(handle));
1369 	REQUIRE(VALID_NMSOCK(handle->sock));
1370 	REQUIRE(handle->sock->type == isc_nm_tlssocket);
1371 
1372 	sock = handle->sock;
1373 	if (sock->outerhandle != NULL) {
1374 		INSIST(VALID_NMHANDLE(sock->outerhandle));
1375 		isc_nmhandle_cleartimeout(sock->outerhandle);
1376 	}
1377 }
1378 
1379 void
1380 isc__nm_tls_settimeout(isc_nmhandle_t *handle, uint32_t timeout) {
1381 	isc_nmsocket_t *sock = NULL;
1382 
1383 	REQUIRE(VALID_NMHANDLE(handle));
1384 	REQUIRE(VALID_NMSOCK(handle->sock));
1385 	REQUIRE(handle->sock->type == isc_nm_tlssocket);
1386 
1387 	sock = handle->sock;
1388 	if (sock->outerhandle != NULL) {
1389 		INSIST(VALID_NMHANDLE(sock->outerhandle));
1390 		isc_nmhandle_settimeout(sock->outerhandle, timeout);
1391 	}
1392 }
1393 
1394 void
1395 isc__nmhandle_tls_keepalive(isc_nmhandle_t *handle, bool value) {
1396 	isc_nmsocket_t *sock = NULL;
1397 
1398 	REQUIRE(VALID_NMHANDLE(handle));
1399 	REQUIRE(VALID_NMSOCK(handle->sock));
1400 	REQUIRE(handle->sock->type == isc_nm_tlssocket);
1401 
1402 	sock = handle->sock;
1403 	if (sock->outerhandle != NULL) {
1404 		INSIST(VALID_NMHANDLE(sock->outerhandle));
1405 
1406 		isc_nmhandle_keepalive(sock->outerhandle, value);
1407 	}
1408 }
1409 
1410 void
1411 isc__nmhandle_tls_setwritetimeout(isc_nmhandle_t *handle,
1412 				  uint64_t write_timeout) {
1413 	isc_nmsocket_t *sock = NULL;
1414 
1415 	REQUIRE(VALID_NMHANDLE(handle));
1416 	REQUIRE(VALID_NMSOCK(handle->sock));
1417 	REQUIRE(handle->sock->type == isc_nm_tlssocket);
1418 
1419 	sock = handle->sock;
1420 	if (sock->outerhandle != NULL) {
1421 		INSIST(VALID_NMHANDLE(sock->outerhandle));
1422 
1423 		isc_nmhandle_setwritetimeout(sock->outerhandle, write_timeout);
1424 	}
1425 }
1426 
1427 void
1428 isc__nmsocket_tls_reset(isc_nmsocket_t *sock) {
1429 	REQUIRE(VALID_NMSOCK(sock));
1430 	REQUIRE(sock->type == isc_nm_tlssocket);
1431 
1432 	if (sock->outerhandle != NULL) {
1433 		INSIST(VALID_NMHANDLE(sock->outerhandle));
1434 		REQUIRE(VALID_NMSOCK(sock->outerhandle->sock));
1435 		isc__nmsocket_reset(sock->outerhandle->sock);
1436 	}
1437 }
1438 
1439 bool
1440 isc__nmsocket_tls_timer_running(isc_nmsocket_t *sock) {
1441 	REQUIRE(VALID_NMSOCK(sock));
1442 	REQUIRE(sock->type == isc_nm_tlssocket);
1443 
1444 	if (sock->outerhandle != NULL) {
1445 		INSIST(VALID_NMHANDLE(sock->outerhandle));
1446 		REQUIRE(VALID_NMSOCK(sock->outerhandle->sock));
1447 		return isc__nmsocket_timer_running(sock->outerhandle->sock);
1448 	}
1449 
1450 	return false;
1451 }
1452 
1453 void
1454 isc__nmsocket_tls_timer_restart(isc_nmsocket_t *sock) {
1455 	REQUIRE(VALID_NMSOCK(sock));
1456 	REQUIRE(sock->type == isc_nm_tlssocket);
1457 
1458 	if (sock->outerhandle != NULL) {
1459 		INSIST(VALID_NMHANDLE(sock->outerhandle));
1460 		REQUIRE(VALID_NMSOCK(sock->outerhandle->sock));
1461 		isc__nmsocket_timer_restart(sock->outerhandle->sock);
1462 	}
1463 }
1464 
1465 void
1466 isc__nmsocket_tls_timer_stop(isc_nmsocket_t *sock) {
1467 	REQUIRE(VALID_NMSOCK(sock));
1468 	REQUIRE(sock->type == isc_nm_tlssocket);
1469 
1470 	if (sock->outerhandle != NULL) {
1471 		INSIST(VALID_NMHANDLE(sock->outerhandle));
1472 		REQUIRE(VALID_NMSOCK(sock->outerhandle->sock));
1473 		isc__nmsocket_timer_stop(sock->outerhandle->sock);
1474 	}
1475 }
1476 
1477 const char *
1478 isc__nm_tls_verify_tls_peer_result_string(const isc_nmhandle_t *handle) {
1479 	isc_nmsocket_t *sock = NULL;
1480 
1481 	REQUIRE(VALID_NMHANDLE(handle));
1482 	REQUIRE(VALID_NMSOCK(handle->sock));
1483 	REQUIRE(handle->sock->type == isc_nm_tlssocket);
1484 
1485 	sock = handle->sock;
1486 	if (sock->tlsstream.tls == NULL) {
1487 		return NULL;
1488 	}
1489 
1490 	return isc_tls_verify_peer_result_string(sock->tlsstream.tls);
1491 }
1492 
1493 static void
1494 tls_init_listener_tlsctx(isc_nmsocket_t *listener, isc_tlsctx_t *ctx) {
1495 	size_t nworkers;
1496 
1497 	REQUIRE(VALID_NMSOCK(listener));
1498 	REQUIRE(ctx != NULL);
1499 
1500 	nworkers =
1501 		(size_t)isc_loopmgr_nloops(listener->worker->netmgr->loopmgr);
1502 	INSIST(nworkers > 0);
1503 
1504 	listener->tlsstream.listener_tls_ctx = isc_mem_cget(
1505 		listener->worker->mctx, nworkers, sizeof(isc_tlsctx_t *));
1506 	listener->tlsstream.n_listener_tls_ctx = nworkers;
1507 	for (size_t i = 0; i < nworkers; i++) {
1508 		listener->tlsstream.listener_tls_ctx[i] = NULL;
1509 		isc_tlsctx_attach(ctx,
1510 				  &listener->tlsstream.listener_tls_ctx[i]);
1511 	}
1512 }
1513 
1514 static void
1515 tls_cleanup_listener_tlsctx(isc_nmsocket_t *listener) {
1516 	REQUIRE(VALID_NMSOCK(listener));
1517 
1518 	if (listener->tlsstream.listener_tls_ctx == NULL) {
1519 		return;
1520 	}
1521 
1522 	for (size_t i = 0; i < listener->tlsstream.n_listener_tls_ctx; i++) {
1523 		isc_tlsctx_free(&listener->tlsstream.listener_tls_ctx[i]);
1524 	}
1525 	isc_mem_cput(
1526 		listener->worker->mctx, listener->tlsstream.listener_tls_ctx,
1527 		listener->tlsstream.n_listener_tls_ctx, sizeof(isc_tlsctx_t *));
1528 	listener->tlsstream.n_listener_tls_ctx = 0;
1529 }
1530 
1531 static isc_tlsctx_t *
1532 tls_get_listener_tlsctx(isc_nmsocket_t *listener, const int tid) {
1533 	REQUIRE(VALID_NMSOCK(listener));
1534 	REQUIRE(tid >= 0);
1535 
1536 	if (listener->tlsstream.listener_tls_ctx == NULL) {
1537 		return NULL;
1538 	}
1539 
1540 	return listener->tlsstream.listener_tls_ctx[tid];
1541 }
1542 
1543 void
1544 isc__nm_async_tls_set_tlsctx(isc_nmsocket_t *listener, isc_tlsctx_t *tlsctx,
1545 			     const int tid) {
1546 	REQUIRE(tid >= 0);
1547 
1548 	isc_tlsctx_free(&listener->tlsstream.listener_tls_ctx[tid]);
1549 	isc_tlsctx_attach(tlsctx, &listener->tlsstream.listener_tls_ctx[tid]);
1550 }
1551 
1552 static void
1553 tls_keep_client_tls_session(isc_nmsocket_t *sock) {
1554 	/*
1555 	 * Ensure that the isc_tls_t is being accessed from
1556 	 * within the worker thread the socket is bound to.
1557 	 */
1558 	REQUIRE(sock->tid == isc_tid());
1559 	if (sock->tlsstream.client_sess_cache != NULL &&
1560 	    sock->tlsstream.client_session_saved == false)
1561 	{
1562 		INSIST(sock->client);
1563 		isc_tlsctx_client_session_cache_keep_sockaddr(
1564 			sock->tlsstream.client_sess_cache, &sock->peer,
1565 			sock->tlsstream.tls);
1566 		sock->tlsstream.client_session_saved = true;
1567 	}
1568 }
1569 
1570 static void
1571 tls_try_shutdown(isc_tls_t *tls, const bool force) {
1572 	if (force) {
1573 		(void)SSL_set_shutdown(tls, SSL_SENT_SHUTDOWN);
1574 	} else if ((SSL_get_shutdown(tls) & SSL_SENT_SHUTDOWN) == 0) {
1575 		(void)SSL_shutdown(tls);
1576 	}
1577 }
1578 
1579 void
1580 isc__nmhandle_tls_set_manual_timer(isc_nmhandle_t *handle, const bool manual) {
1581 	isc_nmsocket_t *sock;
1582 
1583 	REQUIRE(VALID_NMHANDLE(handle));
1584 	sock = handle->sock;
1585 	REQUIRE(VALID_NMSOCK(sock));
1586 	REQUIRE(sock->type == isc_nm_tlssocket);
1587 	REQUIRE(sock->tid == isc_tid());
1588 
1589 	sock->manual_read_timer = manual;
1590 }
1591 
1592 void
1593 isc__nmhandle_tls_get_selected_alpn(isc_nmhandle_t *handle,
1594 				    const unsigned char **alpn,
1595 				    unsigned int *alpnlen) {
1596 	isc_nmsocket_t *sock;
1597 
1598 	REQUIRE(VALID_NMHANDLE(handle));
1599 	sock = handle->sock;
1600 	REQUIRE(VALID_NMSOCK(sock));
1601 	REQUIRE(sock->type == isc_nm_tlssocket);
1602 	REQUIRE(sock->tid == isc_tid());
1603 
1604 	isc_tls_get_selected_alpn(sock->tlsstream.tls, alpn, alpnlen);
1605 }
1606 
1607 isc_result_t
1608 isc__nmhandle_tls_set_tcp_nodelay(isc_nmhandle_t *handle, const bool value) {
1609 	isc_nmsocket_t *sock = NULL;
1610 	isc_result_t result = ISC_R_FAILURE;
1611 
1612 	REQUIRE(VALID_NMHANDLE(handle));
1613 	REQUIRE(VALID_NMSOCK(handle->sock));
1614 	REQUIRE(handle->sock->type == isc_nm_tlssocket);
1615 
1616 	sock = handle->sock;
1617 	if (sock->outerhandle != NULL) {
1618 		INSIST(VALID_NMHANDLE(sock->outerhandle));
1619 
1620 		if (value == sock->tlsstream.tcp_nodelay_value) {
1621 			result = ISC_R_SUCCESS;
1622 		} else {
1623 			result = isc_nmhandle_set_tcp_nodelay(sock->outerhandle,
1624 							      value);
1625 			if (result == ISC_R_SUCCESS) {
1626 				sock->tlsstream.tcp_nodelay_value = value;
1627 			}
1628 		}
1629 	}
1630 
1631 	return result;
1632 }
1633