xref: /openbsd/lib/libtls/tls.c (revision 4bdff4be)
1 /* $OpenBSD: tls.c,v 1.98 2023/07/02 06:37:27 beck 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 	EC_KEY_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 		    EC_KEY_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 			    EC_KEY_set_ex_data(eckey, 1, ctx->config) == 0 ||
438 			    EC_KEY_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 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1);
524 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
525 
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_2) == 0)
530 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
531 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_3) == 0)
532 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_3);
533 
534 	if (ctx->config->alpn != NULL) {
535 		if (SSL_CTX_set_alpn_protos(ssl_ctx, ctx->config->alpn,
536 		    ctx->config->alpn_len) != 0) {
537 			tls_set_errorx(ctx, "failed to set alpn");
538 			goto err;
539 		}
540 	}
541 
542 	if (ctx->config->ciphers != NULL) {
543 		if (SSL_CTX_set_cipher_list(ssl_ctx,
544 		    ctx->config->ciphers) != 1) {
545 			tls_set_errorx(ctx, "failed to set ciphers");
546 			goto err;
547 		}
548 	}
549 
550 	if (ctx->config->verify_time == 0) {
551 		X509_VERIFY_PARAM_set_flags(SSL_CTX_get0_param(ssl_ctx),
552 		    X509_V_FLAG_NO_CHECK_TIME);
553 	}
554 
555 	/* Disable any form of session caching by default */
556 	SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);
557 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
558 
559 	return (0);
560 
561  err:
562 	return (-1);
563 }
564 
565 static int
566 tls_ssl_cert_verify_cb(X509_STORE_CTX *x509_ctx, void *arg)
567 {
568 	struct tls *ctx = arg;
569 	int x509_err;
570 
571 	if (ctx->config->verify_cert == 0)
572 		return (1);
573 
574 	if ((X509_verify_cert(x509_ctx)) < 0) {
575 		tls_set_errorx(ctx, "X509 verify cert failed");
576 		return (0);
577 	}
578 
579 	x509_err = X509_STORE_CTX_get_error(x509_ctx);
580 	if (x509_err == X509_V_OK)
581 		return (1);
582 
583 	tls_set_errorx(ctx, "certificate verification failed: %s",
584 	    X509_verify_cert_error_string(x509_err));
585 
586 	return (0);
587 }
588 
589 int
590 tls_configure_ssl_verify(struct tls *ctx, SSL_CTX *ssl_ctx, int verify)
591 {
592 	size_t ca_len = ctx->config->ca_len;
593 	char *ca_mem = ctx->config->ca_mem;
594 	char *crl_mem = ctx->config->crl_mem;
595 	size_t crl_len = ctx->config->crl_len;
596 	char *ca_free = NULL;
597 	STACK_OF(X509_INFO) *xis = NULL;
598 	X509_STORE *store;
599 	X509_INFO *xi;
600 	BIO *bio = NULL;
601 	int rv = -1;
602 	int i;
603 
604 	SSL_CTX_set_verify(ssl_ctx, verify, NULL);
605 	SSL_CTX_set_cert_verify_callback(ssl_ctx, tls_ssl_cert_verify_cb, ctx);
606 
607 	if (ctx->config->verify_depth >= 0)
608 		SSL_CTX_set_verify_depth(ssl_ctx, ctx->config->verify_depth);
609 
610 	if (ctx->config->verify_cert == 0)
611 		goto done;
612 
613 	/* If no CA has been specified, attempt to load the default. */
614 	if (ctx->config->ca_mem == NULL && ctx->config->ca_path == NULL) {
615 		if (tls_config_load_file(&ctx->error, "CA", tls_default_ca_cert_file(),
616 		    &ca_mem, &ca_len) != 0)
617 			goto err;
618 		ca_free = ca_mem;
619 	}
620 
621 	if (ca_mem != NULL) {
622 		if (ca_len > INT_MAX) {
623 			tls_set_errorx(ctx, "ca too long");
624 			goto err;
625 		}
626 		if (SSL_CTX_load_verify_mem(ssl_ctx, ca_mem, ca_len) != 1) {
627 			tls_set_errorx(ctx, "ssl verify memory setup failure");
628 			goto err;
629 		}
630 	} else if (SSL_CTX_load_verify_locations(ssl_ctx, NULL,
631 	    ctx->config->ca_path) != 1) {
632 		tls_set_errorx(ctx, "ssl verify locations failure");
633 		goto err;
634 	}
635 
636 	if (crl_mem != NULL) {
637 		if (crl_len > INT_MAX) {
638 			tls_set_errorx(ctx, "crl too long");
639 			goto err;
640 		}
641 		if ((bio = BIO_new_mem_buf(crl_mem, crl_len)) == NULL) {
642 			tls_set_errorx(ctx, "failed to create buffer");
643 			goto err;
644 		}
645 		if ((xis = PEM_X509_INFO_read_bio(bio, NULL, tls_password_cb,
646 		    NULL)) == NULL) {
647 			tls_set_errorx(ctx, "failed to parse crl");
648 			goto err;
649 		}
650 		store = SSL_CTX_get_cert_store(ssl_ctx);
651 		for (i = 0; i < sk_X509_INFO_num(xis); i++) {
652 			xi = sk_X509_INFO_value(xis, i);
653 			if (xi->crl == NULL)
654 				continue;
655 			if (!X509_STORE_add_crl(store, xi->crl)) {
656 				tls_set_error(ctx, "failed to add crl");
657 				goto err;
658 			}
659 		}
660 		X509_STORE_set_flags(store,
661 		    X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
662 	}
663 
664  done:
665 	rv = 0;
666 
667  err:
668 	sk_X509_INFO_pop_free(xis, X509_INFO_free);
669 	BIO_free(bio);
670 	free(ca_free);
671 
672 	return (rv);
673 }
674 
675 void
676 tls_free(struct tls *ctx)
677 {
678 	if (ctx == NULL)
679 		return;
680 
681 	tls_reset(ctx);
682 
683 	free(ctx);
684 }
685 
686 void
687 tls_reset(struct tls *ctx)
688 {
689 	struct tls_sni_ctx *sni, *nsni;
690 
691 	tls_config_free(ctx->config);
692 	ctx->config = NULL;
693 
694 	SSL_CTX_free(ctx->ssl_ctx);
695 	SSL_free(ctx->ssl_conn);
696 	X509_free(ctx->ssl_peer_cert);
697 
698 	ctx->ssl_conn = NULL;
699 	ctx->ssl_ctx = NULL;
700 	ctx->ssl_peer_cert = NULL;
701 	/* X509 objects in chain are freed with the SSL */
702 	ctx->ssl_peer_chain = NULL;
703 
704 	ctx->socket = -1;
705 	ctx->state = 0;
706 
707 	free(ctx->servername);
708 	ctx->servername = NULL;
709 
710 	free(ctx->error.msg);
711 	ctx->error.msg = NULL;
712 	ctx->error.num = -1;
713 
714 	tls_conninfo_free(ctx->conninfo);
715 	ctx->conninfo = NULL;
716 
717 	tls_ocsp_free(ctx->ocsp);
718 	ctx->ocsp = NULL;
719 
720 	for (sni = ctx->sni_ctx; sni != NULL; sni = nsni) {
721 		nsni = sni->next;
722 		tls_sni_ctx_free(sni);
723 	}
724 	ctx->sni_ctx = NULL;
725 
726 	ctx->read_cb = NULL;
727 	ctx->write_cb = NULL;
728 	ctx->cb_arg = NULL;
729 }
730 
731 int
732 tls_ssl_error(struct tls *ctx, SSL *ssl_conn, int ssl_ret, const char *prefix)
733 {
734 	const char *errstr = "unknown error";
735 	unsigned long err;
736 	int ssl_err;
737 
738 	ssl_err = SSL_get_error(ssl_conn, ssl_ret);
739 	switch (ssl_err) {
740 	case SSL_ERROR_NONE:
741 	case SSL_ERROR_ZERO_RETURN:
742 		return (0);
743 
744 	case SSL_ERROR_WANT_READ:
745 		return (TLS_WANT_POLLIN);
746 
747 	case SSL_ERROR_WANT_WRITE:
748 		return (TLS_WANT_POLLOUT);
749 
750 	case SSL_ERROR_SYSCALL:
751 		if ((err = ERR_peek_error()) != 0) {
752 			errstr = ERR_error_string(err, NULL);
753 		} else if (ssl_ret == 0) {
754 			if ((ctx->state & TLS_HANDSHAKE_COMPLETE) != 0) {
755 				ctx->state |= TLS_EOF_NO_CLOSE_NOTIFY;
756 				return (0);
757 			}
758 			errstr = "unexpected EOF";
759 		} else if (ssl_ret == -1) {
760 			errstr = strerror(errno);
761 		}
762 		tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
763 		return (-1);
764 
765 	case SSL_ERROR_SSL:
766 		if ((err = ERR_peek_error()) != 0) {
767 			errstr = ERR_error_string(err, NULL);
768 		}
769 		tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
770 		return (-1);
771 
772 	case SSL_ERROR_WANT_CONNECT:
773 	case SSL_ERROR_WANT_ACCEPT:
774 	case SSL_ERROR_WANT_X509_LOOKUP:
775 	default:
776 		tls_set_ssl_errorx(ctx, "%s failed (%d)", prefix, ssl_err);
777 		return (-1);
778 	}
779 }
780 
781 int
782 tls_handshake(struct tls *ctx)
783 {
784 	int rv = -1;
785 
786 	tls_error_clear(&ctx->error);
787 
788 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
789 		tls_set_errorx(ctx, "invalid operation for context");
790 		goto out;
791 	}
792 
793 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) != 0) {
794 		tls_set_errorx(ctx, "handshake already completed");
795 		goto out;
796 	}
797 
798 	if ((ctx->flags & TLS_CLIENT) != 0)
799 		rv = tls_handshake_client(ctx);
800 	else if ((ctx->flags & TLS_SERVER_CONN) != 0)
801 		rv = tls_handshake_server(ctx);
802 
803 	if (rv == 0) {
804 		ctx->ssl_peer_cert = SSL_get_peer_certificate(ctx->ssl_conn);
805 		ctx->ssl_peer_chain = SSL_get_peer_cert_chain(ctx->ssl_conn);
806 		if (tls_conninfo_populate(ctx) == -1)
807 			rv = -1;
808 		if (ctx->ocsp == NULL)
809 			ctx->ocsp = tls_ocsp_setup_from_peer(ctx);
810 	}
811  out:
812 	/* Prevent callers from performing incorrect error handling */
813 	errno = 0;
814 	return (rv);
815 }
816 
817 ssize_t
818 tls_read(struct tls *ctx, void *buf, size_t buflen)
819 {
820 	ssize_t rv = -1;
821 	int ssl_ret;
822 
823 	tls_error_clear(&ctx->error);
824 
825 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
826 		if ((rv = tls_handshake(ctx)) != 0)
827 			goto out;
828 	}
829 
830 	if (buflen > INT_MAX) {
831 		tls_set_errorx(ctx, "buflen too long");
832 		goto out;
833 	}
834 
835 	ERR_clear_error();
836 	if ((ssl_ret = SSL_read(ctx->ssl_conn, buf, buflen)) > 0) {
837 		rv = (ssize_t)ssl_ret;
838 		goto out;
839 	}
840 	rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "read");
841 
842  out:
843 	/* Prevent callers from performing incorrect error handling */
844 	errno = 0;
845 	return (rv);
846 }
847 
848 ssize_t
849 tls_write(struct tls *ctx, const void *buf, size_t buflen)
850 {
851 	ssize_t rv = -1;
852 	int ssl_ret;
853 
854 	tls_error_clear(&ctx->error);
855 
856 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
857 		if ((rv = tls_handshake(ctx)) != 0)
858 			goto out;
859 	}
860 
861 	if (buflen > INT_MAX) {
862 		tls_set_errorx(ctx, "buflen too long");
863 		goto out;
864 	}
865 
866 	ERR_clear_error();
867 	if ((ssl_ret = SSL_write(ctx->ssl_conn, buf, buflen)) > 0) {
868 		rv = (ssize_t)ssl_ret;
869 		goto out;
870 	}
871 	rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "write");
872 
873  out:
874 	/* Prevent callers from performing incorrect error handling */
875 	errno = 0;
876 	return (rv);
877 }
878 
879 int
880 tls_close(struct tls *ctx)
881 {
882 	int ssl_ret;
883 	int rv = 0;
884 
885 	tls_error_clear(&ctx->error);
886 
887 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
888 		tls_set_errorx(ctx, "invalid operation for context");
889 		rv = -1;
890 		goto out;
891 	}
892 
893 	if (ctx->state & TLS_SSL_NEEDS_SHUTDOWN) {
894 		ERR_clear_error();
895 		ssl_ret = SSL_shutdown(ctx->ssl_conn);
896 		if (ssl_ret < 0) {
897 			rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret,
898 			    "shutdown");
899 			if (rv == TLS_WANT_POLLIN || rv == TLS_WANT_POLLOUT)
900 				goto out;
901 		}
902 		ctx->state &= ~TLS_SSL_NEEDS_SHUTDOWN;
903 	}
904 
905 	if (ctx->socket != -1) {
906 		if (shutdown(ctx->socket, SHUT_RDWR) != 0) {
907 			if (rv == 0 &&
908 			    errno != ENOTCONN && errno != ECONNRESET) {
909 				tls_set_error(ctx, "shutdown");
910 				rv = -1;
911 			}
912 		}
913 		if (close(ctx->socket) != 0) {
914 			if (rv == 0) {
915 				tls_set_error(ctx, "close");
916 				rv = -1;
917 			}
918 		}
919 		ctx->socket = -1;
920 	}
921 
922 	if ((ctx->state & TLS_EOF_NO_CLOSE_NOTIFY) != 0) {
923 		tls_set_errorx(ctx, "EOF without close notify");
924 		rv = -1;
925 	}
926 
927  out:
928 	/* Prevent callers from performing incorrect error handling */
929 	errno = 0;
930 	return (rv);
931 }
932