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 /* 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 /* TLS Context Structure */
54 CRYPTO_PEM_PASSWD_CB *pem_callback;
55 const void *pem_userdata;
60 struct TLS_Connection {
62 pthread_mutex_t wlock; /* make openssl_bsock_readwrite() atomic when writing */
63 pthread_mutex_t rwlock; /* only one SSL_read() or SSL_write() at a time */
67 * OpenSSL certificate verification callback.
68 * OpenSSL has already performed internal certificate verification.
69 * We just report any errors that occured.
71 static int openssl_verify_peer(int ok, X509_STORE_CTX *store)
74 X509 *cert = X509_STORE_CTX_get_current_cert(store);
75 int depth = X509_STORE_CTX_get_error_depth(store);
76 int err = X509_STORE_CTX_get_error(store);
80 X509_NAME_oneline(X509_get_issuer_name(cert), issuer, 256);
81 X509_NAME_oneline(X509_get_subject_name(cert), subject, 256);
83 Jmsg5(NULL, M_ERROR, 0, _("Error with certificate at depth: %d, issuer = %s,"
84 " subject = %s, ERR=%d:%s\n"), depth, issuer,
85 subject, err, X509_verify_cert_error_string(err));
92 /* Dispatch user PEM encryption callbacks */
93 static int tls_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
95 TLS_CONTEXT *ctx = (TLS_CONTEXT *)userdata;
96 return (ctx->pem_callback(buf, size, ctx->pem_userdata));
100 * Create a new TLS_CONTEXT instance.
101 * Returns: Pointer to TLS_CONTEXT instance on success
104 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
105 const char *certfile, const char *keyfile,
106 CRYPTO_PEM_PASSWD_CB *pem_callback,
107 const void *pem_userdata, const char *dhfile,
114 ctx = (TLS_CONTEXT *)malloc(sizeof(TLS_CONTEXT));
116 /* Allocate our OpenSSL TLS Context */
117 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
118 /* Allows SSLv3, TLSv1, TLSv1.1 and TLSv1.2 protocols */
119 ctx->openssl = SSL_CTX_new(TLS_method());
121 #elif (OPENSSL_VERSION_NUMBER >= 0x10000000L)
122 /* Allows most all protocols */
123 ctx->openssl = SSL_CTX_new(SSLv23_method());
126 /* Older method only understands TLSv1 */
127 ctx->openssl = SSL_CTX_new(TLSv1_method());
130 /* Use SSL_OP_ALL to turn on all "rather harmless" workarounds that
133 SSL_CTX_set_options(ctx->openssl, SSL_OP_ALL);
135 /* Now disable old broken SSLv3 and SSLv2 protocols */
136 SSL_CTX_set_options(ctx->openssl, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
139 openssl_post_errors(M_FATAL, _("Error initializing SSL context"));
143 /* Set up pem encryption callback */
145 ctx->pem_callback = pem_callback;
146 ctx->pem_userdata = pem_userdata;
148 ctx->pem_callback = crypto_default_pem_callback;
149 ctx->pem_userdata = NULL;
151 SSL_CTX_set_default_passwd_cb(ctx->openssl, tls_pem_callback_dispatch);
152 SSL_CTX_set_default_passwd_cb_userdata(ctx->openssl, (void *) ctx);
155 * Set certificate verification paths. This requires that at least one
158 if (ca_certfile || ca_certdir) {
159 if (!SSL_CTX_load_verify_locations(ctx->openssl, ca_certfile, ca_certdir)) {
160 openssl_post_errors(M_FATAL, _("Error loading certificate verification stores"));
163 } else if (verify_peer) {
164 /* At least one CA is required for peer verification */
165 Jmsg0(NULL, M_ERROR, 0, _("Either a certificate file or a directory must be"
166 " specified as a verification store\n"));
171 * Load our certificate file, if available. This file may also contain a
172 * private key, though this usage is somewhat unusual.
175 if (!SSL_CTX_use_certificate_chain_file(ctx->openssl, certfile)) {
176 openssl_post_errors(M_FATAL, _("Error loading certificate file"));
181 /* Load our private key. */
183 if (!SSL_CTX_use_PrivateKey_file(ctx->openssl, keyfile, SSL_FILETYPE_PEM)) {
184 openssl_post_errors(M_FATAL, _("Error loading private key"));
189 /* Load Diffie-Hellman Parameters. */
191 if (!(bio = BIO_new_file(dhfile, "r"))) {
192 openssl_post_errors(M_FATAL, _("Unable to open DH parameters file"));
195 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
198 openssl_post_errors(M_FATAL, _("Unable to load DH parameters from specified file"));
201 if (!SSL_CTX_set_tmp_dh(ctx->openssl, dh)) {
202 openssl_post_errors(M_FATAL, _("Failed to set TLS Diffie-Hellman parameters"));
206 /* Enable Single-Use DH for Ephemeral Keying */
207 SSL_CTX_set_options(ctx->openssl, SSL_OP_SINGLE_DH_USE);
210 if (SSL_CTX_set_cipher_list(ctx->openssl, TLS_DEFAULT_CIPHERS) != 1) {
211 Jmsg0(NULL, M_ERROR, 0,
212 _("Error setting cipher list, no valid ciphers available\n"));
216 /* Verify Peer Certificate */
218 /* SSL_VERIFY_FAIL_IF_NO_PEER_CERT has no effect in client mode */
219 SSL_CTX_set_verify(ctx->openssl,
220 SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
221 openssl_verify_peer);
227 /* Clean up after ourselves */
229 SSL_CTX_free(ctx->openssl);
236 * Free TLS_CONTEXT instance
238 void free_tls_context(TLS_CONTEXT *ctx)
240 SSL_CTX_free(ctx->openssl);
244 bool get_tls_require(TLS_CONTEXT *ctx)
246 return ctx->tls_require;
249 bool get_tls_enable(TLS_CONTEXT *ctx)
251 return ctx->tls_enable;
256 * Verifies a list of common names against the certificate
257 * commonName attribute.
258 * Returns: true on success
261 bool tls_postconnect_verify_cn(JCR *jcr, TLS_CONNECTION *tls, alist *verify_list)
263 SSL *ssl = tls->openssl;
266 bool auth_success = false;
269 /* Check if peer provided a certificate */
270 if (!(cert = SSL_get_peer_certificate(ssl))) {
271 Qmsg0(jcr, M_ERROR, 0, _("Peer failed to present a TLS certificate\n"));
275 if ((subject = X509_get_subject_name(cert)) != NULL) {
276 if (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) > 0) {
278 /* NULL terminate data */
281 /* Try all the CNs in the list */
282 foreach_alist(cn, verify_list) {
283 if (strcasecmp(data, cn) == 0) {
295 * Verifies a peer's hostname against the subjectAltName and commonName
297 * Returns: true on success
300 bool tls_postconnect_verify_host(JCR *jcr, TLS_CONNECTION *tls, const char *host)
302 SSL *ssl = tls->openssl;
305 bool auth_success = false;
308 const char *pval, *phost;
311 X509_NAME_ENTRY *neCN;
314 /* Check if peer provided a certificate */
315 if (!(cert = SSL_get_peer_certificate(ssl))) {
316 Qmsg1(jcr, M_ERROR, 0,
317 _("Peer %s failed to present a TLS certificate\n"), host);
318 Dmsg1(250, _("Peer %s failed to present a TLS certificate\n"), host);
322 /* Check subjectAltName extensions first */
323 if ((extensions = X509_get_ext_count(cert)) > 0) {
324 for (i = 0; i < extensions; i++) {
328 ext = X509_get_ext(cert, i);
329 extname = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
331 if (strcmp(extname, "subjectAltName") == 0) {
332 #ifdef HAVE_OPENSSLv1
333 const X509V3_EXT_METHOD *method;
335 X509V3_EXT_METHOD *method;
337 STACK_OF(CONF_VALUE) *val;
340 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
341 const unsigned char *ext_value_data;
343 unsigned char *ext_value_data;
346 /* Get x509 extension method structure */
347 if (!(method = X509V3_EXT_get(ext))) {
351 ext_value_data = ext->value->data;
353 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
357 /* Decode ASN1 item in data */
358 extstr = ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
359 ASN1_ITEM_ptr(method->it));
363 /* Decode ASN1 item in data */
364 extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
368 extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
371 /* Iterate through to find the dNSName field(s) */
372 val = method->i2v(method, extstr, NULL);
374 /* dNSName shortname is "DNS" */
375 Dmsg0(250, "Check DNS name\n");
376 for (j = 0; j < sk_CONF_VALUE_num(val); j++) {
377 nval = sk_CONF_VALUE_value(val, j);
378 if (strcmp(nval->name, "DNS") == 0) {
379 if (strncasecmp(nval->value, "*.", 2) == 0) {
380 Dmsg0(250, "Wildcard Certificate\n");
381 pval = strstr(nval->value, ".");
382 phost = strstr(host, ".");
383 if (pval && phost && (strcasecmp(pval, phost) == 0)) {
387 } else if (strcasecmp(nval->value, host) == 0) {
391 Dmsg2(250, "No DNS name match. Host=%s cert=%s\n", host, nval->value);
398 /* Try verifying against the subject name */
400 Dmsg0(250, "Check subject name name\n");
401 if ((subject = X509_get_subject_name(cert)) != NULL) {
402 /* Loop through all CNs */
404 cnLastPos = X509_NAME_get_index_by_NID(subject, NID_commonName, cnLastPos);
405 if (cnLastPos == -1) {
408 neCN = X509_NAME_get_entry(subject, cnLastPos);
409 asn1CN = X509_NAME_ENTRY_get_data(neCN);
410 if (strncasecmp((const char*)asn1CN->data, "*.", 2) == 0) {
411 /* wildcard certificate */
412 Dmsg0(250, "Wildcard Certificate\n");
413 pval = strstr((const char*)asn1CN->data, ".");
414 phost = strstr(host, ".");
415 if (pval && phost && (strcasecmp(pval, phost) == 0)) {
419 } else if (strcasecmp((const char*)asn1CN->data, host) == 0) {
423 Dmsg2(250, "No subject name match. Host=%s cert=%s\n", host, (const char*)asn1CN->data);
434 * Create a new TLS_CONNECTION instance.
436 * Returns: Pointer to TLS_CONNECTION instance on success
439 TLS_CONNECTION *new_tls_connection(TLS_CONTEXT *ctx, int fd)
444 * Create a new BIO and assign the fd.
445 * The caller will remain responsible for closing the associated fd
447 bio = BIO_new(BIO_s_socket());
449 /* Not likely, but never say never */
450 openssl_post_errors(M_FATAL, _("Error creating file descriptor-based BIO"));
451 return NULL; /* Nothing allocated, nothing to clean up */
453 BIO_set_fd(bio, fd, BIO_NOCLOSE);
455 /* Allocate our new tls connection */
456 TLS_CONNECTION *tls = (TLS_CONNECTION *)malloc(sizeof(TLS_CONNECTION));
458 /* Create the SSL object and attach the socket BIO */
459 if ((tls->openssl = SSL_new(ctx->openssl)) == NULL) {
460 /* Not likely, but never say never */
461 openssl_post_errors(M_FATAL, _("Error creating new SSL object"));
465 SSL_set_bio(tls->openssl, bio, bio);
467 /* Non-blocking partial writes */
468 SSL_set_mode(tls->openssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
470 pthread_mutex_init(&tls->wlock, NULL);
471 pthread_mutex_init(&tls->rwlock, NULL);
478 SSL_free(tls->openssl);
484 * Free TLS_CONNECTION instance
486 void free_tls_connection(TLS_CONNECTION *tls)
488 pthread_mutex_destroy(&tls->rwlock);
489 pthread_mutex_destroy(&tls->wlock);
490 SSL_free(tls->openssl);
494 /* Does all the manual labor for tls_bsock_accept() and tls_bsock_connect() */
495 static inline bool openssl_bsock_session_start(BSOCK *bsock, bool server)
497 TLS_CONNECTION *tls = bsock->tls;
502 /* Ensure that socket is non-blocking */
503 flags = bsock->set_nonblocking();
506 bsock->timer_start = watchdog_time;
507 bsock->clear_timed_out();
508 bsock->set_killable(false);
512 err = SSL_accept(tls->openssl);
514 err = SSL_connect(tls->openssl);
518 switch (SSL_get_error(tls->openssl, err)) {
522 case SSL_ERROR_ZERO_RETURN:
523 /* TLS connection was cleanly shut down */
524 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
527 case SSL_ERROR_WANT_READ:
528 /* Block until we can read */
529 fd_wait_data(bsock->m_fd, WAIT_READ, 10, 0);
531 case SSL_ERROR_WANT_WRITE:
532 /* Block until we can write */
533 fd_wait_data(bsock->m_fd, WAIT_WRITE, 10, 0);
536 /* Socket Error Occurred */
537 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
542 if (bsock->is_timed_out()) {
548 /* Restore saved flags */
549 bsock->restore_blocking(flags);
551 bsock->timer_start = 0;
552 bsock->set_killable(true);
558 * Initiates a TLS connection with the server.
559 * Returns: true on success
562 bool tls_bsock_connect(BSOCK *bsock)
564 /* SSL_connect(bsock->tls) */
565 return openssl_bsock_session_start(bsock, false);
569 * Listens for a TLS connection from a client.
570 * Returns: true on success
573 bool tls_bsock_accept(BSOCK *bsock)
575 /* SSL_accept(bsock->tls) */
576 return openssl_bsock_session_start(bsock, true);
580 * Shutdown TLS_CONNECTION instance
582 void tls_bsock_shutdown(BSOCK *bsock)
585 * SSL_shutdown must be called twice to fully complete the process -
586 * The first time to initiate the shutdown handshake, and the second to
587 * receive the peer's reply.
589 * In addition, if the underlying socket is blocking, SSL_shutdown()
590 * will not return until the current stage of the shutdown process has
591 * completed or an error has occured. By setting the socket blocking
592 * we can avoid the ugly for()/switch()/select() loop.
598 /* Set socket blocking for shutdown */
599 bsock->set_blocking();
601 tid = start_bsock_timer(bsock, 60 * 2);
602 err = SSL_shutdown(bsock->tls->openssl);
603 stop_bsock_timer(tid);
605 /* Complete shutdown */
606 tid = start_bsock_timer(bsock, 60 * 2);
607 err = SSL_shutdown(bsock->tls->openssl);
608 stop_bsock_timer(tid);
612 switch (SSL_get_error(bsock->tls->openssl, err)) {
615 case SSL_ERROR_ZERO_RETURN:
616 /* TLS connection was shut down on us via a TLS protocol-level closure */
617 openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
620 /* Socket Error Occurred */
621 openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
626 /* Does all the manual labor for tls_bsock_readn() and tls_bsock_writen() */
627 static inline int openssl_bsock_readwrite(BSOCK *bsock, char *ptr, int nbytes, bool write)
629 TLS_CONNECTION *tls = bsock->tls;
634 /* Ensure that socket is non-blocking */
635 flags = bsock->set_nonblocking();
638 bsock->timer_start = watchdog_time;
639 bsock->clear_timed_out();
640 bsock->set_killable(false);
645 pthread_mutex_lock(&tls->wlock);
649 pthread_mutex_lock(&tls->rwlock);
651 nwritten = SSL_write(tls->openssl, ptr, nleft);
653 nwritten = SSL_read(tls->openssl, ptr, nleft);
655 pthread_mutex_unlock(&tls->rwlock);
658 switch (SSL_get_error(tls->openssl, nwritten)) {
666 case SSL_ERROR_SYSCALL:
667 if (nwritten == -1) {
668 if (errno == EINTR) {
671 if (errno == EAGAIN) {
672 bmicrosleep(0, 20000); /* try again in 20 ms */
676 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
679 case SSL_ERROR_WANT_READ:
680 /* Block until we can read */
681 fd_wait_data(bsock->m_fd, WAIT_READ, 10, 0);
684 case SSL_ERROR_WANT_WRITE:
685 /* Block until we can read */
686 fd_wait_data(bsock->m_fd, WAIT_WRITE, 10, 0);
689 case SSL_ERROR_ZERO_RETURN:
690 /* TLS connection was cleanly shut down */
691 /* Fall through wanted */
693 /* Socket Error Occured */
694 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
698 /* Everything done? */
703 /* Timeout/Termination, let's take what we can get */
704 if (bsock->is_timed_out() || bsock->is_terminated()) {
711 pthread_mutex_unlock(&tls->wlock);
713 /* Restore saved flags */
714 bsock->restore_blocking(flags);
717 bsock->timer_start = 0;
718 bsock->set_killable(true);
719 return nbytes - nleft;
723 int tls_bsock_writen(BSOCK *bsock, char *ptr, int32_t nbytes)
725 /* SSL_write(bsock->tls->openssl, ptr, nbytes) */
726 return openssl_bsock_readwrite(bsock, ptr, nbytes, true);
729 int tls_bsock_readn(BSOCK *bsock, char *ptr, int32_t nbytes)
731 /* SSL_read(bsock->tls->openssl, ptr, nbytes) */
732 return openssl_bsock_readwrite(bsock, ptr, nbytes, false);
735 /* test if 4 bytes can be read without "blocking" */
736 bool tls_bsock_probe(BSOCK *bsock)
739 return SSL_peek(bsock->tls->openssl, &pktsiz, sizeof(pktsiz))==sizeof(pktsiz);
743 #else /* HAVE_OPENSSL */
744 # error No TLS implementation available.
745 #endif /* !HAVE_OPENSSL */
748 #else /* TLS NOT enabled, dummy routines substituted */
752 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
753 const char *certfile, const char *keyfile,
754 CRYPTO_PEM_PASSWD_CB *pem_callback,
755 const void *pem_userdata, const char *dhfile,
760 void free_tls_context(TLS_CONTEXT *ctx) { }
762 void tls_bsock_shutdown(BSOCK *bsock) { }
764 void free_tls_connection(TLS_CONNECTION *tls) { }
766 bool get_tls_require(TLS_CONTEXT *ctx)
771 bool get_tls_enable(TLS_CONTEXT *ctx)
776 #endif /* HAVE_TLS */