2 Bacula® - The Network Backup Solution
4 Copyright (C) 2005-2014 Free Software Foundation Europe e.V.
6 The main author of Bacula is Kern Sibbald, with contributions from many
7 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 Bacula® is a registered trademark of Kern Sibbald.
17 * tls.c TLS support functions
19 * Author: Landon Fuller <landonf@threerings.net>
21 * This file was contributed to the Bacula project by Landon Fuller
22 * and Three Rings Design, Inc.
24 * Three Rings Design, Inc. has been granted a perpetual, worldwide,
25 * non-exclusive, no-charge, royalty-free, irrevocable copyright
26 * license to reproduce, prepare derivative works of, publicly
27 * display, publicly perform, sublicense, and distribute the original
28 * work contributed by Three Rings Design, Inc. and its employees to
29 * the Bacula project in source or object form.
31 * If you wish to license contributions from Three Rings Design, Inc,
32 * under an alternate open source license please contact
33 * Landon Fuller <landonf@threerings.net>.
41 #ifdef HAVE_TLS /* Is TLS enabled? */
43 #ifdef HAVE_OPENSSL /* How about OpenSSL? */
45 /* No anonymous ciphers, no <128 bit ciphers, no export ciphers, no MD5 ciphers */
46 #define TLS_DEFAULT_CIPHERS "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
48 /* TLS Context Structure */
51 CRYPTO_PEM_PASSWD_CB *pem_callback;
52 const void *pem_userdata;
57 struct TLS_Connection {
62 * OpenSSL certificate verification callback.
63 * OpenSSL has already performed internal certificate verification.
64 * We just report any errors that occured.
66 static int openssl_verify_peer(int ok, X509_STORE_CTX *store)
69 X509 *cert = X509_STORE_CTX_get_current_cert(store);
70 int depth = X509_STORE_CTX_get_error_depth(store);
71 int err = X509_STORE_CTX_get_error(store);
75 X509_NAME_oneline(X509_get_issuer_name(cert), issuer, 256);
76 X509_NAME_oneline(X509_get_subject_name(cert), subject, 256);
78 Jmsg5(NULL, M_ERROR, 0, _("Error with certificate at depth: %d, issuer = %s,"
79 " subject = %s, ERR=%d:%s\n"), depth, issuer,
80 subject, err, X509_verify_cert_error_string(err));
87 /* Dispatch user PEM encryption callbacks */
88 static int tls_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
90 TLS_CONTEXT *ctx = (TLS_CONTEXT *)userdata;
91 return (ctx->pem_callback(buf, size, ctx->pem_userdata));
95 * Create a new TLS_CONTEXT instance.
96 * Returns: Pointer to TLS_CONTEXT instance on success
99 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
100 const char *certfile, const char *keyfile,
101 CRYPTO_PEM_PASSWD_CB *pem_callback,
102 const void *pem_userdata, const char *dhfile,
109 ctx = (TLS_CONTEXT *)malloc(sizeof(TLS_CONTEXT));
111 /* Allocate our OpenSSL TLSv1 Context */
112 ctx->openssl = SSL_CTX_new(TLSv1_method());
115 openssl_post_errors(M_FATAL, _("Error initializing SSL context"));
119 /* Set up pem encryption callback */
121 ctx->pem_callback = pem_callback;
122 ctx->pem_userdata = pem_userdata;
124 ctx->pem_callback = crypto_default_pem_callback;
125 ctx->pem_userdata = NULL;
127 SSL_CTX_set_default_passwd_cb(ctx->openssl, tls_pem_callback_dispatch);
128 SSL_CTX_set_default_passwd_cb_userdata(ctx->openssl, (void *) ctx);
131 * Set certificate verification paths. This requires that at least one
134 if (ca_certfile || ca_certdir) {
135 if (!SSL_CTX_load_verify_locations(ctx->openssl, ca_certfile, ca_certdir)) {
136 openssl_post_errors(M_FATAL, _("Error loading certificate verification stores"));
139 } else if (verify_peer) {
140 /* At least one CA is required for peer verification */
141 Jmsg0(NULL, M_ERROR, 0, _("Either a certificate file or a directory must be"
142 " specified as a verification store\n"));
147 * Load our certificate file, if available. This file may also contain a
148 * private key, though this usage is somewhat unusual.
151 if (!SSL_CTX_use_certificate_chain_file(ctx->openssl, certfile)) {
152 openssl_post_errors(M_FATAL, _("Error loading certificate file"));
157 /* Load our private key. */
159 if (!SSL_CTX_use_PrivateKey_file(ctx->openssl, keyfile, SSL_FILETYPE_PEM)) {
160 openssl_post_errors(M_FATAL, _("Error loading private key"));
165 /* Load Diffie-Hellman Parameters. */
167 if (!(bio = BIO_new_file(dhfile, "r"))) {
168 openssl_post_errors(M_FATAL, _("Unable to open DH parameters file"));
171 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
174 openssl_post_errors(M_FATAL, _("Unable to load DH parameters from specified file"));
177 if (!SSL_CTX_set_tmp_dh(ctx->openssl, dh)) {
178 openssl_post_errors(M_FATAL, _("Failed to set TLS Diffie-Hellman parameters"));
182 /* Enable Single-Use DH for Ephemeral Keying */
183 SSL_CTX_set_options(ctx->openssl, SSL_OP_SINGLE_DH_USE);
186 if (SSL_CTX_set_cipher_list(ctx->openssl, TLS_DEFAULT_CIPHERS) != 1) {
187 Jmsg0(NULL, M_ERROR, 0,
188 _("Error setting cipher list, no valid ciphers available\n"));
192 /* Verify Peer Certificate */
194 /* SSL_VERIFY_FAIL_IF_NO_PEER_CERT has no effect in client mode */
195 SSL_CTX_set_verify(ctx->openssl,
196 SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
197 openssl_verify_peer);
203 /* Clean up after ourselves */
205 SSL_CTX_free(ctx->openssl);
212 * Free TLS_CONTEXT instance
214 void free_tls_context(TLS_CONTEXT *ctx)
216 SSL_CTX_free(ctx->openssl);
220 bool get_tls_require(TLS_CONTEXT *ctx)
222 return ctx->tls_require;
225 bool get_tls_enable(TLS_CONTEXT *ctx)
227 return ctx->tls_enable;
232 * Verifies a list of common names against the certificate
233 * commonName attribute.
234 * Returns: true on success
237 bool tls_postconnect_verify_cn(JCR *jcr, TLS_CONNECTION *tls, alist *verify_list)
239 SSL *ssl = tls->openssl;
242 bool auth_success = false;
245 /* Check if peer provided a certificate */
246 if (!(cert = SSL_get_peer_certificate(ssl))) {
247 Qmsg0(jcr, M_ERROR, 0, _("Peer failed to present a TLS certificate\n"));
251 if ((subject = X509_get_subject_name(cert)) != NULL) {
252 if (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) > 0) {
254 /* NULL terminate data */
257 /* Try all the CNs in the list */
258 foreach_alist(cn, verify_list) {
259 if (strcasecmp(data, cn) == 0) {
271 * Verifies a peer's hostname against the subjectAltName and commonName
273 * Returns: true on success
276 bool tls_postconnect_verify_host(JCR *jcr, TLS_CONNECTION *tls, const char *host)
278 SSL *ssl = tls->openssl;
281 bool auth_success = false;
284 const char *pval, *phost;
287 X509_NAME_ENTRY *neCN;
290 /* Check if peer provided a certificate */
291 if (!(cert = SSL_get_peer_certificate(ssl))) {
292 Qmsg1(jcr, M_ERROR, 0,
293 _("Peer %s failed to present a TLS certificate\n"), host);
294 Dmsg1(250, _("Peer %s failed to present a TLS certificate\n"), host);
298 /* Check subjectAltName extensions first */
299 if ((extensions = X509_get_ext_count(cert)) > 0) {
300 for (i = 0; i < extensions; i++) {
304 ext = X509_get_ext(cert, i);
305 extname = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
307 if (strcmp(extname, "subjectAltName") == 0) {
308 #ifdef HAVE_OPENSSLv1
309 const X509V3_EXT_METHOD *method;
311 X509V3_EXT_METHOD *method;
313 STACK_OF(CONF_VALUE) *val;
316 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
317 const unsigned char *ext_value_data;
319 unsigned char *ext_value_data;
322 /* Get x509 extension method structure */
323 if (!(method = X509V3_EXT_get(ext))) {
327 ext_value_data = ext->value->data;
329 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
333 /* Decode ASN1 item in data */
334 extstr = ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
335 ASN1_ITEM_ptr(method->it));
339 /* Decode ASN1 item in data */
340 extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
344 extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
347 /* Iterate through to find the dNSName field(s) */
348 val = method->i2v(method, extstr, NULL);
350 /* dNSName shortname is "DNS" */
351 Dmsg0(250, "Check DNS name\n");
352 for (j = 0; j < sk_CONF_VALUE_num(val); j++) {
353 nval = sk_CONF_VALUE_value(val, j);
354 if (strcmp(nval->name, "DNS") == 0) {
355 if (strncasecmp(nval->value, "*.", 2) == 0) {
356 Dmsg0(250, "Wildcard Certificate\n");
357 pval = strstr(nval->value, ".");
358 phost = strstr(host, ".");
359 if (pval && phost && (strcasecmp(pval, phost) == 0)) {
363 } else if (strcasecmp(nval->value, host) == 0) {
367 Dmsg2(250, "No DNS name match. Host=%s cert=%s\n", host, nval->value);
374 /* Try verifying against the subject name */
376 Dmsg0(250, "Check subject name name\n");
377 if ((subject = X509_get_subject_name(cert)) != NULL) {
378 /* Loop through all CNs */
380 cnLastPos = X509_NAME_get_index_by_NID(subject, NID_commonName, cnLastPos);
381 if (cnLastPos == -1) {
384 neCN = X509_NAME_get_entry(subject, cnLastPos);
385 asn1CN = X509_NAME_ENTRY_get_data(neCN);
386 if (strncasecmp((const char*)asn1CN->data, "*.", 2) == 0) {
387 /* wildcard certificate */
388 Dmsg0(250, "Wildcard Certificate\n");
389 pval = strstr((const char*)asn1CN->data, ".");
390 phost = strstr(host, ".");
391 if (pval && phost && (strcasecmp(pval, phost) == 0)) {
395 } else if (strcasecmp((const char*)asn1CN->data, host) == 0) {
399 Dmsg2(250, "No subject name match. Host=%s cert=%s\n", host, (const char*)asn1CN->data);
410 * Create a new TLS_CONNECTION instance.
412 * Returns: Pointer to TLS_CONNECTION instance on success
415 TLS_CONNECTION *new_tls_connection(TLS_CONTEXT *ctx, int fd)
420 * Create a new BIO and assign the fd.
421 * The caller will remain responsible for closing the associated fd
423 bio = BIO_new(BIO_s_socket());
425 /* Not likely, but never say never */
426 openssl_post_errors(M_FATAL, _("Error creating file descriptor-based BIO"));
427 return NULL; /* Nothing allocated, nothing to clean up */
429 BIO_set_fd(bio, fd, BIO_NOCLOSE);
431 /* Allocate our new tls connection */
432 TLS_CONNECTION *tls = (TLS_CONNECTION *)malloc(sizeof(TLS_CONNECTION));
434 /* Create the SSL object and attach the socket BIO */
435 if ((tls->openssl = SSL_new(ctx->openssl)) == NULL) {
436 /* Not likely, but never say never */
437 openssl_post_errors(M_FATAL, _("Error creating new SSL object"));
441 SSL_set_bio(tls->openssl, bio, bio);
443 /* Non-blocking partial writes */
444 SSL_set_mode(tls->openssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
451 SSL_free(tls->openssl);
457 * Free TLS_CONNECTION instance
459 void free_tls_connection(TLS_CONNECTION *tls)
461 SSL_free(tls->openssl);
465 /* Does all the manual labor for tls_bsock_accept() and tls_bsock_connect() */
466 static inline bool openssl_bsock_session_start(BSOCK *bsock, bool server)
468 TLS_CONNECTION *tls = bsock->tls;
475 /* Zero the fdset, we'll set our fd prior to each invocation of select() */
477 fdmax = bsock->m_fd + 1;
479 /* Ensure that socket is non-blocking */
480 flags = bsock->set_nonblocking();
483 bsock->timer_start = watchdog_time;
484 bsock->clear_timed_out();
485 bsock->set_killable(false);
489 err = SSL_accept(tls->openssl);
491 err = SSL_connect(tls->openssl);
495 switch (SSL_get_error(tls->openssl, err)) {
499 case SSL_ERROR_ZERO_RETURN:
500 /* TLS connection was cleanly shut down */
501 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
504 case SSL_ERROR_WANT_READ:
505 /* If we timeout of a select, this will be unset */
506 FD_SET((unsigned) bsock->m_fd, &fdset);
507 /* Set our timeout */
510 /* Block until we can read */
511 select(fdmax, &fdset, NULL, NULL, &tv);
513 case SSL_ERROR_WANT_WRITE:
514 /* If we timeout of a select, this will be unset */
515 FD_SET((unsigned) bsock->m_fd, &fdset);
516 /* Set our timeout */
519 /* Block until we can write */
520 select(fdmax, NULL, &fdset, NULL, &tv);
523 /* Socket Error Occurred */
524 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
529 if (bsock->is_timed_out()) {
535 /* Restore saved flags */
536 bsock->restore_blocking(flags);
538 bsock->timer_start = 0;
539 bsock->set_killable(true);
545 * Initiates a TLS connection with the server.
546 * Returns: true on success
549 bool tls_bsock_connect(BSOCK *bsock)
551 /* SSL_connect(bsock->tls) */
552 return openssl_bsock_session_start(bsock, false);
556 * Listens for a TLS connection from a client.
557 * Returns: true on success
560 bool tls_bsock_accept(BSOCK *bsock)
562 /* SSL_accept(bsock->tls) */
563 return openssl_bsock_session_start(bsock, true);
567 * Shutdown TLS_CONNECTION instance
569 void tls_bsock_shutdown(BSOCK *bsock)
572 * SSL_shutdown must be called twice to fully complete the process -
573 * The first time to initiate the shutdown handshake, and the second to
574 * receive the peer's reply.
576 * In addition, if the underlying socket is blocking, SSL_shutdown()
577 * will not return until the current stage of the shutdown process has
578 * completed or an error has occured. By setting the socket blocking
579 * we can avoid the ugly for()/switch()/select() loop.
585 /* Set socket blocking for shutdown */
586 bsock->set_blocking();
588 tid = start_bsock_timer(bsock, 60 * 2);
589 err = SSL_shutdown(bsock->tls->openssl);
590 stop_bsock_timer(tid);
592 /* Complete shutdown */
593 tid = start_bsock_timer(bsock, 60 * 2);
594 err = SSL_shutdown(bsock->tls->openssl);
595 stop_bsock_timer(tid);
599 switch (SSL_get_error(bsock->tls->openssl, err)) {
602 case SSL_ERROR_ZERO_RETURN:
603 /* TLS connection was shut down on us via a TLS protocol-level closure */
604 openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
607 /* Socket Error Occurred */
608 openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
613 /* Does all the manual labor for tls_bsock_readn() and tls_bsock_writen() */
614 static inline int openssl_bsock_readwrite(BSOCK *bsock, char *ptr, int nbytes, bool write)
616 TLS_CONNECTION *tls = bsock->tls;
623 /* Zero the fdset, we'll set our fd prior to each invocation of select() */
625 fdmax = bsock->m_fd + 1;
627 /* Ensure that socket is non-blocking */
628 flags = bsock->set_nonblocking();
631 bsock->timer_start = watchdog_time;
632 bsock->clear_timed_out();
633 bsock->set_killable(false);
639 nwritten = SSL_write(tls->openssl, ptr, nleft);
641 nwritten = SSL_read(tls->openssl, ptr, nleft);
645 switch (SSL_get_error(tls->openssl, nwritten)) {
653 case SSL_ERROR_SYSCALL:
654 if (nwritten == -1) {
655 if (errno == EINTR) {
658 if (errno == EAGAIN) {
659 bmicrosleep(0, 20000); /* try again in 20 ms */
663 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
666 case SSL_ERROR_WANT_READ:
667 /* If we timeout on a select, this will be unset */
668 FD_SET((unsigned)bsock->m_fd, &fdset);
671 /* Block until we can read */
672 select(fdmax, &fdset, NULL, NULL, &tv);
675 case SSL_ERROR_WANT_WRITE:
676 /* If we timeout on a select, this will be unset */
677 FD_SET((unsigned)bsock->m_fd, &fdset);
680 /* Block until we can write */
681 select(fdmax, NULL, &fdset, NULL, &tv);
684 case SSL_ERROR_ZERO_RETURN:
685 /* TLS connection was cleanly shut down */
686 /* Fall through wanted */
688 /* Socket Error Occured */
689 openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
693 /* Everything done? */
698 /* Timeout/Termination, let's take what we can get */
699 if (bsock->is_timed_out() || bsock->is_terminated()) {
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 #else /* HAVE_OPENSSL */
728 # error No TLS implementation available.
729 #endif /* !HAVE_OPENSSL */
732 #else /* TLS NOT enabled, dummy routines substituted */
736 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
737 const char *certfile, const char *keyfile,
738 CRYPTO_PEM_PASSWD_CB *pem_callback,
739 const void *pem_userdata, const char *dhfile,
744 void free_tls_context(TLS_CONTEXT *ctx) { }
746 void tls_bsock_shutdown(BSOCK *bsock) { }
748 void free_tls_connection(TLS_CONNECTION *tls) { }
750 bool get_tls_require(TLS_CONTEXT *ctx)
755 bool get_tls_enable(TLS_CONTEXT *ctx)
760 #endif /* HAVE_TLS */