]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/tls.c
Merge the Bacula Encryption branch to HEAD.
[bacula/bacula] / bacula / src / lib / tls.c
1 /*
2  * tls.c TLS support functions
3  *
4  * Author: Landon Fuller <landonf@threerings.net>
5  *
6  * Version $Id$
7  *
8  * Copyright (C) 2005 Kern Sibbald
9  *
10  * This file was contributed to the Bacula project by Landon Fuller
11  * and Three Rings Design, Inc.
12  *
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.
19  *
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>.
23  */
24 /*
25    Copyright (C) 2005 Kern Sibbald
26
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.
31
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.
36
37  */
38
39
40 #include "bacula.h"
41 #include <assert.h>
42
43 extern time_t watchdog_time;
44
45 #ifdef HAVE_TLS /* Is TLS enabled? */
46
47 #ifdef HAVE_OPENSSL /* How about OpenSSL? */
48
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"
51
52 /* TLS Context Structure */
53 struct TLS_Context {
54    SSL_CTX *openssl;
55    CRYPTO_PEM_PASSWD_CB *pem_callback;
56    const void *pem_userdata;
57 };
58
59 struct TLS_Connection {
60    SSL *openssl;
61 };
62
63 /*
64  * OpenSSL certificate verification callback.
65  * OpenSSL has already performed internal certificate verification.
66  * We just report any errors that occured.
67  */
68 static int openssl_verify_peer(int ok, X509_STORE_CTX *store)
69 {
70
71    if (!ok) {
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);
75       char issuer[256];
76       char subject[256];
77
78       X509_NAME_oneline(X509_get_issuer_name(cert), issuer, 256);
79       X509_NAME_oneline(X509_get_subject_name(cert), subject, 256);
80
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));
84
85    }
86
87    return ok;
88 }
89
90 /* Dispatch user PEM encryption callbacks */
91 static int tls_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
92 {
93    TLS_CONTEXT *ctx = (TLS_CONTEXT *) userdata;
94    return (ctx->pem_callback(buf, size, ctx->pem_userdata));
95 }
96
97 /*
98  * Create a new TLS_CONTEXT instance.
99  *  Returns: Pointer to TLS_CONTEXT instance on success
100  *           NULL on failure;
101  */
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,
106                              bool verify_peer)
107 {
108    TLS_CONTEXT *ctx;
109    BIO *bio;
110    DH *dh;
111
112    ctx = (TLS_CONTEXT *) malloc(sizeof(TLS_CONTEXT));
113
114    /* Allocate our OpenSSL TLSv1 Context */
115    ctx->openssl = SSL_CTX_new(TLSv1_method());
116
117    if (!ctx->openssl) {
118       openssl_post_errors(M_ERROR, _("Error initializing SSL context"));
119       goto err;
120    }
121
122    /* Set up pem encryption callback */
123    if (pem_callback) {
124       ctx->pem_callback = pem_callback;
125       ctx->pem_userdata = pem_userdata;
126    } else {
127       ctx->pem_callback = crypto_default_pem_callback;
128       ctx->pem_userdata = NULL;
129    }
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);
132
133    /*
134     * Set certificate verification paths. This requires that at least one
135     * value be non-NULL
136     */
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"));
140          goto err;
141       }
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"));
146       goto err;
147    }
148
149    /*
150     * Load our certificate file, if available. This file may also contain a
151     * private key, though this usage is somewhat unusual.
152     */
153    if (certfile) {
154       if (!SSL_CTX_use_certificate_chain_file(ctx->openssl, certfile)) {
155          openssl_post_errors(M_ERROR, _("Error loading certificate file"));
156          goto err;
157       }
158    }
159
160    /* Load our private key. */
161    if (keyfile) {
162       if (!SSL_CTX_use_PrivateKey_file(ctx->openssl, keyfile, SSL_FILETYPE_PEM)) {
163          openssl_post_errors(M_ERROR, _("Error loading private key"));
164          goto err;
165       }
166    }
167
168    /* Load Diffie-Hellman Parameters. */
169    if (dhfile) {
170       if (!(bio = BIO_new_file(dhfile, "r"))) {
171          openssl_post_errors(M_ERROR, _("Unable to open DH parameters file"));
172          goto err;
173       }
174       dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
175       BIO_free(bio);
176       if (!dh) {
177          openssl_post_errors(M_ERROR, _("Unable to load DH parameters from specified file"));
178          goto err;
179       }
180       if (!SSL_CTX_set_tmp_dh(ctx->openssl, dh)) {
181          openssl_post_errors(M_ERROR, _("Failed to set TLS Diffie-Hellman parameters"));
182          DH_free(dh);
183          goto err;
184       }
185       /* Enable Single-Use DH for Ephemeral Keying */
186       SSL_CTX_set_options(ctx->openssl, SSL_OP_SINGLE_DH_USE);
187    }
188
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"));
191       goto err;
192    }
193
194    /* Verify Peer Certificate */
195    if (verify_peer) {
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);
200    }
201
202    return ctx;
203
204 err:
205    /* Clean up after ourselves */
206    if(ctx->openssl) {
207       SSL_CTX_free(ctx->openssl);
208    }
209    free(ctx);
210    return NULL;
211 }
212
213 /*
214  * Free TLS_CONTEXT instance
215  */
216 void free_tls_context(TLS_CONTEXT *ctx)
217 {
218    SSL_CTX_free(ctx->openssl);
219    free(ctx);
220 }
221
222 /*
223  * Verifies a list of common names against the certificate
224  * commonName attribute.
225  *  Returns: true on success
226  *           false on failure
227  */
228 bool tls_postconnect_verify_cn(TLS_CONNECTION *tls, alist *verify_list)
229 {
230    SSL *ssl = tls->openssl;
231    X509 *cert;
232    X509_NAME *subject;
233    int auth_success = false;
234    char data[256];
235
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"));
239       return false;
240    }
241
242    if ((subject = X509_get_subject_name(cert)) != NULL) {
243       if (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) > 0) {
244          char *cn;
245          /* NULL terminate data */
246          data[255] = 0;
247
248          /* Try all the CNs in the list */
249          foreach_alist(cn, verify_list) {
250             if (strcasecmp(data, cn) == 0) {
251                auth_success = true;
252             }
253          }
254       }
255    }
256
257    X509_free(cert);
258    return auth_success;
259 }
260
261 /*
262  * Verifies a peer's hostname against the subjectAltName and commonName
263  * attributes.
264  *  Returns: true on success
265  *           false on failure
266  */
267 bool tls_postconnect_verify_host(TLS_CONNECTION *tls, const char *host)
268 {
269    SSL *ssl = tls->openssl;
270    X509 *cert;
271    X509_NAME *subject;
272    int auth_success = false;
273    int extensions;
274    char data[256];
275    int i, j;
276
277
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);
281       return false;
282    }
283
284    /* Check subjectAltName extensions first */
285    if ((extensions = X509_get_ext_count(cert)) > 0) {
286       for (i = 0; i < extensions; i++) {
287          X509_EXTENSION *ext;
288          const char *extname;
289
290          ext = X509_get_ext(cert, i);
291          extname = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
292
293          if (strcmp(extname, "subjectAltName") == 0) {
294             X509V3_EXT_METHOD *method;
295             STACK_OF(CONF_VALUE) *val;
296             CONF_VALUE *nval;
297             void *extstr = NULL;
298 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
299             const unsigned char *ext_value_data;
300 #else
301             unsigned char *ext_value_data;
302 #endif
303
304             /* Get x509 extension method structure */
305             if (!(method = X509V3_EXT_get(ext))) {
306                break;
307             }
308
309             ext_value_data = ext->value->data;
310
311 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
312             if (method->it) {
313                /* New style ASN1 */
314
315                /* Decode ASN1 item in data */
316                extstr = ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
317                                       ASN1_ITEM_ptr(method->it));
318             } else {
319                /* Old style ASN1 */
320
321                /* Decode ASN1 item in data */
322                extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
323             }
324
325 #else
326             extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
327 #endif
328
329             /* Iterate through to find the dNSName field(s) */
330             val = method->i2v(method, extstr, NULL);
331
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) {
337                      auth_success = true;
338                      goto success;
339                   }
340                }
341             }
342          }
343       }
344    }
345
346    /* Try verifying against the subject name */
347    if (!auth_success) {
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 */
351             data[255] = 0;
352             if (strcasecmp(data, host) == 0) {
353                auth_success = true;
354             }
355          }
356       }
357    }
358
359
360 success:
361    X509_free(cert);
362
363    return auth_success;
364 }
365
366 /*
367  * Create a new TLS_CONNECTION instance.
368  *
369  * Returns: Pointer to TLS_CONNECTION instance on success
370  *          NULL on failure;
371  */
372 TLS_CONNECTION *new_tls_connection (TLS_CONTEXT *ctx, int fd)
373 {
374    BIO *bio;
375
376    /*
377     * Create a new BIO and assign the fd.
378     * The caller will remain responsible for closing the associated fd
379     */
380    bio = BIO_new(BIO_s_socket());
381    if (!bio) {
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 */
385    }
386    BIO_set_fd(bio, fd, BIO_NOCLOSE);
387
388    /* Allocate our new tls connection */
389    TLS_CONNECTION *tls = (TLS_CONNECTION *) malloc(sizeof(TLS_CONNECTION));
390
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"));
395       goto err;
396    }
397
398    SSL_set_bio(tls->openssl, bio, bio);
399
400    /* Non-blocking partial writes */
401    SSL_set_mode(tls->openssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
402
403    return (tls);
404
405 err:
406    /* Clean up */
407    BIO_free(bio);
408    SSL_free(tls->openssl);
409    free(tls);
410
411    return NULL;
412 }
413
414 /*
415  * Free TLS_CONNECTION instance
416  */
417 void free_tls_connection (TLS_CONNECTION *tls)
418 {
419    SSL_free(tls->openssl);
420    free(tls);
421 }
422
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)
425 {
426    TLS_CONNECTION *tls = bsock->tls;
427    int err;
428    int fdmax, flags;
429    int stat = true;
430    fd_set fdset;
431    struct timeval tv;
432
433    /* Zero the fdset, we'll set our fd prior to each invocation of select() */
434    FD_ZERO(&fdset);
435    tv.tv_sec = 10;
436    tv.tv_usec = 0;
437    fdmax = bsock->fd + 1;
438
439    /* Ensure that socket is non-blocking */
440    flags = bnet_set_nonblocking(bsock);
441
442    /* start timer */
443    bsock->timer_start = watchdog_time;
444    bsock->timed_out = 0;
445
446    for (;;) { 
447       if (server) {
448          err = SSL_accept(tls->openssl);
449       } else {
450          err = SSL_connect(tls->openssl);
451       }
452
453       /* Handle errors */
454       switch (SSL_get_error(tls->openssl, err)) {
455            case SSL_ERROR_NONE:
456               stat = true;
457               goto cleanup;
458            case SSL_ERROR_ZERO_RETURN:
459               /* TLS connection was cleanly shut down */
460               openssl_post_errors(M_ERROR, _("Connect failure"));
461               stat = false;
462               goto cleanup;
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);
468               break;
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);
474               break;
475            default:
476               /* Socket Error Occured */
477               openssl_post_errors(M_ERROR, _("Connect failure"));
478               stat = false;
479               goto cleanup;
480       }
481
482       if (bsock->timed_out) {
483          goto cleanup;
484       }
485    }
486
487 cleanup:
488    /* Restore saved flags */
489    bnet_restore_blocking(bsock, flags);
490    /* Clear timer */
491    bsock->timer_start = 0;
492
493    return stat;
494 }
495
496 /*
497  * Initiates a TLS connection with the server.
498  *  Returns: true on success
499  *           false on failure
500  */
501 bool tls_bsock_connect(BSOCK *bsock)
502 {
503    /* SSL_connect(bsock->tls) */
504    return (openssl_bsock_session_start(bsock, false));
505 }
506
507 /*
508  * Listens for a TLS connection from a client.
509  *  Returns: true on success
510  *           false on failure
511  */
512 bool tls_bsock_accept(BSOCK *bsock)
513 {
514    /* SSL_accept(bsock->tls) */
515    return (openssl_bsock_session_start(bsock, true));
516 }
517
518 /*
519  * Shutdown TLS_CONNECTION instance
520  */
521 void tls_bsock_shutdown (BSOCK *bsock)
522 {
523    /*
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.
527     *
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.
532     *
533     * Because we do not re-use SSL connection objects, I do not bother
534     * calling SSL_shutdown a second time.
535     *
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.
540     */
541    int err;
542    int flags;
543
544    /* Set socket blocking for shutdown */
545    flags = bnet_set_blocking(bsock);
546
547    err = SSL_shutdown(bsock->tls->openssl);
548
549    switch (SSL_get_error(bsock->tls->openssl, err)) {
550       case SSL_ERROR_NONE:
551          break;
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."));
555          break;
556       default:
557          /* Socket Error Occured */
558          openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
559          break;
560    }
561
562    /* Restore saved flags */
563    bnet_restore_blocking(bsock, flags);
564 }
565
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)
568 {
569    TLS_CONNECTION *tls = bsock->tls;
570    int fdmax, flags;
571    fd_set fdset;
572    struct timeval tv;
573    int nleft = 0;
574    int nwritten = 0;
575
576    /* Zero the fdset, we'll set our fd prior to each invocation of select() */
577    FD_ZERO(&fdset);
578    tv.tv_sec = 10;
579    tv.tv_usec = 0;
580    fdmax = bsock->fd + 1;
581
582    /* Ensure that socket is non-blocking */
583    flags = bnet_set_nonblocking(bsock);
584
585    /* start timer */
586    bsock->timer_start = watchdog_time;
587    bsock->timed_out = 0;
588
589    nleft = nbytes;
590
591    while (nleft > 0) { 
592
593       if (write) {
594          nwritten = SSL_write(tls->openssl, ptr, nleft);
595       } else {
596          nwritten = SSL_read(tls->openssl, ptr, nleft);
597       }
598
599       /* Handle errors */
600       switch (SSL_get_error(tls->openssl, nwritten)) {
601          case SSL_ERROR_NONE:
602             nleft -= nwritten;
603             if (nleft) {
604                ptr += nwritten;
605             }
606             break;
607          case SSL_ERROR_ZERO_RETURN:
608             /* TLS connection was cleanly shut down */
609             openssl_post_errors(M_ERROR, _("TLS read/write failure."));
610             goto cleanup;
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);
616             break;
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);
622             break;
623          default:
624             /* Socket Error Occured */
625             openssl_post_errors(M_ERROR, _("TLS read/write failure."));
626             goto cleanup;
627       }
628
629       /* Everything done? */
630       if (nleft == 0) {
631          goto cleanup;
632       }
633
634       /* Timeout/Termination, let's take what we can get */
635       if (bsock->timed_out || bsock->terminated) {
636          goto cleanup;
637       }
638    }
639
640 cleanup:
641    /* Restore saved flags */
642    bnet_restore_blocking(bsock, flags);
643
644    /* Clear timer */
645    bsock->timer_start = 0;
646
647    return nbytes - nleft;
648 }
649
650
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));
654 }
655
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));
659 }
660
661 #else /* HAVE_OPENSSL */
662 # error No TLS implementation available.
663 #endif /* !HAVE_OPENSSL */
664
665 #else
666
667 /* Dummy routines */
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,
672                              bool verify_peer)
673 {
674    return NULL;
675 }
676 void free_tls_context(TLS_CONTEXT *ctx) { }
677
678 #endif /* HAVE_TLS */