preprocessor cleanup: __lint
[unleashed/tickless.git] / lib / libtls / tls.c
blob9b03c2b6f013b945779be764d35aeef1a5fec463
1 /* $OpenBSD: tls.c,v 1.59 2017/01/26 12:56:37 jsing Exp $ */
2 /*
3 * Copyright (c) 2014 Joel Sing <jsing@openbsd.org>
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.
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.
18 #include <sys/socket.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <stdlib.h>
23 #include <unistd.h>
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>
31 #include <tls.h>
32 #include "tls_internal.h"
34 static struct tls_config *tls_config_default;
36 int
37 tls_init(void)
39 static int tls_initialised = 0;
41 if (tls_initialised)
42 return (0);
44 SSL_load_error_strings();
45 SSL_library_init();
47 if (BIO_sock_init() != 1)
48 return (-1);
50 if ((tls_config_default = tls_config_new()) == NULL)
51 return (-1);
53 tls_initialised = 1;
55 return (0);
58 const char *
59 tls_error(struct tls *ctx)
61 return ctx->error.msg;
64 void
65 tls_error_clear(struct tls_error *error)
67 free(error->msg);
68 error->msg = NULL;
69 error->num = 0;
70 error->tls = 0;
73 static int
74 tls_error_vset(struct tls_error *error, int errnum, const char *fmt, va_list ap)
76 char *errmsg = NULL;
77 int rv = -1;
79 tls_error_clear(error);
81 error->num = errnum;
82 error->tls = 1;
84 if (vasprintf(&errmsg, fmt, ap) == -1) {
85 errmsg = NULL;
86 goto err;
89 if (errnum == -1) {
90 error->msg = errmsg;
91 return (0);
94 if (asprintf(&error->msg, "%s: %s", errmsg, strerror(errnum)) == -1) {
95 error->msg = NULL;
96 goto err;
98 rv = 0;
100 err:
101 free(errmsg);
103 return (rv);
107 tls_error_set(struct tls_error *error, const char *fmt, ...)
109 va_list ap;
110 int errnum, rv;
112 errnum = errno;
114 va_start(ap, fmt);
115 rv = tls_error_vset(error, errnum, fmt, ap);
116 va_end(ap);
118 return (rv);
122 tls_error_setx(struct tls_error *error, const char *fmt, ...)
124 va_list ap;
125 int rv;
127 va_start(ap, fmt);
128 rv = tls_error_vset(error, -1, fmt, ap);
129 va_end(ap);
131 return (rv);
135 tls_config_set_error(struct tls_config *config, const char *fmt, ...)
137 va_list ap;
138 int errnum, rv;
140 errnum = errno;
142 va_start(ap, fmt);
143 rv = tls_error_vset(&config->error, errnum, fmt, ap);
144 va_end(ap);
146 return (rv);
150 tls_config_set_errorx(struct tls_config *config, const char *fmt, ...)
152 va_list ap;
153 int rv;
155 va_start(ap, fmt);
156 rv = tls_error_vset(&config->error, -1, fmt, ap);
157 va_end(ap);
159 return (rv);
163 tls_set_error(struct tls *ctx, const char *fmt, ...)
165 va_list ap;
166 int errnum, rv;
168 errnum = errno;
170 va_start(ap, fmt);
171 rv = tls_error_vset(&ctx->error, errnum, fmt, ap);
172 va_end(ap);
174 return (rv);
178 tls_set_errorx(struct tls *ctx, const char *fmt, ...)
180 va_list ap;
181 int rv;
183 va_start(ap, fmt);
184 rv = tls_error_vset(&ctx->error, -1, fmt, ap);
185 va_end(ap);
187 return (rv);
191 tls_set_ssl_errorx(struct tls *ctx, const char *fmt, ...)
193 va_list ap;
194 int rv;
196 /* Only set an error if a more specific one does not already exist. */
197 if (ctx->error.tls != 0)
198 return (0);
200 va_start(ap, fmt);
201 rv = tls_error_vset(&ctx->error, -1, fmt, ap);
202 va_end(ap);
204 return (rv);
207 struct tls_sni_ctx *
208 tls_sni_ctx_new(void)
210 return (calloc(1, sizeof(struct tls_sni_ctx)));
213 void
214 tls_sni_ctx_free(struct tls_sni_ctx *sni_ctx)
216 if (sni_ctx == NULL)
217 return;
219 SSL_CTX_free(sni_ctx->ssl_ctx);
220 X509_free(sni_ctx->ssl_cert);
222 free(sni_ctx);
225 struct tls *
226 tls_new(void)
228 struct tls *ctx;
230 if ((ctx = calloc(1, sizeof(*ctx))) == NULL)
231 return (NULL);
233 ctx->config = tls_config_default;
235 tls_reset(ctx);
237 return (ctx);
241 tls_configure(struct tls *ctx, struct tls_config *config)
243 if (config == NULL)
244 config = tls_config_default;
246 ctx->config = config;
248 if ((ctx->flags & TLS_SERVER) != 0)
249 return (tls_configure_server(ctx));
251 return (0);
255 tls_configure_ssl_keypair(struct tls *ctx, SSL_CTX *ssl_ctx,
256 struct tls_keypair *keypair, int required)
258 EVP_PKEY *pkey = NULL;
259 X509 *cert = NULL;
260 BIO *bio = NULL;
262 if (!required &&
263 keypair->cert_mem == NULL &&
264 keypair->key_mem == NULL)
265 return(0);
267 if (keypair->cert_mem != NULL) {
268 if (keypair->cert_len > INT_MAX) {
269 tls_set_errorx(ctx, "certificate too long");
270 goto err;
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;
278 cert = NULL;
280 if (keypair->key_mem != NULL) {
281 if (keypair->key_len > INT_MAX) {
282 tls_set_errorx(ctx, "key too long");
283 goto err;
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;
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;
296 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1) {
297 tls_set_errorx(ctx, "failed to load private key");
298 goto err;
300 BIO_free(bio);
301 bio = NULL;
302 EVP_PKEY_free(pkey);
303 pkey = NULL;
306 if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
307 tls_set_errorx(ctx, "private/public key mismatch");
308 goto err;
311 return (0);
313 err:
314 EVP_PKEY_free(pkey);
315 X509_free(cert);
316 BIO_free(bio);
318 return (1);
322 tls_configure_ssl(struct tls *ctx, SSL_CTX *ssl_ctx)
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);
327 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2);
328 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv3);
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);
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);
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;
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;
357 if (ctx->config->verify_time == 0) {
358 X509_VERIFY_PARAM_set_flags(ssl_ctx->param,
359 X509_V_FLAG_NO_CHECK_TIME);
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);
366 return (0);
368 err:
369 return (-1);
372 static int
373 tls_ssl_cert_verify_cb(X509_STORE_CTX *x509_ctx, void *arg)
375 struct tls *ctx = arg;
376 int x509_err;
378 if (ctx->config->verify_cert == 0)
379 return (1);
381 if ((X509_verify_cert(x509_ctx)) < 0) {
382 tls_set_errorx(ctx, "X509 verify cert failed");
383 return (0);
386 x509_err = X509_STORE_CTX_get_error(x509_ctx);
387 if (x509_err == X509_V_OK)
388 return (1);
390 tls_set_errorx(ctx, "certificate verification failed: %s",
391 X509_verify_cert_error_string(x509_err));
393 return (0);
397 tls_configure_ssl_verify(struct tls *ctx, SSL_CTX *ssl_ctx, int verify)
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;
404 SSL_CTX_set_verify(ssl_ctx, verify, NULL);
405 SSL_CTX_set_cert_verify_callback(ssl_ctx, tls_ssl_cert_verify_cb, ctx);
407 if (ctx->config->verify_depth >= 0)
408 SSL_CTX_set_verify_depth(ssl_ctx, ctx->config->verify_depth);
410 if (ctx->config->verify_cert == 0)
411 goto done;
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;
421 if (ca_mem != NULL) {
422 if (ca_len > INT_MAX) {
423 tls_set_errorx(ctx, "ca too long");
424 goto err;
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;
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;
436 done:
437 rv = 0;
439 err:
440 free(ca_free);
442 return (rv);
445 void
446 tls_free(struct tls *ctx)
448 if (ctx == NULL)
449 return;
451 tls_reset(ctx);
453 free(ctx);
456 void
457 tls_reset(struct tls *ctx)
459 struct tls_sni_ctx *sni, *nsni;
461 SSL_CTX_free(ctx->ssl_ctx);
462 SSL_free(ctx->ssl_conn);
463 X509_free(ctx->ssl_peer_cert);
465 ctx->ssl_conn = NULL;
466 ctx->ssl_ctx = NULL;
467 ctx->ssl_peer_cert = NULL;
469 ctx->socket = -1;
470 ctx->state = 0;
472 free(ctx->servername);
473 ctx->servername = NULL;
475 free(ctx->error.msg);
476 ctx->error.msg = NULL;
477 ctx->error.num = -1;
479 tls_conninfo_free(ctx->conninfo);
480 ctx->conninfo = NULL;
482 tls_ocsp_free(ctx->ocsp);
483 ctx->ocsp = NULL;
485 for (sni = ctx->sni_ctx; sni != NULL; sni = nsni) {
486 nsni = sni->next;
487 tls_sni_ctx_free(sni);
489 ctx->sni_ctx = NULL;
491 ctx->read_cb = NULL;
492 ctx->write_cb = NULL;
493 ctx->cb_arg = NULL;
497 tls_ssl_error(struct tls *ctx, SSL *ssl_conn, int ssl_ret, const char *prefix)
499 const char *errstr = "unknown error";
500 unsigned long err;
501 int ssl_err;
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);
509 case SSL_ERROR_WANT_READ:
510 return (TLS_WANT_POLLIN);
512 case SSL_ERROR_WANT_WRITE:
513 return (TLS_WANT_POLLOUT);
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);
523 errstr = "unexpected EOF";
524 } else if (ssl_ret == -1) {
525 errstr = strerror(errno);
527 tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
528 return (-1);
530 case SSL_ERROR_SSL:
531 if ((err = ERR_peek_error()) != 0) {
532 errstr = ERR_error_string(err, NULL);
534 tls_set_ssl_errorx(ctx, "%s failed: %s", prefix, errstr);
535 return (-1);
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);
547 tls_handshake(struct tls *ctx)
549 int rv = -1;
551 tls_error_clear(&ctx->error);
553 if ((ctx->flags & (TLS_CLIENT | TLS_SERVER_CONN)) == 0) {
554 tls_set_errorx(ctx, "invalid operation for context");
555 goto out;
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);
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);
570 out:
571 /* Prevent callers from performing incorrect error handling */
572 errno = 0;
573 return (rv);
576 ssize_t
577 tls_read(struct tls *ctx, void *buf, size_t buflen)
579 ssize_t rv = -1;
580 int ssl_ret;
582 tls_error_clear(&ctx->error);
584 if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
585 if ((rv = tls_handshake(ctx)) != 0)
586 goto out;
589 if (buflen > INT_MAX) {
590 tls_set_errorx(ctx, "buflen too long");
591 goto out;
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;
599 rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "read");
601 out:
602 /* Prevent callers from performing incorrect error handling */
603 errno = 0;
604 return (rv);
607 ssize_t
608 tls_write(struct tls *ctx, const void *buf, size_t buflen)
610 ssize_t rv = -1;
611 int ssl_ret;
613 tls_error_clear(&ctx->error);
615 if ((ctx->state & TLS_HANDSHAKE_COMPLETE) == 0) {
616 if ((rv = tls_handshake(ctx)) != 0)
617 goto out;
620 if (buflen > INT_MAX) {
621 tls_set_errorx(ctx, "buflen too long");
622 goto out;
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;
630 rv = (ssize_t)tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "write");
632 out:
633 /* Prevent callers from performing incorrect error handling */
634 errno = 0;
635 return (rv);
639 tls_close(struct tls *ctx)
641 int ssl_ret;
642 int rv = 0;
644 tls_error_clear(&ctx->error);
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;
652 if (ctx->state & TLS_SSL_NEEDS_SHUTDOWN) {
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;
661 ctx->state &= ~TLS_SSL_NEEDS_SHUTDOWN;
664 if (ctx->socket != -1) {
665 if (shutdown(ctx->socket, SHUT_RDWR) != 0) {
666 if (rv == 0 &&
667 errno != ENOTCONN && errno != ECONNRESET) {
668 tls_set_error(ctx, "shutdown");
669 rv = -1;
672 if (close(ctx->socket) != 0) {
673 if (rv == 0) {
674 tls_set_error(ctx, "close");
675 rv = -1;
678 ctx->socket = -1;
681 if ((ctx->state & TLS_EOF_NO_CLOSE_NOTIFY) != 0) {
682 tls_set_errorx(ctx, "EOF without close notify");
683 rv = -1;
686 out:
687 /* Prevent callers from performing incorrect error handling */
688 errno = 0;
689 return (rv);