]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/tls.c
- Remove warning message about multiple saves of hardlinked files
[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    fdmax = bsock->fd + 1;
436
437    /* Ensure that socket is non-blocking */
438    flags = bnet_set_nonblocking(bsock);
439
440    /* start timer */
441    bsock->timer_start = watchdog_time;
442    bsock->timed_out = 0;
443
444    for (;;) { 
445       if (server) {
446          err = SSL_accept(tls->openssl);
447       } else {
448          err = SSL_connect(tls->openssl);
449       }
450
451       /* Handle errors */
452       switch (SSL_get_error(tls->openssl, err)) {
453       case SSL_ERROR_NONE:
454          stat = true;
455          goto cleanup;
456       case SSL_ERROR_ZERO_RETURN:
457          /* TLS connection was cleanly shut down */
458          openssl_post_errors(M_ERROR, _("Connect failure"));
459          stat = false;
460          goto cleanup;
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 */
465          tv.tv_sec = 10;
466          tv.tv_usec = 0;
467          /* Block until we can read */
468          select(fdmax, &fdset, NULL, &fdset, &tv);
469          break;
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 */
474          tv.tv_sec = 10;
475          tv.tv_usec = 0;
476          /* Block until we can write */
477          select(fdmax, NULL, &fdset, &fdset, &tv);
478          break;
479       default:
480          /* Socket Error Occured */
481          openssl_post_errors(M_ERROR, _("Connect failure"));
482          stat = false;
483          goto cleanup;
484       }
485
486       if (bsock->timed_out) {
487          goto cleanup;
488       }
489    }
490
491 cleanup:
492    /* Restore saved flags */
493    bnet_restore_blocking(bsock, flags);
494    /* Clear timer */
495    bsock->timer_start = 0;
496
497    return stat;
498 }
499
500 /*
501  * Initiates a TLS connection with the server.
502  *  Returns: true on success
503  *           false on failure
504  */
505 bool tls_bsock_connect(BSOCK *bsock)
506 {
507    /* SSL_connect(bsock->tls) */
508    return (openssl_bsock_session_start(bsock, false));
509 }
510
511 /*
512  * Listens for a TLS connection from a client.
513  *  Returns: true on success
514  *           false on failure
515  */
516 bool tls_bsock_accept(BSOCK *bsock)
517 {
518    /* SSL_accept(bsock->tls) */
519    return (openssl_bsock_session_start(bsock, true));
520 }
521
522 /*
523  * Shutdown TLS_CONNECTION instance
524  */
525 void tls_bsock_shutdown (BSOCK *bsock)
526 {
527    /*
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.
531     *
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.
536     *
537     * Because we do not re-use SSL connection objects, I do not bother
538     * calling SSL_shutdown a second time.
539     *
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.
544     */
545    int err;
546    int flags;
547
548    /* Set socket blocking for shutdown */
549    flags = bnet_set_blocking(bsock);
550
551    err = SSL_shutdown(bsock->tls->openssl);
552
553    switch (SSL_get_error(bsock->tls->openssl, err)) {
554       case SSL_ERROR_NONE:
555          break;
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."));
559          break;
560       default:
561          /* Socket Error Occured */
562          openssl_post_errors(M_ERROR, _("TLS shutdown failure."));
563          break;
564    }
565
566    /* Restore saved flags */
567    bnet_restore_blocking(bsock, flags);
568 }
569
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)
572 {
573    TLS_CONNECTION *tls = bsock->tls;
574    int fdmax, flags;
575    fd_set fdset;
576    struct timeval tv;
577    int nleft = 0;
578    int nwritten = 0;
579
580    /* Zero the fdset, we'll set our fd prior to each invocation of select() */
581    FD_ZERO(&fdset);
582    fdmax = bsock->fd + 1;
583
584    /* Ensure that socket is non-blocking */
585    flags = bnet_set_nonblocking(bsock);
586
587    /* start timer */
588    bsock->timer_start = watchdog_time;
589    bsock->timed_out = 0;
590
591    nleft = nbytes;
592
593    while (nleft > 0) { 
594
595       if (write) {
596          nwritten = SSL_write(tls->openssl, ptr, nleft);
597       } else {
598          nwritten = SSL_read(tls->openssl, ptr, nleft);
599       }
600
601       /* Handle errors */
602       switch (SSL_get_error(tls->openssl, nwritten)) {
603       case SSL_ERROR_NONE:
604          nleft -= nwritten;
605          if (nleft) {
606             ptr += nwritten;
607          }
608          break;
609       case SSL_ERROR_ZERO_RETURN:
610          /* TLS connection was cleanly shut down */
611          openssl_post_errors(M_ERROR, _("TLS read/write failure."));
612          goto cleanup;
613       case SSL_ERROR_WANT_READ:
614          /* If we timeout of a select, this will be unset */
615          FD_SET((unsigned) bsock->fd, &fdset);
616          tv.tv_sec = 10;
617          tv.tv_usec = 0;
618          /* Block until we can read */
619          select(fdmax, &fdset, NULL, &fdset, &tv);
620          break;
621       case SSL_ERROR_WANT_WRITE:
622          /* If we timeout of a select, this will be unset */
623          FD_SET((unsigned) bsock->fd, &fdset);
624          tv.tv_sec = 10;
625          tv.tv_usec = 0;
626          /* Block until we can write */
627          select(fdmax, NULL, &fdset, &fdset, &tv);
628          break;
629       default:
630          /* Socket Error Occured */
631          openssl_post_errors(M_ERROR, _("TLS read/write failure."));
632          goto cleanup;
633       }
634
635       /* Everything done? */
636       if (nleft == 0) {
637          goto cleanup;
638       }
639
640       /* Timeout/Termination, let's take what we can get */
641       if (bsock->timed_out || bsock->terminated) {
642          goto cleanup;
643       }
644    }
645
646 cleanup:
647    /* Restore saved flags */
648    bnet_restore_blocking(bsock, flags);
649
650    /* Clear timer */
651    bsock->timer_start = 0;
652
653    return nbytes - nleft;
654 }
655
656
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));
660 }
661
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));
665 }
666
667 #else /* HAVE_OPENSSL */
668 # error No TLS implementation available.
669 #endif /* !HAVE_OPENSSL */
670
671 #else
672
673 /* Dummy routines */
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,
678                              bool verify_peer)
679 {
680    return NULL;
681 }
682 void free_tls_context(TLS_CONTEXT *ctx) { }
683
684 #endif /* HAVE_TLS */