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