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