xref: /openbsd-src/lib/libtls/tls.c (revision aa997e528a848ca5596493c2a801bdd6fb26ae61)
1 /* $OpenBSD: tls.c,v 1.79 2018/03/19 16:34:47 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 	SSL_load_error_strings();
45 	SSL_library_init();
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 	config->refcount++;
261 
262 	tls_config_free(ctx->config);
263 
264 	ctx->config = config;
265 	ctx->keypair = config->keypair;
266 
267 	if ((ctx->flags & TLS_SERVER) != 0)
268 		return (tls_configure_server(ctx));
269 
270 	return (0);
271 }
272 
273 int
274 tls_cert_hash(X509 *cert, char **hash)
275 {
276 	char d[EVP_MAX_MD_SIZE], *dhex = NULL;
277 	int dlen, rv = -1;
278 
279 	free(*hash);
280 	*hash = NULL;
281 
282 	if (X509_digest(cert, EVP_sha256(), d, &dlen) != 1)
283 		goto err;
284 
285 	if (tls_hex_string(d, dlen, &dhex, NULL) != 0)
286 		goto err;
287 
288 	if (asprintf(hash, "SHA256:%s", dhex) == -1) {
289 		*hash = NULL;
290 		goto err;
291 	}
292 
293 	rv = 0;
294  err:
295 	free(dhex);
296 
297 	return (rv);
298 }
299 
300 int
301 tls_cert_pubkey_hash(X509 *cert, char **hash)
302 {
303 	char d[EVP_MAX_MD_SIZE], *dhex = NULL;
304 	int dlen, rv = -1;
305 
306 	free(*hash);
307 	*hash = NULL;
308 
309 	if (X509_pubkey_digest(cert, EVP_sha256(), d, &dlen) != 1)
310 		goto err;
311 
312 	if (tls_hex_string(d, dlen, &dhex, NULL) != 0)
313 		goto err;
314 
315 	if (asprintf(hash, "SHA256:%s", dhex) == -1) {
316 		*hash = NULL;
317 		goto err;
318 	}
319 
320 	rv = 0;
321 
322  err:
323 	free(dhex);
324 
325 	return (rv);
326 }
327 
328 int
329 tls_configure_ssl_keypair(struct tls *ctx, SSL_CTX *ssl_ctx,
330     struct tls_keypair *keypair, int required)
331 {
332 	EVP_PKEY *pkey = NULL;
333 	BIO *bio = NULL;
334 
335 	if (!required &&
336 	    keypair->cert_mem == NULL &&
337 	    keypair->key_mem == NULL)
338 		return(0);
339 
340 	if (keypair->cert_mem != NULL) {
341 		if (keypair->cert_len > INT_MAX) {
342 			tls_set_errorx(ctx, "certificate too long");
343 			goto err;
344 		}
345 
346 		if (SSL_CTX_use_certificate_chain_mem(ssl_ctx,
347 		    keypair->cert_mem, keypair->cert_len) != 1) {
348 			tls_set_errorx(ctx, "failed to load certificate");
349 			goto err;
350 		}
351 	}
352 
353 	if (keypair->key_mem != NULL) {
354 		if (keypair->key_len > INT_MAX) {
355 			tls_set_errorx(ctx, "key too long");
356 			goto err;
357 		}
358 
359 		if ((bio = BIO_new_mem_buf(keypair->key_mem,
360 		    keypair->key_len)) == NULL) {
361 			tls_set_errorx(ctx, "failed to create buffer");
362 			goto err;
363 		}
364 		if ((pkey = PEM_read_bio_PrivateKey(bio, NULL, tls_password_cb,
365 		    NULL)) == NULL) {
366 			tls_set_errorx(ctx, "failed to read private key");
367 			goto err;
368 		}
369 
370 		if (keypair->pubkey_hash != NULL) {
371 			RSA *rsa;
372 			/* XXX only RSA for now for relayd privsep */
373 			if ((rsa = EVP_PKEY_get1_RSA(pkey)) != NULL) {
374 				RSA_set_ex_data(rsa, 0, keypair->pubkey_hash);
375 				RSA_free(rsa);
376 			}
377 		}
378 
379 		if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1) {
380 			tls_set_errorx(ctx, "failed to load private key");
381 			goto err;
382 		}
383 		BIO_free(bio);
384 		bio = NULL;
385 		EVP_PKEY_free(pkey);
386 		pkey = NULL;
387 	}
388 
389 	if (!ctx->config->skip_private_key_check &&
390 	    SSL_CTX_check_private_key(ssl_ctx) != 1) {
391 		tls_set_errorx(ctx, "private/public key mismatch");
392 		goto err;
393 	}
394 
395 	return (0);
396 
397  err:
398 	EVP_PKEY_free(pkey);
399 	BIO_free(bio);
400 
401 	return (1);
402 }
403 
404 int
405 tls_configure_ssl(struct tls *ctx, SSL_CTX *ssl_ctx)
406 {
407 	SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
408 	SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
409 
410 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2);
411 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv3);
412 
413 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1);
414 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
415 	SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
416 
417 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_0) == 0)
418 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1);
419 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_1) == 0)
420 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_1);
421 	if ((ctx->config->protocols & TLS_PROTOCOL_TLSv1_2) == 0)
422 		SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TLSv1_2);
423 
424 	if (ctx->config->alpn != NULL) {
425 		if (SSL_CTX_set_alpn_protos(ssl_ctx, ctx->config->alpn,
426 		    ctx->config->alpn_len) != 0) {
427 			tls_set_errorx(ctx, "failed to set alpn");
428 			goto err;
429 		}
430 	}
431 
432 	if (ctx->config->ciphers != NULL) {
433 		if (SSL_CTX_set_cipher_list(ssl_ctx,
434 		    ctx->config->ciphers) != 1) {
435 			tls_set_errorx(ctx, "failed to set ciphers");
436 			goto err;
437 		}
438 	}
439 
440 	if (ctx->config->verify_time == 0) {
441 		X509_VERIFY_PARAM_set_flags(ssl_ctx->param,
442 		    X509_V_FLAG_NO_CHECK_TIME);
443 	}
444 
445 	/* Disable any form of session caching by default */
446 	SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_OFF);
447 	SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
448 
449 	return (0);
450 
451  err:
452 	return (-1);
453 }
454 
455 static int
456 tls_ssl_cert_verify_cb(X509_STORE_CTX *x509_ctx, void *arg)
457 {
458 	struct tls *ctx = arg;
459 	int x509_err;
460 
461 	if (ctx->config->verify_cert == 0)
462 		return (1);
463 
464 	if ((X509_verify_cert(x509_ctx)) < 0) {
465 		tls_set_errorx(ctx, "X509 verify cert failed");
466 		return (0);
467 	}
468 
469 	x509_err = X509_STORE_CTX_get_error(x509_ctx);
470 	if (x509_err == X509_V_OK)
471 		return (1);
472 
473 	tls_set_errorx(ctx, "certificate verification failed: %s",
474 	    X509_verify_cert_error_string(x509_err));
475 
476 	return (0);
477 }
478 
479 int
480 tls_configure_ssl_verify(struct tls *ctx, SSL_CTX *ssl_ctx, int verify)
481 {
482 	size_t ca_len = ctx->config->ca_len;
483 	char *ca_mem = ctx->config->ca_mem;
484 	char *crl_mem = ctx->config->crl_mem;
485 	size_t crl_len = ctx->config->crl_len;
486 	char *ca_free = NULL;
487 	STACK_OF(X509_INFO) *xis = NULL;
488 	X509_STORE *store;
489 	X509_INFO *xi;
490 	BIO *bio = NULL;
491 	int rv = -1;
492 	int i;
493 
494 	SSL_CTX_set_verify(ssl_ctx, verify, NULL);
495 	SSL_CTX_set_cert_verify_callback(ssl_ctx, tls_ssl_cert_verify_cb, ctx);
496 
497 	if (ctx->config->verify_depth >= 0)
498 		SSL_CTX_set_verify_depth(ssl_ctx, ctx->config->verify_depth);
499 
500 	if (ctx->config->verify_cert == 0)
501 		goto done;
502 
503 	/* If no CA has been specified, attempt to load the default. */
504 	if (ctx->config->ca_mem == NULL && ctx->config->ca_path == NULL) {
505 		if (tls_config_load_file(&ctx->error, "CA", _PATH_SSL_CA_FILE,
506 		    &ca_mem, &ca_len) != 0)
507 			goto err;
508 		ca_free = ca_mem;
509 	}
510 
511 	if (ca_mem != NULL) {
512 		if (ca_len > INT_MAX) {
513 			tls_set_errorx(ctx, "ca too long");
514 			goto err;
515 		}
516 		if (SSL_CTX_load_verify_mem(ssl_ctx, ca_mem, ca_len) != 1) {
517 			tls_set_errorx(ctx, "ssl verify memory setup failure");
518 			goto err;
519 		}
520 	} else if (SSL_CTX_load_verify_locations(ssl_ctx, NULL,
521 	    ctx->config->ca_path) != 1) {
522 		tls_set_errorx(ctx, "ssl verify locations failure");
523 		goto err;
524 	}
525 
526 	if (crl_mem != NULL) {
527 		if (crl_len > INT_MAX) {
528 			tls_set_errorx(ctx, "crl too long");
529 			goto err;
530 		}
531 		if ((bio = BIO_new_mem_buf(crl_mem, crl_len)) == NULL) {
532 			tls_set_errorx(ctx, "failed to create buffer");
533 			goto err;
534 		}
535 		if ((xis = PEM_X509_INFO_read_bio(bio, NULL, tls_password_cb,
536 		    NULL)) == NULL) {
537 			tls_set_errorx(ctx, "failed to parse crl");
538 			goto err;
539 		}
540 		store = SSL_CTX_get_cert_store(ssl_ctx);
541 		for (i = 0; i < sk_X509_INFO_num(xis); i++) {
542 			xi = sk_X509_INFO_value(xis, i);
543 			if (xi->crl == NULL)
544 				continue;
545 			if (!X509_STORE_add_crl(store, xi->crl)) {
546 				tls_set_error(ctx, "failed to add crl");
547 				goto err;
548 			}
549 			xi->crl = NULL;
550 		}
551 		X509_VERIFY_PARAM_set_flags(store->param,
552 		    X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
553 	}
554 
555  done:
556 	rv = 0;
557 
558  err:
559 	sk_X509_INFO_pop_free(xis, X509_INFO_free);
560 	BIO_free(bio);
561 	free(ca_free);
562 
563 	return (rv);
564 }
565 
566 void
567 tls_free(struct tls *ctx)
568 {
569 	if (ctx == NULL)
570 		return;
571 
572 	tls_reset(ctx);
573 
574 	free(ctx);
575 }
576 
577 void
578 tls_reset(struct tls *ctx)
579 {
580 	struct tls_sni_ctx *sni, *nsni;
581 
582 	tls_config_free(ctx->config);
583 	ctx->config = NULL;
584 
585 	SSL_CTX_free(ctx->ssl_ctx);
586 	SSL_free(ctx->ssl_conn);
587 	X509_free(ctx->ssl_peer_cert);
588 
589 	ctx->ssl_conn = NULL;
590 	ctx->ssl_ctx = NULL;
591 	ctx->ssl_peer_cert = NULL;
592 	/* X509 objects in chain are freed with the SSL */
593 	ctx->ssl_peer_chain = NULL;
594 
595 	ctx->socket = -1;
596 	ctx->state = 0;
597 
598 	free(ctx->servername);
599 	ctx->servername = NULL;
600 
601 	free(ctx->error.msg);
602 	ctx->error.msg = NULL;
603 	ctx->error.num = -1;
604 
605 	tls_conninfo_free(ctx->conninfo);
606 	ctx->conninfo = NULL;
607 
608 	tls_ocsp_free(ctx->ocsp);
609 	ctx->ocsp = NULL;
610 
611 	for (sni = ctx->sni_ctx; sni != NULL; sni = nsni) {
612 		nsni = sni->next;
613 		tls_sni_ctx_free(sni);
614 	}
615 	ctx->sni_ctx = NULL;
616 
617 	ctx->read_cb = NULL;
618 	ctx->write_cb = NULL;
619 	ctx->cb_arg = NULL;
620 }
621 
622 int
623 tls_ssl_error(struct tls *ctx, SSL *ssl_conn, int ssl_ret, const char *prefix)
624 {
625 	const char *errstr = "unknown error";
626 	unsigned long err;
627 	int ssl_err;
628 
629 	ssl_err = SSL_get_error(ssl_conn, ssl_ret);
630 	switch (ssl_err) {
631 	case SSL_ERROR_NONE:
632 	case SSL_ERROR_ZERO_RETURN:
633 		return (0);
634 
635 	case SSL_ERROR_WANT_READ:
636 		return (TLS_WANT_POLLIN);
637 
638 	case SSL_ERROR_WANT_WRITE:
639 		return (TLS_WANT_POLLOUT);
640 
641 	case SSL_ERROR_SYSCALL:
642 		if ((err = ERR_peek_error()) != 0) {
643 			errstr = ERR_error_string(err, NULL);
644 		} else if (ssl_ret == 0) {
645 			if ((ctx->state & TLS_HANDSHAKE_COMPLETE) != 0) {
646 				ctx->state |= TLS_EOF_NO_CLOSE_NOTIFY;
647 				return (0);
648 			}
649 			errstr = "unexpected EOF";
650 		} else if (ssl_ret == -1) {
651 			errstr = strerror(errno);
652 		}
653 		tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
654 		return (-1);
655 
656 	case SSL_ERROR_SSL:
657 		if ((err = ERR_peek_error()) != 0) {
658 			errstr = ERR_error_string(err, NULL);
659 		}
660 		tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
661 		return (-1);
662 
663 	case SSL_ERROR_WANT_CONNECT:
664 	case SSL_ERROR_WANT_ACCEPT:
665 	case SSL_ERROR_WANT_X509_LOOKUP:
666 	default:
667 		tls_set_ssl_errorx(ctx, "%s failed (%i)", prefix, ssl_err);
668 		return (-1);
669 	}
670 }
671 
672 int
673 tls_handshake(struct tls *ctx)
674 {
675 	int rv = -1;
676 
677 	tls_error_clear(&ctx->error);
678 
679 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
680 		tls_set_errorx(ctx, "invalid operation for context");
681 		goto out;
682 	}
683 
684 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) != 0) {
685 		tls_set_errorx(ctx, "handshake already completed");
686 		goto out;
687 	}
688 
689 	if ((ctx->flags & TLS_CLIENT) != 0)
690 		rv = tls_handshake_client(ctx);
691 	else if ((ctx->flags & TLS_SERVER_CONN) != 0)
692 		rv = tls_handshake_server(ctx);
693 
694 	if (rv == 0) {
695 		ctx->ssl_peer_cert = SSL_get_peer_certificate(ctx->ssl_conn);
696 		ctx->ssl_peer_chain = SSL_get_peer_cert_chain(ctx->ssl_conn);
697 		if (tls_conninfo_populate(ctx) == -1)
698 			rv = -1;
699 		if (ctx->ocsp == NULL)
700 			ctx->ocsp = tls_ocsp_setup_from_peer(ctx);
701 	}
702  out:
703 	/* Prevent callers from performing incorrect error handling */
704 	errno = 0;
705 	return (rv);
706 }
707 
708 ssize_t
709 tls_read(struct tls *ctx, void *buf, size_t buflen)
710 {
711 	ssize_t rv = -1;
712 	int ssl_ret;
713 
714 	tls_error_clear(&ctx->error);
715 
716 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
717 		if ((rv = tls_handshake(ctx)) != 0)
718 			goto out;
719 	}
720 
721 	if (buflen > INT_MAX) {
722 		tls_set_errorx(ctx, "buflen too long");
723 		goto out;
724 	}
725 
726 	ERR_clear_error();
727 	if ((ssl_ret = SSL_read(ctx->ssl_conn, buf, buflen)) > 0) {
728 		rv = (ssize_t)ssl_ret;
729 		goto out;
730 	}
731 	rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "read");
732 
733  out:
734 	/* Prevent callers from performing incorrect error handling */
735 	errno = 0;
736 	return (rv);
737 }
738 
739 ssize_t
740 tls_write(struct tls *ctx, const void *buf, size_t buflen)
741 {
742 	ssize_t rv = -1;
743 	int ssl_ret;
744 
745 	tls_error_clear(&ctx->error);
746 
747 	if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
748 		if ((rv = tls_handshake(ctx)) != 0)
749 			goto out;
750 	}
751 
752 	if (buflen > INT_MAX) {
753 		tls_set_errorx(ctx, "buflen too long");
754 		goto out;
755 	}
756 
757 	ERR_clear_error();
758 	if ((ssl_ret = SSL_write(ctx->ssl_conn, buf, buflen)) > 0) {
759 		rv = (ssize_t)ssl_ret;
760 		goto out;
761 	}
762 	rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "write");
763 
764  out:
765 	/* Prevent callers from performing incorrect error handling */
766 	errno = 0;
767 	return (rv);
768 }
769 
770 int
771 tls_close(struct tls *ctx)
772 {
773 	int ssl_ret;
774 	int rv = 0;
775 
776 	tls_error_clear(&ctx->error);
777 
778 	if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
779 		tls_set_errorx(ctx, "invalid operation for context");
780 		rv = -1;
781 		goto out;
782 	}
783 
784 	if (ctx->state & TLS_SSL_NEEDS_SHUTDOWN) {
785 		ERR_clear_error();
786 		ssl_ret = SSL_shutdown(ctx->ssl_conn);
787 		if (ssl_ret < 0) {
788 			rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret,
789 			    "shutdown");
790 			if (rv == TLS_WANT_POLLIN || rv == TLS_WANT_POLLOUT)
791 				goto out;
792 		}
793 		ctx->state &= ~TLS_SSL_NEEDS_SHUTDOWN;
794 	}
795 
796 	if (ctx->socket != -1) {
797 		if (shutdown(ctx->socket, SHUT_RDWR) != 0) {
798 			if (rv == 0 &&
799 			    errno != ENOTCONN && errno != ECONNRESET) {
800 				tls_set_error(ctx, "shutdown");
801 				rv = -1;
802 			}
803 		}
804 		if (close(ctx->socket) != 0) {
805 			if (rv == 0) {
806 				tls_set_error(ctx, "close");
807 				rv = -1;
808 			}
809 		}
810 		ctx->socket = -1;
811 	}
812 
813 	if ((ctx->state & TLS_EOF_NO_CLOSE_NOTIFY) != 0) {
814 		tls_set_errorx(ctx, "EOF without close notify");
815 		rv = -1;
816 	}
817 
818  out:
819 	/* Prevent callers from performing incorrect error handling */
820 	errno = 0;
821 	return (rv);
822 }
823