1 /* $OpenBSD: tls.c,v 1.94 2022/02/08 19:13:50 tb Exp $ */
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>
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>
35 #include "tls_internal.h"
37 static struct tls_config
*tls_config_default
;
39 static int tls_init_rv
= -1;
44 OPENSSL_init_ssl(OPENSSL_INIT_NO_LOAD_CONFIG
, NULL
);
46 if (BIO_sock_init() != 1)
49 if ((tls_config_default
= tls_config_new_internal()) == NULL
)
52 tls_config_default
->refcount
++;
60 static pthread_once_t once
= PTHREAD_ONCE_INIT
;
62 if (pthread_once(&once
, tls_do_init
) != 0)
69 tls_error(struct tls
*ctx
)
71 return ctx
->error
.msg
;
75 tls_error_clear(struct tls_error
*error
)
84 tls_error_vset(struct tls_error
*error
, int errnum
, const char *fmt
, va_list ap
)
89 tls_error_clear(error
);
94 if (vasprintf(&errmsg
, fmt
, ap
) == -1) {
104 if (asprintf(&error
->msg
, "%s: %s", errmsg
, strerror(errnum
)) == -1) {
117 tls_error_set(struct tls_error
*error
, const char *fmt
, ...)
125 rv
= tls_error_vset(error
, errnum
, fmt
, ap
);
132 tls_error_setx(struct tls_error
*error
, const char *fmt
, ...)
138 rv
= tls_error_vset(error
, -1, fmt
, ap
);
145 tls_config_set_error(struct tls_config
*config
, const char *fmt
, ...)
153 rv
= tls_error_vset(&config
->error
, errnum
, fmt
, ap
);
160 tls_config_set_errorx(struct tls_config
*config
, const char *fmt
, ...)
166 rv
= tls_error_vset(&config
->error
, -1, fmt
, ap
);
173 tls_set_error(struct tls
*ctx
, const char *fmt
, ...)
181 rv
= tls_error_vset(&ctx
->error
, errnum
, fmt
, ap
);
188 tls_set_errorx(struct tls
*ctx
, const char *fmt
, ...)
194 rv
= tls_error_vset(&ctx
->error
, -1, fmt
, ap
);
201 tls_set_ssl_errorx(struct tls
*ctx
, const char *fmt
, ...)
206 /* Only set an error if a more specific one does not already exist. */
207 if (ctx
->error
.tls
!= 0)
211 rv
= tls_error_vset(&ctx
->error
, -1, fmt
, ap
);
218 tls_sni_ctx_new(void)
220 return (calloc(1, sizeof(struct tls_sni_ctx
)));
224 tls_sni_ctx_free(struct tls_sni_ctx
*sni_ctx
)
229 SSL_CTX_free(sni_ctx
->ssl_ctx
);
230 X509_free(sni_ctx
->ssl_cert
);
240 if ((ctx
= calloc(1, sizeof(*ctx
))) == NULL
)
245 if (tls_configure(ctx
, tls_config_default
) == -1) {
254 tls_configure(struct tls
*ctx
, struct tls_config
*config
)
257 config
= tls_config_default
;
259 pthread_mutex_lock(&config
->mutex
);
261 pthread_mutex_unlock(&config
->mutex
);
263 tls_config_free(ctx
->config
);
265 ctx
->config
= config
;
266 ctx
->keypair
= config
->keypair
;
268 if ((ctx
->flags
& TLS_SERVER
) != 0)
269 return (tls_configure_server(ctx
));
275 tls_cert_hash(X509
*cert
, char **hash
)
277 char d
[EVP_MAX_MD_SIZE
], *dhex
= NULL
;
283 if (X509_digest(cert
, EVP_sha256(), d
, &dlen
) != 1)
286 if (tls_hex_string(d
, dlen
, &dhex
, NULL
) != 0)
289 if (asprintf(hash
, "SHA256:%s", dhex
) == -1) {
302 tls_cert_pubkey_hash(X509
*cert
, char **hash
)
304 char d
[EVP_MAX_MD_SIZE
], *dhex
= NULL
;
310 if (X509_pubkey_digest(cert
, EVP_sha256(), d
, &dlen
) != 1)
313 if (tls_hex_string(d
, dlen
, &dhex
, NULL
) != 0)
316 if (asprintf(hash
, "SHA256:%s", dhex
) == -1) {
330 tls_keypair_to_pkey(struct tls
*ctx
, struct tls_keypair
*keypair
, EVP_PKEY
**pkey
)
340 if (ctx
->config
->use_fake_private_key
) {
341 mem
= keypair
->cert_mem
;
342 len
= keypair
->cert_len
;
344 mem
= keypair
->key_mem
;
345 len
= keypair
->key_len
;
352 tls_set_errorx(ctx
, ctx
->config
->use_fake_private_key
?
353 "cert too long" : "key too long");
357 if ((bio
= BIO_new_mem_buf(mem
, len
)) == NULL
) {
358 tls_set_errorx(ctx
, "failed to create buffer");
362 if (ctx
->config
->use_fake_private_key
) {
363 if ((x509
= PEM_read_bio_X509(bio
, NULL
, tls_password_cb
,
365 tls_set_errorx(ctx
, "failed to read X509 certificate");
368 if ((*pkey
= X509_get_pubkey(x509
)) == NULL
) {
369 tls_set_errorx(ctx
, "failed to retrieve pubkey");
373 if ((*pkey
= PEM_read_bio_PrivateKey(bio
, NULL
, tls_password_cb
,
375 tls_set_errorx(ctx
, "failed to read private key");
388 tls_keypair_setup_pkey(struct tls
*ctx
, struct tls_keypair
*keypair
, EVP_PKEY
*pkey
)
390 RSA_METHOD
*rsa_method
;
391 ECDSA_METHOD
*ecdsa_method
;
393 EC_KEY
*eckey
= NULL
;
396 /* Only install the pubkey hash if fake private keys are used. */
397 if (!ctx
->config
->skip_private_key_check
)
400 if (keypair
->pubkey_hash
== NULL
) {
401 tls_set_errorx(ctx
, "public key hash not set");
405 switch (EVP_PKEY_id(pkey
)) {
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");
412 if (ctx
->config
->sign_cb
== NULL
)
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");
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");
427 if (ctx
->config
->sign_cb
== NULL
)
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");
437 tls_set_errorx(ctx
, "incorrect key type");
450 tls_configure_ssl_keypair(struct tls
*ctx
, SSL_CTX
*ssl_ctx
,
451 struct tls_keypair
*keypair
, int required
)
453 EVP_PKEY
*pkey
= NULL
;
456 keypair
->cert_mem
== NULL
&&
457 keypair
->key_mem
== NULL
)
460 if (keypair
->cert_mem
!= NULL
) {
461 if (keypair
->cert_len
> INT_MAX
) {
462 tls_set_errorx(ctx
, "certificate too long");
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");
473 if (tls_keypair_to_pkey(ctx
, keypair
, &pkey
) == -1)
476 if (tls_keypair_setup_pkey(ctx
, keypair
, pkey
) == -1)
478 if (SSL_CTX_use_PrivateKey(ssl_ctx
, pkey
) != 1) {
479 tls_set_errorx(ctx
, "failed to load private key");
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");
501 tls_configure_ssl(struct tls
*ctx
, SSL_CTX
*ssl_ctx
)
503 SSL_CTX_clear_mode(ssl_ctx
, SSL_MODE_AUTO_RETRY
);
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
);
508 SSL_CTX_set_options(ssl_ctx
, SSL_OP_NO_SSLv2
);
509 SSL_CTX_set_options(ssl_ctx
, SSL_OP_NO_SSLv3
);
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
);
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
);
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");
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");
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
);
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
);
557 tls_ssl_cert_verify_cb(X509_STORE_CTX
*x509_ctx
, void *arg
)
559 struct tls
*ctx
= arg
;
562 if (ctx
->config
->verify_cert
== 0)
565 if ((X509_verify_cert(x509_ctx
)) < 0) {
566 tls_set_errorx(ctx
, "X509 verify cert failed");
570 x509_err
= X509_STORE_CTX_get_error(x509_ctx
);
571 if (x509_err
== X509_V_OK
)
574 tls_set_errorx(ctx
, "certificate verification failed: %s",
575 X509_verify_cert_error_string(x509_err
));
581 tls_configure_ssl_verify(struct tls
*ctx
, SSL_CTX
*ssl_ctx
, int verify
)
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
;
595 SSL_CTX_set_verify(ssl_ctx
, verify
, NULL
);
596 SSL_CTX_set_cert_verify_callback(ssl_ctx
, tls_ssl_cert_verify_cb
, ctx
);
598 if (ctx
->config
->verify_depth
>= 0)
599 SSL_CTX_set_verify_depth(ssl_ctx
, ctx
->config
->verify_depth
);
601 if (ctx
->config
->verify_cert
== 0)
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)
612 if (ca_mem
!= NULL
) {
613 if (ca_len
> INT_MAX
) {
614 tls_set_errorx(ctx
, "ca too long");
617 if (SSL_CTX_load_verify_mem(ssl_ctx
, ca_mem
, ca_len
) != 1) {
618 tls_set_errorx(ctx
, "ssl verify memory setup failure");
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");
627 if (crl_mem
!= NULL
) {
628 if (crl_len
> INT_MAX
) {
629 tls_set_errorx(ctx
, "crl too long");
632 if ((bio
= BIO_new_mem_buf(crl_mem
, crl_len
)) == NULL
) {
633 tls_set_errorx(ctx
, "failed to create buffer");
636 if ((xis
= PEM_X509_INFO_read_bio(bio
, NULL
, tls_password_cb
,
638 tls_set_errorx(ctx
, "failed to parse crl");
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
);
646 if (!X509_STORE_add_crl(store
, xi
->crl
)) {
647 tls_set_error(ctx
, "failed to add crl");
651 X509_STORE_set_flags(store
,
652 X509_V_FLAG_CRL_CHECK
| X509_V_FLAG_CRL_CHECK_ALL
);
659 sk_X509_INFO_pop_free(xis
, X509_INFO_free
);
667 tls_free(struct tls
*ctx
)
678 tls_reset(struct tls
*ctx
)
680 struct tls_sni_ctx
*sni
, *nsni
;
682 tls_config_free(ctx
->config
);
685 SSL_CTX_free(ctx
->ssl_ctx
);
686 SSL_free(ctx
->ssl_conn
);
687 X509_free(ctx
->ssl_peer_cert
);
689 ctx
->ssl_conn
= NULL
;
691 ctx
->ssl_peer_cert
= NULL
;
692 /* X509 objects in chain are freed with the SSL */
693 ctx
->ssl_peer_chain
= NULL
;
698 free(ctx
->servername
);
699 ctx
->servername
= NULL
;
701 free(ctx
->error
.msg
);
702 ctx
->error
.msg
= NULL
;
705 tls_conninfo_free(ctx
->conninfo
);
706 ctx
->conninfo
= NULL
;
708 tls_ocsp_free(ctx
->ocsp
);
711 for (sni
= ctx
->sni_ctx
; sni
!= NULL
; sni
= nsni
) {
713 tls_sni_ctx_free(sni
);
718 ctx
->write_cb
= NULL
;
723 tls_ssl_error(struct tls
*ctx
, SSL
*ssl_conn
, int ssl_ret
, const char *prefix
)
725 const char *errstr
= "unknown error";
729 ssl_err
= SSL_get_error(ssl_conn
, ssl_ret
);
732 case SSL_ERROR_ZERO_RETURN
:
735 case SSL_ERROR_WANT_READ
:
736 return (TLS_WANT_POLLIN
);
738 case SSL_ERROR_WANT_WRITE
:
739 return (TLS_WANT_POLLOUT
);
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
;
749 errstr
= "unexpected EOF";
750 } else if (ssl_ret
== -1) {
751 errstr
= strerror(errno
);
753 tls_set_ssl_errorx(ctx
, "%s failed: %s", prefix
, errstr
);
757 if ((err
= ERR_peek_error()) != 0) {
758 errstr
= ERR_error_string(err
, NULL
);
760 tls_set_ssl_errorx(ctx
, "%s failed: %s", prefix
, errstr
);
763 case SSL_ERROR_WANT_CONNECT
:
764 case SSL_ERROR_WANT_ACCEPT
:
765 case SSL_ERROR_WANT_X509_LOOKUP
:
767 tls_set_ssl_errorx(ctx
, "%s failed (%d)", prefix
, ssl_err
);
773 tls_handshake(struct tls
*ctx
)
777 tls_error_clear(&ctx
->error
);
779 if ((ctx
->flags
& (TLS_CLIENT
| TLS_SERVER_CONN
)) == 0) {
780 tls_set_errorx(ctx
, "invalid operation for context");
784 if ((ctx
->state
& TLS_HANDSHAKE_COMPLETE
) != 0) {
785 tls_set_errorx(ctx
, "handshake already completed");
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
);
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)
799 if (ctx
->ocsp
== NULL
)
800 ctx
->ocsp
= tls_ocsp_setup_from_peer(ctx
);
803 /* Prevent callers from performing incorrect error handling */
809 tls_read(struct tls
*ctx
, void *buf
, size_t buflen
)
814 tls_error_clear(&ctx
->error
);
816 if ((ctx
->state
& TLS_HANDSHAKE_COMPLETE
) == 0) {
817 if ((rv
= tls_handshake(ctx
)) != 0)
821 if (buflen
> INT_MAX
) {
822 tls_set_errorx(ctx
, "buflen too long");
827 if ((ssl_ret
= SSL_read(ctx
->ssl_conn
, buf
, buflen
)) > 0) {
828 rv
= (ssize_t
)ssl_ret
;
831 rv
= (ssize_t
)tls_ssl_error(ctx
, ctx
->ssl_conn
, ssl_ret
, "read");
834 /* Prevent callers from performing incorrect error handling */
840 tls_write(struct tls
*ctx
, const void *buf
, size_t buflen
)
845 tls_error_clear(&ctx
->error
);
847 if ((ctx
->state
& TLS_HANDSHAKE_COMPLETE
) == 0) {
848 if ((rv
= tls_handshake(ctx
)) != 0)
852 if (buflen
> INT_MAX
) {
853 tls_set_errorx(ctx
, "buflen too long");
858 if ((ssl_ret
= SSL_write(ctx
->ssl_conn
, buf
, buflen
)) > 0) {
859 rv
= (ssize_t
)ssl_ret
;
862 rv
= (ssize_t
)tls_ssl_error(ctx
, ctx
->ssl_conn
, ssl_ret
, "write");
865 /* Prevent callers from performing incorrect error handling */
871 tls_close(struct tls
*ctx
)
876 tls_error_clear(&ctx
->error
);
878 if ((ctx
->flags
& (TLS_CLIENT
| TLS_SERVER_CONN
)) == 0) {
879 tls_set_errorx(ctx
, "invalid operation for context");
884 if (ctx
->state
& TLS_SSL_NEEDS_SHUTDOWN
) {
886 ssl_ret
= SSL_shutdown(ctx
->ssl_conn
);
888 rv
= tls_ssl_error(ctx
, ctx
->ssl_conn
, ssl_ret
,
890 if (rv
== TLS_WANT_POLLIN
|| rv
== TLS_WANT_POLLOUT
)
893 ctx
->state
&= ~TLS_SSL_NEEDS_SHUTDOWN
;
896 if (ctx
->socket
!= -1) {
897 if (shutdown(ctx
->socket
, SHUT_RDWR
) != 0) {
899 errno
!= ENOTCONN
&& errno
!= ECONNRESET
) {
900 tls_set_error(ctx
, "shutdown");
904 if (close(ctx
->socket
) != 0) {
906 tls_set_error(ctx
, "close");
913 if ((ctx
->state
& TLS_EOF_NO_CLOSE_NOTIFY
) != 0) {
914 tls_set_errorx(ctx
, "EOF without close notify");
919 /* Prevent callers from performing incorrect error handling */