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