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.
43 extern time_t watchdog_time;
45 #ifdef HAVE_TLS /* Is TLS enabled? */
47 #ifdef HAVE_OPENSSL /* How about OpenSSL? */
49 /* No anonymous ciphers, no <128 bit ciphers, no export ciphers, no MD5 ciphers */
50 #define TLS_DEFAULT_CIPHERS "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
52 /* TLS Context Structure */
55 CRYPTO_PEM_PASSWD_CB *pem_callback;
56 const void *pem_userdata;
59 struct TLS_Connection {
64 * OpenSSL certificate verification callback.
65 * OpenSSL has already performed internal certificate verification.
66 * We just report any errors that occured.
68 static int openssl_verify_peer(int ok, X509_STORE_CTX *store)
72 X509 *cert = X509_STORE_CTX_get_current_cert(store);
73 int depth = X509_STORE_CTX_get_error_depth(store);
74 int err = X509_STORE_CTX_get_error(store);
78 X509_NAME_oneline(X509_get_issuer_name(cert), issuer, 256);
79 X509_NAME_oneline(X509_get_subject_name(cert), subject, 256);
81 Emsg5(M_ERROR, 0, _("Error with certificate at depth: %d, issuer = %s,"
82 " subject = %s, ERR=%d:%s\n"), depth, issuer,
83 subject, err, X509_verify_cert_error_string(err));
90 /* Dispatch user PEM encryption callbacks */
91 static int tls_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
93 TLS_CONTEXT *ctx = (TLS_CONTEXT *) userdata;
94 return (ctx->pem_callback(buf, size, ctx->pem_userdata));
98 * Create a new TLS_CONTEXT instance.
99 * Returns: Pointer to TLS_CONTEXT instance on success
102 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
103 const char *certfile, const char *keyfile,
104 CRYPTO_PEM_PASSWD_CB *pem_callback,
105 const void *pem_userdata, const char *dhfile,
112 ctx = (TLS_CONTEXT *) malloc(sizeof(TLS_CONTEXT));
114 /* Allocate our OpenSSL TLSv1 Context */
115 ctx->openssl = SSL_CTX_new(TLSv1_method());
118 openssl_post_errors(M_ERROR, _("Error initializing SSL context"));
122 /* Set up pem encryption callback */
124 ctx->pem_callback = pem_callback;
125 ctx->pem_userdata = pem_userdata;
127 ctx->pem_callback = crypto_default_pem_callback;
128 ctx->pem_userdata = NULL;
130 SSL_CTX_set_default_passwd_cb(ctx->openssl, tls_pem_callback_dispatch);
131 SSL_CTX_set_default_passwd_cb_userdata(ctx->openssl, (void *) ctx);
134 * Set certificate verification paths. This requires that at least one
137 if (ca_certfile || ca_certdir) {
138 if (!SSL_CTX_load_verify_locations(ctx->openssl, ca_certfile, ca_certdir)) {
139 openssl_post_errors(M_ERROR, _("Error loading certificate verification stores"));
142 } else if (verify_peer) {
143 /* At least one CA is required for peer verification */
144 Emsg0(M_ERROR, 0, _("Either a certificate file or a directory must be"
145 " specified as a verification store\n"));
150 * Load our certificate file, if available. This file may also contain a
151 * private key, though this usage is somewhat unusual.
154 if (!SSL_CTX_use_certificate_chain_file(ctx->openssl, certfile)) {
155 openssl_post_errors(M_ERROR, _("Error loading certificate file"));
160 /* Load our private key. */
162 if (!SSL_CTX_use_PrivateKey_file(ctx->openssl, keyfile, SSL_FILETYPE_PEM)) {
163 openssl_post_errors(M_ERROR, _("Error loading private key"));
168 /* Load Diffie-Hellman Parameters. */
170 if (!(bio = BIO_new_file(dhfile, "r"))) {
171 openssl_post_errors(M_ERROR, _("Unable to open DH parameters file"));
174 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
177 openssl_post_errors(M_ERROR, _("Unable to load DH parameters from specified file"));
180 if (!SSL_CTX_set_tmp_dh(ctx->openssl, dh)) {
181 openssl_post_errors(M_ERROR, _("Failed to set TLS Diffie-Hellman parameters"));
185 /* Enable Single-Use DH for Ephemeral Keying */
186 SSL_CTX_set_options(ctx->openssl, SSL_OP_SINGLE_DH_USE);
189 if (SSL_CTX_set_cipher_list(ctx->openssl, TLS_DEFAULT_CIPHERS) != 1) {
190 Emsg0(M_ERROR, 0, _("Error setting cipher list, no valid ciphers available\n"));
194 /* Verify Peer Certificate */
196 /* SSL_VERIFY_FAIL_IF_NO_PEER_CERT has no effect in client mode */
197 SSL_CTX_set_verify(ctx->openssl,
198 SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
199 openssl_verify_peer);
205 /* Clean up after ourselves */
207 SSL_CTX_free(ctx->openssl);
214 * Free TLS_CONTEXT instance
216 void free_tls_context(TLS_CONTEXT *ctx)
218 SSL_CTX_free(ctx->openssl);
223 * Verifies a list of common names against the certificate
224 * commonName attribute.
225 * Returns: true on success
228 bool tls_postconnect_verify_cn(TLS_CONNECTION *tls, alist *verify_list)
230 SSL *ssl = tls->openssl;
233 int auth_success = false;
236 /* Check if peer provided a certificate */
237 if (!(cert = SSL_get_peer_certificate(ssl))) {
238 Emsg0(M_ERROR, 0, _("Peer failed to present a TLS certificate\n"));
242 if ((subject = X509_get_subject_name(cert)) != NULL) {
243 if (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) > 0) {
245 /* NULL terminate data */
248 /* Try all the CNs in the list */
249 foreach_alist(cn, verify_list) {
250 if (strcasecmp(data, cn) == 0) {
262 * Verifies a peer's hostname against the subjectAltName and commonName
264 * Returns: true on success
267 bool tls_postconnect_verify_host(TLS_CONNECTION *tls, const char *host)
269 SSL *ssl = tls->openssl;
272 int auth_success = false;
278 /* Check if peer provided a certificate */
279 if (!(cert = SSL_get_peer_certificate(ssl))) {
280 Emsg1(M_ERROR, 0, _("Peer %s failed to present a TLS certificate\n"), host);
284 /* Check subjectAltName extensions first */
285 if ((extensions = X509_get_ext_count(cert)) > 0) {
286 for (i = 0; i < extensions; i++) {
290 ext = X509_get_ext(cert, i);
291 extname = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
293 if (strcmp(extname, "subjectAltName") == 0) {
294 X509V3_EXT_METHOD *method;
295 STACK_OF(CONF_VALUE) *val;
298 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
299 const unsigned char *ext_value_data;
301 unsigned char *ext_value_data;
304 /* Get x509 extension method structure */
305 if (!(method = X509V3_EXT_get(ext))) {
309 ext_value_data = ext->value->data;
311 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
315 /* Decode ASN1 item in data */
316 extstr = ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
317 ASN1_ITEM_ptr(method->it));
321 /* Decode ASN1 item in data */
322 extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
326 extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
329 /* Iterate through to find the dNSName field(s) */
330 val = method->i2v(method, extstr, NULL);
332 /* dNSName shortname is "DNS" */
333 for (j = 0; j < sk_CONF_VALUE_num(val); j++) {
334 nval = sk_CONF_VALUE_value(val, j);
335 if (strcmp(nval->name, "DNS") == 0) {
336 if (strcasecmp(nval->value, host) == 0) {
346 /* Try verifying against the subject name */
348 if ((subject = X509_get_subject_name(cert)) != NULL) {
349 if (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) > 0) {
350 /* NULL terminate data */
352 if (strcasecmp(data, host) == 0) {
367 * Create a new TLS_CONNECTION instance.
369 * Returns: Pointer to TLS_CONNECTION instance on success
372 TLS_CONNECTION *new_tls_connection (TLS_CONTEXT *ctx, int fd)
377 * Create a new BIO and assign the fd.
378 * The caller will remain responsible for closing the associated fd
380 bio = BIO_new(BIO_s_socket());
382 /* Not likely, but never say never */
383 openssl_post_errors(M_ERROR, _("Error creating file descriptor-based BIO"));
384 return NULL; /* Nothing allocated, nothing to clean up */
386 BIO_set_fd(bio, fd, BIO_NOCLOSE);
388 /* Allocate our new tls connection */
389 TLS_CONNECTION *tls = (TLS_CONNECTION *) malloc(sizeof(TLS_CONNECTION));
391 /* Create the SSL object and attach the socket BIO */
392 if ((tls->openssl = SSL_new(ctx->openssl)) == NULL) {
393 /* Not likely, but never say never */
394 openssl_post_errors(M_ERROR, _("Error creating new SSL object"));
398 SSL_set_bio(tls->openssl, bio, bio);
400 /* Non-blocking partial writes */
401 SSL_set_mode(tls->openssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
408 SSL_free(tls->openssl);
415 * Free TLS_CONNECTION instance
417 void free_tls_connection (TLS_CONNECTION *tls)
419 SSL_free(tls->openssl);
423 /* Does all the manual labor for tls_bsock_accept() and tls_bsock_connect() */
424 static inline bool openssl_bsock_session_start(BSOCK *bsock, bool server)
426 TLS_CONNECTION *tls = bsock->tls;
433 /* Zero the fdset, we'll set our fd prior to each invocation of select() */
437 fdmax = bsock->fd + 1;
439 /* Ensure that socket is non-blocking */
440 flags = bnet_set_nonblocking(bsock);
443 bsock->timer_start = watchdog_time;
444 bsock->timed_out = 0;
448 err = SSL_accept(tls->openssl);
450 err = SSL_connect(tls->openssl);
454 switch (SSL_get_error(tls->openssl, err)) {
458 case SSL_ERROR_ZERO_RETURN:
459 /* TLS connection was cleanly shut down */
460 openssl_post_errors(M_ERROR, _("Connect failure"));
463 case SSL_ERROR_WANT_READ:
464 /* If we timeout of a select, this will be unset */
465 FD_SET((unsigned) bsock->fd, &fdset);
466 /* Block until we can read */
467 select(fdmax, &fdset, NULL, &fdset, &tv);
469 case SSL_ERROR_WANT_WRITE:
470 /* If we timeout of a select, this will be unset */
471 FD_SET((unsigned) bsock->fd, &fdset);
472 /* Block until we can write */
473 select(fdmax, NULL, &fdset, &fdset, &tv);
476 /* Socket Error Occured */
477 openssl_post_errors(M_ERROR, _("Connect failure"));
482 if (bsock->timed_out) {
488 /* Restore saved flags */
489 bnet_restore_blocking(bsock, flags);
491 bsock->timer_start = 0;
497 * Initiates a TLS connection with the server.
498 * Returns: true on success
501 bool tls_bsock_connect(BSOCK *bsock)
503 /* SSL_connect(bsock->tls) */
504 return (openssl_bsock_session_start(bsock, false));
508 * Listens for a TLS connection from a client.
509 * Returns: true on success
512 bool tls_bsock_accept(BSOCK *bsock)
514 /* SSL_accept(bsock->tls) */
515 return (openssl_bsock_session_start(bsock, true));
519 * Shutdown TLS_CONNECTION instance
521 void tls_bsock_shutdown (BSOCK *bsock)
524 * SSL_shutdown must be called twice to fully complete the process -
525 * The first time to initiate the shutdown handshake, and the second to
526 * receive the peer's reply.
528 * However, it is valid to close the SSL connection after the initial
529 * shutdown notification is sent to the peer, without waiting for the
530 * peer's reply, as long as you do not plan to re-use that particular
531 * SSL connection object.
533 * Because we do not re-use SSL connection objects, I do not bother
534 * calling SSL_shutdown a second time.
536 * In addition, if the underlying socket is blocking, SSL_shutdown()
537 * will not return until the current stage of the shutdown process has
538 * completed or an error has occured. By setting the socket blocking
539 * we can avoid the ugly for()/switch()/select() loop.
544 /* Set socket blocking for shutdown */
545 flags = bnet_set_blocking(bsock);
547 err = SSL_shutdown(bsock->tls->openssl);
549 switch (SSL_get_error(bsock->tls->openssl, err)) {
552 case SSL_ERROR_ZERO_RETURN:
553 /* TLS connection was shut down on us via a TLS protocol-level closure */
554 openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
557 /* Socket Error Occured */
558 openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
562 /* Restore saved flags */
563 bnet_restore_blocking(bsock, flags);
566 /* Does all the manual labor for tls_bsock_readn() and tls_bsock_writen() */
567 static inline int openssl_bsock_readwrite(BSOCK *bsock, char *ptr, int nbytes, bool write)
569 TLS_CONNECTION *tls = bsock->tls;
576 /* Zero the fdset, we'll set our fd prior to each invocation of select() */
580 fdmax = bsock->fd + 1;
582 /* Ensure that socket is non-blocking */
583 flags = bnet_set_nonblocking(bsock);
586 bsock->timer_start = watchdog_time;
587 bsock->timed_out = 0;
594 nwritten = SSL_write(tls->openssl, ptr, nleft);
596 nwritten = SSL_read(tls->openssl, ptr, nleft);
600 switch (SSL_get_error(tls->openssl, nwritten)) {
607 case SSL_ERROR_ZERO_RETURN:
608 /* TLS connection was cleanly shut down */
609 openssl_post_errors(M_ERROR, _("TLS read/write failure."));
611 case SSL_ERROR_WANT_READ:
612 /* If we timeout of a select, this will be unset */
613 FD_SET((unsigned) bsock->fd, &fdset);
614 /* Block until we can read */
615 select(fdmax, &fdset, NULL, &fdset, &tv);
617 case SSL_ERROR_WANT_WRITE:
618 /* If we timeout of a select, this will be unset */
619 FD_SET((unsigned) bsock->fd, &fdset);
620 /* Block until we can write */
621 select(fdmax, NULL, &fdset, &fdset, &tv);
624 /* Socket Error Occured */
625 openssl_post_errors(M_ERROR, _("TLS read/write failure."));
629 /* Everything done? */
634 /* Timeout/Termination, let's take what we can get */
635 if (bsock->timed_out || bsock->terminated) {
641 /* Restore saved flags */
642 bnet_restore_blocking(bsock, flags);
645 bsock->timer_start = 0;
647 return nbytes - nleft;
651 int tls_bsock_writen(BSOCK *bsock, char *ptr, int32_t nbytes) {
652 /* SSL_write(bsock->tls->openssl, ptr, nbytes) */
653 return (openssl_bsock_readwrite(bsock, ptr, nbytes, true));
656 int tls_bsock_readn(BSOCK *bsock, char *ptr, int32_t nbytes) {
657 /* SSL_read(bsock->tls->openssl, ptr, nbytes) */
658 return (openssl_bsock_readwrite(bsock, ptr, nbytes, false));
661 #else /* HAVE_OPENSSL */
662 # error No TLS implementation available.
663 #endif /* !HAVE_OPENSSL */
668 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
669 const char *certfile, const char *keyfile,
670 CRYPTO_PEM_PASSWD_CB *pem_callback,
671 const void *pem_userdata, const char *dhfile,
676 void free_tls_context(TLS_CONTEXT *ctx) { }
678 #endif /* HAVE_TLS */