]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/tls.c
Big backport from Enterprise
[bacula/bacula] / bacula / src / lib / tls.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2017 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 flags;
500    int stat = true;
501
502    /* Ensure that socket is non-blocking */
503    flags = bsock->set_nonblocking();
504
505    /* start timer */
506    bsock->timer_start = watchdog_time;
507    bsock->clear_timed_out();
508    bsock->set_killable(false);
509
510    for (;;) {
511       if (server) {
512          err = SSL_accept(tls->openssl);
513       } else {
514          err = SSL_connect(tls->openssl);
515       }
516
517       /* Handle errors */
518       switch (SSL_get_error(tls->openssl, err)) {
519       case SSL_ERROR_NONE:
520          stat = true;
521          goto cleanup;
522       case SSL_ERROR_ZERO_RETURN:
523          /* TLS connection was cleanly shut down */
524          openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
525          stat = false;
526          goto cleanup;
527       case SSL_ERROR_WANT_READ:
528          /* Block until we can read */
529          fd_wait_data(bsock->m_fd, WAIT_READ, 10, 0);
530          break;
531       case SSL_ERROR_WANT_WRITE:
532          /* Block until we can write */
533          fd_wait_data(bsock->m_fd, WAIT_WRITE, 10, 0);
534          break;
535       default:
536          /* Socket Error Occurred */
537          openssl_post_errors(bsock->get_jcr(), M_FATAL, _("Connect failure"));
538          stat = false;
539          goto cleanup;
540       }
541
542       if (bsock->is_timed_out()) {
543          goto cleanup;
544       }
545    }
546
547 cleanup:
548    /* Restore saved flags */
549    bsock->restore_blocking(flags);
550    /* Clear timer */
551    bsock->timer_start = 0;
552    bsock->set_killable(true);
553
554    return stat;
555 }
556
557 /*
558  * Initiates a TLS connection with the server.
559  *  Returns: true on success
560  *           false on failure
561  */
562 bool tls_bsock_connect(BSOCK *bsock)
563 {
564    /* SSL_connect(bsock->tls) */
565    return openssl_bsock_session_start(bsock, false);
566 }
567
568 /*
569  * Listens for a TLS connection from a client.
570  *  Returns: true on success
571  *           false on failure
572  */
573 bool tls_bsock_accept(BSOCK *bsock)
574 {
575    /* SSL_accept(bsock->tls) */
576    return openssl_bsock_session_start(bsock, true);
577 }
578
579 /*
580  * Shutdown TLS_CONNECTION instance
581  */
582 void tls_bsock_shutdown(BSOCK *bsock)
583 {
584    /*
585     * SSL_shutdown must be called twice to fully complete the process -
586     * The first time to initiate the shutdown handshake, and the second to
587     * receive the peer's reply.
588     *
589     * In addition, if the underlying socket is blocking, SSL_shutdown()
590     * will not return until the current stage of the shutdown process has
591     * completed or an error has occured. By setting the socket blocking
592     * we can avoid the ugly for()/switch()/select() loop.
593     */
594    int err;
595
596    btimer_t *tid;
597
598    /* Set socket blocking for shutdown */
599    bsock->set_blocking();
600
601    tid = start_bsock_timer(bsock, 60 * 2);
602    err = SSL_shutdown(bsock->tls->openssl);
603    stop_bsock_timer(tid);
604    if (err == 0) {
605       /* Complete shutdown */
606       tid = start_bsock_timer(bsock, 60 * 2);
607       err = SSL_shutdown(bsock->tls->openssl);
608       stop_bsock_timer(tid);
609    }
610
611
612    switch (SSL_get_error(bsock->tls->openssl, err)) {
613    case SSL_ERROR_NONE:
614       break;
615    case SSL_ERROR_ZERO_RETURN:
616       /* TLS connection was shut down on us via a TLS protocol-level closure */
617       openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
618       break;
619    default:
620       /* Socket Error Occurred */
621       openssl_post_errors(bsock->get_jcr(), M_ERROR, _("TLS shutdown failure."));
622       break;
623    }
624 }
625
626 /* Does all the manual labor for tls_bsock_readn() and tls_bsock_writen() */
627 static inline int openssl_bsock_readwrite(BSOCK *bsock, char *ptr, int nbytes, bool write)
628 {
629    TLS_CONNECTION *tls = bsock->tls;
630    int flags;
631    int nleft = 0;
632    int nwritten = 0;
633
634    /* Ensure that socket is non-blocking */
635    flags = bsock->set_nonblocking();
636
637    /* start timer */
638    bsock->timer_start = watchdog_time;
639    bsock->clear_timed_out();
640    bsock->set_killable(false);
641
642    nleft = nbytes;
643
644    if (write) {
645       pthread_mutex_lock(&tls->wlock);
646    }
647    while (nleft > 0) {
648
649       pthread_mutex_lock(&tls->rwlock);
650       if (write) {
651          nwritten = SSL_write(tls->openssl, ptr, nleft);
652       } else {
653          nwritten = SSL_read(tls->openssl, ptr, nleft);
654       }
655       pthread_mutex_unlock(&tls->rwlock);
656
657       /* Handle errors */
658       switch (SSL_get_error(tls->openssl, nwritten)) {
659       case SSL_ERROR_NONE:
660          nleft -= nwritten;
661          if (nleft) {
662             ptr += nwritten;
663          }
664          break;
665
666       case SSL_ERROR_SYSCALL:
667          if (nwritten == -1) {
668             if (errno == EINTR) {
669                continue;
670             }
671             if (errno == EAGAIN) {
672                bmicrosleep(0, 20000); /* try again in 20 ms */
673                continue;
674             }
675          }
676          openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
677          goto cleanup;
678
679       case SSL_ERROR_WANT_READ:
680          /* Block until we can read */
681          fd_wait_data(bsock->m_fd, WAIT_READ, 10, 0);
682          break;
683
684       case SSL_ERROR_WANT_WRITE:
685          /* Block until we can read */
686          fd_wait_data(bsock->m_fd, WAIT_WRITE, 10, 0);
687          break;
688
689       case SSL_ERROR_ZERO_RETURN:
690          /* TLS connection was cleanly shut down */
691          /* Fall through wanted */
692       default:
693          /* Socket Error Occured */
694          openssl_post_errors(bsock->get_jcr(), M_FATAL, _("TLS read/write failure."));
695          goto cleanup;
696       }
697
698       /* Everything done? */
699       if (nleft == 0) {
700          goto cleanup;
701       }
702
703       /* Timeout/Termination, let's take what we can get */
704       if (bsock->is_timed_out() || bsock->is_terminated()) {
705          goto cleanup;
706       }
707    }
708
709 cleanup:
710    if (write) {
711       pthread_mutex_unlock(&tls->wlock);
712    }
713    /* Restore saved flags */
714    bsock->restore_blocking(flags);
715
716    /* Clear timer */
717    bsock->timer_start = 0;
718    bsock->set_killable(true);
719    return nbytes - nleft;
720 }
721
722
723 int tls_bsock_writen(BSOCK *bsock, char *ptr, int32_t nbytes)
724 {
725    /* SSL_write(bsock->tls->openssl, ptr, nbytes) */
726    return openssl_bsock_readwrite(bsock, ptr, nbytes, true);
727 }
728
729 int tls_bsock_readn(BSOCK *bsock, char *ptr, int32_t nbytes)
730 {
731    /* SSL_read(bsock->tls->openssl, ptr, nbytes) */
732    return openssl_bsock_readwrite(bsock, ptr, nbytes, false);
733 }
734
735 /* test if 4 bytes can be read without "blocking" */
736 bool tls_bsock_probe(BSOCK *bsock)
737 {
738    int32_t pktsiz;
739    return SSL_peek(bsock->tls->openssl, &pktsiz, sizeof(pktsiz))==sizeof(pktsiz);
740 }
741
742
743 #else /* HAVE_OPENSSL */
744 # error No TLS implementation available.
745 #endif /* !HAVE_OPENSSL */
746
747
748 #else     /* TLS NOT enabled, dummy routines substituted */
749
750
751 /* Dummy routines */
752 TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
753                              const char *certfile, const char *keyfile,
754                              CRYPTO_PEM_PASSWD_CB *pem_callback,
755                              const void *pem_userdata, const char *dhfile,
756                              bool verify_peer)
757 {
758    return NULL;
759 }
760 void free_tls_context(TLS_CONTEXT *ctx) { }
761
762 void tls_bsock_shutdown(BSOCK *bsock) { }
763
764 void free_tls_connection(TLS_CONNECTION *tls) { }
765
766 bool get_tls_require(TLS_CONTEXT *ctx)
767 {
768    return false;
769 }
770
771 bool get_tls_enable(TLS_CONTEXT *ctx)
772 {
773    return false;
774 }
775
776 #endif /* HAVE_TLS */