DANE/GnuTLS: split verification of mixed sets of TLSA records by usage
[exim.git] / src / src / tls-gnu.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2017 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* Copyright (c) Phil Pennock 2012 */
9
10 /* This file provides TLS/SSL support for Exim using the GnuTLS library,
11 one of the available supported implementations.  This file is #included into
12 tls.c when USE_GNUTLS has been set.
13
14 The code herein is a revamp of GnuTLS integration using the current APIs; the
15 original tls-gnu.c was based on a patch which was contributed by Nikos
16 Mavrogiannopoulos.  The revamp is partially a rewrite, partially cut&paste as
17 appropriate.
18
19 APIs current as of GnuTLS 2.12.18; note that the GnuTLS manual is for GnuTLS 3,
20 which is not widely deployed by OS vendors.  Will note issues below, which may
21 assist in updating the code in the future.  Another sources of hints is
22 mod_gnutls for Apache (SNI callback registration and handling).
23
24 Keeping client and server variables more split than before and is currently
25 the norm, in anticipation of TLS in ACL callouts.
26
27 I wanted to switch to gnutls_certificate_set_verify_function() so that
28 certificate rejection could happen during handshake where it belongs, rather
29 than being dropped afterwards, but that was introduced in 2.10.0 and Debian
30 (6.0.5) is still on 2.8.6.  So for now we have to stick with sub-par behaviour.
31
32 (I wasn't looking for libraries quite that old, when updating to get rid of
33 compiler warnings of deprecated APIs.  If it turns out that a lot of the rest
34 require current GnuTLS, then we'll drop support for the ancient libraries).
35 */
36
37 #include <gnutls/gnutls.h>
38 /* needed for cert checks in verification and DN extraction: */
39 #include <gnutls/x509.h>
40 /* man-page is incorrect, gnutls_rnd() is not in gnutls.h: */
41 #include <gnutls/crypto.h>
42 /* needed to disable PKCS11 autoload unless requested */
43 #if GNUTLS_VERSION_NUMBER >= 0x020c00
44 # include <gnutls/pkcs11.h>
45 # define SUPPORT_PARAM_TO_PK_BITS
46 #endif
47 #if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
48 # warning "GnuTLS library version too old; define DISABLE_OCSP in Makefile"
49 # define DISABLE_OCSP
50 #endif
51 #if GNUTLS_VERSION_NUMBER < 0x020a00 && !defined(DISABLE_EVENT)
52 # warning "GnuTLS library version too old; tls:cert event unsupported"
53 # define DISABLE_EVENT
54 #endif
55 #if GNUTLS_VERSION_NUMBER >= 0x030306
56 # define SUPPORT_CA_DIR
57 #else
58 # undef  SUPPORT_CA_DIR
59 #endif
60 #if GNUTLS_VERSION_NUMBER >= 0x030014
61 # define SUPPORT_SYSDEFAULT_CABUNDLE
62 #endif
63 #if GNUTLS_VERSION_NUMBER >= 0x030109
64 # define SUPPORT_CORK
65 #endif
66 #if GNUTLS_VERSION_NUMBER >= 0x030506 && !defined(DISABLE_OCSP)
67 # define SUPPORT_SRV_OCSP_STACK
68 #endif
69 #if GNUTLS_VERSION_NUMBER >= 0x030000 && defined(EXPERIMENTAL_DANE)
70 # define SUPPORT_DANE
71 # define DANESSL_USAGE_DANE_TA 2
72 # define DANESSL_USAGE_DANE_EE 3
73 #endif
74 #if GNUTLS_VERSION_NUMBER < 0x999999 && defined(EXPERIMENTAL_DANE)
75 # define GNUTLS_BROKEN_DANE_VALIDATION
76 #endif
77
78 #ifndef DISABLE_OCSP
79 # include <gnutls/ocsp.h>
80 #endif
81 #ifdef SUPPORT_DANE
82 # include <gnutls/dane.h>
83 #endif
84
85 /* GnuTLS 2 vs 3
86
87 GnuTLS 3 only:
88   gnutls_global_set_audit_log_function()
89
90 Changes:
91   gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
92 */
93
94 /* Local static variables for GnuTLS */
95
96 /* Values for verify_requirement */
97
98 enum peer_verify_requirement
99   { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED, VERIFY_DANE };
100
101 /* This holds most state for server or client; with this, we can set up an
102 outbound TLS-enabled connection in an ACL callout, while not stomping all
103 over the TLS variables available for expansion.
104
105 Some of these correspond to variables in globals.c; those variables will
106 be set to point to content in one of these instances, as appropriate for
107 the stage of the process lifetime.
108
109 Not handled here: global tls_channelbinding_b64.
110 */
111
112 typedef struct exim_gnutls_state {
113   gnutls_session_t      session;
114   gnutls_certificate_credentials_t x509_cred;
115   gnutls_priority_t     priority_cache;
116   enum peer_verify_requirement verify_requirement;
117   int                   fd_in;
118   int                   fd_out;
119   BOOL                  peer_cert_verified;
120   BOOL                  peer_dane_verified;
121   BOOL                  trigger_sni_changes;
122   BOOL                  have_set_peerdn;
123   const struct host_item *host;
124   gnutls_x509_crt_t     peercert;
125   uschar                *peerdn;
126   uschar                *ciphersuite;
127   uschar                *received_sni;
128
129   const uschar *tls_certificate;
130   const uschar *tls_privatekey;
131   const uschar *tls_sni; /* client send only, not received */
132   const uschar *tls_verify_certificates;
133   const uschar *tls_crl;
134   const uschar *tls_require_ciphers;
135
136   uschar *exp_tls_certificate;
137   uschar *exp_tls_privatekey;
138   uschar *exp_tls_verify_certificates;
139   uschar *exp_tls_crl;
140   uschar *exp_tls_require_ciphers;
141   const uschar *exp_tls_verify_cert_hostnames;
142 #ifndef DISABLE_EVENT
143   uschar *event_action;
144 #endif
145 #ifdef SUPPORT_DANE
146   char * const *        dane_data;
147   const int *           dane_data_len;
148 #endif
149
150   tls_support *tlsp;    /* set in tls_init() */
151
152   uschar *xfer_buffer;
153   int xfer_buffer_lwm;
154   int xfer_buffer_hwm;
155   int xfer_eof;
156   int xfer_error;
157 } exim_gnutls_state_st;
158
159 static const exim_gnutls_state_st exim_gnutls_state_init = {
160   .session =            NULL,
161   .x509_cred =          NULL,
162   .priority_cache =     NULL,
163   .verify_requirement = VERIFY_NONE,
164   .fd_in =              -1,
165   .fd_out =             -1,
166   .peer_cert_verified = FALSE,
167   .peer_dane_verified = FALSE,
168   .trigger_sni_changes =FALSE,
169   .have_set_peerdn =    FALSE,
170   .host =               NULL,
171   .peercert =           NULL,
172   .peerdn =             NULL,
173   .ciphersuite =        NULL,
174   .received_sni =       NULL,
175
176   .tls_certificate =    NULL,
177   .tls_privatekey =     NULL,
178   .tls_sni =            NULL,
179   .tls_verify_certificates = NULL,
180   .tls_crl =            NULL,
181   .tls_require_ciphers =NULL,
182
183   .exp_tls_certificate = NULL,
184   .exp_tls_privatekey = NULL,
185   .exp_tls_verify_certificates = NULL,
186   .exp_tls_crl =        NULL,
187   .exp_tls_require_ciphers = NULL,
188   .exp_tls_verify_cert_hostnames = NULL,
189 #ifndef DISABLE_EVENT
190   .event_action =       NULL,
191 #endif
192   .tlsp =               NULL,
193
194   .xfer_buffer =        NULL,
195   .xfer_buffer_lwm =    0,
196   .xfer_buffer_hwm =    0,
197   .xfer_eof =           0,
198   .xfer_error =         0,
199 };
200
201 /* Not only do we have our own APIs which don't pass around state, assuming
202 it's held in globals, GnuTLS doesn't appear to let us register callback data
203 for callbacks, or as part of the session, so we have to keep a "this is the
204 context we're currently dealing with" pointer and rely upon being
205 single-threaded to keep from processing data on an inbound TLS connection while
206 talking to another TLS connection for an outbound check.  This does mean that
207 there's no way for heart-beats to be responded to, for the duration of the
208 second connection.
209 XXX But see gnutls_session_get_ptr()
210 */
211
212 static exim_gnutls_state_st state_server, state_client;
213
214 /* dh_params are initialised once within the lifetime of a process using TLS;
215 if we used TLS in a long-lived daemon, we'd have to reconsider this.  But we
216 don't want to repeat this. */
217
218 static gnutls_dh_params_t dh_server_params = NULL;
219
220 /* No idea how this value was chosen; preserving it.  Default is 3600. */
221
222 static const int ssl_session_timeout = 200;
223
224 static const char * const exim_default_gnutls_priority = "NORMAL";
225
226 /* Guard library core initialisation */
227
228 static BOOL exim_gnutls_base_init_done = FALSE;
229
230 #ifndef DISABLE_OCSP
231 static BOOL gnutls_buggy_ocsp = FALSE;
232 #endif
233
234
235 /* ------------------------------------------------------------------------ */
236 /* macros */
237
238 #define MAX_HOST_LEN 255
239
240 /* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
241 the library logging; a value less than 0 disables the calls to set up logging
242 callbacks.  Possibly GNuTLS also looks for an environment variable
243 "GNUTLS_DEBUG_LEVEL". */
244 #ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
245 # define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
246 #endif
247
248 #ifndef EXIM_CLIENT_DH_MIN_BITS
249 # define EXIM_CLIENT_DH_MIN_BITS 1024
250 #endif
251
252 /* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
253 can ask for a bit-strength.  Without that, we stick to the constant we had
254 before, for now. */
255 #ifndef EXIM_SERVER_DH_BITS_PRE2_12
256 # define EXIM_SERVER_DH_BITS_PRE2_12 1024
257 #endif
258
259 #define exim_gnutls_err_check(rc, Label) do { \
260   if ((rc) != GNUTLS_E_SUCCESS) \
261     return tls_error((Label), gnutls_strerror(rc), host, errstr); \
262   } while (0)
263
264 #define expand_check_tlsvar(Varname, errstr) \
265   expand_check(state->Varname, US #Varname, &state->exp_##Varname, errstr)
266
267 #if GNUTLS_VERSION_NUMBER >= 0x020c00
268 # define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
269 # define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
270 # define HAVE_GNUTLS_RND
271 /* The security fix we provide with the gnutls_allow_auto_pkcs11 option
272  * (4.82 PP/09) introduces a compatibility regression. The symbol simply
273  * isn't available sometimes, so this needs to become a conditional
274  * compilation; the sanest way to deal with this being a problem on
275  * older OSes is to block it in the Local/Makefile with this compiler
276  * definition  */
277 # ifndef AVOID_GNUTLS_PKCS11
278 #  define HAVE_GNUTLS_PKCS11
279 # endif /* AVOID_GNUTLS_PKCS11 */
280 #endif
281
282
283
284
285 /* ------------------------------------------------------------------------ */
286 /* Callback declarations */
287
288 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
289 static void exim_gnutls_logger_cb(int level, const char *message);
290 #endif
291
292 static int exim_sni_handling_cb(gnutls_session_t session);
293
294 #ifndef DISABLE_OCSP
295 static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
296   gnutls_datum_t * ocsp_response);
297 #endif
298
299
300
301 /* ------------------------------------------------------------------------ */
302 /* Static functions */
303
304 /*************************************************
305 *               Handle TLS error                 *
306 *************************************************/
307
308 /* Called from lots of places when errors occur before actually starting to do
309 the TLS handshake, that is, while the session is still in clear. Always returns
310 DEFER for a server and FAIL for a client so that most calls can use "return
311 tls_error(...)" to do this processing and then give an appropriate return. A
312 single function is used for both server and client, because it is called from
313 some shared functions.
314
315 Argument:
316   prefix    text to include in the logged error
317   msg       additional error string (may be NULL)
318             usually obtained from gnutls_strerror()
319   host      NULL if setting up a server;
320             the connected host if setting up a client
321   errstr    pointer to returned error string
322
323 Returns:    OK/DEFER/FAIL
324 */
325
326 static int
327 tls_error(const uschar *prefix, const char *msg, const host_item *host,
328   uschar ** errstr)
329 {
330 if (errstr)
331   *errstr = string_sprintf("(%s)%s%s", prefix, msg ? ": " : "", msg ? msg : "");
332 return host ? FAIL : DEFER;
333 }
334
335
336
337
338 /*************************************************
339 *    Deal with logging errors during I/O         *
340 *************************************************/
341
342 /* We have to get the identity of the peer from saved data.
343
344 Argument:
345   state    the current GnuTLS exim state container
346   rc       the GnuTLS error code, or 0 if it's a local error
347   when     text identifying read or write
348   text     local error text when ec is 0
349
350 Returns:   nothing
351 */
352
353 static void
354 record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
355 {
356 const char * msg;
357 uschar * errstr;
358
359 if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
360   msg = CS string_sprintf("%s: %s", US gnutls_strerror(rc),
361     US gnutls_alert_get_name(gnutls_alert_get(state->session)));
362 else
363   msg = gnutls_strerror(rc);
364
365 (void) tls_error(when, msg, state->host, &errstr);
366
367 if (state->host)
368   log_write(0, LOG_MAIN, "H=%s [%s] TLS error on connection %s",
369     state->host->name, state->host->address, errstr);
370 else
371   {
372   uschar * conn_info = smtp_get_connection_info();
373   if (Ustrncmp(conn_info, US"SMTP ", 5) == 0) conn_info += 5;
374   /* I'd like to get separated H= here, but too hard for now */
375   log_write(0, LOG_MAIN, "TLS error on %s %s", conn_info, errstr);
376   }
377 }
378
379
380
381
382 /*************************************************
383 *        Set various Exim expansion vars         *
384 *************************************************/
385
386 #define exim_gnutls_cert_err(Label) \
387   do \
388     { \
389     if (rc != GNUTLS_E_SUCCESS) \
390       { \
391       DEBUG(D_tls) debug_printf("TLS: cert problem: %s: %s\n", \
392         (Label), gnutls_strerror(rc)); \
393       return rc; \
394       } \
395     } while (0)
396
397 static int
398 import_cert(const gnutls_datum_t * cert, gnutls_x509_crt_t * crtp)
399 {
400 int rc;
401
402 rc = gnutls_x509_crt_init(crtp);
403 exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
404
405 rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
406 exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
407
408 return rc;
409 }
410
411 #undef exim_gnutls_cert_err
412
413
414 /* We set various Exim global variables from the state, once a session has
415 been established.  With TLS callouts, may need to change this to stack
416 variables, or just re-call it with the server state after client callout
417 has finished.
418
419 Make sure anything set here is unset in tls_getc().
420
421 Sets:
422   tls_active                fd
423   tls_bits                  strength indicator
424   tls_certificate_verified  bool indicator
425   tls_channelbinding_b64    for some SASL mechanisms
426   tls_cipher                a string
427   tls_peercert              pointer to library internal
428   tls_peerdn                a string
429   tls_sni                   a (UTF-8) string
430   tls_ourcert               pointer to library internal
431
432 Argument:
433   state      the relevant exim_gnutls_state_st *
434 */
435
436 static void
437 extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
438 {
439 gnutls_cipher_algorithm_t cipher;
440 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
441 int old_pool;
442 int rc;
443 gnutls_datum_t channel;
444 #endif
445 tls_support * tlsp = state->tlsp;
446
447 tlsp->active = state->fd_out;
448
449 cipher = gnutls_cipher_get(state->session);
450 /* returns size in "bytes" */
451 tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
452
453 tlsp->cipher = state->ciphersuite;
454
455 DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
456
457 tlsp->certificate_verified = state->peer_cert_verified;
458 #ifdef SUPPORT_DANE
459 tlsp->dane_verified = state->peer_dane_verified;
460 #endif
461
462 /* note that tls_channelbinding_b64 is not saved to the spool file, since it's
463 only available for use for authenticators while this TLS session is running. */
464
465 tls_channelbinding_b64 = NULL;
466 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
467 channel.data = NULL;
468 channel.size = 0;
469 rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel);
470 if (rc) {
471   DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc));
472 } else {
473   old_pool = store_pool;
474   store_pool = POOL_PERM;
475   tls_channelbinding_b64 = b64encode(channel.data, (int)channel.size);
476   store_pool = old_pool;
477   DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
478 }
479 #endif
480
481 /* peercert is set in peer_status() */
482 tlsp->peerdn = state->peerdn;
483 tlsp->sni =    state->received_sni;
484
485 /* record our certificate */
486   {
487   const gnutls_datum_t * cert = gnutls_certificate_get_ours(state->session);
488   gnutls_x509_crt_t crt;
489
490   tlsp->ourcert = cert && import_cert(cert, &crt)==0 ? crt : NULL;
491   }
492 }
493
494
495
496
497 /*************************************************
498 *            Setup up DH parameters              *
499 *************************************************/
500
501 /* Generating the D-H parameters may take a long time. They only need to
502 be re-generated every so often, depending on security policy. What we do is to
503 keep these parameters in a file in the spool directory. If the file does not
504 exist, we generate them. This means that it is easy to cause a regeneration.
505
506 The new file is written as a temporary file and renamed, so that an incomplete
507 file is never present. If two processes both compute some new parameters, you
508 waste a bit of effort, but it doesn't seem worth messing around with locking to
509 prevent this.
510
511 Returns:     OK/DEFER/FAIL
512 */
513
514 static int
515 init_server_dh(uschar ** errstr)
516 {
517 int fd, rc;
518 unsigned int dh_bits;
519 gnutls_datum_t m;
520 uschar filename_buf[PATH_MAX];
521 uschar *filename = NULL;
522 size_t sz;
523 uschar *exp_tls_dhparam;
524 BOOL use_file_in_spool = FALSE;
525 BOOL use_fixed_file = FALSE;
526 host_item *host = NULL; /* dummy for macros */
527
528 DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
529
530 rc = gnutls_dh_params_init(&dh_server_params);
531 exim_gnutls_err_check(rc, US"gnutls_dh_params_init");
532
533 m.data = NULL;
534 m.size = 0;
535
536 if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam, errstr))
537   return DEFER;
538
539 if (!exp_tls_dhparam)
540   {
541   DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
542   m.data = US std_dh_prime_default();
543   m.size = Ustrlen(m.data);
544   }
545 else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
546   use_file_in_spool = TRUE;
547 else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
548   {
549   DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
550   return OK;
551   }
552 else if (exp_tls_dhparam[0] != '/')
553   {
554   if (!(m.data = US std_dh_prime_named(exp_tls_dhparam)))
555     return tls_error(US"No standard prime named", CS exp_tls_dhparam, NULL, errstr);
556   m.size = Ustrlen(m.data);
557   }
558 else
559   {
560   use_fixed_file = TRUE;
561   filename = exp_tls_dhparam;
562   }
563
564 if (m.data)
565   {
566   rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
567   exim_gnutls_err_check(rc, US"gnutls_dh_params_import_pkcs3");
568   DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
569   return OK;
570   }
571
572 #ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
573 /* If you change this constant, also change dh_param_fn_ext so that we can use a
574 different filename and ensure we have sufficient bits. */
575 dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
576 if (!dh_bits)
577   return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL, errstr);
578 DEBUG(D_tls)
579   debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
580       dh_bits);
581 #else
582 dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
583 DEBUG(D_tls)
584   debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
585       dh_bits);
586 #endif
587
588 /* Some clients have hard-coded limits. */
589 if (dh_bits > tls_dh_max_bits)
590   {
591   DEBUG(D_tls)
592     debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
593         tls_dh_max_bits);
594   dh_bits = tls_dh_max_bits;
595   }
596
597 if (use_file_in_spool)
598   {
599   if (!string_format(filename_buf, sizeof(filename_buf),
600         "%s/gnutls-params-%d", spool_directory, dh_bits))
601     return tls_error(US"overlong filename", NULL, NULL, errstr);
602   filename = filename_buf;
603   }
604
605 /* Open the cache file for reading and if successful, read it and set up the
606 parameters. */
607
608 if ((fd = Uopen(filename, O_RDONLY, 0)) >= 0)
609   {
610   struct stat statbuf;
611   FILE *fp;
612   int saved_errno;
613
614   if (fstat(fd, &statbuf) < 0)  /* EIO */
615     {
616     saved_errno = errno;
617     (void)close(fd);
618     return tls_error(US"TLS cache stat failed", strerror(saved_errno), NULL, errstr);
619     }
620   if (!S_ISREG(statbuf.st_mode))
621     {
622     (void)close(fd);
623     return tls_error(US"TLS cache not a file", NULL, NULL, errstr);
624     }
625   if (!(fp = fdopen(fd, "rb")))
626     {
627     saved_errno = errno;
628     (void)close(fd);
629     return tls_error(US"fdopen(TLS cache stat fd) failed",
630         strerror(saved_errno), NULL, errstr);
631     }
632
633   m.size = statbuf.st_size;
634   if (!(m.data = malloc(m.size)))
635     {
636     fclose(fp);
637     return tls_error(US"malloc failed", strerror(errno), NULL, errstr);
638     }
639   if (!(sz = fread(m.data, m.size, 1, fp)))
640     {
641     saved_errno = errno;
642     fclose(fp);
643     free(m.data);
644     return tls_error(US"fread failed", strerror(saved_errno), NULL, errstr);
645     }
646   fclose(fp);
647
648   rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
649   free(m.data);
650   exim_gnutls_err_check(rc, US"gnutls_dh_params_import_pkcs3");
651   DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
652   }
653
654 /* If the file does not exist, fall through to compute new data and cache it.
655 If there was any other opening error, it is serious. */
656
657 else if (errno == ENOENT)
658   {
659   rc = -1;
660   DEBUG(D_tls)
661     debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
662   }
663 else
664   return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
665       NULL, NULL, errstr);
666
667 /* If ret < 0, either the cache file does not exist, or the data it contains
668 is not useful. One particular case of this is when upgrading from an older
669 release of Exim in which the data was stored in a different format. We don't
670 try to be clever and support both formats; we just regenerate new data in this
671 case. */
672
673 if (rc < 0)
674   {
675   uschar *temp_fn;
676   unsigned int dh_bits_gen = dh_bits;
677
678   if ((PATH_MAX - Ustrlen(filename)) < 10)
679     return tls_error(US"Filename too long to generate replacement",
680         CS filename, NULL, errstr);
681
682   temp_fn = string_copy(US "%s.XXXXXXX");
683   if ((fd = mkstemp(CS temp_fn)) < 0)   /* modifies temp_fn */
684     return tls_error(US"Unable to open temp file", strerror(errno), NULL, errstr);
685   (void)fchown(fd, exim_uid, exim_gid);   /* Probably not necessary */
686
687   /* GnuTLS overshoots!
688    * If we ask for 2236, we might get 2237 or more.
689    * But there's no way to ask GnuTLS how many bits there really are.
690    * We can ask how many bits were used in a TLS session, but that's it!
691    * The prime itself is hidden behind too much abstraction.
692    * So we ask for less, and proceed on a wing and a prayer.
693    * First attempt, subtracted 3 for 2233 and got 2240.
694    */
695   if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
696     {
697     dh_bits_gen = dh_bits - 10;
698     DEBUG(D_tls)
699       debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
700           dh_bits_gen);
701     }
702
703   DEBUG(D_tls)
704     debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
705         dh_bits_gen);
706   rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen);
707   exim_gnutls_err_check(rc, US"gnutls_dh_params_generate2");
708
709   /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
710   and I confirmed that a NULL call to get the size first is how the GnuTLS
711   sample apps handle this. */
712
713   sz = 0;
714   m.data = NULL;
715   rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
716       m.data, &sz);
717   if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
718     exim_gnutls_err_check(rc, US"gnutls_dh_params_export_pkcs3(NULL) sizing");
719   m.size = sz;
720   if (!(m.data = malloc(m.size)))
721     return tls_error(US"memory allocation failed", strerror(errno), NULL, errstr);
722
723   /* this will return a size 1 less than the allocation size above */
724   rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
725       m.data, &sz);
726   if (rc != GNUTLS_E_SUCCESS)
727     {
728     free(m.data);
729     exim_gnutls_err_check(rc, US"gnutls_dh_params_export_pkcs3() real");
730     }
731   m.size = sz; /* shrink by 1, probably */
732
733   if ((sz = write_to_fd_buf(fd, m.data, (size_t) m.size)) != m.size)
734     {
735     free(m.data);
736     return tls_error(US"TLS cache write D-H params failed",
737         strerror(errno), NULL, errstr);
738     }
739   free(m.data);
740   if ((sz = write_to_fd_buf(fd, US"\n", 1)) != 1)
741     return tls_error(US"TLS cache write D-H params final newline failed",
742         strerror(errno), NULL, errstr);
743
744   if ((rc = close(fd)))
745     return tls_error(US"TLS cache write close() failed", strerror(errno), NULL, errstr);
746
747   if (Urename(temp_fn, filename) < 0)
748     return tls_error(string_sprintf("failed to rename \"%s\" as \"%s\"",
749           temp_fn, filename), strerror(errno), NULL, errstr);
750
751   DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
752   }
753
754 DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
755 return OK;
756 }
757
758
759
760
761 /* Create and install a selfsigned certificate, for use in server mode */
762
763 static int
764 tls_install_selfsign(exim_gnutls_state_st * state, uschar ** errstr)
765 {
766 gnutls_x509_crt_t cert = NULL;
767 time_t now;
768 gnutls_x509_privkey_t pkey = NULL;
769 const uschar * where;
770 int rc;
771
772 where = US"initialising pkey";
773 if ((rc = gnutls_x509_privkey_init(&pkey))) goto err;
774
775 where = US"initialising cert";
776 if ((rc = gnutls_x509_crt_init(&cert))) goto err;
777
778 where = US"generating pkey";
779 if ((rc = gnutls_x509_privkey_generate(pkey, GNUTLS_PK_RSA,
780 #ifdef SUPPORT_PARAM_TO_PK_BITS
781             gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_LOW),
782 #else
783             1024,
784 #endif
785             0)))
786   goto err;
787
788 where = US"configuring cert";
789 now = 0;
790 if (  (rc = gnutls_x509_crt_set_version(cert, 3))
791    || (rc = gnutls_x509_crt_set_serial(cert, &now, sizeof(now)))
792    || (rc = gnutls_x509_crt_set_activation_time(cert, now = time(NULL)))
793    || (rc = gnutls_x509_crt_set_expiration_time(cert, now + 60 * 60)) /* 1 hr */
794    || (rc = gnutls_x509_crt_set_key(cert, pkey))
795
796    || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
797               GNUTLS_OID_X520_COUNTRY_NAME, 0, "UK", 2))
798    || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
799               GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "Exim Developers", 15))
800    || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
801               GNUTLS_OID_X520_COMMON_NAME, 0,
802               smtp_active_hostname, Ustrlen(smtp_active_hostname)))
803    )
804   goto err;
805
806 where = US"signing cert";
807 if ((rc = gnutls_x509_crt_sign(cert, cert, pkey))) goto err;
808
809 where = US"installing selfsign cert";
810                                         /* Since: 2.4.0 */
811 if ((rc = gnutls_certificate_set_x509_key(state->x509_cred, &cert, 1, pkey)))
812   goto err;
813
814 rc = OK;
815
816 out:
817   if (cert) gnutls_x509_crt_deinit(cert);
818   if (pkey) gnutls_x509_privkey_deinit(pkey);
819   return rc;
820
821 err:
822   rc = tls_error(where, gnutls_strerror(rc), NULL, errstr);
823   goto out;
824 }
825
826
827
828
829 /* Add certificate and key, from files.
830
831 Return:
832   Zero or negative: good.  Negate value for certificate index if < 0.
833   Greater than zero: FAIL or DEFER code.
834 */
835
836 static int
837 tls_add_certfile(exim_gnutls_state_st * state, const host_item * host,
838   uschar * certfile, uschar * keyfile, uschar ** errstr)
839 {
840 int rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
841     CS certfile, CS keyfile, GNUTLS_X509_FMT_PEM);
842 if (rc < 0)
843   return tls_error(
844     string_sprintf("cert/key setup: cert=%s key=%s", certfile, keyfile),
845     gnutls_strerror(rc), host, errstr);
846 return -rc;
847 }
848
849
850 /*************************************************
851 *       Variables re-expanded post-SNI           *
852 *************************************************/
853
854 /* Called from both server and client code, via tls_init(), and also from
855 the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
856
857 We can tell the two apart by state->received_sni being non-NULL in callback.
858
859 The callback should not call us unless state->trigger_sni_changes is true,
860 which we are responsible for setting on the first pass through.
861
862 Arguments:
863   state           exim_gnutls_state_st *
864   errstr          error string pointer
865
866 Returns:          OK/DEFER/FAIL
867 */
868
869 static int
870 tls_expand_session_files(exim_gnutls_state_st * state, uschar ** errstr)
871 {
872 struct stat statbuf;
873 int rc;
874 const host_item *host = state->host;  /* macro should be reconsidered? */
875 uschar *saved_tls_certificate = NULL;
876 uschar *saved_tls_privatekey = NULL;
877 uschar *saved_tls_verify_certificates = NULL;
878 uschar *saved_tls_crl = NULL;
879 int cert_count;
880
881 /* We check for tls_sni *before* expansion. */
882 if (!host)      /* server */
883   if (!state->received_sni)
884     {
885     if (  state->tls_certificate
886        && (  Ustrstr(state->tls_certificate, US"tls_sni")
887           || Ustrstr(state->tls_certificate, US"tls_in_sni")
888           || Ustrstr(state->tls_certificate, US"tls_out_sni")
889        )  )
890       {
891       DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
892       state->trigger_sni_changes = TRUE;
893       }
894     }
895   else
896     {
897     /* useful for debugging */
898     saved_tls_certificate = state->exp_tls_certificate;
899     saved_tls_privatekey = state->exp_tls_privatekey;
900     saved_tls_verify_certificates = state->exp_tls_verify_certificates;
901     saved_tls_crl = state->exp_tls_crl;
902     }
903
904 rc = gnutls_certificate_allocate_credentials(&state->x509_cred);
905 exim_gnutls_err_check(rc, US"gnutls_certificate_allocate_credentials");
906
907 #ifdef SUPPORT_SRV_OCSP_STACK
908 gnutls_certificate_set_flags(state->x509_cred, GNUTLS_CERTIFICATE_API_V2);
909 #endif
910
911 /* remember: expand_check_tlsvar() is expand_check() but fiddling with
912 state members, assuming consistent naming; and expand_check() returns
913 false if expansion failed, unless expansion was forced to fail. */
914
915 /* check if we at least have a certificate, before doing expensive
916 D-H generation. */
917
918 if (!expand_check_tlsvar(tls_certificate, errstr))
919   return DEFER;
920
921 /* certificate is mandatory in server, optional in client */
922
923 if (  !state->exp_tls_certificate
924    || !*state->exp_tls_certificate
925    )
926   if (!host)
927     return tls_install_selfsign(state, errstr);
928   else
929     DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
930
931 if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey, errstr))
932   return DEFER;
933
934 /* tls_privatekey is optional, defaulting to same file as certificate */
935
936 if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
937   {
938   state->tls_privatekey = state->tls_certificate;
939   state->exp_tls_privatekey = state->exp_tls_certificate;
940   }
941
942
943 if (state->exp_tls_certificate && *state->exp_tls_certificate)
944   {
945   DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
946       state->exp_tls_certificate, state->exp_tls_privatekey);
947
948   if (state->received_sni)
949     if (  Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0
950        && Ustrcmp(state->exp_tls_privatekey,  saved_tls_privatekey)  == 0
951        )
952       {
953       DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
954       }
955     else
956       {
957       DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
958       }
959
960   if (!host)    /* server */
961     {
962     const uschar * clist = state->exp_tls_certificate;
963     const uschar * klist = state->exp_tls_privatekey;
964     const uschar * olist;
965     int csep = 0, ksep = 0, osep = 0, cnt = 0;
966     uschar * cfile, * kfile, * ofile;
967
968 #ifndef DISABLE_OCSP
969     if (!expand_check(tls_ocsp_file, US"tls_ocsp_file", &ofile, errstr))
970       return DEFER;
971     olist = ofile;
972 #endif
973
974     while (cfile = string_nextinlist(&clist, &csep, NULL, 0))
975
976       if (!(kfile = string_nextinlist(&klist, &ksep, NULL, 0)))
977         return tls_error(US"cert/key setup: out of keys", NULL, host, errstr);
978       else if (0 < (rc = tls_add_certfile(state, host, cfile, kfile, errstr)))
979         return rc;
980       else
981         {
982         int gnutls_cert_index = -rc;
983         DEBUG(D_tls) debug_printf("TLS: cert/key %s registered\n", cfile);
984
985         /* Set the OCSP stapling server info */
986
987 #ifndef DISABLE_OCSP
988         if (tls_ocsp_file)
989           if (gnutls_buggy_ocsp)
990             {
991             DEBUG(D_tls)
992               debug_printf("GnuTLS library is buggy for OCSP; avoiding\n");
993             }
994           else if ((ofile = string_nextinlist(&olist, &osep, NULL, 0)))
995             {
996             /* Use the full callback method for stapling just to get
997             observability.  More efficient would be to read the file once only,
998             if it never changed (due to SNI). Would need restart on file update,
999             or watch datestamp.  */
1000
1001 # ifdef SUPPORT_SRV_OCSP_STACK
1002             rc = gnutls_certificate_set_ocsp_status_request_function2(
1003               state->x509_cred, gnutls_cert_index,
1004               server_ocsp_stapling_cb, ofile);
1005
1006             exim_gnutls_err_check(rc,
1007               US"gnutls_certificate_set_ocsp_status_request_function2");
1008 # else
1009             if (cnt++ > 0)
1010               {
1011               DEBUG(D_tls)
1012                 debug_printf("oops; multiple OCSP files not supported\n");
1013               break;
1014               }
1015               gnutls_certificate_set_ocsp_status_request_function(
1016                 state->x509_cred, server_ocsp_stapling_cb, ofile);
1017 # endif
1018
1019             DEBUG(D_tls) debug_printf("OCSP response file = %s\n", ofile);
1020             }
1021           else
1022             DEBUG(D_tls) debug_printf("ran out of OCSP response files in list\n");
1023 #endif
1024         }
1025     }
1026   else
1027     {
1028     if (0 < (rc = tls_add_certfile(state, host,
1029                 state->exp_tls_certificate, state->exp_tls_privatekey, errstr)))
1030       return rc;
1031     DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
1032     }
1033
1034   } /* tls_certificate */
1035
1036
1037 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
1038 provided. Experiment shows that, if the certificate file is empty, an unhelpful
1039 error message is provided. However, if we just refrain from setting anything up
1040 in that case, certificate verification fails, which seems to be the correct
1041 behaviour. */
1042
1043 if (state->tls_verify_certificates && *state->tls_verify_certificates)
1044   {
1045   if (!expand_check_tlsvar(tls_verify_certificates, errstr))
1046     return DEFER;
1047 #ifndef SUPPORT_SYSDEFAULT_CABUNDLE
1048   if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1049     state->exp_tls_verify_certificates = NULL;
1050 #endif
1051   if (state->tls_crl && *state->tls_crl)
1052     if (!expand_check_tlsvar(tls_crl, errstr))
1053       return DEFER;
1054
1055   if (!(state->exp_tls_verify_certificates &&
1056         *state->exp_tls_verify_certificates))
1057     {
1058     DEBUG(D_tls)
1059       debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
1060     /* With no tls_verify_certificates, we ignore tls_crl too */
1061     return OK;
1062     }
1063   }
1064 else
1065   {
1066   DEBUG(D_tls)
1067     debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
1068   return OK;
1069   }
1070
1071 #ifdef SUPPORT_SYSDEFAULT_CABUNDLE
1072 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1073   cert_count = gnutls_certificate_set_x509_system_trust(state->x509_cred);
1074 else
1075 #endif
1076   {
1077   if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
1078     {
1079     log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
1080         "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
1081         strerror(errno));
1082     return DEFER;
1083     }
1084
1085 #ifndef SUPPORT_CA_DIR
1086   /* The test suite passes in /dev/null; we could check for that path explicitly,
1087   but who knows if someone has some weird FIFO which always dumps some certs, or
1088   other weirdness.  The thing we really want to check is that it's not a
1089   directory, since while OpenSSL supports that, GnuTLS does not.
1090   So s/!S_ISREG/S_ISDIR/ and change some messaging ... */
1091   if (S_ISDIR(statbuf.st_mode))
1092     {
1093     DEBUG(D_tls)
1094       debug_printf("verify certificates path is a dir: \"%s\"\n",
1095           state->exp_tls_verify_certificates);
1096     log_write(0, LOG_MAIN|LOG_PANIC,
1097         "tls_verify_certificates \"%s\" is a directory",
1098         state->exp_tls_verify_certificates);
1099     return DEFER;
1100     }
1101 #endif
1102
1103   DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
1104           state->exp_tls_verify_certificates, statbuf.st_size);
1105
1106   if (statbuf.st_size == 0)
1107     {
1108     DEBUG(D_tls)
1109       debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
1110     return OK;
1111     }
1112
1113   cert_count =
1114
1115 #ifdef SUPPORT_CA_DIR
1116     (statbuf.st_mode & S_IFMT) == S_IFDIR
1117     ?
1118     gnutls_certificate_set_x509_trust_dir(state->x509_cred,
1119       CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM)
1120     :
1121 #endif
1122     gnutls_certificate_set_x509_trust_file(state->x509_cred,
1123       CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
1124   }
1125
1126 if (cert_count < 0)
1127   {
1128   rc = cert_count;
1129   exim_gnutls_err_check(rc, US"setting certificate trust");
1130   }
1131 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n", cert_count);
1132
1133 if (state->tls_crl && *state->tls_crl &&
1134     state->exp_tls_crl && *state->exp_tls_crl)
1135   {
1136   DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
1137   cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
1138       CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM);
1139   if (cert_count < 0)
1140     {
1141     rc = cert_count;
1142     exim_gnutls_err_check(rc, US"gnutls_certificate_set_x509_crl_file");
1143     }
1144   DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
1145   }
1146
1147 return OK;
1148 }
1149
1150
1151
1152
1153 /*************************************************
1154 *          Set X.509 state variables             *
1155 *************************************************/
1156
1157 /* In GnuTLS, the registered cert/key are not replaced by a later
1158 set of a cert/key, so for SNI support we need a whole new x509_cred
1159 structure.  Which means various other non-re-expanded pieces of state
1160 need to be re-set in the new struct, so the setting logic is pulled
1161 out to this.
1162
1163 Arguments:
1164   state           exim_gnutls_state_st *
1165   errstr          error string pointer
1166
1167 Returns:          OK/DEFER/FAIL
1168 */
1169
1170 static int
1171 tls_set_remaining_x509(exim_gnutls_state_st *state, uschar ** errstr)
1172 {
1173 int rc;
1174 const host_item *host = state->host;  /* macro should be reconsidered? */
1175
1176 /* Create D-H parameters, or read them from the cache file. This function does
1177 its own SMTP error messaging. This only happens for the server, TLS D-H ignores
1178 client-side params. */
1179
1180 if (!state->host)
1181   {
1182   if (!dh_server_params)
1183     {
1184     rc = init_server_dh(errstr);
1185     if (rc != OK) return rc;
1186     }
1187   gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
1188   }
1189
1190 /* Link the credentials to the session. */
1191
1192 rc = gnutls_credentials_set(state->session, GNUTLS_CRD_CERTIFICATE, state->x509_cred);
1193 exim_gnutls_err_check(rc, US"gnutls_credentials_set");
1194
1195 return OK;
1196 }
1197
1198 /*************************************************
1199 *            Initialize for GnuTLS               *
1200 *************************************************/
1201
1202
1203 #ifndef DISABLE_OCSP
1204
1205 static BOOL
1206 tls_is_buggy_ocsp(void)
1207 {
1208 const uschar * s;
1209 uschar maj, mid, mic;
1210
1211 s = CUS gnutls_check_version(NULL);
1212 maj = atoi(CCS s);
1213 if (maj == 3)
1214   {
1215   while (*s && *s != '.') s++;
1216   mid = atoi(CCS ++s);
1217   if (mid <= 2)
1218     return TRUE;
1219   else if (mid >= 5)
1220     return FALSE;
1221   else
1222     {
1223     while (*s && *s != '.') s++;
1224     mic = atoi(CCS ++s);
1225     return mic <= (mid == 3 ? 16 : 3);
1226     }
1227   }
1228 return FALSE;
1229 }
1230
1231 #endif
1232
1233
1234 /* Called from both server and client code. In the case of a server, errors
1235 before actual TLS negotiation return DEFER.
1236
1237 Arguments:
1238   host            connected host, if client; NULL if server
1239   certificate     certificate file
1240   privatekey      private key file
1241   sni             TLS SNI to send, sometimes when client; else NULL
1242   cas             CA certs file
1243   crl             CRL file
1244   require_ciphers tls_require_ciphers setting
1245   caller_state    returned state-info structure
1246   errstr          error string pointer
1247
1248 Returns:          OK/DEFER/FAIL
1249 */
1250
1251 static int
1252 tls_init(
1253     const host_item *host,
1254     const uschar *certificate,
1255     const uschar *privatekey,
1256     const uschar *sni,
1257     const uschar *cas,
1258     const uschar *crl,
1259     const uschar *require_ciphers,
1260     exim_gnutls_state_st **caller_state,
1261     uschar ** errstr)
1262 {
1263 exim_gnutls_state_st *state;
1264 int rc;
1265 size_t sz;
1266 const char *errpos;
1267 uschar *p;
1268 BOOL want_default_priorities;
1269
1270 if (!exim_gnutls_base_init_done)
1271   {
1272   DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1273
1274 #ifdef HAVE_GNUTLS_PKCS11
1275   /* By default, gnutls_global_init will init PKCS11 support in auto mode,
1276   which loads modules from a config file, which sounds good and may be wanted
1277   by some sysadmin, but also means in common configurations that GNOME keyring
1278   environment variables are used and so breaks for users calling mailq.
1279   To prevent this, we init PKCS11 first, which is the documented approach. */
1280   if (!gnutls_allow_auto_pkcs11)
1281     {
1282     rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
1283     exim_gnutls_err_check(rc, US"gnutls_pkcs11_init");
1284     }
1285 #endif
1286
1287   rc = gnutls_global_init();
1288   exim_gnutls_err_check(rc, US"gnutls_global_init");
1289
1290 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1291   DEBUG(D_tls)
1292     {
1293     gnutls_global_set_log_function(exim_gnutls_logger_cb);
1294     /* arbitrarily chosen level; bump upto 9 for more */
1295     gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
1296     }
1297 #endif
1298
1299 #ifndef DISABLE_OCSP
1300   if (tls_ocsp_file && (gnutls_buggy_ocsp = tls_is_buggy_ocsp()))
1301     log_write(0, LOG_MAIN, "OCSP unusable with this GnuTLS library version");
1302 #endif
1303
1304   exim_gnutls_base_init_done = TRUE;
1305   }
1306
1307 if (host)
1308   {
1309   state = &state_client;
1310   memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1311   state->tlsp = &tls_out;
1312   DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1313   rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1314   }
1315 else
1316   {
1317   state = &state_server;
1318   memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1319   state->tlsp = &tls_in;
1320   DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1321   rc = gnutls_init(&state->session, GNUTLS_SERVER);
1322   }
1323 exim_gnutls_err_check(rc, US"gnutls_init");
1324
1325 state->host = host;
1326
1327 state->tls_certificate = certificate;
1328 state->tls_privatekey = privatekey;
1329 state->tls_require_ciphers = require_ciphers;
1330 state->tls_sni = sni;
1331 state->tls_verify_certificates = cas;
1332 state->tls_crl = crl;
1333
1334 /* This handles the variables that might get re-expanded after TLS SNI;
1335 that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
1336
1337 DEBUG(D_tls)
1338   debug_printf("Expanding various TLS configuration options for session credentials.\n");
1339 if ((rc = tls_expand_session_files(state, errstr)) != OK) return rc;
1340
1341 /* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1342 requires a new structure afterwards. */
1343
1344 if ((rc = tls_set_remaining_x509(state, errstr)) != OK) return rc;
1345
1346 /* set SNI in client, only */
1347 if (host)
1348   {
1349   if (!expand_check(sni, US"tls_out_sni", &state->tlsp->sni, errstr))
1350     return DEFER;
1351   if (state->tlsp->sni && *state->tlsp->sni)
1352     {
1353     DEBUG(D_tls)
1354       debug_printf("Setting TLS client SNI to \"%s\"\n", state->tlsp->sni);
1355     sz = Ustrlen(state->tlsp->sni);
1356     rc = gnutls_server_name_set(state->session,
1357         GNUTLS_NAME_DNS, state->tlsp->sni, sz);
1358     exim_gnutls_err_check(rc, US"gnutls_server_name_set");
1359     }
1360   }
1361 else if (state->tls_sni)
1362   DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
1363       "have an SNI set for a server [%s]\n", state->tls_sni);
1364
1365 /* This is the priority string support,
1366 http://www.gnutls.org/manual/html_node/Priority-Strings.html
1367 and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1368 This was backwards incompatible, but means Exim no longer needs to track
1369 all algorithms and provide string forms for them. */
1370
1371 want_default_priorities = TRUE;
1372
1373 if (state->tls_require_ciphers && *state->tls_require_ciphers)
1374   {
1375   if (!expand_check_tlsvar(tls_require_ciphers, errstr))
1376     return DEFER;
1377   if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
1378     {
1379     DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n",
1380         state->exp_tls_require_ciphers);
1381
1382     rc = gnutls_priority_init(&state->priority_cache,
1383         CS state->exp_tls_require_ciphers, &errpos);
1384     want_default_priorities = FALSE;
1385     p = state->exp_tls_require_ciphers;
1386     }
1387   }
1388 if (want_default_priorities)
1389   {
1390   DEBUG(D_tls)
1391     debug_printf("GnuTLS using default session cipher/priority \"%s\"\n",
1392         exim_default_gnutls_priority);
1393   rc = gnutls_priority_init(&state->priority_cache,
1394       exim_default_gnutls_priority, &errpos);
1395   p = US exim_default_gnutls_priority;
1396   }
1397
1398 exim_gnutls_err_check(rc, string_sprintf(
1399       "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1400       p, errpos - CS p, errpos));
1401
1402 rc = gnutls_priority_set(state->session, state->priority_cache);
1403 exim_gnutls_err_check(rc, US"gnutls_priority_set");
1404
1405 gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1406
1407 /* Reduce security in favour of increased compatibility, if the admin
1408 decides to make that trade-off. */
1409 if (gnutls_compat_mode)
1410   {
1411 #if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1412   DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1413   gnutls_session_enable_compatibility_mode(state->session);
1414 #else
1415   DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1416 #endif
1417   }
1418
1419 *caller_state = state;
1420 return OK;
1421 }
1422
1423
1424
1425 /*************************************************
1426 *            Extract peer information            *
1427 *************************************************/
1428
1429 /* Called from both server and client code.
1430 Only this is allowed to set state->peerdn and state->have_set_peerdn
1431 and we use that to detect double-calls.
1432
1433 NOTE: the state blocks last while the TLS connection is up, which is fine
1434 for logging in the server side, but for the client side, we log after teardown
1435 in src/deliver.c.  While the session is up, we can twist about states and
1436 repoint tls_* globals, but those variables used for logging or other variable
1437 expansion that happens _after_ delivery need to have a longer life-time.
1438
1439 So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1440 doing this more than once per generation of a state context.  We set them in
1441 the state context, and repoint tls_* to them.  After the state goes away, the
1442 tls_* copies of the pointers remain valid and client delivery logging is happy.
1443
1444 tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1445 don't apply.
1446
1447 Arguments:
1448   state           exim_gnutls_state_st *
1449   errstr          pointer to error string
1450
1451 Returns:          OK/DEFER/FAIL
1452 */
1453
1454 static int
1455 peer_status(exim_gnutls_state_st *state, uschar ** errstr)
1456 {
1457 uschar cipherbuf[256];
1458 const gnutls_datum_t *cert_list;
1459 int old_pool, rc;
1460 unsigned int cert_list_size = 0;
1461 gnutls_protocol_t protocol;
1462 gnutls_cipher_algorithm_t cipher;
1463 gnutls_kx_algorithm_t kx;
1464 gnutls_mac_algorithm_t mac;
1465 gnutls_certificate_type_t ct;
1466 gnutls_x509_crt_t crt;
1467 uschar *p, *dn_buf;
1468 size_t sz;
1469
1470 if (state->have_set_peerdn)
1471   return OK;
1472 state->have_set_peerdn = TRUE;
1473
1474 state->peerdn = NULL;
1475
1476 /* tls_cipher */
1477 cipher = gnutls_cipher_get(state->session);
1478 protocol = gnutls_protocol_get_version(state->session);
1479 mac = gnutls_mac_get(state->session);
1480 kx = gnutls_kx_get(state->session);
1481
1482 string_format(cipherbuf, sizeof(cipherbuf),
1483     "%s:%s:%d",
1484     gnutls_protocol_get_name(protocol),
1485     gnutls_cipher_suite_get_name(kx, cipher, mac),
1486     (int) gnutls_cipher_get_key_size(cipher) * 8);
1487
1488 /* I don't see a way that spaces could occur, in the current GnuTLS
1489 code base, but it was a concern in the old code and perhaps older GnuTLS
1490 releases did return "TLS 1.0"; play it safe, just in case. */
1491 for (p = cipherbuf; *p != '\0'; ++p)
1492   if (isspace(*p))
1493     *p = '-';
1494 old_pool = store_pool;
1495 store_pool = POOL_PERM;
1496 state->ciphersuite = string_copy(cipherbuf);
1497 store_pool = old_pool;
1498 state->tlsp->cipher = state->ciphersuite;
1499
1500 /* tls_peerdn */
1501 cert_list = gnutls_certificate_get_peers(state->session, &cert_list_size);
1502
1503 if (cert_list == NULL || cert_list_size == 0)
1504   {
1505   DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1506       cert_list, cert_list_size);
1507   if (state->verify_requirement >= VERIFY_REQUIRED)
1508     return tls_error(US"certificate verification failed",
1509         "no certificate received from peer", state->host, errstr);
1510   return OK;
1511   }
1512
1513 ct = gnutls_certificate_type_get(state->session);
1514 if (ct != GNUTLS_CRT_X509)
1515   {
1516   const char *ctn = gnutls_certificate_type_get_name(ct);
1517   DEBUG(D_tls)
1518     debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
1519   if (state->verify_requirement >= VERIFY_REQUIRED)
1520     return tls_error(US"certificate verification not possible, unhandled type",
1521         ctn, state->host, errstr);
1522   return OK;
1523   }
1524
1525 #define exim_gnutls_peer_err(Label) \
1526   do { \
1527     if (rc != GNUTLS_E_SUCCESS) \
1528       { \
1529       DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", \
1530         (Label), gnutls_strerror(rc)); \
1531       if (state->verify_requirement >= VERIFY_REQUIRED) \
1532         return tls_error((Label), gnutls_strerror(rc), state->host, errstr); \
1533       return OK; \
1534       } \
1535     } while (0)
1536
1537 rc = import_cert(&cert_list[0], &crt);
1538 exim_gnutls_peer_err(US"cert 0");
1539
1540 state->tlsp->peercert = state->peercert = crt;
1541
1542 sz = 0;
1543 rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1544 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
1545   {
1546   exim_gnutls_peer_err(US"getting size for cert DN failed");
1547   return FAIL; /* should not happen */
1548   }
1549 dn_buf = store_get_perm(sz);
1550 rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1551 exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
1552
1553 state->peerdn = dn_buf;
1554
1555 return OK;
1556 #undef exim_gnutls_peer_err
1557 }
1558
1559
1560
1561
1562 /*************************************************
1563 *            Verify peer certificate             *
1564 *************************************************/
1565
1566 /* Called from both server and client code.
1567 *Should* be using a callback registered with
1568 gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1569 the peer information, but that's too new for some OSes.
1570
1571 Arguments:
1572   state         exim_gnutls_state_st *
1573   errstr        where to put an error message
1574
1575 Returns:
1576   FALSE     if the session should be rejected
1577   TRUE      if the cert is okay or we just don't care
1578 */
1579
1580 static BOOL
1581 verify_certificate(exim_gnutls_state_st * state, uschar ** errstr)
1582 {
1583 int rc;
1584 uint verify;
1585
1586 if (state->verify_requirement == VERIFY_NONE)
1587   return TRUE;
1588
1589 *errstr = NULL;
1590
1591 if ((rc = peer_status(state, errstr)) != OK)
1592   {
1593   verify = GNUTLS_CERT_INVALID;
1594   *errstr = US"certificate not supplied";
1595   }
1596 else
1597
1598   {
1599 #ifdef SUPPORT_DANE
1600   if (state->verify_requirement == VERIFY_DANE && state->host)
1601     {
1602     /* Using dane_verify_session_crt() would be easy, as it does it all for us
1603     including talking to a DNS resolver.  But we want to do that bit ourselves
1604     as the testsuite intercepts and fakes its own DNS environment. */
1605
1606     dane_state_t s;
1607     dane_query_t r;
1608     uint lsize;
1609     const gnutls_datum_t * certlist =
1610       gnutls_certificate_get_peers(state->session, &lsize);
1611     int usage = tls_out.tlsa_usage;
1612
1613 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1614     /* Split the TLSA records into two sets, TA and EE selectors.  Run the
1615     dane-verification separately so that we know which selector verified;
1616     then we know whether to do CA-chain-verification and name-verification
1617     (needed for TA but not EE). */
1618
1619     if (usage == ((1<<DANESSL_USAGE_DANE_TA) | (1<<DANESSL_USAGE_DANE_EE)))
1620     {                                           /* a mixed-usage bundle */
1621       int i, j, nrec;
1622       const char ** dd;
1623       int * ddl;
1624
1625       for(nrec = 0; state->dane_data_len[nrec]; ) nrec++;
1626       nrec++;
1627
1628       dd = store_get(nrec * sizeof(uschar *));
1629       ddl = store_get(nrec * sizeof(int));
1630       nrec--;
1631
1632       if ((rc = dane_state_init(&s, 0)))
1633         goto tlsa_prob;
1634
1635       for (usage = DANESSL_USAGE_DANE_EE;
1636            usage >= DANESSL_USAGE_DANE_TA; usage--)
1637         {                               /* take records with this usage */
1638         for (j = i = 0; i < nrec; i++)
1639           if (state->dane_data[i][0] == usage)
1640             {
1641             dd[j] = state->dane_data[i];
1642             ddl[j++] = state->dane_data_len[i];
1643             }
1644         if (j)
1645           {
1646           dd[j] = NULL;
1647           ddl[j] = 0;
1648
1649           if ((rc = dane_raw_tlsa(s, &r, (char * const *)dd, ddl, 1, 0)))
1650             goto tlsa_prob;
1651
1652           if ((rc = dane_verify_crt_raw(s, certlist, lsize,
1653                             gnutls_certificate_type_get(state->session),
1654                             r, 0,
1655                             usage == DANESSL_USAGE_DANE_EE
1656                             ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1657                             &verify)))
1658             {
1659             DEBUG(D_tls)
1660               debug_printf("TLSA record problem: %s\n", dane_strerror(rc));
1661             }
1662           else if (verify == 0) /* verification passed */
1663             {
1664             usage = 1 << usage;
1665             break;
1666             }
1667           }
1668         }
1669
1670         if (rc) goto tlsa_prob;
1671       }
1672     else
1673 # endif
1674       {
1675       if (  (rc = dane_state_init(&s, 0))
1676          || (rc = dane_raw_tlsa(s, &r, state->dane_data, state->dane_data_len,
1677                         1, 0))
1678          || (rc = dane_verify_crt_raw(s, certlist, lsize,
1679                         gnutls_certificate_type_get(state->session),
1680                         r, 0, 
1681 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1682                         usage == (1 << DANESSL_USAGE_DANE_EE)
1683                         ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1684 # else
1685                         0,
1686 # endif
1687                         &verify))
1688          )
1689         goto tlsa_prob;
1690       }
1691
1692     if (verify != 0)            /* verification failed */
1693       {
1694       gnutls_datum_t str;
1695       (void) dane_verification_status_print(verify, &str, 0);
1696       *errstr = US str.data;    /* don't bother to free */
1697       goto badcert;
1698       }
1699     state->peer_dane_verified = TRUE;
1700
1701 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1702     /* If a TA-mode TLSA record was used for verification we must additionally
1703     verify the CA chain and the cert name.  For EE-mode, skip it. */
1704
1705     if (usage & (1 << DANESSL_USAGE_DANE_EE))
1706 # endif
1707       {
1708       state->peer_cert_verified = TRUE;
1709       goto goodcert;
1710       }
1711     }
1712 #endif
1713
1714   rc = gnutls_certificate_verify_peers2(state->session, &verify);
1715   }
1716
1717 /* Handle the result of verification. INVALID is set if any others are. */
1718
1719 if (rc < 0 || verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED))
1720   {
1721   state->peer_cert_verified = FALSE;
1722   if (!*errstr)
1723     *errstr = verify & GNUTLS_CERT_REVOKED
1724       ? US"certificate revoked" : US"certificate invalid";
1725
1726   DEBUG(D_tls)
1727     debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
1728         *errstr, state->peerdn ? state->peerdn : US"<unset>");
1729
1730   if (state->verify_requirement >= VERIFY_REQUIRED)
1731     goto badcert;
1732   DEBUG(D_tls)
1733     debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
1734   }
1735
1736 else
1737   {
1738   if (state->exp_tls_verify_cert_hostnames)
1739     {
1740     int sep = 0;
1741     const uschar * list = state->exp_tls_verify_cert_hostnames;
1742     uschar * name;
1743     while ((name = string_nextinlist(&list, &sep, NULL, 0)))
1744       if (gnutls_x509_crt_check_hostname(state->tlsp->peercert, CS name))
1745         break;
1746     if (!name)
1747       {
1748       DEBUG(D_tls)
1749         debug_printf("TLS certificate verification failed: cert name mismatch\n");
1750       if (state->verify_requirement >= VERIFY_REQUIRED)
1751         goto badcert;
1752       return TRUE;
1753       }
1754     }
1755   state->peer_cert_verified = TRUE;
1756   DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
1757       state->peerdn ? state->peerdn : US"<unset>");
1758   }
1759
1760 goodcert:
1761   state->tlsp->peerdn = state->peerdn;
1762   return TRUE;
1763
1764 tlsa_prob:
1765   *errstr = string_sprintf("TLSA record problem: %s", dane_strerror(rc));
1766 badcert:
1767   gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1768   return FALSE;
1769 }
1770
1771
1772
1773
1774 /* ------------------------------------------------------------------------ */
1775 /* Callbacks */
1776
1777 /* Logging function which can be registered with
1778  *   gnutls_global_set_log_function()
1779  *   gnutls_global_set_log_level() 0..9
1780  */
1781 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1782 static void
1783 exim_gnutls_logger_cb(int level, const char *message)
1784 {
1785   size_t len = strlen(message);
1786   if (len < 1)
1787     {
1788     DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1789     return;
1790     }
1791   DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1792       message[len-1] == '\n' ? "" : "\n");
1793 }
1794 #endif
1795
1796
1797 /* Called after client hello, should handle SNI work.
1798 This will always set tls_sni (state->received_sni) if available,
1799 and may trigger presenting different certificates,
1800 if state->trigger_sni_changes is TRUE.
1801
1802 Should be registered with
1803   gnutls_handshake_set_post_client_hello_function()
1804
1805 "This callback must return 0 on success or a gnutls error code to terminate the
1806 handshake.".
1807
1808 For inability to get SNI information, we return 0.
1809 We only return non-zero if re-setup failed.
1810 Only used for server-side TLS.
1811 */
1812
1813 static int
1814 exim_sni_handling_cb(gnutls_session_t session)
1815 {
1816 char sni_name[MAX_HOST_LEN];
1817 size_t data_len = MAX_HOST_LEN;
1818 exim_gnutls_state_st *state = &state_server;
1819 unsigned int sni_type;
1820 int rc, old_pool;
1821 uschar * dummy_errstr;
1822
1823 rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1824 if (rc != GNUTLS_E_SUCCESS)
1825   {
1826   DEBUG(D_tls) {
1827     if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1828       debug_printf("TLS: no SNI presented in handshake.\n");
1829     else
1830       debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1831         gnutls_strerror(rc), rc);
1832     }
1833   return 0;
1834   }
1835
1836 if (sni_type != GNUTLS_NAME_DNS)
1837   {
1838   DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1839   return 0;
1840   }
1841
1842 /* We now have a UTF-8 string in sni_name */
1843 old_pool = store_pool;
1844 store_pool = POOL_PERM;
1845 state->received_sni = string_copyn(US sni_name, data_len);
1846 store_pool = old_pool;
1847
1848 /* We set this one now so that variable expansions below will work */
1849 state->tlsp->sni = state->received_sni;
1850
1851 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1852     state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1853
1854 if (!state->trigger_sni_changes)
1855   return 0;
1856
1857 if ((rc = tls_expand_session_files(state, &dummy_errstr)) != OK)
1858   {
1859   /* If the setup of certs/etc failed before handshake, TLS would not have
1860   been offered.  The best we can do now is abort. */
1861   return GNUTLS_E_APPLICATION_ERROR_MIN;
1862   }
1863
1864 rc = tls_set_remaining_x509(state, &dummy_errstr);
1865 if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1866
1867 return 0;
1868 }
1869
1870
1871
1872 #ifndef DISABLE_OCSP
1873
1874 static int
1875 server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1876   gnutls_datum_t * ocsp_response)
1877 {
1878 int ret;
1879 DEBUG(D_tls) debug_printf("OCSP stapling callback: %s\n", US ptr);
1880
1881 if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1882   {
1883   DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
1884                               CS ptr);
1885   tls_in.ocsp = OCSP_NOT_RESP;
1886   return GNUTLS_E_NO_CERTIFICATE_STATUS;
1887   }
1888
1889 tls_in.ocsp = OCSP_VFY_NOT_TRIED;
1890 return 0;
1891 }
1892
1893 #endif
1894
1895
1896 #ifndef DISABLE_EVENT
1897 /*
1898 We use this callback to get observability and detail-level control
1899 for an exim TLS connection (either direction), raising a tls:cert event
1900 for each cert in the chain presented by the peer.  Any event
1901 can deny verification.
1902
1903 Return 0 for the handshake to continue or non-zero to terminate.
1904 */
1905
1906 static int
1907 verify_cb(gnutls_session_t session)
1908 {
1909 const gnutls_datum_t * cert_list;
1910 unsigned int cert_list_size = 0;
1911 gnutls_x509_crt_t crt;
1912 int rc;
1913 uschar * yield;
1914 exim_gnutls_state_st * state = gnutls_session_get_ptr(session);
1915
1916 cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
1917 if (cert_list)
1918   while (cert_list_size--)
1919   {
1920   rc = import_cert(&cert_list[cert_list_size], &crt);
1921   if (rc != GNUTLS_E_SUCCESS)
1922     {
1923     DEBUG(D_tls) debug_printf("TLS: peer cert problem: depth %d: %s\n",
1924       cert_list_size, gnutls_strerror(rc));
1925     break;
1926     }
1927
1928   state->tlsp->peercert = crt;
1929   if ((yield = event_raise(state->event_action,
1930               US"tls:cert", string_sprintf("%d", cert_list_size))))
1931     {
1932     log_write(0, LOG_MAIN,
1933               "SSL verify denied by event-action: depth=%d: %s",
1934               cert_list_size, yield);
1935     return 1;                     /* reject */
1936     }
1937   state->tlsp->peercert = NULL;
1938   }
1939
1940 return 0;
1941 }
1942
1943 #endif
1944
1945
1946
1947 /* ------------------------------------------------------------------------ */
1948 /* Exported functions */
1949
1950
1951
1952
1953 /*************************************************
1954 *       Start a TLS session in a server          *
1955 *************************************************/
1956
1957 /* This is called when Exim is running as a server, after having received
1958 the STARTTLS command. It must respond to that command, and then negotiate
1959 a TLS session.
1960
1961 Arguments:
1962   require_ciphers  list of allowed ciphers or NULL
1963   errstr           pointer to error string
1964
1965 Returns:           OK on success
1966                    DEFER for errors before the start of the negotiation
1967                    FAIL for errors during the negotiation; the server can't
1968                      continue running.
1969 */
1970
1971 int
1972 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
1973 {
1974 int rc;
1975 exim_gnutls_state_st * state = NULL;
1976
1977 /* Check for previous activation */
1978 if (tls_in.active >= 0)
1979   {
1980   tls_error(US"STARTTLS received after TLS started", "", NULL, errstr);
1981   smtp_printf("554 Already in TLS\r\n", FALSE);
1982   return FAIL;
1983   }
1984
1985 /* Initialize the library. If it fails, it will already have logged the error
1986 and sent an SMTP response. */
1987
1988 DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
1989
1990 if ((rc = tls_init(NULL, tls_certificate, tls_privatekey,
1991     NULL, tls_verify_certificates, tls_crl,
1992     require_ciphers, &state, errstr)) != OK) return rc;
1993
1994 /* If this is a host for which certificate verification is mandatory or
1995 optional, set up appropriately. */
1996
1997 if (verify_check_host(&tls_verify_hosts) == OK)
1998   {
1999   DEBUG(D_tls)
2000     debug_printf("TLS: a client certificate will be required.\n");
2001   state->verify_requirement = VERIFY_REQUIRED;
2002   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2003   }
2004 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2005   {
2006   DEBUG(D_tls)
2007     debug_printf("TLS: a client certificate will be requested but not required.\n");
2008   state->verify_requirement = VERIFY_OPTIONAL;
2009   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2010   }
2011 else
2012   {
2013   DEBUG(D_tls)
2014     debug_printf("TLS: a client certificate will not be requested.\n");
2015   state->verify_requirement = VERIFY_NONE;
2016   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2017   }
2018
2019 #ifndef DISABLE_EVENT
2020 if (event_action)
2021   {
2022   state->event_action = event_action;
2023   gnutls_session_set_ptr(state->session, state);
2024   gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2025   }
2026 #endif
2027
2028 /* Register SNI handling; always, even if not in tls_certificate, so that the
2029 expansion variable $tls_sni is always available. */
2030
2031 gnutls_handshake_set_post_client_hello_function(state->session,
2032     exim_sni_handling_cb);
2033
2034 /* Set context and tell client to go ahead, except in the case of TLS startup
2035 on connection, where outputting anything now upsets the clients and tends to
2036 make them disconnect. We need to have an explicit fflush() here, to force out
2037 the response. Other smtp_printf() calls do not need it, because in non-TLS
2038 mode, the fflush() happens when smtp_getc() is called. */
2039
2040 if (!state->tlsp->on_connect)
2041   {
2042   smtp_printf("220 TLS go ahead\r\n", FALSE);
2043   fflush(smtp_out);
2044   }
2045
2046 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2047 that the GnuTLS library doesn't. */
2048
2049 gnutls_transport_set_ptr2(state->session,
2050     (gnutls_transport_ptr_t)(long) fileno(smtp_in),
2051     (gnutls_transport_ptr_t)(long) fileno(smtp_out));
2052 state->fd_in = fileno(smtp_in);
2053 state->fd_out = fileno(smtp_out);
2054
2055 sigalrm_seen = FALSE;
2056 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
2057 do
2058   rc = gnutls_handshake(state->session);
2059 while (rc == GNUTLS_E_AGAIN ||  rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2060 alarm(0);
2061
2062 if (rc != GNUTLS_E_SUCCESS)
2063   {
2064   /* It seems that, except in the case of a timeout, we have to close the
2065   connection right here; otherwise if the other end is running OpenSSL it hangs
2066   until the server times out. */
2067
2068   if (sigalrm_seen)
2069     {
2070     tls_error(US"gnutls_handshake", "timed out", NULL, errstr);
2071     gnutls_db_remove_session(state->session);
2072     }
2073   else
2074     {
2075     tls_error(US"gnutls_handshake", gnutls_strerror(rc), NULL, errstr);
2076     (void) gnutls_alert_send_appropriate(state->session, rc);
2077     gnutls_deinit(state->session);
2078     gnutls_certificate_free_credentials(state->x509_cred);
2079     millisleep(500);
2080     shutdown(state->fd_out, SHUT_WR);
2081     for (rc = 1024; fgetc(smtp_in) != EOF && rc > 0; ) rc--;    /* drain skt */
2082     (void)fclose(smtp_out);
2083     (void)fclose(smtp_in);
2084     smtp_out = smtp_in = NULL;
2085     }
2086
2087   return FAIL;
2088   }
2089
2090 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
2091
2092 /* Verify after the fact */
2093
2094 if (!verify_certificate(state, errstr))
2095   {
2096   if (state->verify_requirement != VERIFY_OPTIONAL)
2097     {
2098     (void) tls_error(US"certificate verification failed", *errstr, NULL, errstr);
2099     return FAIL;
2100     }
2101   DEBUG(D_tls)
2102     debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
2103         *errstr);
2104   }
2105
2106 /* Figure out peer DN, and if authenticated, etc. */
2107
2108 if ((rc = peer_status(state, NULL)) != OK) return rc;
2109
2110 /* Sets various Exim expansion variables; always safe within server */
2111
2112 extract_exim_vars_from_tls_state(state);
2113
2114 /* TLS has been set up. Adjust the input functions to read via TLS,
2115 and initialize appropriately. */
2116
2117 state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2118
2119 receive_getc = tls_getc;
2120 receive_getbuf = tls_getbuf;
2121 receive_get_cache = tls_get_cache;
2122 receive_ungetc = tls_ungetc;
2123 receive_feof = tls_feof;
2124 receive_ferror = tls_ferror;
2125 receive_smtp_buffered = tls_smtp_buffered;
2126
2127 return OK;
2128 }
2129
2130
2131
2132
2133 static void
2134 tls_client_setup_hostname_checks(host_item * host, exim_gnutls_state_st * state,
2135   smtp_transport_options_block * ob)
2136 {
2137 if (verify_check_given_host(&ob->tls_verify_cert_hostnames, host) == OK)
2138   {
2139   state->exp_tls_verify_cert_hostnames =
2140 #ifdef SUPPORT_I18N
2141     string_domain_utf8_to_alabel(host->name, NULL);
2142 #else
2143     host->name;
2144 #endif
2145   DEBUG(D_tls)
2146     debug_printf("TLS: server cert verification includes hostname: \"%s\".\n",
2147                     state->exp_tls_verify_cert_hostnames);
2148   }
2149 }
2150
2151
2152
2153
2154 #ifdef SUPPORT_DANE
2155 /* Given our list of RRs from the TLSA lookup, build a lookup block in
2156 GnuTLS-DANE's preferred format.  Hang it on the state str for later
2157 use in DANE verification.
2158
2159 We point at the dnsa data not copy it, so it must remain valid until
2160 after verification is done.*/
2161
2162 static BOOL
2163 dane_tlsa_load(exim_gnutls_state_st * state, dns_answer * dnsa)
2164 {
2165 dns_record * rr;
2166 dns_scan dnss;
2167 int i;
2168 const char **   dane_data;
2169 int *           dane_data_len;
2170
2171 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS), i = 1;
2172      rr;
2173      rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2174     ) if (rr->type == T_TLSA) i++;
2175
2176 dane_data = store_get(i * sizeof(uschar *));
2177 dane_data_len = store_get(i * sizeof(int));
2178
2179 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS), i = 0;
2180      rr;
2181      rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2182     ) if (rr->type == T_TLSA)
2183   {
2184   const uschar * p = rr->data;
2185   uint8_t usage = p[0], sel = p[1], type = p[2];
2186
2187   DEBUG(D_tls)
2188     debug_printf("TLSA: %d %d %d size %d\n", usage, sel, type, rr->size);
2189
2190   if (  (usage != DANESSL_USAGE_DANE_TA && usage != DANESSL_USAGE_DANE_EE)
2191      || (sel != 0 && sel != 1)
2192      )
2193     continue;
2194   switch(type)
2195     {
2196     case 0:     /* Full: cannot check at present */
2197                 break;
2198     case 1:     if (rr->size != 3 + 256/8) continue;    /* sha2-256 */
2199                 break;
2200     case 2:     if (rr->size != 3 + 512/8) continue;    /* sha2-512 */
2201                 break;
2202     default:    continue;
2203     }
2204
2205   tls_out.tlsa_usage |= 1<<usage;
2206   dane_data[i] = p;
2207   dane_data_len[i++] = rr->size;
2208   }
2209
2210 if (!i) return FALSE;
2211
2212 dane_data[i] = NULL;
2213 dane_data_len[i] = 0;
2214
2215 state->dane_data = (char * const *)dane_data;
2216 state->dane_data_len = dane_data_len;
2217 return TRUE;
2218 }
2219 #endif
2220
2221
2222
2223 /*************************************************
2224 *    Start a TLS session in a client             *
2225 *************************************************/
2226
2227 /* Called from the smtp transport after STARTTLS has been accepted.
2228
2229 Arguments:
2230   fd                the fd of the connection
2231   host              connected host (for messages)
2232   addr              the first address (not used)
2233   tb                transport (always smtp)
2234   tlsa_dnsa         non-NULL, either request or require dane for this host, and
2235                     a TLSA record found.  Therefore, dane verify required.
2236                     Which implies cert must be requested and supplied, dane
2237                     verify must pass, and cert verify irrelevant (incl.
2238                     hostnames), and (caller handled) require_tls
2239   errstr            error string pointer
2240
2241 Returns:            OK/DEFER/FAIL (because using common functions),
2242                     but for a client, DEFER and FAIL have the same meaning
2243 */
2244
2245 int
2246 tls_client_start(int fd, host_item *host,
2247     address_item *addr ARG_UNUSED,
2248     transport_instance * tb,
2249 #ifdef EXPERIMENTAL_DANE
2250     dns_answer * tlsa_dnsa,
2251 #endif
2252     uschar ** errstr)
2253 {
2254 smtp_transport_options_block *ob =
2255   (smtp_transport_options_block *)tb->options_block;
2256 int rc;
2257 exim_gnutls_state_st * state = NULL;
2258 #ifndef DISABLE_OCSP
2259 BOOL require_ocsp =
2260   verify_check_given_host(&ob->hosts_require_ocsp, host) == OK;
2261 BOOL request_ocsp = require_ocsp ? TRUE
2262   : verify_check_given_host(&ob->hosts_request_ocsp, host) == OK;
2263 #endif
2264
2265 DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
2266
2267 if ((rc = tls_init(host, ob->tls_certificate, ob->tls_privatekey,
2268     ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
2269     ob->tls_require_ciphers, &state, errstr)) != OK)
2270   return rc;
2271
2272   {
2273   int dh_min_bits = ob->tls_dh_min_bits;
2274   if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
2275     {
2276     DEBUG(D_tls)
2277       debug_printf("WARNING: tls_dh_min_bits far too low,"
2278                     " clamping %d up to %d\n",
2279           dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
2280     dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
2281     }
2282
2283   DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
2284                     " acceptable bits to %d\n",
2285       dh_min_bits);
2286   gnutls_dh_set_prime_bits(state->session, dh_min_bits);
2287   }
2288
2289 /* Stick to the old behaviour for compatibility if tls_verify_certificates is
2290 set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
2291 the specified host patterns if one of them is defined */
2292
2293 #ifdef SUPPORT_DANE
2294 if (tlsa_dnsa && dane_tlsa_load(state, tlsa_dnsa))
2295   {
2296   DEBUG(D_tls)
2297     debug_printf("TLS: server certificate DANE required.\n");
2298   state->verify_requirement = VERIFY_DANE;
2299   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2300   }
2301 else
2302 #endif
2303     if (  (  state->exp_tls_verify_certificates
2304           && !ob->tls_verify_hosts
2305           && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2306           )
2307         || verify_check_given_host(&ob->tls_verify_hosts, host) == OK
2308        )
2309   {
2310   tls_client_setup_hostname_checks(host, state, ob);
2311   DEBUG(D_tls)
2312     debug_printf("TLS: server certificate verification required.\n");
2313   state->verify_requirement = VERIFY_REQUIRED;
2314   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2315   }
2316 else if (verify_check_given_host(&ob->tls_try_verify_hosts, host) == OK)
2317   {
2318   tls_client_setup_hostname_checks(host, state, ob);
2319   DEBUG(D_tls)
2320     debug_printf("TLS: server certificate verification optional.\n");
2321   state->verify_requirement = VERIFY_OPTIONAL;
2322   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2323   }
2324 else
2325   {
2326   DEBUG(D_tls)
2327     debug_printf("TLS: server certificate verification not required.\n");
2328   state->verify_requirement = VERIFY_NONE;
2329   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2330   }
2331
2332 #ifndef DISABLE_OCSP
2333                         /* supported since GnuTLS 3.1.3 */
2334 if (request_ocsp)
2335   {
2336   DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
2337   if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
2338                     NULL, 0, NULL)) != OK)
2339     return tls_error(US"cert-status-req",
2340                     gnutls_strerror(rc), state->host, errstr);
2341   tls_out.ocsp = OCSP_NOT_RESP;
2342   }
2343 #endif
2344
2345 #ifndef DISABLE_EVENT
2346 if (tb->event_action)
2347   {
2348   state->event_action = tb->event_action;
2349   gnutls_session_set_ptr(state->session, state);
2350   gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2351   }
2352 #endif
2353
2354 gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr_t)(long) fd);
2355 state->fd_in = fd;
2356 state->fd_out = fd;
2357
2358 DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
2359 /* There doesn't seem to be a built-in timeout on connection. */
2360
2361 sigalrm_seen = FALSE;
2362 alarm(ob->command_timeout);
2363 do
2364   {
2365   rc = gnutls_handshake(state->session);
2366   } while ((rc == GNUTLS_E_AGAIN) ||
2367       (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
2368 alarm(0);
2369
2370 if (rc != GNUTLS_E_SUCCESS)
2371   if (sigalrm_seen)
2372     {
2373     gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_USER_CANCELED);
2374     return tls_error(US"gnutls_handshake", "timed out", state->host, errstr);
2375     }
2376   else
2377     return tls_error(US"gnutls_handshake", gnutls_strerror(rc), state->host, errstr);
2378
2379 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
2380
2381 /* Verify late */
2382
2383 if (!verify_certificate(state, errstr))
2384   return tls_error(US"certificate verification failed", *errstr, state->host, errstr);
2385
2386 #ifndef DISABLE_OCSP
2387 if (require_ocsp)
2388   {
2389   DEBUG(D_tls)
2390     {
2391     gnutls_datum_t stapling;
2392     gnutls_ocsp_resp_t resp;
2393     gnutls_datum_t printed;
2394     if (  (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
2395        && (rc= gnutls_ocsp_resp_init(&resp)) == 0
2396        && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
2397        && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
2398        )
2399       {
2400       debug_printf("%.4096s", printed.data);
2401       gnutls_free(printed.data);
2402       }
2403     else
2404       (void) tls_error(US"ocsp decode", gnutls_strerror(rc), state->host, errstr);
2405     }
2406
2407   if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
2408     {
2409     tls_out.ocsp = OCSP_FAILED;
2410     return tls_error(US"certificate status check failed", NULL, state->host, errstr);
2411     }
2412   DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
2413   tls_out.ocsp = OCSP_VFIED;
2414   }
2415 #endif
2416
2417 /* Figure out peer DN, and if authenticated, etc. */
2418
2419 if ((rc = peer_status(state, errstr)) != OK)
2420   return rc;
2421
2422 /* Sets various Exim expansion variables; may need to adjust for ACL callouts */
2423
2424 extract_exim_vars_from_tls_state(state);
2425
2426 return OK;
2427 }
2428
2429
2430
2431
2432 /*************************************************
2433 *         Close down a TLS session               *
2434 *************************************************/
2435
2436 /* This is also called from within a delivery subprocess forked from the
2437 daemon, to shut down the TLS library, without actually doing a shutdown (which
2438 would tamper with the TLS session in the parent process).
2439
2440 Arguments:   TRUE if gnutls_bye is to be called
2441 Returns:     nothing
2442 */
2443
2444 void
2445 tls_close(BOOL is_server, BOOL shutdown)
2446 {
2447 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2448
2449 if (!state->tlsp || state->tlsp->active < 0) return;  /* TLS was not active */
2450
2451 if (shutdown)
2452   {
2453   DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
2454   gnutls_bye(state->session, GNUTLS_SHUT_WR);
2455   }
2456
2457 gnutls_deinit(state->session);
2458 gnutls_certificate_free_credentials(state->x509_cred);
2459
2460
2461 state->tlsp->active = -1;
2462 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
2463
2464 if ((state_server.session == NULL) && (state_client.session == NULL))
2465   {
2466   gnutls_global_deinit();
2467   exim_gnutls_base_init_done = FALSE;
2468   }
2469 }
2470
2471
2472
2473
2474 static BOOL
2475 tls_refill(unsigned lim)
2476 {
2477 exim_gnutls_state_st * state = &state_server;
2478 ssize_t inbytes;
2479
2480 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
2481   state->session, state->xfer_buffer, ssl_xfer_buffer_size);
2482
2483 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
2484 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
2485   MIN(ssl_xfer_buffer_size, lim));
2486 alarm(0);
2487
2488 /* Timeouts do not get this far; see command_timeout_handler().
2489    A zero-byte return appears to mean that the TLS session has been
2490    closed down, not that the socket itself has been closed down. Revert to
2491    non-TLS handling. */
2492
2493 if (sigalrm_seen)
2494   {
2495   DEBUG(D_tls) debug_printf("Got tls read timeout\n");
2496   state->xfer_error = 1;
2497   return FALSE;
2498   }
2499
2500 else if (inbytes == 0)
2501   {
2502   DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2503
2504   receive_getc = smtp_getc;
2505   receive_getbuf = smtp_getbuf;
2506   receive_get_cache = smtp_get_cache;
2507   receive_ungetc = smtp_ungetc;
2508   receive_feof = smtp_feof;
2509   receive_ferror = smtp_ferror;
2510   receive_smtp_buffered = smtp_buffered;
2511
2512   gnutls_deinit(state->session);
2513   gnutls_certificate_free_credentials(state->x509_cred);
2514
2515   state->session = NULL;
2516   state->tlsp->active = -1;
2517   state->tlsp->bits = 0;
2518   state->tlsp->certificate_verified = FALSE;
2519   tls_channelbinding_b64 = NULL;
2520   state->tlsp->cipher = NULL;
2521   state->tlsp->peercert = NULL;
2522   state->tlsp->peerdn = NULL;
2523
2524   return FALSE;
2525   }
2526
2527 /* Handle genuine errors */
2528
2529 else if (inbytes < 0)
2530   {
2531   record_io_error(state, (int) inbytes, US"recv", NULL);
2532   state->xfer_error = 1;
2533   return FALSE;
2534   }
2535 #ifndef DISABLE_DKIM
2536 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
2537 #endif
2538 state->xfer_buffer_hwm = (int) inbytes;
2539 state->xfer_buffer_lwm = 0;
2540 return TRUE;
2541 }
2542
2543 /*************************************************
2544 *            TLS version of getc                 *
2545 *************************************************/
2546
2547 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
2548 it refills the buffer via the GnuTLS reading function.
2549 Only used by the server-side TLS.
2550
2551 This feeds DKIM and should be used for all message-body reads.
2552
2553 Arguments:  lim         Maximum amount to read/bufffer
2554 Returns:    the next character or EOF
2555 */
2556
2557 int
2558 tls_getc(unsigned lim)
2559 {
2560 exim_gnutls_state_st * state = &state_server;
2561
2562 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2563   if (!tls_refill(lim))
2564     return state->xfer_error ? EOF : smtp_getc(lim);
2565
2566 /* Something in the buffer; return next uschar */
2567
2568 return state->xfer_buffer[state->xfer_buffer_lwm++];
2569 }
2570
2571 uschar *
2572 tls_getbuf(unsigned * len)
2573 {
2574 exim_gnutls_state_st * state = &state_server;
2575 unsigned size;
2576 uschar * buf;
2577
2578 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2579   if (!tls_refill(*len))
2580     {
2581     if (!state->xfer_error) return smtp_getbuf(len);
2582     *len = 0;
2583     return NULL;
2584     }
2585
2586 if ((size = state->xfer_buffer_hwm - state->xfer_buffer_lwm) > *len)
2587   size = *len;
2588 buf = &state->xfer_buffer[state->xfer_buffer_lwm];
2589 state->xfer_buffer_lwm += size;
2590 *len = size;
2591 return buf;
2592 }
2593
2594
2595 void
2596 tls_get_cache()
2597 {
2598 #ifndef DISABLE_DKIM
2599 exim_gnutls_state_st * state = &state_server;
2600 int n = state->xfer_buffer_hwm - state->xfer_buffer_lwm;
2601 if (n > 0)
2602   dkim_exim_verify_feed(state->xfer_buffer+state->xfer_buffer_lwm, n);
2603 #endif
2604 }
2605
2606
2607 BOOL
2608 tls_could_read(void)
2609 {
2610 return state_server.xfer_buffer_lwm < state_server.xfer_buffer_hwm
2611  || gnutls_record_check_pending(state_server.session) > 0;
2612 }
2613
2614
2615
2616
2617 /*************************************************
2618 *          Read bytes from TLS channel           *
2619 *************************************************/
2620
2621 /* This does not feed DKIM, so if the caller uses this for reading message body,
2622 then the caller must feed DKIM.
2623
2624 Arguments:
2625   buff      buffer of data
2626   len       size of buffer
2627
2628 Returns:    the number of bytes read
2629             -1 after a failed read
2630 */
2631
2632 int
2633 tls_read(BOOL is_server, uschar *buff, size_t len)
2634 {
2635 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2636 ssize_t inbytes;
2637
2638 if (len > INT_MAX)
2639   len = INT_MAX;
2640
2641 if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
2642   DEBUG(D_tls)
2643     debug_printf("*** PROBABLY A BUG *** " \
2644         "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
2645         state->xfer_buffer_hwm - state->xfer_buffer_lwm);
2646
2647 DEBUG(D_tls)
2648   debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
2649       state->session, buff, len);
2650
2651 inbytes = gnutls_record_recv(state->session, buff, len);
2652 if (inbytes > 0) return inbytes;
2653 if (inbytes == 0)
2654   {
2655   DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2656   }
2657 else record_io_error(state, (int)inbytes, US"recv", NULL);
2658
2659 return -1;
2660 }
2661
2662
2663
2664
2665 /*************************************************
2666 *         Write bytes down TLS channel           *
2667 *************************************************/
2668
2669 /*
2670 Arguments:
2671   is_server channel specifier
2672   buff      buffer of data
2673   len       number of bytes
2674   more      more data expected soon
2675
2676 Returns:    the number of bytes after a successful write,
2677             -1 after a failed write
2678 */
2679
2680 int
2681 tls_write(BOOL is_server, const uschar *buff, size_t len, BOOL more)
2682 {
2683 ssize_t outbytes;
2684 size_t left = len;
2685 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2686 #ifdef SUPPORT_CORK
2687 static BOOL corked = FALSE;
2688
2689 if (more && !corked) gnutls_record_cork(state->session);
2690 #endif
2691
2692 DEBUG(D_tls) debug_printf("%s(%p, " SIZE_T_FMT "%s)\n", __FUNCTION__,
2693   buff, left, more ? ", more" : "");
2694
2695 while (left > 0)
2696   {
2697   DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
2698       buff, left);
2699   outbytes = gnutls_record_send(state->session, buff, left);
2700
2701   DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
2702   if (outbytes < 0)
2703     {
2704     record_io_error(state, outbytes, US"send", NULL);
2705     return -1;
2706     }
2707   if (outbytes == 0)
2708     {
2709     record_io_error(state, 0, US"send", US"TLS channel closed on write");
2710     return -1;
2711     }
2712
2713   left -= outbytes;
2714   buff += outbytes;
2715   }
2716
2717 if (len > INT_MAX)
2718   {
2719   DEBUG(D_tls)
2720     debug_printf("Whoops!  Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
2721         len);
2722   len = INT_MAX;
2723   }
2724
2725 #ifdef SUPPORT_CORK
2726 if (more != corked)
2727   {
2728   if (!more) (void) gnutls_record_uncork(state->session, 0);
2729   corked = more;
2730   }
2731 #endif
2732
2733 return (int) len;
2734 }
2735
2736
2737
2738
2739 /*************************************************
2740 *            Random number generation            *
2741 *************************************************/
2742
2743 /* Pseudo-random number generation.  The result is not expected to be
2744 cryptographically strong but not so weak that someone will shoot themselves
2745 in the foot using it as a nonce in input in some email header scheme or
2746 whatever weirdness they'll twist this into.  The result should handle fork()
2747 and avoid repeating sequences.  OpenSSL handles that for us.
2748
2749 Arguments:
2750   max       range maximum
2751 Returns     a random number in range [0, max-1]
2752 */
2753
2754 #ifdef HAVE_GNUTLS_RND
2755 int
2756 vaguely_random_number(int max)
2757 {
2758 unsigned int r;
2759 int i, needed_len;
2760 uschar *p;
2761 uschar smallbuf[sizeof(r)];
2762
2763 if (max <= 1)
2764   return 0;
2765
2766 needed_len = sizeof(r);
2767 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
2768  * asked for a number less than 10. */
2769 for (r = max, i = 0; r; ++i)
2770   r >>= 1;
2771 i = (i + 7) / 8;
2772 if (i < needed_len)
2773   needed_len = i;
2774
2775 i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2776 if (i < 0)
2777   {
2778   DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2779   return vaguely_random_number_fallback(max);
2780   }
2781 r = 0;
2782 for (p = smallbuf; needed_len; --needed_len, ++p)
2783   {
2784   r *= 256;
2785   r += *p;
2786   }
2787
2788 /* We don't particularly care about weighted results; if someone wants
2789  * smooth distribution and cares enough then they should submit a patch then. */
2790 return r % max;
2791 }
2792 #else /* HAVE_GNUTLS_RND */
2793 int
2794 vaguely_random_number(int max)
2795 {
2796   return vaguely_random_number_fallback(max);
2797 }
2798 #endif /* HAVE_GNUTLS_RND */
2799
2800
2801
2802
2803 /*************************************************
2804 *  Let tls_require_ciphers be checked at startup *
2805 *************************************************/
2806
2807 /* The tls_require_ciphers option, if set, must be something which the
2808 library can parse.
2809
2810 Returns:     NULL on success, or error message
2811 */
2812
2813 uschar *
2814 tls_validate_require_cipher(void)
2815 {
2816 int rc;
2817 uschar *expciphers = NULL;
2818 gnutls_priority_t priority_cache;
2819 const char *errpos;
2820 uschar * dummy_errstr;
2821
2822 #define validate_check_rc(Label) do { \
2823   if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
2824   return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
2825 #define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
2826
2827 if (exim_gnutls_base_init_done)
2828   log_write(0, LOG_MAIN|LOG_PANIC,
2829       "already initialised GnuTLS, Exim developer bug");
2830
2831 #ifdef HAVE_GNUTLS_PKCS11
2832 if (!gnutls_allow_auto_pkcs11)
2833   {
2834   rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
2835   validate_check_rc(US"gnutls_pkcs11_init");
2836   }
2837 #endif
2838 rc = gnutls_global_init();
2839 validate_check_rc(US"gnutls_global_init()");
2840 exim_gnutls_base_init_done = TRUE;
2841
2842 if (!(tls_require_ciphers && *tls_require_ciphers))
2843   return_deinit(NULL);
2844
2845 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
2846                   &dummy_errstr))
2847   return_deinit(US"failed to expand tls_require_ciphers");
2848
2849 if (!(expciphers && *expciphers))
2850   return_deinit(NULL);
2851
2852 DEBUG(D_tls)
2853   debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2854
2855 rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
2856 validate_check_rc(string_sprintf(
2857       "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
2858       expciphers, errpos - CS expciphers, errpos));
2859
2860 #undef return_deinit
2861 #undef validate_check_rc
2862 gnutls_global_deinit();
2863
2864 return NULL;
2865 }
2866
2867
2868
2869
2870 /*************************************************
2871 *         Report the library versions.           *
2872 *************************************************/
2873
2874 /* See a description in tls-openssl.c for an explanation of why this exists.
2875
2876 Arguments:   a FILE* to print the results to
2877 Returns:     nothing
2878 */
2879
2880 void
2881 tls_version_report(FILE *f)
2882 {
2883 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
2884            "                         Runtime: %s\n",
2885            LIBGNUTLS_VERSION,
2886            gnutls_check_version(NULL));
2887 }
2888
2889 /* vi: aw ai sw=2
2890 */
2891 /* End of tls-gnu.c */