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