]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/tls.c
Change copyright as per agreement with FSFE
[bacula/bacula] / bacula / src / lib / tls.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2016 Kern Sibbald
5
6    The original author of Bacula is Kern Sibbald, with contributions
7    from many others, a complete list can be found in the file AUTHORS.
8
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.
13
14    This notice must be preserved when any source code is 
15    conveyed and/or propagated.
16
17    Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20  * tls.c TLS support functions
21  *
22  * Author: Landon Fuller <landonf@threerings.net>
23  *
24  * This file was contributed to the Bacula project by Landon Fuller
25  * and Three Rings Design, Inc.
26  *
27  * Three Rings Design, Inc. has been granted a perpetual, worldwide,
28  * non-exclusive, no-charge, royalty-free, irrevocable copyright
29  * license to reproduce, prepare derivative works of, publicly
30  * display, publicly perform, sublicense, and distribute the original
31  * work contributed by Three Rings Design, Inc. and its employees to
32  * the Bacula project in source or object form.
33  *
34  * If you wish to license contributions from Three Rings Design, Inc,
35  * under an alternate open source license please contact
36  * Landon Fuller <landonf@threerings.net>.
37  */
38
39
40 #include "bacula.h"
41 #include <assert.h>
42
43
44 #ifdef HAVE_TLS /* Is TLS enabled? */
45
46 #ifdef HAVE_OPENSSL /* How about OpenSSL? */
47
48 /* No anonymous ciphers, no <128 bit ciphers, no export ciphers, no MD5 ciphers */
49 #define TLS_DEFAULT_CIPHERS "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
50
51 /* TLS Context Structure */
52 struct TLS_Context {
53    SSL_CTX *openssl;
54    CRYPTO_PEM_PASSWD_CB *pem_callback;
55    const void *pem_userdata;
56    bool tls_enable;
57    bool tls_require;
58 };
59
60 struct TLS_Connection {
61    SSL *openssl;
62    pthread_mutex_t wlock;  /* make openssl_bsock_readwrite() atomic when writing */
63    pthread_mutex_t rwlock; /* only one SSL_read() or SSL_write() at a time */
64 };
65
66 /*
67  * OpenSSL certificate verification callback.
68  * OpenSSL has already performed internal certificate verification.
69  * We just report any errors that occured.
70  */
71 static int openssl_verify_peer(int ok, X509_STORE_CTX *store)
72 {
73    if (!ok) {
74       X509 *cert = X509_STORE_CTX_get_current_cert(store);
75       int depth = X509_STORE_CTX_get_error_depth(store);
76       int err = X509_STORE_CTX_get_error(store);
77       char issuer[256];
78       char subject[256];
79
80       X509_NAME_oneline(X509_get_issuer_name(cert), issuer, 256);
81       X509_NAME_oneline(X509_get_subject_name(cert), subject, 256);
82
83       Jmsg5(NULL, M_ERROR, 0, _("Error with certificate at depth: %d, issuer = %s,"
84             " subject = %s, ERR=%d:%s\n"), depth, issuer,
85               subject, err, X509_verify_cert_error_string(err));
86
87    }
88
89    return ok;
90 }
91
92 /* Dispatch user PEM encryption callbacks */
93 static int tls_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
94 {
95    TLS_CONTEXT *ctx = (TLS_CONTEXT *)userdata;
96    return (ctx->pem_callback(buf, size, ctx->pem_userdata));
97 }
98
99 /*
100  * Create a new TLS_CONTEXT instance.
101  *  Returns: Pointer to TLS_CONTEXT instance on success
102  *           NULL on failure;
103  */
104 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
105                              const char *certfile, const char *keyfile,
106                              CRYPTO_PEM_PASSWD_CB *pem_callback,
107                              const void *pem_userdata, const char *dhfile,
108                              bool verify_peer)
109 {
110    TLS_CONTEXT *ctx;
111    BIO *bio;
112    DH *dh;
113
114    ctx = (TLS_CONTEXT *)malloc(sizeof(TLS_CONTEXT));
115
116    /* Allocate our OpenSSL TLS Context */
117 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
118    /* Allows SSLv3, TLSv1, TLSv1.1 and TLSv1.2 protocols */
119    ctx->openssl = SSL_CTX_new(TLS_method());
120
121 #elif (OPENSSL_VERSION_NUMBER >= 0x10000000L)
122    /* Allows most all protocols */
123    ctx->openssl = SSL_CTX_new(SSLv23_method());
124
125 #else
126    /* Older method only understands TLSv1 */
127    ctx->openssl = SSL_CTX_new(TLSv1_method());
128 #endif
129
130    /* Use SSL_OP_ALL to turn on all "rather harmless" workarounds that
131     * OpenSSL offers 
132     */
133    SSL_CTX_set_options(ctx->openssl, SSL_OP_ALL);
134
135    /* Now disable old broken SSLv3 and SSLv2 protocols */
136    SSL_CTX_set_options(ctx->openssl, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
137
138    if (!ctx->openssl) {
139       openssl_post_errors(M_FATAL, _("Error initializing SSL context"));
140       goto err;
141    }
142
143    /* Set up pem encryption callback */
144    if (pem_callback) {
145       ctx->pem_callback = pem_callback;
146       ctx->pem_userdata = pem_userdata;
147    } else {
148       ctx->pem_callback = crypto_default_pem_callback;
149       ctx->pem_userdata = NULL;
150    }
151    SSL_CTX_set_default_passwd_cb(ctx->openssl, tls_pem_callback_dispatch);
152    SSL_CTX_set_default_passwd_cb_userdata(ctx->openssl, (void *) ctx);
153
154    /*
155     * Set certificate verification paths. This requires that at least one
156     * value be non-NULL
157     */
158    if (ca_certfile || ca_certdir) {
159       if (!SSL_CTX_load_verify_locations(ctx->openssl, ca_certfile, ca_certdir)) {
160          openssl_post_errors(M_FATAL, _("Error loading certificate verification stores"));
161          goto err;
162       }
163    } else if (verify_peer) {
164       /* At least one CA is required for peer verification */
165       Jmsg0(NULL, M_ERROR, 0, _("Either a certificate file or a directory must be"
166                          " specified as a verification store\n"));
167       goto err;
168    }
169
170    /*
171     * Load our certificate file, if available. This file may also contain a
172     * private key, though this usage is somewhat unusual.
173     */
174    if (certfile) {
175       if (!SSL_CTX_use_certificate_chain_file(ctx->openssl, certfile)) {
176          openssl_post_errors(M_FATAL, _("Error loading certificate file"));
177          goto err;
178       }
179    }
180
181    /* Load our private key. */
182    if (keyfile) {
183       if (!SSL_CTX_use_PrivateKey_file(ctx->openssl, keyfile, SSL_FILETYPE_PEM)) {
184          openssl_post_errors(M_FATAL, _("Error loading private key"));
185          goto err;
186       }
187    }
188
189    /* Load Diffie-Hellman Parameters. */
190    if (dhfile) {
191       if (!(bio = BIO_new_file(dhfile, "r"))) {
192          openssl_post_errors(M_FATAL, _("Unable to open DH parameters file"));
193          goto err;
194       }
195       dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
196       BIO_free(bio);
197       if (!dh) {
198          openssl_post_errors(M_FATAL, _("Unable to load DH parameters from specified file"));
199          goto err;
200       }
201       if (!SSL_CTX_set_tmp_dh(ctx->openssl, dh)) {
202          openssl_post_errors(M_FATAL, _("Failed to set TLS Diffie-Hellman parameters"));
203          DH_free(dh);
204          goto err;
205       }
206       /* Enable Single-Use DH for Ephemeral Keying */
207       SSL_CTX_set_options(ctx->openssl, SSL_OP_SINGLE_DH_USE);
208    }
209
210    if (SSL_CTX_set_cipher_list(ctx->openssl, TLS_DEFAULT_CIPHERS) != 1) {
211       Jmsg0(NULL, M_ERROR, 0,
212              _("Error setting cipher list, no valid ciphers available\n"));
213       goto err;
214    }
215
216    /* Verify Peer Certificate */
217    if (verify_peer) {
218       /* SSL_VERIFY_FAIL_IF_NO_PEER_CERT has no effect in client mode */
219       SSL_CTX_set_verify(ctx->openssl,
220                          SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
221                          openssl_verify_peer);
222    }
223
224    return ctx;
225
226 err:
227    /* Clean up after ourselves */
228    if(ctx->openssl) {
229       SSL_CTX_free(ctx->openssl);
230    }
231    free(ctx);
232    return NULL;
233 }
234
235 /*
236  * Free TLS_CONTEXT instance
237  */
238 void free_tls_context(TLS_CONTEXT *ctx)
239 {
240    SSL_CTX_free(ctx->openssl);
241    free(ctx);
242 }
243
244 bool get_tls_require(TLS_CONTEXT *ctx)
245 {
246    return ctx->tls_require;
247 }
248
249 bool get_tls_enable(TLS_CONTEXT *ctx)
250 {
251    return ctx->tls_enable;
252 }
253
254
255 /*
256  * Verifies a list of common names against the certificate
257  * commonName attribute.
258  *  Returns: true on success
259  *           false on failure
260  */
261 bool tls_postconnect_verify_cn(JCR *jcr, TLS_CONNECTION *tls, alist *verify_list)
262 {
263    SSL *ssl = tls->openssl;
264    X509 *cert;
265    X509_NAME *subject;
266    bool auth_success = false;
267    char data[256];
268
269    /* Check if peer provided a certificate */
270    if (!(cert = SSL_get_peer_certificate(ssl))) {
271       Qmsg0(jcr, M_ERROR, 0, _("Peer failed to present a TLS certificate\n"));
272       return false;
273    }
274
275    if ((subject = X509_get_subject_name(cert)) != NULL) {
276       if (X509_NAME_get_text_by_NID(subject, NID_commonName, data, sizeof(data)) > 0) {
277          char *cn;
278          /* NULL terminate data */
279          data[255] = 0;
280
281          /* Try all the CNs in the list */
282          foreach_alist(cn, verify_list) {
283             if (strcasecmp(data, cn) == 0) {
284                auth_success = true;
285             }
286          }
287       }
288    }
289
290    X509_free(cert);
291    return auth_success;
292 }
293
294 /*
295  * Verifies a peer's hostname against the subjectAltName and commonName
296  * attributes.
297  *  Returns: true on success
298  *           false on failure
299  */
300 bool tls_postconnect_verify_host(JCR *jcr, TLS_CONNECTION *tls, const char *host)
301 {
302    SSL *ssl = tls->openssl;
303    X509 *cert;
304    X509_NAME *subject;
305    bool auth_success = false;
306    int extensions;
307    int i, j;
308    const char *pval, *phost;
309
310    int cnLastPos = -1;
311    X509_NAME_ENTRY *neCN;
312    ASN1_STRING *asn1CN;
313
314    /* Check if peer provided a certificate */
315    if (!(cert = SSL_get_peer_certificate(ssl))) {
316       Qmsg1(jcr, M_ERROR, 0,
317             _("Peer %s failed to present a TLS certificate\n"), host);
318       Dmsg1(250, _("Peer %s failed to present a TLS certificate\n"), host);
319       return false;
320    }
321
322    /* Check subjectAltName extensions first */
323    if ((extensions = X509_get_ext_count(cert)) > 0) {
324       for (i = 0; i < extensions; i++) {
325          X509_EXTENSION *ext;
326          const char *extname;
327
328          ext = X509_get_ext(cert, i);
329          extname = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));
330
331          if (strcmp(extname, "subjectAltName") == 0) {
332 #ifdef HAVE_OPENSSLv1
333             const X509V3_EXT_METHOD *method;
334 #else
335             X509V3_EXT_METHOD *method;
336 #endif
337             STACK_OF(CONF_VALUE) *val;
338             CONF_VALUE *nval;
339             void *extstr = NULL;
340 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
341             const unsigned char *ext_value_data;
342 #else
343             unsigned char *ext_value_data;
344 #endif
345
346             /* Get x509 extension method structure */
347             if (!(method = X509V3_EXT_get(ext))) {
348                break;
349             }
350
351             ext_value_data = ext->value->data;
352
353 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
354             if (method->it) {
355                /* New style ASN1 */
356
357                /* Decode ASN1 item in data */
358                extstr = ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
359                                       ASN1_ITEM_ptr(method->it));
360             } else {
361                /* Old style ASN1 */
362
363                /* Decode ASN1 item in data */
364                extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
365             }
366
367 #else
368             extstr = method->d2i(NULL, &ext_value_data, ext->value->length);
369 #endif
370
371             /* Iterate through to find the dNSName field(s) */
372             val = method->i2v(method, extstr, NULL);
373
374             /* dNSName shortname is "DNS" */
375             Dmsg0(250, "Check DNS name\n");
376             for (j = 0; j < sk_CONF_VALUE_num(val); j++) {
377                nval = sk_CONF_VALUE_value(val, j);
378                if (strcmp(nval->name, "DNS") == 0) {
379                   if (strncasecmp(nval->value, "*.", 2) == 0) {
380                      Dmsg0(250, "Wildcard Certificate\n");
381                      pval = strstr(nval->value, ".");
382                      phost = strstr(host, ".");
383                      if (pval && phost && (strcasecmp(pval, phost) == 0)) {
384                         auth_success = true;
385                         goto success;
386                      }
387                   } else if (strcasecmp(nval->value, host) == 0) {
388                      auth_success = true;
389                      goto success;
390                   }
391                   Dmsg2(250, "No DNS name match. Host=%s cert=%s\n", host, nval->value);
392                }
393             }
394          }
395       }
396    }
397
398    /* Try verifying against the subject name */
399    if (!auth_success) {
400       Dmsg0(250, "Check subject name name\n");
401       if ((subject = X509_get_subject_name(cert)) != NULL) {
402          /* Loop through all CNs */
403          for (;;) {
404             cnLastPos = X509_NAME_get_index_by_NID(subject, NID_commonName, cnLastPos);
405             if (cnLastPos == -1) {
406                break;
407             }
408             neCN = X509_NAME_get_entry(subject, cnLastPos);
409             asn1CN = X509_NAME_ENTRY_get_data(neCN);
410             if (strncasecmp((const char*)asn1CN->data, "*.", 2) == 0) {
411                /* wildcard certificate */
412                Dmsg0(250, "Wildcard Certificate\n");
413                pval = strstr((const char*)asn1CN->data, ".");
414                phost = strstr(host, ".");
415                if (pval && phost && (strcasecmp(pval, phost) == 0)) {
416                   auth_success = true;
417                   goto success;
418                }
419             } else if (strcasecmp((const char*)asn1CN->data, host) == 0) {
420                auth_success = true;
421                break;
422             }
423             Dmsg2(250, "No subject name match. Host=%s cert=%s\n", host, (const char*)asn1CN->data);
424          }
425       }
426    }
427
428 success:
429    X509_free(cert);
430    return auth_success;
431 }
432
433 /*
434  * Create a new TLS_CONNECTION instance.
435  *
436  * Returns: Pointer to TLS_CONNECTION instance on success
437  *          NULL on failure;
438  */
439 TLS_CONNECTION *new_tls_connection(TLS_CONTEXT *ctx, int fd)
440 {
441    BIO *bio;
442
443    /*
444     * Create a new BIO and assign the fd.
445     * The caller will remain responsible for closing the associated fd
446     */
447    bio = BIO_new(BIO_s_socket());
448    if (!bio) {
449       /* Not likely, but never say never */
450       openssl_post_errors(M_FATAL, _("Error creating file descriptor-based BIO"));
451       return NULL; /* Nothing allocated, nothing to clean up */
452    }
453    BIO_set_fd(bio, fd, BIO_NOCLOSE);
454
455    /* Allocate our new tls connection */
456    TLS_CONNECTION *tls = (TLS_CONNECTION *)malloc(sizeof(TLS_CONNECTION));
457
458    /* Create the SSL object and attach the socket BIO */
459    if ((tls->openssl = SSL_new(ctx->openssl)) == NULL) {
460       /* Not likely, but never say never */
461       openssl_post_errors(M_FATAL, _("Error creating new SSL object"));
462       goto err;
463    }
464
465    SSL_set_bio(tls->openssl, bio, bio);
466
467    /* Non-blocking partial writes */
468    SSL_set_mode(tls->openssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
469
470    pthread_mutex_init(&tls->wlock, NULL);
471    pthread_mutex_init(&tls->rwlock, NULL);
472
473    return tls;
474
475 err:
476    /* Clean up */
477    BIO_free(bio);
478    SSL_free(tls->openssl);
479    free(tls);
480    return NULL;
481 }
482
483 /*
484  * Free TLS_CONNECTION instance
485  */
486 void free_tls_connection(TLS_CONNECTION *tls)
487 {
488    pthread_mutex_destroy(&tls->rwlock);
489    pthread_mutex_destroy(&tls->wlock);
490    SSL_free(tls->openssl);
491    free(tls);
492 }
493
494 /* Does all the manual labor for tls_bsock_accept() and tls_bsock_connect() */
495 static inline bool openssl_bsock_session_start(BSOCK *bsock, bool server)
496 {
497    TLS_CONNECTION *tls = bsock->tls;
498    int err;
499    int fdmax, flags;
500    int stat = true;
501    fd_set fdset;
502    struct timeval tv;
503
504    /* Zero the fdset, we'll set our fd prior to each invocation of select() */
505    FD_ZERO(&fdset);
506    fdmax = bsock->m_fd + 1;
507
508    /* Ensure that socket is non-blocking */
509    flags = bsock->set_nonblocking();
510
511    /* start timer */
512    bsock->timer_start = watchdog_time;
513    bsock->clear_timed_out();
514    bsock->set_killable(false);
515
516    for (;;) {
517       if (server) {
518          err = SSL_accept(tls->openssl);
519       } else {
520          err = SSL_connect(tls->openssl);
521       }
522
523       /* Handle errors */
524       switch (SSL_get_error(tls->openssl, err)) {
525       case SSL_ERROR_NONE:
526          stat = true;
527          goto cleanup;
528       case SSL_ERROR_ZERO_RETURN:
529          /* TLS connection was cleanly shut down */
530          openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
531          stat = false;
532          goto cleanup;
533       case SSL_ERROR_WANT_READ:
534          /* If we timeout of a select, this will be unset */
535          FD_SET((unsigned) bsock->m_fd, &fdset);
536          /* Set our timeout */
537          tv.tv_sec = 10;
538          tv.tv_usec = 0;
539          /* Block until we can read */
540          select(fdmax, &fdset, NULL, NULL, &tv);
541          break;
542       case SSL_ERROR_WANT_WRITE:
543          /* If we timeout of a select, this will be unset */
544          FD_SET((unsigned) bsock->m_fd, &fdset);
545          /* Set our timeout */
546          tv.tv_sec = 10;
547          tv.tv_usec = 0;
548          /* Block until we can write */
549          select(fdmax, NULL, &fdset, NULL, &tv);
550          break;
551       default:
552          /* Socket Error Occurred */
553          openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
554          stat = false;
555          goto cleanup;
556       }
557
558       if (bsock->is_timed_out()) {
559          goto cleanup;
560       }
561    }
562
563 cleanup:
564    /* Restore saved flags */
565    bsock->restore_blocking(flags);
566    /* Clear timer */
567    bsock->timer_start = 0;
568    bsock->set_killable(true);
569
570    return stat;
571 }
572
573 /*
574  * Initiates a TLS connection with the server.
575  *  Returns: true on success
576  *           false on failure
577  */
578 bool tls_bsock_connect(BSOCK *bsock)
579 {
580    /* SSL_connect(bsock->tls) */
581    return openssl_bsock_session_start(bsock, false);
582 }
583
584 /*
585  * Listens for a TLS connection from a client.
586  *  Returns: true on success
587  *           false on failure
588  */
589 bool tls_bsock_accept(BSOCK *bsock)
590 {
591    /* SSL_accept(bsock->tls) */
592    return openssl_bsock_session_start(bsock, true);
593 }
594
595 /*
596  * Shutdown TLS_CONNECTION instance
597  */
598 void tls_bsock_shutdown(BSOCK *bsock)
599 {
600    /*
601     * SSL_shutdown must be called twice to fully complete the process -
602     * The first time to initiate the shutdown handshake, and the second to
603     * receive the peer's reply.
604     *
605     * In addition, if the underlying socket is blocking, SSL_shutdown()
606     * will not return until the current stage of the shutdown process has
607     * completed or an error has occured. By setting the socket blocking
608     * we can avoid the ugly for()/switch()/select() loop.
609     */
610    int err;
611
612    btimer_t *tid;
613
614    /* Set socket blocking for shutdown */
615    bsock->set_blocking();
616
617    tid = start_bsock_timer(bsock, 60 * 2);
618    err = SSL_shutdown(bsock->tls->openssl);
619    stop_bsock_timer(tid);
620    if (err == 0) {
621       /* Complete shutdown */
622       tid = start_bsock_timer(bsock, 60 * 2);
623       err = SSL_shutdown(bsock->tls->openssl);
624       stop_bsock_timer(tid);
625    }
626
627
628    switch (SSL_get_error(bsock->tls->openssl, err)) {
629    case SSL_ERROR_NONE:
630       break;
631    case SSL_ERROR_ZERO_RETURN:
632       /* TLS connection was shut down on us via a TLS protocol-level closure */
633       openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
634       break;
635    default:
636       /* Socket Error Occurred */
637       openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
638       break;
639    }
640 }
641
642 /* Does all the manual labor for tls_bsock_readn() and tls_bsock_writen() */
643 static inline int openssl_bsock_readwrite(BSOCK *bsock, char *ptr, int nbytes, bool write)
644 {
645    TLS_CONNECTION *tls = bsock->tls;
646    int fdmax, flags;
647    fd_set fdset;
648    struct timeval tv;
649    int nleft = 0;
650    int nwritten = 0;
651
652    /* Zero the fdset, we'll set our fd prior to each invocation of select() */
653    FD_ZERO(&fdset);
654    fdmax = bsock->m_fd + 1;
655
656    /* Ensure that socket is non-blocking */
657    flags = bsock->set_nonblocking();
658
659    /* start timer */
660    bsock->timer_start = watchdog_time;
661    bsock->clear_timed_out();
662    bsock->set_killable(false);
663
664    nleft = nbytes;
665
666    if (write) {
667       pthread_mutex_lock(&tls->wlock);
668    }
669    while (nleft > 0) {
670
671       pthread_mutex_lock(&tls->rwlock);
672       if (write) {
673          nwritten = SSL_write(tls->openssl, ptr, nleft);
674       } else {
675          nwritten = SSL_read(tls->openssl, ptr, nleft);
676       }
677       pthread_mutex_unlock(&tls->rwlock);
678
679       /* Handle errors */
680       switch (SSL_get_error(tls->openssl, nwritten)) {
681       case SSL_ERROR_NONE:
682          nleft -= nwritten;
683          if (nleft) {
684             ptr += nwritten;
685          }
686          break;
687
688       case SSL_ERROR_SYSCALL:
689          if (nwritten == -1) {
690             if (errno == EINTR) {
691                continue;
692             }
693             if (errno == EAGAIN) {
694                bmicrosleep(0, 20000); /* try again in 20 ms */
695                continue;
696             }
697          }
698          openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
699          goto cleanup;
700
701       case SSL_ERROR_WANT_READ:
702          /* If we timeout on a select, this will be unset */
703          FD_SET((unsigned)bsock->m_fd, &fdset);
704          tv.tv_sec = 10;
705          tv.tv_usec = 0;
706          /* Block until we can read */
707          select(fdmax, &fdset, NULL, NULL, &tv);
708          break;
709
710       case SSL_ERROR_WANT_WRITE:
711          /* If we timeout on a select, this will be unset */
712          FD_SET((unsigned)bsock->m_fd, &fdset);
713          tv.tv_sec = 10;
714          tv.tv_usec = 0;
715          /* Block until we can write */
716          select(fdmax, NULL, &fdset, NULL, &tv);
717          break;
718
719       case SSL_ERROR_ZERO_RETURN:
720          /* TLS connection was cleanly shut down */
721          /* Fall through wanted */
722       default:
723          /* Socket Error Occured */
724          openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
725          goto cleanup;
726       }
727
728       /* Everything done? */
729       if (nleft == 0) {
730          goto cleanup;
731       }
732
733       /* Timeout/Termination, let's take what we can get */
734       if (bsock->is_timed_out() || bsock->is_terminated()) {
735          goto cleanup;
736       }
737    }
738
739 cleanup:
740    if (write) {
741       pthread_mutex_unlock(&tls->wlock);
742    }
743    /* Restore saved flags */
744    bsock->restore_blocking(flags);
745
746    /* Clear timer */
747    bsock->timer_start = 0;
748    bsock->set_killable(true);
749    return nbytes - nleft;
750 }
751
752
753 int tls_bsock_writen(BSOCK *bsock, char *ptr, int32_t nbytes)
754 {
755    /* SSL_write(bsock->tls->openssl, ptr, nbytes) */
756    return openssl_bsock_readwrite(bsock, ptr, nbytes, true);
757 }
758
759 int tls_bsock_readn(BSOCK *bsock, char *ptr, int32_t nbytes)
760 {
761    /* SSL_read(bsock->tls->openssl, ptr, nbytes) */
762    return openssl_bsock_readwrite(bsock, ptr, nbytes, false);
763 }
764
765 /* test if 4 bytes can be read without "blocking" */
766 bool tls_bsock_probe(BSOCK *bsock)
767 {
768    int32_t pktsiz;
769    return SSL_peek(bsock->tls->openssl, &pktsiz, sizeof(pktsiz))==sizeof(pktsiz);
770 }
771
772
773 #else /* HAVE_OPENSSL */
774 # error No TLS implementation available.
775 #endif /* !HAVE_OPENSSL */
776
777
778 #else     /* TLS NOT enabled, dummy routines substituted */
779
780
781 /* Dummy routines */
782 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
783                              const char *certfile, const char *keyfile,
784                              CRYPTO_PEM_PASSWD_CB *pem_callback,
785                              const void *pem_userdata, const char *dhfile,
786                              bool verify_peer)
787 {
788    return NULL;
789 }
790 void free_tls_context(TLS_CONTEXT *ctx) { }
791
792 void tls_bsock_shutdown(BSOCK *bsock) { }
793
794 void free_tls_connection(TLS_CONNECTION *tls) { }
795
796 bool get_tls_require(TLS_CONTEXT *ctx)
797 {
798    return false;
799 }
800
801 bool get_tls_enable(TLS_CONTEXT *ctx)
802 {
803    return false;
804 }
805
806 #endif /* HAVE_TLS */