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