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