xref: /openbsd-src/lib/libtls/tls.c (revision fc405d53b73a2d73393cb97f684863d17b583e38)
1 /* $OpenBSD: tls.c,v 1.95 2023/05/14 07:26:25 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 			break;
415 		if ((rsa_method = tls_signer_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 		break;
422 	case EVP_PKEY_EC:
423 		if ((eckey = EVP_PKEY_get1_EC_KEY(pkey)) == NULL ||
424 		    ECDSA_set_ex_data(eckey, 0, keypair->pubkey_hash) == 0) {
425 			tls_set_errorx(ctx, "EC key setup failure");
426 			goto err;
427 		}
428 		if (ctx->config->sign_cb == NULL)
429 			break;
430 		if ((ecdsa_method = tls_signer_ecdsa_method()) == NULL ||
431 		    ECDSA_set_ex_data(eckey, 1, ctx->config) == 0 ||
432 		    ECDSA_set_method(eckey, ecdsa_method) == 0) {
433 			tls_set_errorx(ctx, "failed to setup EC key");
434 			goto err;
435 		}
436 		break;
437 	default:
438 		tls_set_errorx(ctx, "incorrect key type");
439 		goto err;
440 	}
441 
442 	ret = 0;
443 
444  err:
445 	RSA_free(rsa);
446 	EC_KEY_free(eckey);
447 	return (ret);
448 }
449 
450 int
451 tls_configure_ssl_keypair(struct tls *ctx, SSL_CTX *ssl_ctx,
452     struct tls_keypair *keypair, int required)
453 {
454 	EVP_PKEY *pkey = NULL;
455 
456 	if (!required &&
457 	    keypair->cert_mem == NULL &&
458 	    keypair->key_mem == NULL)
459 		return(0);
460 
461 	if (keypair->cert_mem != NULL) {
462 		if (keypair->cert_len > INT_MAX) {
463 			tls_set_errorx(ctx, "certificate too long");
464 			goto err;
465 		}
466 
467 		if (SSL_CTX_use_certificate_chain_mem(ssl_ctx,
468 		    keypair->cert_mem, keypair->cert_len) != 1) {
469 			tls_set_errorx(ctx, "failed to load certificate");
470 			goto err;
471 		}
472 	}
473 
474 	if (tls_keypair_to_pkey(ctx, keypair, &pkey) == -1)
475 		goto err;
476 	if (pkey != NULL) {
477 		if (tls_keypair_setup_pkey(ctx, keypair, pkey) == -1)
478 			goto err;
479 		if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1) {
480 			tls_set_errorx(ctx, "failed to load private key");
481 			goto err;
482 		}
483 		EVP_PKEY_free(pkey);
484 		pkey = NULL;
485 	}
486 
487 	if (!ctx->config->skip_private_key_check &&
488 	    SSL_CTX_check_private_key(ssl_ctx) != 1) {
489 		tls_set_errorx(ctx, "private/public key mismatch");
490 		goto err;
491 	}
492 
493 	return (0);
494 
495  err:
496 	EVP_PKEY_free(pkey);
497 
498 	return (-1);
499 }
500 
501 int
502 tls_configure_ssl(struct tls *ctx, SSL_CTX *ssl_ctx)
503 {
504 	SSL_CTX_clear_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
505 
506 	SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
507 	SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
508 
509 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2);
510 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv3);
511 
512 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1);
513 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
514 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
515 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_3);
516 
517 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_0) == 0)
518 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1);
519 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_1) == 0)
520 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
521 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_2) == 0)
522 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
523 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_3) == 0)
524 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_3);
525 
526 	if (ctx->config->alpn != NULL) {
527 		if (SSL_CTX_set_alpn_protos(ssl_ctx, ctx->config->alpn,
528 		    ctx->config->alpn_len) != 0) {
529 			tls_set_errorx(ctx, "failed to set alpn");
530 			goto err;
531 		}
532 	}
533 
534 	if (ctx->config->ciphers != NULL) {
535 		if (SSL_CTX_set_cipher_list(ssl_ctx,
536 		    ctx->config->ciphers) != 1) {
537 			tls_set_errorx(ctx, "failed to set ciphers");
538 			goto err;
539 		}
540 	}
541 
542 	if (ctx->config->verify_time == 0) {
543 		X509_VERIFY_PARAM_set_flags(SSL_CTX_get0_param(ssl_ctx),
544 		    X509_V_FLAG_NO_CHECK_TIME);
545 	}
546 
547 	/* Disable any form of session caching by default */
548 	SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);
549 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
550 
551 	return (0);
552 
553  err:
554 	return (-1);
555 }
556 
557 static int
558 tls_ssl_cert_verify_cb(X509_STORE_CTX *x509_ctx, void *arg)
559 {
560 	struct tls *ctx = arg;
561 	int x509_err;
562 
563 	if (ctx->config->verify_cert == 0)
564 		return (1);
565 
566 	if ((X509_verify_cert(x509_ctx)) < 0) {
567 		tls_set_errorx(ctx, "X509 verify cert failed");
568 		return (0);
569 	}
570 
571 	x509_err = X509_STORE_CTX_get_error(x509_ctx);
572 	if (x509_err == X509_V_OK)
573 		return (1);
574 
575 	tls_set_errorx(ctx, "certificate verification failed: %s",
576 	    X509_verify_cert_error_string(x509_err));
577 
578 	return (0);
579 }
580 
581 int
582 tls_configure_ssl_verify(struct tls *ctx, SSL_CTX *ssl_ctx, int verify)
583 {
584 	size_t ca_len = ctx->config->ca_len;
585 	char *ca_mem = ctx->config->ca_mem;
586 	char *crl_mem = ctx->config->crl_mem;
587 	size_t crl_len = ctx->config->crl_len;
588 	char *ca_free = NULL;
589 	STACK_OF(X509_INFO) *xis = NULL;
590 	X509_STORE *store;
591 	X509_INFO *xi;
592 	BIO *bio = NULL;
593 	int rv = -1;
594 	int i;
595 
596 	SSL_CTX_set_verify(ssl_ctx, verify, NULL);
597 	SSL_CTX_set_cert_verify_callback(ssl_ctx, tls_ssl_cert_verify_cb, ctx);
598 
599 	if (ctx->config->verify_depth >= 0)
600 		SSL_CTX_set_verify_depth(ssl_ctx, ctx->config->verify_depth);
601 
602 	if (ctx->config->verify_cert == 0)
603 		goto done;
604 
605 	/* If no CA has been specified, attempt to load the default. */
606 	if (ctx->config->ca_mem == NULL && ctx->config->ca_path == NULL) {
607 		if (tls_config_load_file(&ctx->error, "CA", tls_default_ca_cert_file(),
608 		    &ca_mem, &ca_len) != 0)
609 			goto err;
610 		ca_free = ca_mem;
611 	}
612 
613 	if (ca_mem != NULL) {
614 		if (ca_len > INT_MAX) {
615 			tls_set_errorx(ctx, "ca too long");
616 			goto err;
617 		}
618 		if (SSL_CTX_load_verify_mem(ssl_ctx, ca_mem, ca_len) != 1) {
619 			tls_set_errorx(ctx, "ssl verify memory setup failure");
620 			goto err;
621 		}
622 	} else if (SSL_CTX_load_verify_locations(ssl_ctx, NULL,
623 	    ctx->config->ca_path) != 1) {
624 		tls_set_errorx(ctx, "ssl verify locations failure");
625 		goto err;
626 	}
627 
628 	if (crl_mem != NULL) {
629 		if (crl_len > INT_MAX) {
630 			tls_set_errorx(ctx, "crl too long");
631 			goto err;
632 		}
633 		if ((bio = BIO_new_mem_buf(crl_mem, crl_len)) == NULL) {
634 			tls_set_errorx(ctx, "failed to create buffer");
635 			goto err;
636 		}
637 		if ((xis = PEM_X509_INFO_read_bio(bio, NULL, tls_password_cb,
638 		    NULL)) == NULL) {
639 			tls_set_errorx(ctx, "failed to parse crl");
640 			goto err;
641 		}
642 		store = SSL_CTX_get_cert_store(ssl_ctx);
643 		for (i = 0; i < sk_X509_INFO_num(xis); i++) {
644 			xi = sk_X509_INFO_value(xis, i);
645 			if (xi->crl == NULL)
646 				continue;
647 			if (!X509_STORE_add_crl(store, xi->crl)) {
648 				tls_set_error(ctx, "failed to add crl");
649 				goto err;
650 			}
651 		}
652 		X509_STORE_set_flags(store,
653 		    X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
654 	}
655 
656  done:
657 	rv = 0;
658 
659  err:
660 	sk_X509_INFO_pop_free(xis, X509_INFO_free);
661 	BIO_free(bio);
662 	free(ca_free);
663 
664 	return (rv);
665 }
666 
667 void
668 tls_free(struct tls *ctx)
669 {
670 	if (ctx == NULL)
671 		return;
672 
673 	tls_reset(ctx);
674 
675 	free(ctx);
676 }
677 
678 void
679 tls_reset(struct tls *ctx)
680 {
681 	struct tls_sni_ctx *sni, *nsni;
682 
683 	tls_config_free(ctx->config);
684 	ctx->config = NULL;
685 
686 	SSL_CTX_free(ctx->ssl_ctx);
687 	SSL_free(ctx->ssl_conn);
688 	X509_free(ctx->ssl_peer_cert);
689 
690 	ctx->ssl_conn = NULL;
691 	ctx->ssl_ctx = NULL;
692 	ctx->ssl_peer_cert = NULL;
693 	/* X509 objects in chain are freed with the SSL */
694 	ctx->ssl_peer_chain = NULL;
695 
696 	ctx->socket = -1;
697 	ctx->state = 0;
698 
699 	free(ctx->servername);
700 	ctx->servername = NULL;
701 
702 	free(ctx->error.msg);
703 	ctx->error.msg = NULL;
704 	ctx->error.num = -1;
705 
706 	tls_conninfo_free(ctx->conninfo);
707 	ctx->conninfo = NULL;
708 
709 	tls_ocsp_free(ctx->ocsp);
710 	ctx->ocsp = NULL;
711 
712 	for (sni = ctx->sni_ctx; sni != NULL; sni = nsni) {
713 		nsni = sni->next;
714 		tls_sni_ctx_free(sni);
715 	}
716 	ctx->sni_ctx = NULL;
717 
718 	ctx->read_cb = NULL;
719 	ctx->write_cb = NULL;
720 	ctx->cb_arg = NULL;
721 }
722 
723 int
724 tls_ssl_error(struct tls *ctx, SSL *ssl_conn, int ssl_ret, const char *prefix)
725 {
726 	const char *errstr = "unknown error";
727 	unsigned long err;
728 	int ssl_err;
729 
730 	ssl_err = SSL_get_error(ssl_conn, ssl_ret);
731 	switch (ssl_err) {
732 	case SSL_ERROR_NONE:
733 	case SSL_ERROR_ZERO_RETURN:
734 		return (0);
735 
736 	case SSL_ERROR_WANT_READ:
737 		return (TLS_WANT_POLLIN);
738 
739 	case SSL_ERROR_WANT_WRITE:
740 		return (TLS_WANT_POLLOUT);
741 
742 	case SSL_ERROR_SYSCALL:
743 		if ((err = ERR_peek_error()) != 0) {
744 			errstr = ERR_error_string(err, NULL);
745 		} else if (ssl_ret == 0) {
746 			if ((ctx->state & TLS_HANDSHAKE_COMPLETE) != 0) {
747 				ctx->state |= TLS_EOF_NO_CLOSE_NOTIFY;
748 				return (0);
749 			}
750 			errstr = "unexpected EOF";
751 		} else if (ssl_ret == -1) {
752 			errstr = strerror(errno);
753 		}
754 		tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
755 		return (-1);
756 
757 	case SSL_ERROR_SSL:
758 		if ((err = ERR_peek_error()) != 0) {
759 			errstr = ERR_error_string(err, NULL);
760 		}
761 		tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
762 		return (-1);
763 
764 	case SSL_ERROR_WANT_CONNECT:
765 	case SSL_ERROR_WANT_ACCEPT:
766 	case SSL_ERROR_WANT_X509_LOOKUP:
767 	default:
768 		tls_set_ssl_errorx(ctx, "%s failed (%d)", prefix, ssl_err);
769 		return (-1);
770 	}
771 }
772 
773 int
774 tls_handshake(struct tls *ctx)
775 {
776 	int rv = -1;
777 
778 	tls_error_clear(&ctx->error);
779 
780 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
781 		tls_set_errorx(ctx, "invalid operation for context");
782 		goto out;
783 	}
784 
785 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) != 0) {
786 		tls_set_errorx(ctx, "handshake already completed");
787 		goto out;
788 	}
789 
790 	if ((ctx->flags & TLS_CLIENT) != 0)
791 		rv = tls_handshake_client(ctx);
792 	else if ((ctx->flags & TLS_SERVER_CONN) != 0)
793 		rv = tls_handshake_server(ctx);
794 
795 	if (rv == 0) {
796 		ctx->ssl_peer_cert = SSL_get_peer_certificate(ctx->ssl_conn);
797 		ctx->ssl_peer_chain = SSL_get_peer_cert_chain(ctx->ssl_conn);
798 		if (tls_conninfo_populate(ctx) == -1)
799 			rv = -1;
800 		if (ctx->ocsp == NULL)
801 			ctx->ocsp = tls_ocsp_setup_from_peer(ctx);
802 	}
803  out:
804 	/* Prevent callers from performing incorrect error handling */
805 	errno = 0;
806 	return (rv);
807 }
808 
809 ssize_t
810 tls_read(struct tls *ctx, void *buf, size_t buflen)
811 {
812 	ssize_t rv = -1;
813 	int ssl_ret;
814 
815 	tls_error_clear(&ctx->error);
816 
817 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
818 		if ((rv = tls_handshake(ctx)) != 0)
819 			goto out;
820 	}
821 
822 	if (buflen > INT_MAX) {
823 		tls_set_errorx(ctx, "buflen too long");
824 		goto out;
825 	}
826 
827 	ERR_clear_error();
828 	if ((ssl_ret = SSL_read(ctx->ssl_conn, buf, buflen)) > 0) {
829 		rv = (ssize_t)ssl_ret;
830 		goto out;
831 	}
832 	rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "read");
833 
834  out:
835 	/* Prevent callers from performing incorrect error handling */
836 	errno = 0;
837 	return (rv);
838 }
839 
840 ssize_t
841 tls_write(struct tls *ctx, const void *buf, size_t buflen)
842 {
843 	ssize_t rv = -1;
844 	int ssl_ret;
845 
846 	tls_error_clear(&ctx->error);
847 
848 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
849 		if ((rv = tls_handshake(ctx)) != 0)
850 			goto out;
851 	}
852 
853 	if (buflen > INT_MAX) {
854 		tls_set_errorx(ctx, "buflen too long");
855 		goto out;
856 	}
857 
858 	ERR_clear_error();
859 	if ((ssl_ret = SSL_write(ctx->ssl_conn, buf, buflen)) > 0) {
860 		rv = (ssize_t)ssl_ret;
861 		goto out;
862 	}
863 	rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "write");
864 
865  out:
866 	/* Prevent callers from performing incorrect error handling */
867 	errno = 0;
868 	return (rv);
869 }
870 
871 int
872 tls_close(struct tls *ctx)
873 {
874 	int ssl_ret;
875 	int rv = 0;
876 
877 	tls_error_clear(&ctx->error);
878 
879 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
880 		tls_set_errorx(ctx, "invalid operation for context");
881 		rv = -1;
882 		goto out;
883 	}
884 
885 	if (ctx->state & TLS_SSL_NEEDS_SHUTDOWN) {
886 		ERR_clear_error();
887 		ssl_ret = SSL_shutdown(ctx->ssl_conn);
888 		if (ssl_ret < 0) {
889 			rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret,
890 			    "shutdown");
891 			if (rv == TLS_WANT_POLLIN || rv == TLS_WANT_POLLOUT)
892 				goto out;
893 		}
894 		ctx->state &= ~TLS_SSL_NEEDS_SHUTDOWN;
895 	}
896 
897 	if (ctx->socket != -1) {
898 		if (shutdown(ctx->socket, SHUT_RDWR) != 0) {
899 			if (rv == 0 &&
900 			    errno != ENOTCONN && errno != ECONNRESET) {
901 				tls_set_error(ctx, "shutdown");
902 				rv = -1;
903 			}
904 		}
905 		if (close(ctx->socket) != 0) {
906 			if (rv == 0) {
907 				tls_set_error(ctx, "close");
908 				rv = -1;
909 			}
910 		}
911 		ctx->socket = -1;
912 	}
913 
914 	if ((ctx->state & TLS_EOF_NO_CLOSE_NOTIFY) != 0) {
915 		tls_set_errorx(ctx, "EOF without close notify");
916 		rv = -1;
917 	}
918 
919  out:
920 	/* Prevent callers from performing incorrect error handling */
921 	errno = 0;
922 	return (rv);
923 }
924