2 * tls.c TLS support functions
4 * Author: Landon Fuller <landonf@threerings.net>
8 * Copyright (C) 2005 Kern Sibbald
10 * This file was contributed to the Bacula project by Landon Fuller
11 * and Three Rings Design, Inc.
13 * Three Rings Design, Inc. has been granted a perpetual, worldwide,
14 * non-exclusive, no-charge, royalty-free, irrevocable copyright
15 * license to reproduce, prepare derivative works of, publicly
16 * display, publicly perform, sublicense, and distribute the original
17 * work contributed by Three Rings Design, Inc. and its employees to
18 * the Bacula project in source or object form.
20 * If you wish to license contributions from Three Rings Design, Inc,
21 * under an alternate open source license please contact
22 * Landon Fuller <landonf@threerings.net>.
25 Copyright (C) 2005 Kern Sibbald
27 This program is free software; you can redistribute it and/or
28 modify it under the terms of the GNU General Public License
29 version 2 as amended with additional clauses defined in the
30 file LICENSE in the main source directory.
32 This program is distributed in the hope that it will be useful,
33 but WITHOUT ANY WARRANTY; without even the implied warranty of
34 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 the file LICENSE for additional details.
42 extern time_t watchdog_time;
44 #ifdef HAVE_TLS /* Is TLS enabled? */
46 #ifdef HAVE_OPENSSL /* How about OpenSSL? */
48 /* No anonymous ciphers, no <128 bit ciphers, no export ciphers, no MD5 ciphers */
49 #define TLS_DEFAULT_CIPHERS "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
51 /* Array of mutexes for use with OpenSSL static locking */
52 static pthread_mutex_t *mutexes;
54 /* OpenSSL dynamic locking structure */
55 struct CRYPTO_dynlock_value {
56 pthread_mutex_t mutex;
59 /* Are we initialized? */
60 static int tls_initialized = false;
62 /* TLS Context Structure */
65 TLS_PEM_PASSWD_CB *pem_callback;
66 const void *pem_userdata;
69 struct TLS_Connection {
73 /* post all per-thread openssl errors */
74 static void openssl_post_errors(int code, const char *errstring)
79 /* Pop errors off of the per-thread queue */
80 while((sslerr = ERR_get_error()) != 0) {
81 /* Acquire the human readable string */
82 ERR_error_string_n(sslerr, (char *) &buf, sizeof(buf));
83 Emsg2(M_ERROR, 0, "%s: ERR=%s\n", errstring, buf);
88 * OpenSSL certificate verification callback.
89 * OpenSSL has already performed internal certificate verification.
90 * We just report any errors that occured.
92 static int openssl_verify_peer(int ok, X509_STORE_CTX *store)
96 X509 *cert = X509_STORE_CTX_get_current_cert(store);
97 int depth = X509_STORE_CTX_get_error_depth(store);
98 int err = X509_STORE_CTX_get_error(store);
102 X509_NAME_oneline(X509_get_issuer_name(cert), issuer, 256);
103 X509_NAME_oneline(X509_get_subject_name(cert), subject, 256);
105 Emsg5(M_ERROR, 0, _("Error with certificate at depth: %d, issuer = %s,"
106 " subject = %s, ERR=%d:%s\n"), depth, issuer,
107 subject, err, X509_verify_cert_error_string(err));
115 * Default PEM encryption passphrase callback.
116 * Returns an empty password.
118 static int tls_default_pem_callback(char *buf, int size, const void *userdata)
120 bstrncpy(buf, "", size);
121 return (strlen(buf));
124 /* Dispatch user PEM encryption callbacks */
125 static int openssl_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
127 TLS_CONTEXT *ctx = (TLS_CONTEXT *) userdata;
128 return (ctx->pem_callback(buf, size, ctx->pem_userdata));
132 * Create a new TLS_CONTEXT instance.
133 * Returns: Pointer to TLS_CONTEXT instance on success
136 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
137 const char *certfile, const char *keyfile,
138 TLS_PEM_PASSWD_CB *pem_callback,
139 const void *pem_userdata, const char *dhfile,
146 ctx = (TLS_CONTEXT *) malloc(sizeof(TLS_CONTEXT));
148 /* Allocate our OpenSSL TLSv1 Context */
149 ctx->openssl = SSL_CTX_new(TLSv1_method());
152 openssl_post_errors(M_ERROR, _("Error initializing SSL context"));
156 /* Set up pem encryption callback */
158 ctx->pem_callback = pem_callback;
159 ctx->pem_userdata = pem_userdata;
161 ctx->pem_callback = tls_default_pem_callback;
162 ctx->pem_userdata = NULL;
164 SSL_CTX_set_default_passwd_cb(ctx->openssl, openssl_pem_callback_dispatch);
165 SSL_CTX_set_default_passwd_cb_userdata(ctx->openssl, (void *) ctx);
168 * Set certificate verification paths. This requires that at least one
171 if (ca_certfile || ca_certdir) {
172 if (!SSL_CTX_load_verify_locations(ctx->openssl, ca_certfile, ca_certdir)) {
173 openssl_post_errors(M_ERROR, _("Error loading certificate verification stores"));
176 } else if (verify_peer) {
177 /* At least one CA is required for peer verification */
178 Emsg0(M_ERROR, 0, _("Either a certificate file or a directory must be"
179 " specified as a verification store\n"));
184 * Load our certificate file, if available. This file may also contain a
185 * private key, though this usage is somewhat unusual.
188 if (!SSL_CTX_use_certificate_chain_file(ctx->openssl, certfile)) {
189 openssl_post_errors(M_ERROR, _("Error loading certificate file"));
194 /* Load our private key. */
196 if (!SSL_CTX_use_PrivateKey_file(ctx->openssl, keyfile, SSL_FILETYPE_PEM)) {
197 openssl_post_errors(M_ERROR, _("Error loading private key"));
202 /* Load Diffie-Hellman Parameters. */
204 if (!(bio = BIO_new_file(dhfile, "r"))) {
205 openssl_post_errors(M_ERROR, _("Unable to open DH parameters file"));
208 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
211 openssl_post_errors(M_ERROR, _("Unable to load DH parameters from specified file"));
214 if (!SSL_CTX_set_tmp_dh(ctx->openssl, dh)) {
215 openssl_post_errors(M_ERROR, _("Failed to set TLS Diffie-Hellman parameters"));
219 /* Enable Single-Use DH for Ephemeral Keying */
220 SSL_CTX_set_options(ctx->openssl, SSL_OP_SINGLE_DH_USE);
223 if (SSL_CTX_set_cipher_list(ctx->openssl, TLS_DEFAULT_CIPHERS) != 1) {
224 Emsg0(M_ERROR, 0, _("Error setting cipher list, no valid ciphers available\n"));
228 /* Verify Peer Certificate */
230 /* SSL_VERIFY_FAIL_IF_NO_PEER_CERT has no effect in client mode */
231 SSL_CTX_set_verify(ctx->openssl,
232 SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
233 openssl_verify_peer);
239 /* Clean up after ourselves */
241 SSL_CTX_free(ctx->openssl);
248 * Free TLS_CONTEXT instance
250 void free_tls_context(TLS_CONTEXT *ctx)
252 SSL_CTX_free(ctx->openssl);
257 * Verifies a list of common names against the certificate
258 * commonName attribute.
259 * Returns: true on success
262 bool tls_postconnect_verify_cn(TLS_CONNECTION *tls, alist *verify_list)
264 SSL *ssl = tls->openssl;
267 int auth_success = false;
270 /* Check if peer provided a certificate */
271 if (!(cert = SSL_get_peer_certificate(ssl))) {
272 Emsg0(M_ERROR, 0, _("Peer failed to present a TLS certificate\n"));
276 if ((subject = X509_get_subject_name(cert)) != NULL) {
277 if (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) > 0) {
279 /* NULL terminate data */
282 /* Try all the CNs in the list */
283 foreach_alist(cn, verify_list) {
284 if (strcasecmp(data, cn) == 0) {
296 * Verifies a peer's hostname against the subjectAltName and commonName
298 * Returns: true on success
301 bool tls_postconnect_verify_host(TLS_CONNECTION *tls, const char *host)
303 SSL *ssl = tls->openssl;
306 int auth_success = false;
312 /* Check if peer provided a certificate */
313 if (!(cert = SSL_get_peer_certificate(ssl))) {
314 Emsg1(M_ERROR, 0, _("Peer %s failed to present a TLS certificate\n"), host);
318 /* Check subjectAltName extensions first */
319 if ((extensions = X509_get_ext_count(cert)) > 0) {
320 for (i = 0; i < extensions; i++) {
324 ext = X509_get_ext(cert, i);
325 extname = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
327 if (strcmp(extname, "subjectAltName") == 0) {
328 X509V3_EXT_METHOD *method;
329 STACK_OF(CONF_VALUE) *val;
332 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
333 const unsigned char *ext_value_data;
335 unsigned char *ext_value_data;
338 /* Get x509 extension method structure */
339 if (!(method = X509V3_EXT_get(ext))) {
343 ext_value_data = ext->value->data;
345 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
349 /* Decode ASN1 item in data */
350 extstr = ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
351 ASN1_ITEM_ptr(method->it));
355 /* Decode ASN1 item in data */
356 extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
360 extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
363 /* Iterate through to find the dNSName field(s) */
364 val = method->i2v(method, extstr, NULL);
366 /* dNSName shortname is "DNS" */
367 for (j = 0; j < sk_CONF_VALUE_num(val); j++) {
368 nval = sk_CONF_VALUE_value(val, j);
369 if (strcmp(nval->name, "DNS") == 0) {
370 if (strcasecmp(nval->name, host) == 0) {
380 /* Try verifying against the subject name */
382 if ((subject = X509_get_subject_name(cert)) != NULL) {
383 if (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) > 0) {
384 /* NULL terminate data */
386 if (strcasecmp(data, host) == 0) {
401 * Create a new TLS_CONNECTION instance.
403 * Returns: Pointer to TLS_CONNECTION instance on success
406 TLS_CONNECTION *new_tls_connection (TLS_CONTEXT *ctx, int fd)
411 * Create a new BIO and assign the fd.
412 * The caller will remain responsible for closing the associated fd
414 bio = BIO_new(BIO_s_socket());
416 /* Not likely, but never say never */
417 openssl_post_errors(M_ERROR, _("Error creating file descriptor-based BIO"));
418 return NULL; /* Nothing allocated, nothing to clean up */
420 BIO_set_fd(bio, fd, BIO_NOCLOSE);
422 /* Allocate our new tls connection */
423 TLS_CONNECTION *tls = (TLS_CONNECTION *) malloc(sizeof(TLS_CONNECTION));
425 /* Create the SSL object and attach the socket BIO */
426 if ((tls->openssl = SSL_new(ctx->openssl)) == NULL) {
427 /* Not likely, but never say never */
428 openssl_post_errors(M_ERROR, _("Error creating new SSL object"));
432 SSL_set_bio(tls->openssl, bio, bio);
434 /* Non-blocking partial writes */
435 SSL_set_mode(tls->openssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
442 SSL_free(tls->openssl);
449 * Free TLS_CONNECTION instance
451 void free_tls_connection (TLS_CONNECTION *tls)
453 SSL_free(tls->openssl);
457 /* Does all the manual labor for tls_bsock_accept() and tls_bsock_connect() */
458 static inline bool openssl_bsock_session_start(BSOCK *bsock, bool server)
460 TLS_CONNECTION *tls = bsock->tls;
467 /* Zero the fdset, we'll set our fd prior to each invocation of select() */
469 fdmax = bsock->fd + 1;
471 /* Ensure that socket is non-blocking */
472 flags = bnet_set_nonblocking(bsock);
475 bsock->timer_start = watchdog_time;
476 bsock->timed_out = 0;
480 err = SSL_accept(tls->openssl);
482 err = SSL_connect(tls->openssl);
486 switch (SSL_get_error(tls->openssl, err)) {
490 case SSL_ERROR_ZERO_RETURN:
491 /* TLS connection was cleanly shut down */
492 openssl_post_errors(M_ERROR, _("Connect failure"));
495 case SSL_ERROR_WANT_READ:
496 /* If we timeout of a select, this will be unset */
497 FD_SET((unsigned) bsock->fd, &fdset);
498 /* Set our timeout */
501 /* Block until we can read */
502 select(fdmax, &fdset, NULL, &fdset, &tv);
504 case SSL_ERROR_WANT_WRITE:
505 /* If we timeout of a select, this will be unset */
506 FD_SET((unsigned) bsock->fd, &fdset);
507 /* Set our timeout */
510 /* Block until we can write */
511 select(fdmax, NULL, &fdset, &fdset, &tv);
514 /* Socket Error Occured */
515 openssl_post_errors(M_ERROR, _("Connect failure"));
520 if (bsock->timed_out) {
526 /* Restore saved flags */
527 bnet_restore_blocking(bsock, flags);
529 bsock->timer_start = 0;
535 * Initiates a TLS connection with the server.
536 * Returns: true on success
539 bool tls_bsock_connect(BSOCK *bsock)
541 /* SSL_connect(bsock->tls) */
542 return (openssl_bsock_session_start(bsock, false));
546 * Listens for a TLS connection from a client.
547 * Returns: true on success
550 bool tls_bsock_accept(BSOCK *bsock)
552 /* SSL_accept(bsock->tls) */
553 return (openssl_bsock_session_start(bsock, true));
557 * Shutdown TLS_CONNECTION instance
559 void tls_bsock_shutdown (BSOCK *bsock)
562 * SSL_shutdown must be called twice to fully complete the process -
563 * The first time to initiate the shutdown handshake, and the second to
564 * receive the peer's reply.
566 * However, it is valid to close the SSL connection after the initial
567 * shutdown notification is sent to the peer, without waiting for the
568 * peer's reply, as long as you do not plan to re-use that particular
569 * SSL connection object.
571 * Because we do not re-use SSL connection objects, I do not bother
572 * calling SSL_shutdown a second time.
574 * In addition, if the underlying socket is blocking, SSL_shutdown()
575 * will not return until the current stage of the shutdown process has
576 * completed or an error has occured. By setting the socket blocking
577 * we can avoid the ugly for()/switch()/select() loop.
582 /* Set socket blocking for shutdown */
583 flags = bnet_set_blocking(bsock);
585 err = SSL_shutdown(bsock->tls->openssl);
587 switch (SSL_get_error(bsock->tls->openssl, err)) {
590 case SSL_ERROR_ZERO_RETURN:
591 /* TLS connection was shut down on us via a TLS protocol-level closure */
592 openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
595 /* Socket Error Occured */
596 openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
600 /* Restore saved flags */
601 bnet_restore_blocking(bsock, flags);
604 /* Does all the manual labor for tls_bsock_readn() and tls_bsock_writen() */
605 static inline int openssl_bsock_readwrite(BSOCK *bsock, char *ptr, int nbytes, bool write)
607 TLS_CONNECTION *tls = bsock->tls;
614 /* Zero the fdset, we'll set our fd prior to each invocation of select() */
616 fdmax = bsock->fd + 1;
618 /* Ensure that socket is non-blocking */
619 flags = bnet_set_nonblocking(bsock);
622 bsock->timer_start = watchdog_time;
623 bsock->timed_out = 0;
630 nwritten = SSL_write(tls->openssl, ptr, nleft);
632 nwritten = SSL_read(tls->openssl, ptr, nleft);
636 switch (SSL_get_error(tls->openssl, nwritten)) {
643 case SSL_ERROR_ZERO_RETURN:
644 /* TLS connection was cleanly shut down */
645 openssl_post_errors(M_ERROR, _("TLS read/write failure."));
647 case SSL_ERROR_WANT_READ:
648 /* If we timeout of a select, this will be unset */
649 FD_SET((unsigned) bsock->fd, &fdset);
652 /* Block until we can read */
653 select(fdmax, &fdset, NULL, &fdset, &tv);
655 case SSL_ERROR_WANT_WRITE:
656 /* If we timeout of a select, this will be unset */
657 FD_SET((unsigned) bsock->fd, &fdset);
660 /* Block until we can write */
661 select(fdmax, NULL, &fdset, &fdset, &tv);
664 /* Socket Error Occured */
665 openssl_post_errors(M_ERROR, _("TLS read/write failure."));
669 /* Everything done? */
674 /* Timeout/Termination, let's take what we can get */
675 if (bsock->timed_out || bsock->terminated) {
681 /* Restore saved flags */
682 bnet_restore_blocking(bsock, flags);
685 bsock->timer_start = 0;
687 return nbytes - nleft;
691 int tls_bsock_writen(BSOCK *bsock, char *ptr, int32_t nbytes) {
692 /* SSL_write(bsock->tls->openssl, ptr, nbytes) */
693 return (openssl_bsock_readwrite(bsock, ptr, nbytes, true));
696 int tls_bsock_readn(BSOCK *bsock, char *ptr, int32_t nbytes) {
697 /* SSL_read(bsock->tls->openssl, ptr, nbytes) */
698 return (openssl_bsock_readwrite(bsock, ptr, nbytes, false));
702 * Return an OpenSSL thread ID
706 static unsigned long get_openssl_thread_id (void)
708 /* Comparison without use of pthread_equal() is mandated by the OpenSSL API */
709 return ((unsigned long) pthread_self());
713 * Allocate a dynamic OpenSSL mutex
715 static struct CRYPTO_dynlock_value *openssl_create_dynamic_mutex (const char *file, int line)
717 struct CRYPTO_dynlock_value *dynlock;
720 dynlock = (struct CRYPTO_dynlock_value *) malloc(sizeof(struct CRYPTO_dynlock_value));
722 if ((stat = pthread_mutex_init(&dynlock->mutex, NULL)) != 0) {
723 Emsg1(M_ABORT, 0, _("Unable to init mutex: ERR=%s\n"), strerror(stat));
729 static void openssl_update_dynamic_mutex (int mode, struct CRYPTO_dynlock_value *dynlock, const char *file, int line)
731 if (mode & CRYPTO_LOCK) {
738 static void openssl_destroy_dynamic_mutex (struct CRYPTO_dynlock_value *dynlock, const char *file, int line)
742 if ((stat = pthread_mutex_destroy(&dynlock->mutex)) != 0) {
743 Emsg1(M_ABORT, 0, _("Unable to destroy mutex: ERR=%s\n"), strerror(stat));
750 * (Un)Lock a static OpenSSL mutex
752 static void openssl_update_static_mutex (int mode, int i, const char *file, int line)
754 if (mode & CRYPTO_LOCK) {
762 * Initialize OpenSSL thread support
763 * Returns: 0 on success
766 static int openssl_init_threads (void)
772 /* Set thread ID callback */
773 CRYPTO_set_id_callback(get_openssl_thread_id);
775 /* Initialize static locking */
776 numlocks = CRYPTO_num_locks();
777 mutexes = (pthread_mutex_t *) malloc(numlocks * sizeof(pthread_mutex_t));
778 for (i = 0; i < numlocks; i++) {
779 if ((stat = pthread_mutex_init(&mutexes[i], NULL)) != 0) {
780 Emsg1(M_ERROR, 0, _("Unable to init mutex: ERR=%s\n"), strerror(stat));
785 /* Set static locking callback */
786 CRYPTO_set_locking_callback(openssl_update_static_mutex);
788 /* Initialize dyanmic locking */
789 CRYPTO_set_dynlock_create_callback(openssl_create_dynamic_mutex);
790 CRYPTO_set_dynlock_lock_callback(openssl_update_dynamic_mutex);
791 CRYPTO_set_dynlock_destroy_callback(openssl_destroy_dynamic_mutex);
797 * Clean up OpenSSL threading support
799 static void openssl_cleanup_threads (void)
804 /* Unset thread ID callback */
805 CRYPTO_set_id_callback(NULL);
807 /* Deallocate static lock mutexes */
808 numlocks = CRYPTO_num_locks();
809 for (i = 0; i < numlocks; i++) {
810 if ((stat = pthread_mutex_destroy(&mutexes[i])) != 0) {
811 /* We don't halt execution, reporting the error should be sufficient */
812 Emsg1(M_ERROR, 0, _("Unable to destroy mutex: ERR=%s\n"), strerror(stat));
816 /* Unset static locking callback */
817 CRYPTO_set_locking_callback(NULL);
819 /* Free static lock array */
822 /* Unset dynamic locking callbacks */
823 CRYPTO_set_dynlock_create_callback(NULL);
824 CRYPTO_set_dynlock_lock_callback(NULL);
825 CRYPTO_set_dynlock_destroy_callback(NULL);
831 * Returns: 1 on success
834 static int seed_tls_prng (void)
836 const char *names[] = { "/dev/urandom", "/dev/random", NULL };
841 // Read saved entropy?
843 for (i = 0; names[i]; i++) {
844 if (RAND_load_file(names[i], 1024) != -1) {
856 * Returns: 1 on success
859 static int save_tls_prng (void)
862 // Implement PRNG state save
867 * Perform global initialization of TLS
868 * This function is not thread safe.
869 * Returns: 0 on success
876 if ((stat = openssl_init_threads()) != 0) {
877 Emsg1(M_ABORT, 0, _("Unable to init OpenSSL threading: ERR=%s\n"), strerror(stat));
880 /* Load libssl and libcrypto human-readable error strings */
881 SSL_load_error_strings();
883 /* Register OpenSSL ciphers */
886 if (!seed_tls_prng()) {
887 Emsg0(M_ERROR_TERM, 0, _("Failed to seed OpenSSL PRNG\n"));
890 tls_initialized = true;
896 * Perform global cleanup of TLS
897 * All TLS connections must be closed before calling this function.
898 * This function is not thread safe.
899 * Returns: 0 on success
902 int cleanup_tls (void)
905 * Ensure that we've actually been initialized; Doing this here decreases the
906 * complexity of client's termination/cleanup code.
908 if (!tls_initialized) {
912 if (!save_tls_prng()) {
913 Emsg0(M_ERROR, 0, _("Failed to save OpenSSL PRNG\n"));
916 openssl_cleanup_threads();
918 /* Free libssl and libcrypto error strings */
921 /* Free memory used by PRNG */
924 tls_initialized = false;
929 #else /* HAVE_OPENSSL */
930 # error No TLS implementation available.
931 #endif /* !HAVE_OPENSSL */
936 int init_tls(void) { return 0; }
937 int cleanup_tls (void) { return 0; }
938 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
939 const char *certfile, const char *keyfile,
940 TLS_PEM_PASSWD_CB *pem_callback,
941 const void *pem_userdata, const char *dhfile,
946 void free_tls_context(TLS_CONTEXT *ctx) { }
948 #endif /* HAVE_TLS */