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