2 Bacula(R) - The Network Backup Solution
4 Copyright (C) 2000-2017 Kern Sibbald
6 The original author of Bacula is Kern Sibbald, with contributions
7 from many others, a complete list can be found in the file AUTHORS.
9 You may use this file and others of this release according to the
10 license defined in the LICENSE file, which includes the Affero General
11 Public License, v3.0 ("AGPLv3") and some additional permissions and
12 terms pursuant to its AGPLv3 Section 7.
14 This notice must be preserved when any source code is
15 conveyed and/or propagated.
17 Bacula(R) is a registered trademark of Kern Sibbald.
20 * tls.c TLS support functions
22 * Author: Landon Fuller <landonf@threerings.net>
24 * This file was contributed to the Bacula project by Landon Fuller
25 * and Three Rings Design, Inc.
27 * Three Rings Design, Inc. has been granted a perpetual, worldwide,
28 * non-exclusive, no-charge, royalty-free, irrevocable copyright
29 * license to reproduce, prepare derivative works of, publicly
30 * display, publicly perform, sublicense, and distribute the original
31 * work contributed by Three Rings Design, Inc. and its employees to
32 * the Bacula project in source or object form.
34 * If you wish to license contributions from Three Rings Design, Inc,
35 * under an alternate open source license please contact
36 * Landon Fuller <landonf@threerings.net>.
44 #ifdef HAVE_TLS /* Is TLS enabled? */
46 #ifdef HAVE_OPENSSL /* How about OpenSSL? */
48 #include "openssl-compat.h"
50 /* No anonymous ciphers, no <128 bit ciphers, no export ciphers, no MD5 ciphers */
51 #define TLS_DEFAULT_CIPHERS "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
53 /* TLS Context Structure */
56 CRYPTO_PEM_PASSWD_CB *pem_callback;
57 const void *pem_userdata;
62 struct TLS_Connection {
64 pthread_mutex_t wlock; /* make openssl_bsock_readwrite() atomic when writing */
65 pthread_mutex_t rwlock; /* only one SSL_read() or SSL_write() at a time */
69 * OpenSSL certificate verification callback.
70 * OpenSSL has already performed internal certificate verification.
71 * We just report any errors that occured.
73 static int openssl_verify_peer(int ok, X509_STORE_CTX *store)
76 X509 *cert = X509_STORE_CTX_get_current_cert(store);
77 int depth = X509_STORE_CTX_get_error_depth(store);
78 int err = X509_STORE_CTX_get_error(store);
82 X509_NAME_oneline(X509_get_issuer_name(cert), issuer, 256);
83 X509_NAME_oneline(X509_get_subject_name(cert), subject, 256);
85 Jmsg5(NULL, M_ERROR, 0, _("Error with certificate at depth: %d, issuer = %s,"
86 " subject = %s, ERR=%d:%s\n"), depth, issuer,
87 subject, err, X509_verify_cert_error_string(err));
94 /* Dispatch user PEM encryption callbacks */
95 static int tls_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
97 TLS_CONTEXT *ctx = (TLS_CONTEXT *)userdata;
98 return (ctx->pem_callback(buf, size, ctx->pem_userdata));
102 * Create a new TLS_CONTEXT instance.
103 * Returns: Pointer to TLS_CONTEXT instance on success
106 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
107 const char *certfile, const char *keyfile,
108 CRYPTO_PEM_PASSWD_CB *pem_callback,
109 const void *pem_userdata, const char *dhfile,
116 ctx = (TLS_CONTEXT *)malloc(sizeof(TLS_CONTEXT));
118 /* Allocate our OpenSSL TLS Context */
119 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
120 /* Allows SSLv3, TLSv1, TLSv1.1 and TLSv1.2 protocols */
121 ctx->openssl = SSL_CTX_new(TLS_method());
124 /* Allows most all protocols */
125 ctx->openssl = SSL_CTX_new(SSLv23_method());
129 /* Use SSL_OP_ALL to turn on all "rather harmless" workarounds that
132 SSL_CTX_set_options(ctx->openssl, SSL_OP_ALL);
134 /* Now disable old broken SSLv3 and SSLv2 protocols */
135 SSL_CTX_set_options(ctx->openssl, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
138 openssl_post_errors(M_FATAL, _("Error initializing SSL context"));
142 /* Set up pem encryption callback */
144 ctx->pem_callback = pem_callback;
145 ctx->pem_userdata = pem_userdata;
147 ctx->pem_callback = crypto_default_pem_callback;
148 ctx->pem_userdata = NULL;
150 SSL_CTX_set_default_passwd_cb(ctx->openssl, tls_pem_callback_dispatch);
151 SSL_CTX_set_default_passwd_cb_userdata(ctx->openssl, (void *) ctx);
154 * Set certificate verification paths. This requires that at least one
157 if (ca_certfile || ca_certdir) {
158 if (!SSL_CTX_load_verify_locations(ctx->openssl, ca_certfile, ca_certdir)) {
159 openssl_post_errors(M_FATAL, _("Error loading certificate verification stores"));
162 } else if (verify_peer) {
163 /* At least one CA is required for peer verification */
164 Jmsg0(NULL, M_ERROR, 0, _("Either a certificate file or a directory must be"
165 " specified as a verification store\n"));
170 * Load our certificate file, if available. This file may also contain a
171 * private key, though this usage is somewhat unusual.
174 if (!SSL_CTX_use_certificate_chain_file(ctx->openssl, certfile)) {
175 openssl_post_errors(M_FATAL, _("Error loading certificate file"));
180 /* Load our private key. */
182 if (!SSL_CTX_use_PrivateKey_file(ctx->openssl, keyfile, SSL_FILETYPE_PEM)) {
183 openssl_post_errors(M_FATAL, _("Error loading private key"));
188 /* Load Diffie-Hellman Parameters. */
190 if (!(bio = BIO_new_file(dhfile, "r"))) {
191 openssl_post_errors(M_FATAL, _("Unable to open DH parameters file"));
194 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
197 openssl_post_errors(M_FATAL, _("Unable to load DH parameters from specified file"));
200 if (!SSL_CTX_set_tmp_dh(ctx->openssl, dh)) {
201 openssl_post_errors(M_FATAL, _("Failed to set TLS Diffie-Hellman parameters"));
205 /* Enable Single-Use DH for Ephemeral Keying */
206 SSL_CTX_set_options(ctx->openssl, SSL_OP_SINGLE_DH_USE);
209 if (SSL_CTX_set_cipher_list(ctx->openssl, TLS_DEFAULT_CIPHERS) != 1) {
210 Jmsg0(NULL, M_ERROR, 0,
211 _("Error setting cipher list, no valid ciphers available\n"));
215 /* Verify Peer Certificate */
217 /* SSL_VERIFY_FAIL_IF_NO_PEER_CERT has no effect in client mode */
218 SSL_CTX_set_verify(ctx->openssl,
219 SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
220 openssl_verify_peer);
226 /* Clean up after ourselves */
228 SSL_CTX_free(ctx->openssl);
235 * Free TLS_CONTEXT instance
237 void free_tls_context(TLS_CONTEXT *ctx)
239 SSL_CTX_free(ctx->openssl);
243 bool get_tls_require(TLS_CONTEXT *ctx)
245 return ctx->tls_require;
248 bool get_tls_enable(TLS_CONTEXT *ctx)
250 return ctx->tls_enable;
255 * Verifies a list of common names against the certificate
256 * commonName attribute.
257 * Returns: true on success
260 bool tls_postconnect_verify_cn(JCR *jcr, TLS_CONNECTION *tls, alist *verify_list)
262 SSL *ssl = tls->openssl;
265 bool auth_success = false;
268 /* Check if peer provided a certificate */
269 if (!(cert = SSL_get_peer_certificate(ssl))) {
270 Qmsg0(jcr, M_ERROR, 0, _("Peer failed to present a TLS certificate\n"));
274 if ((subject = X509_get_subject_name(cert)) != NULL) {
275 if (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) > 0) {
277 /* NULL terminate data */
280 /* Try all the CNs in the list */
281 foreach_alist(cn, verify_list) {
282 if (strcasecmp(data, cn) == 0) {
294 * Verifies a peer's hostname against the subjectAltName and commonName
296 * Returns: true on success
299 bool tls_postconnect_verify_host(JCR *jcr, TLS_CONNECTION *tls, const char *host)
301 SSL *ssl = tls->openssl;
304 bool auth_success = false;
307 const char *pval, *phost;
310 X509_NAME_ENTRY *neCN;
313 /* Check if peer provided a certificate */
314 if (!(cert = SSL_get_peer_certificate(ssl))) {
315 Qmsg1(jcr, M_ERROR, 0,
316 _("Peer %s failed to present a TLS certificate\n"), host);
317 Dmsg1(250, _("Peer %s failed to present a TLS certificate\n"), host);
321 /* Check subjectAltName extensions first */
322 if ((extensions = X509_get_ext_count(cert)) > 0) {
323 for (i = 0; i < extensions; i++) {
327 ext = X509_get_ext(cert, i);
328 extname = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
330 if (strcmp(extname, "subjectAltName") == 0) {
331 #ifdef HAVE_OPENSSLv1
332 const X509V3_EXT_METHOD *method;
334 X509V3_EXT_METHOD *method;
336 STACK_OF(CONF_VALUE) *val;
339 const unsigned char *ext_value_data;
340 const ASN1_STRING *asn1_ext_val;
342 /* Get x509 extension method structure */
343 if (!(method = X509V3_EXT_get(ext))) {
347 asn1_ext_val = X509_EXTENSION_get_data(ext);
348 ext_value_data = ASN1_STRING_get0_data(asn1_ext_val);
353 /* Decode ASN1 item in data */
354 extstr = ASN1_item_d2i(NULL, &ext_value_data, ASN1_STRING_length(asn1_ext_val),
355 ASN1_ITEM_ptr(method->it));
359 /* Decode ASN1 item in data */
360 extstr = method->d2i(NULL, &ext_value_data, ASN1_STRING_length(asn1_ext_val));
363 /* Iterate through to find the dNSName field(s) */
364 val = method->i2v(method, extstr, NULL);
366 /* dNSName shortname is "DNS" */
367 Dmsg0(250, "Check DNS name\n");
368 for (j = 0; j < sk_CONF_VALUE_num(val); j++) {
369 nval = sk_CONF_VALUE_value(val, j);
370 if (strcmp(nval->name, "DNS") == 0) {
371 if (strncasecmp(nval->value, "*.", 2) == 0) {
372 Dmsg0(250, "Wildcard Certificate\n");
373 pval = strstr(nval->value, ".");
374 phost = strstr(host, ".");
375 if (pval && phost && (strcasecmp(pval, phost) == 0)) {
379 } else if (strcasecmp(nval->value, host) == 0) {
383 Dmsg2(250, "No DNS name match. Host=%s cert=%s\n", host, nval->value);
390 /* Try verifying against the subject name */
392 Dmsg0(250, "Check subject name name\n");
393 if ((subject = X509_get_subject_name(cert)) != NULL) {
394 /* Loop through all CNs */
396 cnLastPos = X509_NAME_get_index_by_NID(subject, NID_commonName, cnLastPos);
397 if (cnLastPos == -1) {
400 neCN = X509_NAME_get_entry(subject, cnLastPos);
401 asn1CN = X509_NAME_ENTRY_get_data(neCN);
402 if (strncasecmp((const char*)asn1CN->data, "*.", 2) == 0) {
403 /* wildcard certificate */
404 Dmsg0(250, "Wildcard Certificate\n");
405 pval = strstr((const char*)asn1CN->data, ".");
406 phost = strstr(host, ".");
407 if (pval && phost && (strcasecmp(pval, phost) == 0)) {
411 } else if (strcasecmp((const char*)asn1CN->data, host) == 0) {
415 Dmsg2(250, "No subject name match. Host=%s cert=%s\n", host, (const char*)asn1CN->data);
426 * Create a new TLS_CONNECTION instance.
428 * Returns: Pointer to TLS_CONNECTION instance on success
431 TLS_CONNECTION *new_tls_connection(TLS_CONTEXT *ctx, int fd)
436 * Create a new BIO and assign the fd.
437 * The caller will remain responsible for closing the associated fd
439 bio = BIO_new(BIO_s_socket());
441 /* Not likely, but never say never */
442 openssl_post_errors(M_FATAL, _("Error creating file descriptor-based BIO"));
443 return NULL; /* Nothing allocated, nothing to clean up */
445 BIO_set_fd(bio, fd, BIO_NOCLOSE);
447 /* Allocate our new tls connection */
448 TLS_CONNECTION *tls = (TLS_CONNECTION *)malloc(sizeof(TLS_CONNECTION));
450 /* Create the SSL object and attach the socket BIO */
451 if ((tls->openssl = SSL_new(ctx->openssl)) == NULL) {
452 /* Not likely, but never say never */
453 openssl_post_errors(M_FATAL, _("Error creating new SSL object"));
457 SSL_set_bio(tls->openssl, bio, bio);
459 /* Non-blocking partial writes */
460 SSL_set_mode(tls->openssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
462 pthread_mutex_init(&tls->wlock, NULL);
463 pthread_mutex_init(&tls->rwlock, NULL);
470 SSL_free(tls->openssl);
476 * Free TLS_CONNECTION instance
478 void free_tls_connection(TLS_CONNECTION *tls)
480 pthread_mutex_destroy(&tls->rwlock);
481 pthread_mutex_destroy(&tls->wlock);
482 SSL_free(tls->openssl);
486 /* Does all the manual labor for tls_bsock_accept() and tls_bsock_connect() */
487 static inline bool openssl_bsock_session_start(BSOCK *bsock, bool server)
489 TLS_CONNECTION *tls = bsock->tls;
494 /* Ensure that socket is non-blocking */
495 flags = bsock->set_nonblocking();
498 bsock->timer_start = watchdog_time;
499 bsock->clear_timed_out();
500 bsock->set_killable(false);
504 err = SSL_accept(tls->openssl);
506 err = SSL_connect(tls->openssl);
510 switch (SSL_get_error(tls->openssl, err)) {
514 case SSL_ERROR_ZERO_RETURN:
515 /* TLS connection was cleanly shut down */
516 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
519 case SSL_ERROR_WANT_READ:
520 /* Block until we can read */
521 fd_wait_data(bsock->m_fd, WAIT_READ, 10, 0);
523 case SSL_ERROR_WANT_WRITE:
524 /* Block until we can write */
525 fd_wait_data(bsock->m_fd, WAIT_WRITE, 10, 0);
528 /* Socket Error Occurred */
529 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
534 if (bsock->is_timed_out()) {
540 /* Restore saved flags */
541 bsock->restore_blocking(flags);
543 bsock->timer_start = 0;
544 bsock->set_killable(true);
550 * Initiates a TLS connection with the server.
551 * Returns: true on success
554 bool tls_bsock_connect(BSOCK *bsock)
556 /* SSL_connect(bsock->tls) */
557 return openssl_bsock_session_start(bsock, false);
561 * Listens for a TLS connection from a client.
562 * Returns: true on success
565 bool tls_bsock_accept(BSOCK *bsock)
567 /* SSL_accept(bsock->tls) */
568 return openssl_bsock_session_start(bsock, true);
572 * Shutdown TLS_CONNECTION instance
574 void tls_bsock_shutdown(BSOCK *bsock)
577 * SSL_shutdown must be called twice to fully complete the process -
578 * The first time to initiate the shutdown handshake, and the second to
579 * receive the peer's reply.
581 * In addition, if the underlying socket is blocking, SSL_shutdown()
582 * will not return until the current stage of the shutdown process has
583 * completed or an error has occured. By setting the socket blocking
584 * we can avoid the ugly for()/switch()/select() loop.
590 /* Set socket blocking for shutdown */
591 bsock->set_blocking();
593 tid = start_bsock_timer(bsock, 60 * 2);
594 err = SSL_shutdown(bsock->tls->openssl);
595 stop_bsock_timer(tid);
597 /* Complete shutdown */
598 tid = start_bsock_timer(bsock, 60 * 2);
599 err = SSL_shutdown(bsock->tls->openssl);
600 stop_bsock_timer(tid);
604 switch (SSL_get_error(bsock->tls->openssl, err)) {
607 case SSL_ERROR_ZERO_RETURN:
608 /* TLS connection was shut down on us via a TLS protocol-level closure */
609 openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
612 /* Socket Error Occurred */
613 openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
618 /* Does all the manual labor for tls_bsock_readn() and tls_bsock_writen() */
619 static inline int openssl_bsock_readwrite(BSOCK *bsock, char *ptr, int nbytes, bool write)
621 TLS_CONNECTION *tls = bsock->tls;
626 /* Ensure that socket is non-blocking */
627 flags = bsock->set_nonblocking();
630 bsock->timer_start = watchdog_time;
631 bsock->clear_timed_out();
632 bsock->set_killable(false);
637 pthread_mutex_lock(&tls->wlock);
641 pthread_mutex_lock(&tls->rwlock);
643 nwritten = SSL_write(tls->openssl, ptr, nleft);
645 nwritten = SSL_read(tls->openssl, ptr, nleft);
647 pthread_mutex_unlock(&tls->rwlock);
650 switch (SSL_get_error(tls->openssl, nwritten)) {
658 case SSL_ERROR_SYSCALL:
659 if (nwritten == -1) {
660 if (errno == EINTR) {
663 if (errno == EAGAIN) {
664 bmicrosleep(0, 20000); /* try again in 20 ms */
668 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
671 case SSL_ERROR_WANT_READ:
672 /* Block until we can read */
673 fd_wait_data(bsock->m_fd, WAIT_READ, 10, 0);
676 case SSL_ERROR_WANT_WRITE:
677 /* Block until we can read */
678 fd_wait_data(bsock->m_fd, WAIT_WRITE, 10, 0);
681 case SSL_ERROR_ZERO_RETURN:
682 /* TLS connection was cleanly shut down */
683 /* Fall through wanted */
685 /* Socket Error Occured */
686 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
690 /* Everything done? */
695 /* Timeout/Termination, let's take what we can get */
696 if (bsock->is_timed_out() || bsock->is_terminated()) {
703 pthread_mutex_unlock(&tls->wlock);
705 /* Restore saved flags */
706 bsock->restore_blocking(flags);
709 bsock->timer_start = 0;
710 bsock->set_killable(true);
711 return nbytes - nleft;
715 int tls_bsock_writen(BSOCK *bsock, char *ptr, int32_t nbytes)
717 /* SSL_write(bsock->tls->openssl, ptr, nbytes) */
718 return openssl_bsock_readwrite(bsock, ptr, nbytes, true);
721 int tls_bsock_readn(BSOCK *bsock, char *ptr, int32_t nbytes)
723 /* SSL_read(bsock->tls->openssl, ptr, nbytes) */
724 return openssl_bsock_readwrite(bsock, ptr, nbytes, false);
727 /* test if 4 bytes can be read without "blocking" */
728 bool tls_bsock_probe(BSOCK *bsock)
731 return SSL_peek(bsock->tls->openssl, &pktsiz, sizeof(pktsiz))==sizeof(pktsiz);
735 #else /* HAVE_OPENSSL */
736 # error No TLS implementation available.
737 #endif /* !HAVE_OPENSSL */
740 #else /* TLS NOT enabled, dummy routines substituted */
744 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
745 const char *certfile, const char *keyfile,
746 CRYPTO_PEM_PASSWD_CB *pem_callback,
747 const void *pem_userdata, const char *dhfile,
752 void free_tls_context(TLS_CONTEXT *ctx) { }
754 void tls_bsock_shutdown(BSOCK *bsock) { }
756 void free_tls_connection(TLS_CONNECTION *tls) { }
758 bool get_tls_require(TLS_CONTEXT *ctx)
763 bool get_tls_enable(TLS_CONTEXT *ctx)
768 #endif /* HAVE_TLS */