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