xref: /openbsd-src/lib/libtls/tls.c (revision ff0e7be1ebbcc809ea8ad2b6dafe215824da9e46)
1 /* $OpenBSD: tls.c,v 1.96 2023/05/25 07:46:21 op Exp $ */
2 /*
3  * Copyright (c) 2014 Joel Sing <jsing@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <sys/socket.h>
19 
20 #include <errno.h>
21 #include <limits.h>
22 #include <pthread.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 
27 #include <openssl/bio.h>
28 #include <openssl/err.h>
29 #include <openssl/evp.h>
30 #include <openssl/pem.h>
31 #include <openssl/safestack.h>
32 #include <openssl/ssl.h>
33 #include <openssl/x509.h>
34 
35 #include <tls.h>
36 #include "tls_internal.h"
37 
38 static struct tls_config *tls_config_default;
39 
40 static int tls_init_rv = -1;
41 
42 static void
43 tls_do_init(void)
44 {
45 	OPENSSL_init_ssl(OPENSSL_INIT_NO_LOAD_CONFIG, NULL);
46 
47 	if (BIO_sock_init() != 1)
48 		return;
49 
50 	if ((tls_config_default = tls_config_new_internal()) == NULL)
51 		return;
52 
53 	tls_config_default->refcount++;
54 
55 	tls_init_rv = 0;
56 }
57 
58 int
59 tls_init(void)
60 {
61 	static pthread_once_t once = PTHREAD_ONCE_INIT;
62 
63 	if (pthread_once(&once, tls_do_init) != 0)
64 		return -1;
65 
66 	return tls_init_rv;
67 }
68 
69 const char *
70 tls_error(struct tls *ctx)
71 {
72 	return ctx->error.msg;
73 }
74 
75 void
76 tls_error_clear(struct tls_error *error)
77 {
78 	free(error->msg);
79 	error->msg = NULL;
80 	error->num = 0;
81 	error->tls = 0;
82 }
83 
84 static int
85 tls_error_vset(struct tls_error *error, int errnum, const char *fmt, va_list ap)
86 {
87 	char *errmsg = NULL;
88 	int rv = -1;
89 
90 	tls_error_clear(error);
91 
92 	error->num = errnum;
93 	error->tls = 1;
94 
95 	if (vasprintf(&errmsg, fmt, ap) == -1) {
96 		errmsg = NULL;
97 		goto err;
98 	}
99 
100 	if (errnum == -1) {
101 		error->msg = errmsg;
102 		return (0);
103 	}
104 
105 	if (asprintf(&error->msg, "%s: %s", errmsg, strerror(errnum)) == -1) {
106 		error->msg = NULL;
107 		goto err;
108 	}
109 	rv = 0;
110 
111  err:
112 	free(errmsg);
113 
114 	return (rv);
115 }
116 
117 int
118 tls_error_set(struct tls_error *error, const char *fmt, ...)
119 {
120 	va_list ap;
121 	int errnum, rv;
122 
123 	errnum = errno;
124 
125 	va_start(ap, fmt);
126 	rv = tls_error_vset(error, errnum, fmt, ap);
127 	va_end(ap);
128 
129 	return (rv);
130 }
131 
132 int
133 tls_error_setx(struct tls_error *error, const char *fmt, ...)
134 {
135 	va_list ap;
136 	int rv;
137 
138 	va_start(ap, fmt);
139 	rv = tls_error_vset(error, -1, fmt, ap);
140 	va_end(ap);
141 
142 	return (rv);
143 }
144 
145 int
146 tls_config_set_error(struct tls_config *config, const char *fmt, ...)
147 {
148 	va_list ap;
149 	int errnum, rv;
150 
151 	errnum = errno;
152 
153 	va_start(ap, fmt);
154 	rv = tls_error_vset(&config->error, errnum, fmt, ap);
155 	va_end(ap);
156 
157 	return (rv);
158 }
159 
160 int
161 tls_config_set_errorx(struct tls_config *config, const char *fmt, ...)
162 {
163 	va_list ap;
164 	int rv;
165 
166 	va_start(ap, fmt);
167 	rv = tls_error_vset(&config->error, -1, fmt, ap);
168 	va_end(ap);
169 
170 	return (rv);
171 }
172 
173 int
174 tls_set_error(struct tls *ctx, const char *fmt, ...)
175 {
176 	va_list ap;
177 	int errnum, rv;
178 
179 	errnum = errno;
180 
181 	va_start(ap, fmt);
182 	rv = tls_error_vset(&ctx->error, errnum, fmt, ap);
183 	va_end(ap);
184 
185 	return (rv);
186 }
187 
188 int
189 tls_set_errorx(struct tls *ctx, const char *fmt, ...)
190 {
191 	va_list ap;
192 	int rv;
193 
194 	va_start(ap, fmt);
195 	rv = tls_error_vset(&ctx->error, -1, fmt, ap);
196 	va_end(ap);
197 
198 	return (rv);
199 }
200 
201 int
202 tls_set_ssl_errorx(struct tls *ctx, const char *fmt, ...)
203 {
204 	va_list ap;
205 	int rv;
206 
207 	/* Only set an error if a more specific one does not already exist. */
208 	if (ctx->error.tls != 0)
209 		return (0);
210 
211 	va_start(ap, fmt);
212 	rv = tls_error_vset(&ctx->error, -1, fmt, ap);
213 	va_end(ap);
214 
215 	return (rv);
216 }
217 
218 struct tls_sni_ctx *
219 tls_sni_ctx_new(void)
220 {
221 	return (calloc(1, sizeof(struct tls_sni_ctx)));
222 }
223 
224 void
225 tls_sni_ctx_free(struct tls_sni_ctx *sni_ctx)
226 {
227 	if (sni_ctx == NULL)
228 		return;
229 
230 	SSL_CTX_free(sni_ctx->ssl_ctx);
231 	X509_free(sni_ctx->ssl_cert);
232 
233 	free(sni_ctx);
234 }
235 
236 struct tls *
237 tls_new(void)
238 {
239 	struct tls *ctx;
240 
241 	if ((ctx = calloc(1, sizeof(*ctx))) == NULL)
242 		return (NULL);
243 
244 	tls_reset(ctx);
245 
246 	if (tls_configure(ctx, tls_config_default) == -1) {
247 		free(ctx);
248 		return NULL;
249 	}
250 
251 	return (ctx);
252 }
253 
254 int
255 tls_configure(struct tls *ctx, struct tls_config *config)
256 {
257 	if (config == NULL)
258 		config = tls_config_default;
259 
260 	pthread_mutex_lock(&config->mutex);
261 	config->refcount++;
262 	pthread_mutex_unlock(&config->mutex);
263 
264 	tls_config_free(ctx->config);
265 
266 	ctx->config = config;
267 	ctx->keypair = config->keypair;
268 
269 	if ((ctx->flags & TLS_SERVER) != 0)
270 		return (tls_configure_server(ctx));
271 
272 	return (0);
273 }
274 
275 int
276 tls_cert_hash(X509 *cert, char **hash)
277 {
278 	char d[EVP_MAX_MD_SIZE], *dhex = NULL;
279 	int dlen, rv = -1;
280 
281 	free(*hash);
282 	*hash = NULL;
283 
284 	if (X509_digest(cert, EVP_sha256(), d, &dlen) != 1)
285 		goto err;
286 
287 	if (tls_hex_string(d, dlen, &dhex, NULL) != 0)
288 		goto err;
289 
290 	if (asprintf(hash, "SHA256:%s", dhex) == -1) {
291 		*hash = NULL;
292 		goto err;
293 	}
294 
295 	rv = 0;
296  err:
297 	free(dhex);
298 
299 	return (rv);
300 }
301 
302 int
303 tls_cert_pubkey_hash(X509 *cert, char **hash)
304 {
305 	char d[EVP_MAX_MD_SIZE], *dhex = NULL;
306 	int dlen, rv = -1;
307 
308 	free(*hash);
309 	*hash = NULL;
310 
311 	if (X509_pubkey_digest(cert, EVP_sha256(), d, &dlen) != 1)
312 		goto err;
313 
314 	if (tls_hex_string(d, dlen, &dhex, NULL) != 0)
315 		goto err;
316 
317 	if (asprintf(hash, "SHA256:%s", dhex) == -1) {
318 		*hash = NULL;
319 		goto err;
320 	}
321 
322 	rv = 0;
323 
324  err:
325 	free(dhex);
326 
327 	return (rv);
328 }
329 
330 static int
331 tls_keypair_to_pkey(struct tls *ctx, struct tls_keypair *keypair, EVP_PKEY **pkey)
332 {
333 	BIO *bio = NULL;
334 	X509 *x509 = NULL;
335 	char *mem;
336 	size_t len;
337 	int ret = -1;
338 
339 	*pkey = NULL;
340 
341 	if (ctx->config->use_fake_private_key) {
342 		mem = keypair->cert_mem;
343 		len = keypair->cert_len;
344 	} else {
345 		mem = keypair->key_mem;
346 		len = keypair->key_len;
347 	}
348 
349 	if (mem == NULL)
350 		return (0);
351 
352 	if (len > INT_MAX) {
353 		tls_set_errorx(ctx, ctx->config->use_fake_private_key ?
354 		    "cert too long" : "key too long");
355 		goto err;
356 	}
357 
358 	if ((bio = BIO_new_mem_buf(mem, len)) == NULL) {
359 		tls_set_errorx(ctx, "failed to create buffer");
360 		goto err;
361 	}
362 
363 	if (ctx->config->use_fake_private_key) {
364 		if ((x509 = PEM_read_bio_X509(bio, NULL, tls_password_cb,
365 		    NULL)) == NULL) {
366 			tls_set_errorx(ctx, "failed to read X509 certificate");
367 			goto err;
368 		}
369 		if ((*pkey = X509_get_pubkey(x509)) == NULL) {
370 			tls_set_errorx(ctx, "failed to retrieve pubkey");
371 			goto err;
372 		}
373 	} else {
374 		if ((*pkey = PEM_read_bio_PrivateKey(bio, NULL, tls_password_cb,
375 		    NULL)) ==  NULL) {
376 			tls_set_errorx(ctx, "failed to read private key");
377 			goto err;
378 		}
379 	}
380 
381 	ret = 0;
382  err:
383 	BIO_free(bio);
384 	X509_free(x509);
385 	return (ret);
386 }
387 
388 static int
389 tls_keypair_setup_pkey(struct tls *ctx, struct tls_keypair *keypair, EVP_PKEY *pkey)
390 {
391 	RSA_METHOD *rsa_method;
392 	ECDSA_METHOD *ecdsa_method;
393 	RSA *rsa = NULL;
394 	EC_KEY *eckey = NULL;
395 	int ret = -1;
396 
397 	/* Only install the pubkey hash if fake private keys are used. */
398 	if (!ctx->config->skip_private_key_check)
399 		return (0);
400 
401 	if (keypair->pubkey_hash == NULL) {
402 		tls_set_errorx(ctx, "public key hash not set");
403 		goto err;
404 	}
405 
406 	switch (EVP_PKEY_id(pkey)) {
407 	case EVP_PKEY_RSA:
408 		if ((rsa = EVP_PKEY_get1_RSA(pkey)) == NULL ||
409 		    RSA_set_ex_data(rsa, 0, keypair->pubkey_hash) == 0) {
410 			tls_set_errorx(ctx, "RSA key setup failure");
411 			goto err;
412 		}
413 		if (ctx->config->sign_cb != NULL) {
414 			rsa_method = tls_signer_rsa_method();
415 			if (rsa_method == NULL ||
416 			    RSA_set_ex_data(rsa, 1, ctx->config) == 0 ||
417 			    RSA_set_method(rsa, rsa_method) == 0) {
418 				tls_set_errorx(ctx, "failed to setup RSA key");
419 				goto err;
420 			}
421 		}
422 		/* Reset the key to work around caching in OpenSSL 3. */
423 		if (EVP_PKEY_set1_RSA(pkey, rsa) == 0) {
424 			tls_set_errorx(ctx, "failed to set RSA key");
425 			goto err;
426 		}
427 		break;
428 	case EVP_PKEY_EC:
429 		if ((eckey = EVP_PKEY_get1_EC_KEY(pkey)) == NULL ||
430 		    ECDSA_set_ex_data(eckey, 0, keypair->pubkey_hash) == 0) {
431 			tls_set_errorx(ctx, "EC key setup failure");
432 			goto err;
433 		}
434 		if (ctx->config->sign_cb != NULL) {
435 			ecdsa_method = tls_signer_ecdsa_method();
436 			if (ecdsa_method == NULL ||
437 			    ECDSA_set_ex_data(eckey, 1, ctx->config) == 0 ||
438 			    ECDSA_set_method(eckey, ecdsa_method) == 0) {
439 				tls_set_errorx(ctx, "failed to setup EC key");
440 				goto err;
441 			}
442 		}
443 		/* Reset the key to work around caching in OpenSSL 3. */
444 		if (EVP_PKEY_set1_EC_KEY(pkey, eckey) == 0) {
445 			tls_set_errorx(ctx, "failed to set EC key");
446 			goto err;
447 		}
448 		break;
449 	default:
450 		tls_set_errorx(ctx, "incorrect key type");
451 		goto err;
452 	}
453 
454 	ret = 0;
455 
456  err:
457 	RSA_free(rsa);
458 	EC_KEY_free(eckey);
459 	return (ret);
460 }
461 
462 int
463 tls_configure_ssl_keypair(struct tls *ctx, SSL_CTX *ssl_ctx,
464     struct tls_keypair *keypair, int required)
465 {
466 	EVP_PKEY *pkey = NULL;
467 
468 	if (!required &&
469 	    keypair->cert_mem == NULL &&
470 	    keypair->key_mem == NULL)
471 		return(0);
472 
473 	if (keypair->cert_mem != NULL) {
474 		if (keypair->cert_len > INT_MAX) {
475 			tls_set_errorx(ctx, "certificate too long");
476 			goto err;
477 		}
478 
479 		if (SSL_CTX_use_certificate_chain_mem(ssl_ctx,
480 		    keypair->cert_mem, keypair->cert_len) != 1) {
481 			tls_set_errorx(ctx, "failed to load certificate");
482 			goto err;
483 		}
484 	}
485 
486 	if (tls_keypair_to_pkey(ctx, keypair, &pkey) == -1)
487 		goto err;
488 	if (pkey != NULL) {
489 		if (tls_keypair_setup_pkey(ctx, keypair, pkey) == -1)
490 			goto err;
491 		if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1) {
492 			tls_set_errorx(ctx, "failed to load private key");
493 			goto err;
494 		}
495 		EVP_PKEY_free(pkey);
496 		pkey = NULL;
497 	}
498 
499 	if (!ctx->config->skip_private_key_check &&
500 	    SSL_CTX_check_private_key(ssl_ctx) != 1) {
501 		tls_set_errorx(ctx, "private/public key mismatch");
502 		goto err;
503 	}
504 
505 	return (0);
506 
507  err:
508 	EVP_PKEY_free(pkey);
509 
510 	return (-1);
511 }
512 
513 int
514 tls_configure_ssl(struct tls *ctx, SSL_CTX *ssl_ctx)
515 {
516 	SSL_CTX_clear_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
517 
518 	SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
519 	SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
520 
521 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2);
522 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv3);
523 
524 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1);
525 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
526 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
527 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_3);
528 
529 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_0) == 0)
530 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1);
531 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_1) == 0)
532 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
533 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_2) == 0)
534 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
535 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_3) == 0)
536 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_3);
537 
538 	if (ctx->config->alpn != NULL) {
539 		if (SSL_CTX_set_alpn_protos(ssl_ctx, ctx->config->alpn,
540 		    ctx->config->alpn_len) != 0) {
541 			tls_set_errorx(ctx, "failed to set alpn");
542 			goto err;
543 		}
544 	}
545 
546 	if (ctx->config->ciphers != NULL) {
547 		if (SSL_CTX_set_cipher_list(ssl_ctx,
548 		    ctx->config->ciphers) != 1) {
549 			tls_set_errorx(ctx, "failed to set ciphers");
550 			goto err;
551 		}
552 	}
553 
554 	if (ctx->config->verify_time == 0) {
555 		X509_VERIFY_PARAM_set_flags(SSL_CTX_get0_param(ssl_ctx),
556 		    X509_V_FLAG_NO_CHECK_TIME);
557 	}
558 
559 	/* Disable any form of session caching by default */
560 	SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);
561 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
562 
563 	return (0);
564 
565  err:
566 	return (-1);
567 }
568 
569 static int
570 tls_ssl_cert_verify_cb(X509_STORE_CTX *x509_ctx, void *arg)
571 {
572 	struct tls *ctx = arg;
573 	int x509_err;
574 
575 	if (ctx->config->verify_cert == 0)
576 		return (1);
577 
578 	if ((X509_verify_cert(x509_ctx)) < 0) {
579 		tls_set_errorx(ctx, "X509 verify cert failed");
580 		return (0);
581 	}
582 
583 	x509_err = X509_STORE_CTX_get_error(x509_ctx);
584 	if (x509_err == X509_V_OK)
585 		return (1);
586 
587 	tls_set_errorx(ctx, "certificate verification failed: %s",
588 	    X509_verify_cert_error_string(x509_err));
589 
590 	return (0);
591 }
592 
593 int
594 tls_configure_ssl_verify(struct tls *ctx, SSL_CTX *ssl_ctx, int verify)
595 {
596 	size_t ca_len = ctx->config->ca_len;
597 	char *ca_mem = ctx->config->ca_mem;
598 	char *crl_mem = ctx->config->crl_mem;
599 	size_t crl_len = ctx->config->crl_len;
600 	char *ca_free = NULL;
601 	STACK_OF(X509_INFO) *xis = NULL;
602 	X509_STORE *store;
603 	X509_INFO *xi;
604 	BIO *bio = NULL;
605 	int rv = -1;
606 	int i;
607 
608 	SSL_CTX_set_verify(ssl_ctx, verify, NULL);
609 	SSL_CTX_set_cert_verify_callback(ssl_ctx, tls_ssl_cert_verify_cb, ctx);
610 
611 	if (ctx->config->verify_depth >= 0)
612 		SSL_CTX_set_verify_depth(ssl_ctx, ctx->config->verify_depth);
613 
614 	if (ctx->config->verify_cert == 0)
615 		goto done;
616 
617 	/* If no CA has been specified, attempt to load the default. */
618 	if (ctx->config->ca_mem == NULL && ctx->config->ca_path == NULL) {
619 		if (tls_config_load_file(&ctx->error, "CA", tls_default_ca_cert_file(),
620 		    &ca_mem, &ca_len) != 0)
621 			goto err;
622 		ca_free = ca_mem;
623 	}
624 
625 	if (ca_mem != NULL) {
626 		if (ca_len > INT_MAX) {
627 			tls_set_errorx(ctx, "ca too long");
628 			goto err;
629 		}
630 		if (SSL_CTX_load_verify_mem(ssl_ctx, ca_mem, ca_len) != 1) {
631 			tls_set_errorx(ctx, "ssl verify memory setup failure");
632 			goto err;
633 		}
634 	} else if (SSL_CTX_load_verify_locations(ssl_ctx, NULL,
635 	    ctx->config->ca_path) != 1) {
636 		tls_set_errorx(ctx, "ssl verify locations failure");
637 		goto err;
638 	}
639 
640 	if (crl_mem != NULL) {
641 		if (crl_len > INT_MAX) {
642 			tls_set_errorx(ctx, "crl too long");
643 			goto err;
644 		}
645 		if ((bio = BIO_new_mem_buf(crl_mem, crl_len)) == NULL) {
646 			tls_set_errorx(ctx, "failed to create buffer");
647 			goto err;
648 		}
649 		if ((xis = PEM_X509_INFO_read_bio(bio, NULL, tls_password_cb,
650 		    NULL)) == NULL) {
651 			tls_set_errorx(ctx, "failed to parse crl");
652 			goto err;
653 		}
654 		store = SSL_CTX_get_cert_store(ssl_ctx);
655 		for (i = 0; i < sk_X509_INFO_num(xis); i++) {
656 			xi = sk_X509_INFO_value(xis, i);
657 			if (xi->crl == NULL)
658 				continue;
659 			if (!X509_STORE_add_crl(store, xi->crl)) {
660 				tls_set_error(ctx, "failed to add crl");
661 				goto err;
662 			}
663 		}
664 		X509_STORE_set_flags(store,
665 		    X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
666 	}
667 
668  done:
669 	rv = 0;
670 
671  err:
672 	sk_X509_INFO_pop_free(xis, X509_INFO_free);
673 	BIO_free(bio);
674 	free(ca_free);
675 
676 	return (rv);
677 }
678 
679 void
680 tls_free(struct tls *ctx)
681 {
682 	if (ctx == NULL)
683 		return;
684 
685 	tls_reset(ctx);
686 
687 	free(ctx);
688 }
689 
690 void
691 tls_reset(struct tls *ctx)
692 {
693 	struct tls_sni_ctx *sni, *nsni;
694 
695 	tls_config_free(ctx->config);
696 	ctx->config = NULL;
697 
698 	SSL_CTX_free(ctx->ssl_ctx);
699 	SSL_free(ctx->ssl_conn);
700 	X509_free(ctx->ssl_peer_cert);
701 
702 	ctx->ssl_conn = NULL;
703 	ctx->ssl_ctx = NULL;
704 	ctx->ssl_peer_cert = NULL;
705 	/* X509 objects in chain are freed with the SSL */
706 	ctx->ssl_peer_chain = NULL;
707 
708 	ctx->socket = -1;
709 	ctx->state = 0;
710 
711 	free(ctx->servername);
712 	ctx->servername = NULL;
713 
714 	free(ctx->error.msg);
715 	ctx->error.msg = NULL;
716 	ctx->error.num = -1;
717 
718 	tls_conninfo_free(ctx->conninfo);
719 	ctx->conninfo = NULL;
720 
721 	tls_ocsp_free(ctx->ocsp);
722 	ctx->ocsp = NULL;
723 
724 	for (sni = ctx->sni_ctx; sni != NULL; sni = nsni) {
725 		nsni = sni->next;
726 		tls_sni_ctx_free(sni);
727 	}
728 	ctx->sni_ctx = NULL;
729 
730 	ctx->read_cb = NULL;
731 	ctx->write_cb = NULL;
732 	ctx->cb_arg = NULL;
733 }
734 
735 int
736 tls_ssl_error(struct tls *ctx, SSL *ssl_conn, int ssl_ret, const char *prefix)
737 {
738 	const char *errstr = "unknown error";
739 	unsigned long err;
740 	int ssl_err;
741 
742 	ssl_err = SSL_get_error(ssl_conn, ssl_ret);
743 	switch (ssl_err) {
744 	case SSL_ERROR_NONE:
745 	case SSL_ERROR_ZERO_RETURN:
746 		return (0);
747 
748 	case SSL_ERROR_WANT_READ:
749 		return (TLS_WANT_POLLIN);
750 
751 	case SSL_ERROR_WANT_WRITE:
752 		return (TLS_WANT_POLLOUT);
753 
754 	case SSL_ERROR_SYSCALL:
755 		if ((err = ERR_peek_error()) != 0) {
756 			errstr = ERR_error_string(err, NULL);
757 		} else if (ssl_ret == 0) {
758 			if ((ctx->state & TLS_HANDSHAKE_COMPLETE) != 0) {
759 				ctx->state |= TLS_EOF_NO_CLOSE_NOTIFY;
760 				return (0);
761 			}
762 			errstr = "unexpected EOF";
763 		} else if (ssl_ret == -1) {
764 			errstr = strerror(errno);
765 		}
766 		tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
767 		return (-1);
768 
769 	case SSL_ERROR_SSL:
770 		if ((err = ERR_peek_error()) != 0) {
771 			errstr = ERR_error_string(err, NULL);
772 		}
773 		tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
774 		return (-1);
775 
776 	case SSL_ERROR_WANT_CONNECT:
777 	case SSL_ERROR_WANT_ACCEPT:
778 	case SSL_ERROR_WANT_X509_LOOKUP:
779 	default:
780 		tls_set_ssl_errorx(ctx, "%s failed (%d)", prefix, ssl_err);
781 		return (-1);
782 	}
783 }
784 
785 int
786 tls_handshake(struct tls *ctx)
787 {
788 	int rv = -1;
789 
790 	tls_error_clear(&ctx->error);
791 
792 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
793 		tls_set_errorx(ctx, "invalid operation for context");
794 		goto out;
795 	}
796 
797 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) != 0) {
798 		tls_set_errorx(ctx, "handshake already completed");
799 		goto out;
800 	}
801 
802 	if ((ctx->flags & TLS_CLIENT) != 0)
803 		rv = tls_handshake_client(ctx);
804 	else if ((ctx->flags & TLS_SERVER_CONN) != 0)
805 		rv = tls_handshake_server(ctx);
806 
807 	if (rv == 0) {
808 		ctx->ssl_peer_cert = SSL_get_peer_certificate(ctx->ssl_conn);
809 		ctx->ssl_peer_chain = SSL_get_peer_cert_chain(ctx->ssl_conn);
810 		if (tls_conninfo_populate(ctx) == -1)
811 			rv = -1;
812 		if (ctx->ocsp == NULL)
813 			ctx->ocsp = tls_ocsp_setup_from_peer(ctx);
814 	}
815  out:
816 	/* Prevent callers from performing incorrect error handling */
817 	errno = 0;
818 	return (rv);
819 }
820 
821 ssize_t
822 tls_read(struct tls *ctx, void *buf, size_t buflen)
823 {
824 	ssize_t rv = -1;
825 	int ssl_ret;
826 
827 	tls_error_clear(&ctx->error);
828 
829 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
830 		if ((rv = tls_handshake(ctx)) != 0)
831 			goto out;
832 	}
833 
834 	if (buflen > INT_MAX) {
835 		tls_set_errorx(ctx, "buflen too long");
836 		goto out;
837 	}
838 
839 	ERR_clear_error();
840 	if ((ssl_ret = SSL_read(ctx->ssl_conn, buf, buflen)) > 0) {
841 		rv = (ssize_t)ssl_ret;
842 		goto out;
843 	}
844 	rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "read");
845 
846  out:
847 	/* Prevent callers from performing incorrect error handling */
848 	errno = 0;
849 	return (rv);
850 }
851 
852 ssize_t
853 tls_write(struct tls *ctx, const void *buf, size_t buflen)
854 {
855 	ssize_t rv = -1;
856 	int ssl_ret;
857 
858 	tls_error_clear(&ctx->error);
859 
860 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
861 		if ((rv = tls_handshake(ctx)) != 0)
862 			goto out;
863 	}
864 
865 	if (buflen > INT_MAX) {
866 		tls_set_errorx(ctx, "buflen too long");
867 		goto out;
868 	}
869 
870 	ERR_clear_error();
871 	if ((ssl_ret = SSL_write(ctx->ssl_conn, buf, buflen)) > 0) {
872 		rv = (ssize_t)ssl_ret;
873 		goto out;
874 	}
875 	rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "write");
876 
877  out:
878 	/* Prevent callers from performing incorrect error handling */
879 	errno = 0;
880 	return (rv);
881 }
882 
883 int
884 tls_close(struct tls *ctx)
885 {
886 	int ssl_ret;
887 	int rv = 0;
888 
889 	tls_error_clear(&ctx->error);
890 
891 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
892 		tls_set_errorx(ctx, "invalid operation for context");
893 		rv = -1;
894 		goto out;
895 	}
896 
897 	if (ctx->state & TLS_SSL_NEEDS_SHUTDOWN) {
898 		ERR_clear_error();
899 		ssl_ret = SSL_shutdown(ctx->ssl_conn);
900 		if (ssl_ret < 0) {
901 			rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret,
902 			    "shutdown");
903 			if (rv == TLS_WANT_POLLIN || rv == TLS_WANT_POLLOUT)
904 				goto out;
905 		}
906 		ctx->state &= ~TLS_SSL_NEEDS_SHUTDOWN;
907 	}
908 
909 	if (ctx->socket != -1) {
910 		if (shutdown(ctx->socket, SHUT_RDWR) != 0) {
911 			if (rv == 0 &&
912 			    errno != ENOTCONN && errno != ECONNRESET) {
913 				tls_set_error(ctx, "shutdown");
914 				rv = -1;
915 			}
916 		}
917 		if (close(ctx->socket) != 0) {
918 			if (rv == 0) {
919 				tls_set_error(ctx, "close");
920 				rv = -1;
921 			}
922 		}
923 		ctx->socket = -1;
924 	}
925 
926 	if ((ctx->state & TLS_EOF_NO_CLOSE_NOTIFY) != 0) {
927 		tls_set_errorx(ctx, "EOF without close notify");
928 		rv = -1;
929 	}
930 
931  out:
932 	/* Prevent callers from performing incorrect error handling */
933 	errno = 0;
934 	return (rv);
935 }
936