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-2006 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() */
435 fdmax = bsock->fd + 1;
437 /* Ensure that socket is non-blocking */
438 flags = bnet_set_nonblocking(bsock);
441 bsock->timer_start = watchdog_time;
442 bsock->timed_out = 0;
446 err = SSL_accept(tls->openssl);
448 err = SSL_connect(tls->openssl);
452 switch (SSL_get_error(tls->openssl, err)) {
456 case SSL_ERROR_ZERO_RETURN:
457 /* TLS connection was cleanly shut down */
458 openssl_post_errors(M_ERROR, _("Connect failure"));
461 case SSL_ERROR_WANT_READ:
462 /* If we timeout of a select, this will be unset */
463 FD_SET((unsigned) bsock->fd, &fdset);
464 /* Set our timeout */
467 /* Block until we can read */
468 select(fdmax, &fdset, NULL, &fdset, &tv);
470 case SSL_ERROR_WANT_WRITE:
471 /* If we timeout of a select, this will be unset */
472 FD_SET((unsigned) bsock->fd, &fdset);
473 /* Set our timeout */
476 /* Block until we can write */
477 select(fdmax, NULL, &fdset, &fdset, &tv);
480 /* Socket Error Occured */
481 openssl_post_errors(M_ERROR, _("Connect failure"));
486 if (bsock->timed_out) {
492 /* Restore saved flags */
493 bnet_restore_blocking(bsock, flags);
495 bsock->timer_start = 0;
501 * Initiates a TLS connection with the server.
502 * Returns: true on success
505 bool tls_bsock_connect(BSOCK *bsock)
507 /* SSL_connect(bsock->tls) */
508 return (openssl_bsock_session_start(bsock, false));
512 * Listens for a TLS connection from a client.
513 * Returns: true on success
516 bool tls_bsock_accept(BSOCK *bsock)
518 /* SSL_accept(bsock->tls) */
519 return (openssl_bsock_session_start(bsock, true));
523 * Shutdown TLS_CONNECTION instance
525 void tls_bsock_shutdown (BSOCK *bsock)
528 * SSL_shutdown must be called twice to fully complete the process -
529 * The first time to initiate the shutdown handshake, and the second to
530 * receive the peer's reply.
532 * However, it is valid to close the SSL connection after the initial
533 * shutdown notification is sent to the peer, without waiting for the
534 * peer's reply, as long as you do not plan to re-use that particular
535 * SSL connection object.
537 * Because we do not re-use SSL connection objects, I do not bother
538 * calling SSL_shutdown a second time.
540 * In addition, if the underlying socket is blocking, SSL_shutdown()
541 * will not return until the current stage of the shutdown process has
542 * completed or an error has occured. By setting the socket blocking
543 * we can avoid the ugly for()/switch()/select() loop.
548 /* Set socket blocking for shutdown */
549 flags = bnet_set_blocking(bsock);
551 err = SSL_shutdown(bsock->tls->openssl);
553 switch (SSL_get_error(bsock->tls->openssl, err)) {
556 case SSL_ERROR_ZERO_RETURN:
557 /* TLS connection was shut down on us via a TLS protocol-level closure */
558 openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
561 /* Socket Error Occured */
562 openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
566 /* Restore saved flags */
567 bnet_restore_blocking(bsock, flags);
570 /* Does all the manual labor for tls_bsock_readn() and tls_bsock_writen() */
571 static inline int openssl_bsock_readwrite(BSOCK *bsock, char *ptr, int nbytes, bool write)
573 TLS_CONNECTION *tls = bsock->tls;
580 /* Zero the fdset, we'll set our fd prior to each invocation of select() */
582 fdmax = bsock->fd + 1;
584 /* Ensure that socket is non-blocking */
585 flags = bnet_set_nonblocking(bsock);
588 bsock->timer_start = watchdog_time;
589 bsock->timed_out = 0;
596 nwritten = SSL_write(tls->openssl, ptr, nleft);
598 nwritten = SSL_read(tls->openssl, ptr, nleft);
602 switch (SSL_get_error(tls->openssl, nwritten)) {
609 case SSL_ERROR_ZERO_RETURN:
610 /* TLS connection was cleanly shut down */
611 openssl_post_errors(M_ERROR, _("TLS read/write failure."));
613 case SSL_ERROR_WANT_READ:
614 /* If we timeout of a select, this will be unset */
615 FD_SET((unsigned) bsock->fd, &fdset);
618 /* Block until we can read */
619 select(fdmax, &fdset, NULL, &fdset, &tv);
621 case SSL_ERROR_WANT_WRITE:
622 /* If we timeout of a select, this will be unset */
623 FD_SET((unsigned) bsock->fd, &fdset);
626 /* Block until we can write */
627 select(fdmax, NULL, &fdset, &fdset, &tv);
630 /* Socket Error Occured */
631 openssl_post_errors(M_ERROR, _("TLS read/write failure."));
635 /* Everything done? */
640 /* Timeout/Termination, let's take what we can get */
641 if (bsock->timed_out || bsock->terminated) {
647 /* Restore saved flags */
648 bnet_restore_blocking(bsock, flags);
651 bsock->timer_start = 0;
653 return nbytes - nleft;
657 int tls_bsock_writen(BSOCK *bsock, char *ptr, int32_t nbytes) {
658 /* SSL_write(bsock->tls->openssl, ptr, nbytes) */
659 return (openssl_bsock_readwrite(bsock, ptr, nbytes, true));
662 int tls_bsock_readn(BSOCK *bsock, char *ptr, int32_t nbytes) {
663 /* SSL_read(bsock->tls->openssl, ptr, nbytes) */
664 return (openssl_bsock_readwrite(bsock, ptr, nbytes, false));
667 #else /* HAVE_OPENSSL */
668 # error No TLS implementation available.
669 #endif /* !HAVE_OPENSSL */
674 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
675 const char *certfile, const char *keyfile,
676 CRYPTO_PEM_PASSWD_CB *pem_callback,
677 const void *pem_userdata, const char *dhfile,
682 void free_tls_context(TLS_CONTEXT *ctx) { }
684 #endif /* HAVE_TLS */