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