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() */
471 fdmax = bsock->fd + 1;
473 /* Ensure that socket is non-blocking */
474 flags = bnet_set_nonblocking(bsock);
477 bsock->timer_start = watchdog_time;
478 bsock->timed_out = 0;
482 err = SSL_accept(tls->openssl);
484 err = SSL_connect(tls->openssl);
488 switch (SSL_get_error(tls->openssl, err)) {
492 case SSL_ERROR_ZERO_RETURN:
493 /* TLS connection was cleanly shut down */
494 openssl_post_errors(M_ERROR, _("Connect failure"));
497 case SSL_ERROR_WANT_READ:
498 /* If we timeout of a select, this will be unset */
499 FD_SET((unsigned) bsock->fd, &fdset);
500 /* Block until we can read */
501 select(fdmax, &fdset, NULL, &fdset, &tv);
503 case SSL_ERROR_WANT_WRITE:
504 /* If we timeout of a select, this will be unset */
505 FD_SET((unsigned) bsock->fd, &fdset);
506 /* Block until we can write */
507 select(fdmax, NULL, &fdset, &fdset, &tv);
510 /* Socket Error Occured */
511 openssl_post_errors(M_ERROR, _("Connect failure"));
516 if (bsock->timed_out) {
522 /* Restore saved flags */
523 bnet_restore_blocking(bsock, flags);
525 bsock->timer_start = 0;
531 * Initiates a TLS connection with the server.
532 * Returns: true on success
535 bool tls_bsock_connect(BSOCK *bsock)
537 /* SSL_connect(bsock->tls) */
538 return (openssl_bsock_session_start(bsock, false));
542 * Listens for a TLS connection from a client.
543 * Returns: true on success
546 bool tls_bsock_accept(BSOCK *bsock)
548 /* SSL_accept(bsock->tls) */
549 return (openssl_bsock_session_start(bsock, true));
553 * Shutdown TLS_CONNECTION instance
555 void tls_bsock_shutdown (BSOCK *bsock)
558 * SSL_shutdown must be called twice to fully complete the process -
559 * The first time to initiate the shutdown handshake, and the second to
560 * receive the peer's reply.
562 * However, it is valid to close the SSL connection after the initial
563 * shutdown notification is sent to the peer, without waiting for the
564 * peer's reply, as long as you do not plan to re-use that particular
565 * SSL connection object.
567 * Because we do not re-use SSL connection objects, I do not bother
568 * calling SSL_shutdown a second time.
570 * In addition, if the underlying socket is blocking, SSL_shutdown()
571 * will not return until the current stage of the shutdown process has
572 * completed or an error has occured. By setting the socket blocking
573 * we can avoid the ugly for()/switch()/select() loop.
578 /* Set socket blocking for shutdown */
579 flags = bnet_set_blocking(bsock);
581 err = SSL_shutdown(bsock->tls->openssl);
583 switch (SSL_get_error(bsock->tls->openssl, err)) {
586 case SSL_ERROR_ZERO_RETURN:
587 /* TLS connection was shut down on us via a TLS protocol-level closure */
588 openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
591 /* Socket Error Occured */
592 openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
596 /* Restore saved flags */
597 bnet_restore_blocking(bsock, flags);
600 /* Does all the manual labor for tls_bsock_readn() and tls_bsock_writen() */
601 static inline int openssl_bsock_readwrite(BSOCK *bsock, char *ptr, int nbytes, bool write)
603 TLS_CONNECTION *tls = bsock->tls;
610 /* Zero the fdset, we'll set our fd prior to each invocation of select() */
614 fdmax = bsock->fd + 1;
616 /* Ensure that socket is non-blocking */
617 flags = bnet_set_nonblocking(bsock);
620 bsock->timer_start = watchdog_time;
621 bsock->timed_out = 0;
628 nwritten = SSL_write(tls->openssl, ptr, nleft);
630 nwritten = SSL_read(tls->openssl, ptr, nleft);
634 switch (SSL_get_error(tls->openssl, nwritten)) {
641 case SSL_ERROR_ZERO_RETURN:
642 /* TLS connection was cleanly shut down */
643 openssl_post_errors(M_ERROR, _("TLS read/write failure."));
645 case SSL_ERROR_WANT_READ:
646 /* If we timeout of a select, this will be unset */
647 FD_SET((unsigned) bsock->fd, &fdset);
648 /* Block until we can read */
649 select(fdmax, &fdset, NULL, &fdset, &tv);
651 case SSL_ERROR_WANT_WRITE:
652 /* If we timeout of a select, this will be unset */
653 FD_SET((unsigned) bsock->fd, &fdset);
654 /* Block until we can write */
655 select(fdmax, NULL, &fdset, &fdset, &tv);
658 /* Socket Error Occured */
659 openssl_post_errors(M_ERROR, _("TLS read/write failure."));
663 /* Everything done? */
668 /* Timeout/Termination, let's take what we can get */
669 if (bsock->timed_out || bsock->terminated) {
675 /* Restore saved flags */
676 bnet_restore_blocking(bsock, flags);
679 bsock->timer_start = 0;
681 return nbytes - nleft;
685 int tls_bsock_writen(BSOCK *bsock, char *ptr, int32_t nbytes) {
686 /* SSL_write(bsock->tls->openssl, ptr, nbytes) */
687 return (openssl_bsock_readwrite(bsock, ptr, nbytes, true));
690 int tls_bsock_readn(BSOCK *bsock, char *ptr, int32_t nbytes) {
691 /* SSL_read(bsock->tls->openssl, ptr, nbytes) */
692 return (openssl_bsock_readwrite(bsock, ptr, nbytes, false));
696 * Return an OpenSSL thread ID
700 static unsigned long get_openssl_thread_id (void)
702 /* Comparison without use of pthread_equal() is mandated by the OpenSSL API */
703 return ((unsigned long) pthread_self());
707 * Allocate a dynamic OpenSSL mutex
709 static struct CRYPTO_dynlock_value *openssl_create_dynamic_mutex (const char *file, int line)
711 struct CRYPTO_dynlock_value *dynlock;
714 dynlock = (struct CRYPTO_dynlock_value *) malloc(sizeof(struct CRYPTO_dynlock_value));
716 if ((stat = pthread_mutex_init(&dynlock->mutex, NULL)) != 0) {
717 Emsg1(M_ABORT, 0, _("Unable to init mutex: ERR=%s\n"), strerror(stat));
723 static void openssl_update_dynamic_mutex (int mode, struct CRYPTO_dynlock_value *dynlock, const char *file, int line)
725 if (mode & CRYPTO_LOCK) {
732 static void openssl_destroy_dynamic_mutex (struct CRYPTO_dynlock_value *dynlock, const char *file, int line)
736 if ((stat = pthread_mutex_destroy(&dynlock->mutex)) != 0) {
737 Emsg1(M_ABORT, 0, _("Unable to destroy mutex: ERR=%s\n"), strerror(stat));
744 * (Un)Lock a static OpenSSL mutex
746 static void openssl_update_static_mutex (int mode, int i, const char *file, int line)
748 if (mode & CRYPTO_LOCK) {
756 * Initialize OpenSSL thread support
757 * Returns: 0 on success
760 static int openssl_init_threads (void)
766 /* Set thread ID callback */
767 CRYPTO_set_id_callback(get_openssl_thread_id);
769 /* Initialize static locking */
770 numlocks = CRYPTO_num_locks();
771 mutexes = (pthread_mutex_t *) malloc(numlocks * sizeof(pthread_mutex_t));
772 for (i = 0; i < numlocks; i++) {
773 if ((stat = pthread_mutex_init(&mutexes[i], NULL)) != 0) {
774 Emsg1(M_ERROR, 0, _("Unable to init mutex: ERR=%s\n"), strerror(stat));
779 /* Set static locking callback */
780 CRYPTO_set_locking_callback(openssl_update_static_mutex);
782 /* Initialize dyanmic locking */
783 CRYPTO_set_dynlock_create_callback(openssl_create_dynamic_mutex);
784 CRYPTO_set_dynlock_lock_callback(openssl_update_dynamic_mutex);
785 CRYPTO_set_dynlock_destroy_callback(openssl_destroy_dynamic_mutex);
791 * Clean up OpenSSL threading support
793 static void openssl_cleanup_threads (void)
798 /* Unset thread ID callback */
799 CRYPTO_set_id_callback(NULL);
801 /* Deallocate static lock mutexes */
802 numlocks = CRYPTO_num_locks();
803 for (i = 0; i < numlocks; i++) {
804 if ((stat = pthread_mutex_destroy(&mutexes[i])) != 0) {
805 /* We don't halt execution, reporting the error should be sufficient */
806 Emsg1(M_ERROR, 0, _("Unable to destroy mutex: ERR=%s\n"), strerror(stat));
810 /* Unset static locking callback */
811 CRYPTO_set_locking_callback(NULL);
813 /* Free static lock array */
816 /* Unset dynamic locking callbacks */
817 CRYPTO_set_dynlock_create_callback(NULL);
818 CRYPTO_set_dynlock_lock_callback(NULL);
819 CRYPTO_set_dynlock_destroy_callback(NULL);
825 * Returns: 1 on success
828 static int seed_tls_prng (void)
830 const char *names[] = { "/dev/urandom", "/dev/random", NULL };
835 // Read saved entropy?
837 for (i = 0; names[i]; i++) {
838 if (RAND_load_file(names[i], 1024) != -1) {
850 * Returns: 1 on success
853 static int save_tls_prng (void)
856 // Implement PRNG state save
861 * Perform global initialization of TLS
862 * This function is not thread safe.
863 * Returns: 0 on success
870 if ((stat = openssl_init_threads()) != 0) {
871 Emsg1(M_ABORT, 0, _("Unable to init OpenSSL threading: ERR=%s\n"), strerror(stat));
874 /* Load libssl and libcrypto human-readable error strings */
875 SSL_load_error_strings();
877 /* Register OpenSSL ciphers */
880 if (!seed_tls_prng()) {
881 Emsg0(M_ERROR_TERM, 0, _("Failed to seed OpenSSL PRNG\n"));
884 tls_initialized = true;
890 * Perform global cleanup of TLS
891 * All TLS connections must be closed before calling this function.
892 * This function is not thread safe.
893 * Returns: 0 on success
896 int cleanup_tls (void)
899 * Ensure that we've actually been initialized; Doing this here decreases the
900 * complexity of client's termination/cleanup code.
902 if (!tls_initialized) {
906 if (!save_tls_prng()) {
907 Emsg0(M_ERROR, 0, _("Failed to save OpenSSL PRNG\n"));
910 openssl_cleanup_threads();
912 /* Free libssl and libcrypto error strings */
915 /* Free memory used by PRNG */
918 tls_initialized = false;
923 #else /* HAVE_OPENSSL */
924 # error No TLS implementation available.
925 #endif /* !HAVE_OPENSSL */
930 int init_tls(void) { return 0; }
931 int cleanup_tls (void) { return 0; }
932 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
933 const char *certfile, const char *keyfile,
934 TLS_PEM_PASSWD_CB *pem_callback,
935 const void *pem_userdata, const char *dhfile,
940 void free_tls_context(TLS_CONTEXT *ctx) { }
942 #endif /* HAVE_TLS */