Fix TLS SNI, and add regression test cases
[exim.git] / src / src / tls-gnu.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2014 */
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 Mavroyanopoulos.  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 #endif
46 #if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
47 # warning "GnuTLS library version too old; define DISABLE_OCSP in Makefile"
48 # define DISABLE_OCSP
49 #endif
50
51 #ifndef DISABLE_OCSP
52 # include <gnutls/ocsp.h>
53 #endif
54
55 /* GnuTLS 2 vs 3
56
57 GnuTLS 3 only:
58   gnutls_global_set_audit_log_function()
59
60 Changes:
61   gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
62 */
63
64 /* Local static variables for GnuTLS */
65
66 /* Values for verify_requirement */
67
68 enum peer_verify_requirement
69   { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED
70 #ifdef EXPERIMENTAL_CERTNAMES
71     ,VERIFY_WITHHOST
72 #endif
73   };
74
75 /* This holds most state for server or client; with this, we can set up an
76 outbound TLS-enabled connection in an ACL callout, while not stomping all
77 over the TLS variables available for expansion.
78
79 Some of these correspond to variables in globals.c; those variables will
80 be set to point to content in one of these instances, as appropriate for
81 the stage of the process lifetime.
82
83 Not handled here: global tls_channelbinding_b64.
84 */
85
86 typedef struct exim_gnutls_state {
87   gnutls_session_t      session;
88   gnutls_certificate_credentials_t x509_cred;
89   gnutls_priority_t     priority_cache;
90   enum peer_verify_requirement verify_requirement;
91   int                   fd_in;
92   int                   fd_out;
93   BOOL                  peer_cert_verified;
94   BOOL                  trigger_sni_changes;
95   BOOL                  have_set_peerdn;
96   const struct host_item *host;
97   gnutls_x509_crt_t     peercert;
98   uschar                *peerdn;
99   uschar                *ciphersuite;
100   uschar                *received_sni;
101
102   const uschar *tls_certificate;
103   const uschar *tls_privatekey;
104   const uschar *tls_sni; /* client send only, not received */
105   const uschar *tls_verify_certificates;
106   const uschar *tls_crl;
107   const uschar *tls_require_ciphers;
108
109   uschar *exp_tls_certificate;
110   uschar *exp_tls_privatekey;
111   uschar *exp_tls_verify_certificates;
112   uschar *exp_tls_crl;
113   uschar *exp_tls_require_ciphers;
114   uschar *exp_tls_ocsp_file;
115 #ifdef EXPERIMENTAL_CERTNAMES
116   uschar *exp_tls_verify_cert_hostnames;
117 #endif
118
119   tls_support *tlsp;    /* set in tls_init() */
120
121   uschar *xfer_buffer;
122   int xfer_buffer_lwm;
123   int xfer_buffer_hwm;
124   int xfer_eof;
125   int xfer_error;
126 } exim_gnutls_state_st;
127
128 static const exim_gnutls_state_st exim_gnutls_state_init = {
129   NULL, NULL, NULL, VERIFY_NONE, -1, -1, FALSE, FALSE, FALSE,
130   NULL, NULL, NULL, NULL,
131   NULL, NULL, NULL, NULL, NULL, NULL,
132   NULL, NULL, NULL, NULL, NULL, NULL, NULL,
133 #ifdef EXPERIMENTAL_CERTNAMES
134                                             NULL,
135 #endif
136   NULL,
137   NULL, 0, 0, 0, 0,
138 };
139
140 /* Not only do we have our own APIs which don't pass around state, assuming
141 it's held in globals, GnuTLS doesn't appear to let us register callback data
142 for callbacks, or as part of the session, so we have to keep a "this is the
143 context we're currently dealing with" pointer and rely upon being
144 single-threaded to keep from processing data on an inbound TLS connection while
145 talking to another TLS connection for an outbound check.  This does mean that
146 there's no way for heart-beats to be responded to, for the duration of the
147 second connection. */
148
149 static exim_gnutls_state_st state_server, state_client;
150
151 /* dh_params are initialised once within the lifetime of a process using TLS;
152 if we used TLS in a long-lived daemon, we'd have to reconsider this.  But we
153 don't want to repeat this. */
154
155 static gnutls_dh_params_t dh_server_params = NULL;
156
157 /* No idea how this value was chosen; preserving it.  Default is 3600. */
158
159 static const int ssl_session_timeout = 200;
160
161 static const char * const exim_default_gnutls_priority = "NORMAL";
162
163 /* Guard library core initialisation */
164
165 static BOOL exim_gnutls_base_init_done = FALSE;
166
167
168 /* ------------------------------------------------------------------------ */
169 /* macros */
170
171 #define MAX_HOST_LEN 255
172
173 /* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
174 the library logging; a value less than 0 disables the calls to set up logging
175 callbacks. */
176 #ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
177 #define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
178 #endif
179
180 #ifndef EXIM_CLIENT_DH_MIN_BITS
181 #define EXIM_CLIENT_DH_MIN_BITS 1024
182 #endif
183
184 /* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
185 can ask for a bit-strength.  Without that, we stick to the constant we had
186 before, for now. */
187 #ifndef EXIM_SERVER_DH_BITS_PRE2_12
188 #define EXIM_SERVER_DH_BITS_PRE2_12 1024
189 #endif
190
191 #define exim_gnutls_err_check(Label) do { \
192   if (rc != GNUTLS_E_SUCCESS) { return tls_error((Label), gnutls_strerror(rc), host); } } while (0)
193
194 #define expand_check_tlsvar(Varname) expand_check(state->Varname, US #Varname, &state->exp_##Varname)
195
196 #if GNUTLS_VERSION_NUMBER >= 0x020c00
197 # define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
198 # define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
199 # define HAVE_GNUTLS_RND
200 /* The security fix we provide with the gnutls_allow_auto_pkcs11 option
201  * (4.82 PP/09) introduces a compatibility regression. The symbol simply
202  * isn't available sometimes, so this needs to become a conditional
203  * compilation; the sanest way to deal with this being a problem on
204  * older OSes is to block it in the Local/Makefile with this compiler
205  * definition  */
206 # ifndef AVOID_GNUTLS_PKCS11
207 #  define HAVE_GNUTLS_PKCS11
208 # endif /* AVOID_GNUTLS_PKCS11 */
209 #endif
210
211
212
213
214 /* ------------------------------------------------------------------------ */
215 /* Callback declarations */
216
217 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
218 static void exim_gnutls_logger_cb(int level, const char *message);
219 #endif
220
221 static int exim_sni_handling_cb(gnutls_session_t session);
222
223 #ifndef DISABLE_OCSP
224 static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
225   gnutls_datum_t * ocsp_response);
226 #endif
227
228
229
230 /* ------------------------------------------------------------------------ */
231 /* Static functions */
232
233 /*************************************************
234 *               Handle TLS error                 *
235 *************************************************/
236
237 /* Called from lots of places when errors occur before actually starting to do
238 the TLS handshake, that is, while the session is still in clear. Always returns
239 DEFER for a server and FAIL for a client so that most calls can use "return
240 tls_error(...)" to do this processing and then give an appropriate return. A
241 single function is used for both server and client, because it is called from
242 some shared functions.
243
244 Argument:
245   prefix    text to include in the logged error
246   msg       additional error string (may be NULL)
247             usually obtained from gnutls_strerror()
248   host      NULL if setting up a server;
249             the connected host if setting up a client
250
251 Returns:    OK/DEFER/FAIL
252 */
253
254 static int
255 tls_error(const uschar *prefix, const char *msg, const host_item *host)
256 {
257 if (host)
258   {
259   log_write(0, LOG_MAIN, "TLS error on connection to %s [%s] (%s)%s%s",
260       host->name, host->address, prefix, msg ? ": " : "", msg ? msg : "");
261   return FAIL;
262   }
263 else
264   {
265   uschar *conn_info = smtp_get_connection_info();
266   if (Ustrncmp(conn_info, US"SMTP ", 5) == 0)
267     conn_info += 5;
268   log_write(0, LOG_MAIN, "TLS error on %s (%s)%s%s",
269       conn_info, prefix, msg ? ": " : "", msg ? msg : "");
270   return DEFER;
271   }
272 }
273
274
275
276
277 /*************************************************
278 *    Deal with logging errors during I/O         *
279 *************************************************/
280
281 /* We have to get the identity of the peer from saved data.
282
283 Argument:
284   state    the current GnuTLS exim state container
285   rc       the GnuTLS error code, or 0 if it's a local error
286   when     text identifying read or write
287   text     local error text when ec is 0
288
289 Returns:   nothing
290 */
291
292 static void
293 record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
294 {
295 const char *msg;
296
297 if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
298   msg = CS string_sprintf("%s: %s", US gnutls_strerror(rc),
299     US gnutls_alert_get_name(gnutls_alert_get(state->session)));
300 else
301   msg = gnutls_strerror(rc);
302
303 tls_error(when, msg, state->host);
304 }
305
306
307
308
309 /*************************************************
310 *        Set various Exim expansion vars         *
311 *************************************************/
312
313 #define exim_gnutls_cert_err(Label) \
314   do \
315     { \
316     if (rc != GNUTLS_E_SUCCESS) \
317       { \
318       DEBUG(D_tls) debug_printf("TLS: cert problem: %s: %s\n", \
319         (Label), gnutls_strerror(rc)); \
320       return rc; \
321       } \
322     } while (0)
323
324 static int
325 import_cert(const gnutls_datum * cert, gnutls_x509_crt_t * crtp)
326 {
327 int rc;
328
329 rc = gnutls_x509_crt_init(crtp);
330 exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
331
332 rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
333 exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
334
335 return rc;
336 }
337
338 #undef exim_gnutls_cert_err
339
340
341 /* We set various Exim global variables from the state, once a session has
342 been established.  With TLS callouts, may need to change this to stack
343 variables, or just re-call it with the server state after client callout
344 has finished.
345
346 Make sure anything set here is unset in tls_getc().
347
348 Sets:
349   tls_active                fd
350   tls_bits                  strength indicator
351   tls_certificate_verified  bool indicator
352   tls_channelbinding_b64    for some SASL mechanisms
353   tls_cipher                a string
354   tls_peercert              pointer to library internal
355   tls_peerdn                a string
356   tls_sni                   a (UTF-8) string
357   tls_ourcert               pointer to library internal
358
359 Argument:
360   state      the relevant exim_gnutls_state_st *
361 */
362
363 static void
364 extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
365 {
366 gnutls_cipher_algorithm_t cipher;
367 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
368 int old_pool;
369 int rc;
370 gnutls_datum_t channel;
371 #endif
372 tls_support * tlsp = state->tlsp;
373
374 tlsp->active = state->fd_out;
375
376 cipher = gnutls_cipher_get(state->session);
377 /* returns size in "bytes" */
378 tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
379
380 tlsp->cipher = state->ciphersuite;
381
382 DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
383
384 tlsp->certificate_verified = state->peer_cert_verified;
385
386 /* note that tls_channelbinding_b64 is not saved to the spool file, since it's
387 only available for use for authenticators while this TLS session is running. */
388
389 tls_channelbinding_b64 = NULL;
390 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
391 channel.data = NULL;
392 channel.size = 0;
393 rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel);
394 if (rc) {
395   DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc));
396 } else {
397   old_pool = store_pool;
398   store_pool = POOL_PERM;
399   tls_channelbinding_b64 = auth_b64encode(channel.data, (int)channel.size);
400   store_pool = old_pool;
401   DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
402 }
403 #endif
404
405 /* peercert is set in peer_status() */
406 tlsp->peerdn = state->peerdn;
407 tlsp->sni =    state->received_sni;
408
409 /* record our certificate */
410   {
411   const gnutls_datum * cert = gnutls_certificate_get_ours(state->session);
412   gnutls_x509_crt_t crt;
413
414   tlsp->ourcert = cert && import_cert(cert, &crt)==0 ? crt : NULL;
415   }
416 }
417
418
419
420
421 /*************************************************
422 *            Setup up DH parameters              *
423 *************************************************/
424
425 /* Generating the D-H parameters may take a long time. They only need to
426 be re-generated every so often, depending on security policy. What we do is to
427 keep these parameters in a file in the spool directory. If the file does not
428 exist, we generate them. This means that it is easy to cause a regeneration.
429
430 The new file is written as a temporary file and renamed, so that an incomplete
431 file is never present. If two processes both compute some new parameters, you
432 waste a bit of effort, but it doesn't seem worth messing around with locking to
433 prevent this.
434
435 Returns:     OK/DEFER/FAIL
436 */
437
438 static int
439 init_server_dh(void)
440 {
441 int fd, rc;
442 unsigned int dh_bits;
443 gnutls_datum m;
444 uschar filename_buf[PATH_MAX];
445 uschar *filename = NULL;
446 size_t sz;
447 uschar *exp_tls_dhparam;
448 BOOL use_file_in_spool = FALSE;
449 BOOL use_fixed_file = FALSE;
450 host_item *host = NULL; /* dummy for macros */
451
452 DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
453
454 rc = gnutls_dh_params_init(&dh_server_params);
455 exim_gnutls_err_check(US"gnutls_dh_params_init");
456
457 m.data = NULL;
458 m.size = 0;
459
460 if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam))
461   return DEFER;
462
463 if (!exp_tls_dhparam)
464   {
465   DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
466   m.data = US std_dh_prime_default();
467   m.size = Ustrlen(m.data);
468   }
469 else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
470   use_file_in_spool = TRUE;
471 else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
472   {
473   DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
474   return OK;
475   }
476 else if (exp_tls_dhparam[0] != '/')
477   {
478   m.data = US std_dh_prime_named(exp_tls_dhparam);
479   if (m.data == NULL)
480     return tls_error(US"No standard prime named", CS exp_tls_dhparam, NULL);
481   m.size = Ustrlen(m.data);
482   }
483 else
484   {
485   use_fixed_file = TRUE;
486   filename = exp_tls_dhparam;
487   }
488
489 if (m.data)
490   {
491   rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
492   exim_gnutls_err_check(US"gnutls_dh_params_import_pkcs3");
493   DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
494   return OK;
495   }
496
497 #ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
498 /* If you change this constant, also change dh_param_fn_ext so that we can use a
499 different filename and ensure we have sufficient bits. */
500 dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
501 if (!dh_bits)
502   return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL);
503 DEBUG(D_tls)
504   debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
505       dh_bits);
506 #else
507 dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
508 DEBUG(D_tls)
509   debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
510       dh_bits);
511 #endif
512
513 /* Some clients have hard-coded limits. */
514 if (dh_bits > tls_dh_max_bits)
515   {
516   DEBUG(D_tls)
517     debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
518         tls_dh_max_bits);
519   dh_bits = tls_dh_max_bits;
520   }
521
522 if (use_file_in_spool)
523   {
524   if (!string_format(filename_buf, sizeof(filename_buf),
525         "%s/gnutls-params-%d", spool_directory, dh_bits))
526     return tls_error(US"overlong filename", NULL, NULL);
527   filename = filename_buf;
528   }
529
530 /* Open the cache file for reading and if successful, read it and set up the
531 parameters. */
532
533 fd = Uopen(filename, O_RDONLY, 0);
534 if (fd >= 0)
535   {
536   struct stat statbuf;
537   FILE *fp;
538   int saved_errno;
539
540   if (fstat(fd, &statbuf) < 0)  /* EIO */
541     {
542     saved_errno = errno;
543     (void)close(fd);
544     return tls_error(US"TLS cache stat failed", strerror(saved_errno), NULL);
545     }
546   if (!S_ISREG(statbuf.st_mode))
547     {
548     (void)close(fd);
549     return tls_error(US"TLS cache not a file", NULL, NULL);
550     }
551   fp = fdopen(fd, "rb");
552   if (!fp)
553     {
554     saved_errno = errno;
555     (void)close(fd);
556     return tls_error(US"fdopen(TLS cache stat fd) failed",
557         strerror(saved_errno), NULL);
558     }
559
560   m.size = statbuf.st_size;
561   m.data = malloc(m.size);
562   if (m.data == NULL)
563     {
564     fclose(fp);
565     return tls_error(US"malloc failed", strerror(errno), NULL);
566     }
567   sz = fread(m.data, m.size, 1, fp);
568   if (!sz)
569     {
570     saved_errno = errno;
571     fclose(fp);
572     free(m.data);
573     return tls_error(US"fread failed", strerror(saved_errno), NULL);
574     }
575   fclose(fp);
576
577   rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
578   free(m.data);
579   exim_gnutls_err_check(US"gnutls_dh_params_import_pkcs3");
580   DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
581   }
582
583 /* If the file does not exist, fall through to compute new data and cache it.
584 If there was any other opening error, it is serious. */
585
586 else if (errno == ENOENT)
587   {
588   rc = -1;
589   DEBUG(D_tls)
590     debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
591   }
592 else
593   return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
594       NULL, NULL);
595
596 /* If ret < 0, either the cache file does not exist, or the data it contains
597 is not useful. One particular case of this is when upgrading from an older
598 release of Exim in which the data was stored in a different format. We don't
599 try to be clever and support both formats; we just regenerate new data in this
600 case. */
601
602 if (rc < 0)
603   {
604   uschar *temp_fn;
605   unsigned int dh_bits_gen = dh_bits;
606
607   if ((PATH_MAX - Ustrlen(filename)) < 10)
608     return tls_error(US"Filename too long to generate replacement",
609         CS filename, NULL);
610
611   temp_fn = string_copy(US "%s.XXXXXXX");
612   fd = mkstemp(CS temp_fn); /* modifies temp_fn */
613   if (fd < 0)
614     return tls_error(US"Unable to open temp file", strerror(errno), NULL);
615   (void)fchown(fd, exim_uid, exim_gid);   /* Probably not necessary */
616
617   /* GnuTLS overshoots!
618    * If we ask for 2236, we might get 2237 or more.
619    * But there's no way to ask GnuTLS how many bits there really are.
620    * We can ask how many bits were used in a TLS session, but that's it!
621    * The prime itself is hidden behind too much abstraction.
622    * So we ask for less, and proceed on a wing and a prayer.
623    * First attempt, subtracted 3 for 2233 and got 2240.
624    */
625   if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
626     {
627     dh_bits_gen = dh_bits - 10;
628     DEBUG(D_tls)
629       debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
630           dh_bits_gen);
631     }
632
633   DEBUG(D_tls)
634     debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
635         dh_bits_gen);
636   rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen);
637   exim_gnutls_err_check(US"gnutls_dh_params_generate2");
638
639   /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
640   and I confirmed that a NULL call to get the size first is how the GnuTLS
641   sample apps handle this. */
642
643   sz = 0;
644   m.data = NULL;
645   rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
646       m.data, &sz);
647   if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
648     exim_gnutls_err_check(US"gnutls_dh_params_export_pkcs3(NULL) sizing");
649   m.size = sz;
650   m.data = malloc(m.size);
651   if (m.data == NULL)
652     return tls_error(US"memory allocation failed", strerror(errno), NULL);
653   /* this will return a size 1 less than the allocation size above */
654   rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
655       m.data, &sz);
656   if (rc != GNUTLS_E_SUCCESS)
657     {
658     free(m.data);
659     exim_gnutls_err_check(US"gnutls_dh_params_export_pkcs3() real");
660     }
661   m.size = sz; /* shrink by 1, probably */
662
663   sz = write_to_fd_buf(fd, m.data, (size_t) m.size);
664   if (sz != m.size)
665     {
666     free(m.data);
667     return tls_error(US"TLS cache write D-H params failed",
668         strerror(errno), NULL);
669     }
670   free(m.data);
671   sz = write_to_fd_buf(fd, US"\n", 1);
672   if (sz != 1)
673     return tls_error(US"TLS cache write D-H params final newline failed",
674         strerror(errno), NULL);
675
676   rc = close(fd);
677   if (rc)
678     return tls_error(US"TLS cache write close() failed",
679         strerror(errno), NULL);
680
681   if (Urename(temp_fn, filename) < 0)
682     return tls_error(string_sprintf("failed to rename \"%s\" as \"%s\"",
683           temp_fn, filename), strerror(errno), NULL);
684
685   DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
686   }
687
688 DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
689 return OK;
690 }
691
692
693
694
695 /*************************************************
696 *       Variables re-expanded post-SNI           *
697 *************************************************/
698
699 /* Called from both server and client code, via tls_init(), and also from
700 the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
701
702 We can tell the two apart by state->received_sni being non-NULL in callback.
703
704 The callback should not call us unless state->trigger_sni_changes is true,
705 which we are responsible for setting on the first pass through.
706
707 Arguments:
708   state           exim_gnutls_state_st *
709
710 Returns:          OK/DEFER/FAIL
711 */
712
713 static int
714 tls_expand_session_files(exim_gnutls_state_st *state)
715 {
716 struct stat statbuf;
717 int rc;
718 const host_item *host = state->host;  /* macro should be reconsidered? */
719 uschar *saved_tls_certificate = NULL;
720 uschar *saved_tls_privatekey = NULL;
721 uschar *saved_tls_verify_certificates = NULL;
722 uschar *saved_tls_crl = NULL;
723 int cert_count;
724
725 /* We check for tls_sni *before* expansion. */
726 if (!host)      /* server */
727   {
728   if (!state->received_sni)
729     {
730     if (state->tls_certificate &&
731         (Ustrstr(state->tls_certificate, US"tls_sni") ||
732          Ustrstr(state->tls_certificate, US"tls_in_sni") ||
733          Ustrstr(state->tls_certificate, US"tls_out_sni")
734        ))
735       {
736       DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
737       state->trigger_sni_changes = TRUE;
738       }
739     }
740   else
741     {
742     /* useful for debugging */
743     saved_tls_certificate = state->exp_tls_certificate;
744     saved_tls_privatekey = state->exp_tls_privatekey;
745     saved_tls_verify_certificates = state->exp_tls_verify_certificates;
746     saved_tls_crl = state->exp_tls_crl;
747     }
748   }
749
750 rc = gnutls_certificate_allocate_credentials(&state->x509_cred);
751 exim_gnutls_err_check(US"gnutls_certificate_allocate_credentials");
752
753 /* remember: expand_check_tlsvar() is expand_check() but fiddling with
754 state members, assuming consistent naming; and expand_check() returns
755 false if expansion failed, unless expansion was forced to fail. */
756
757 /* check if we at least have a certificate, before doing expensive
758 D-H generation. */
759
760 if (!expand_check_tlsvar(tls_certificate))
761   return DEFER;
762
763 /* certificate is mandatory in server, optional in client */
764
765 if ((state->exp_tls_certificate == NULL) ||
766     (*state->exp_tls_certificate == '\0'))
767   {
768   if (!host)
769     return tls_error(US"no TLS server certificate is specified", NULL, NULL);
770   else
771     DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
772   }
773
774 if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey))
775   return DEFER;
776
777 /* tls_privatekey is optional, defaulting to same file as certificate */
778
779 if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
780   {
781   state->tls_privatekey = state->tls_certificate;
782   state->exp_tls_privatekey = state->exp_tls_certificate;
783   }
784
785
786 if (state->exp_tls_certificate && *state->exp_tls_certificate)
787   {
788   DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
789       state->exp_tls_certificate, state->exp_tls_privatekey);
790
791   if (state->received_sni)
792     {
793     if ((Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0) &&
794         (Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0))
795       {
796       DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
797       }
798     else
799       {
800       DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
801       }
802     }
803
804   rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
805       CS state->exp_tls_certificate, CS state->exp_tls_privatekey,
806       GNUTLS_X509_FMT_PEM);
807   exim_gnutls_err_check(
808       string_sprintf("cert/key setup: cert=%s key=%s",
809         state->exp_tls_certificate, state->exp_tls_privatekey));
810   DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
811   } /* tls_certificate */
812
813
814 /* Set the OCSP stapling server info */
815
816 #ifndef DISABLE_OCSP
817 if (  !host     /* server */
818    && tls_ocsp_file
819    )
820   {
821   if (!expand_check(tls_ocsp_file, US"tls_ocsp_file",
822         &state->exp_tls_ocsp_file))
823     return DEFER;
824
825   /* Use the full callback method for stapling just to get observability.
826   More efficient would be to read the file once only, if it never changed
827   (due to SNI). Would need restart on file update, or watch datestamp.  */
828
829   gnutls_certificate_set_ocsp_status_request_function(state->x509_cred,
830     server_ocsp_stapling_cb, state->exp_tls_ocsp_file);
831
832   DEBUG(D_tls) debug_printf("Set OCSP response file %s\n", &state->exp_tls_ocsp_file);
833   }
834 #endif
835
836
837 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
838 provided. Experiment shows that, if the certificate file is empty, an unhelpful
839 error message is provided. However, if we just refrain from setting anything up
840 in that case, certificate verification fails, which seems to be the correct
841 behaviour. */
842
843 if (state->tls_verify_certificates && *state->tls_verify_certificates)
844   {
845   if (!expand_check_tlsvar(tls_verify_certificates))
846     return DEFER;
847   if (state->tls_crl && *state->tls_crl)
848     if (!expand_check_tlsvar(tls_crl))
849       return DEFER;
850
851   if (!(state->exp_tls_verify_certificates &&
852         *state->exp_tls_verify_certificates))
853     {
854     DEBUG(D_tls)
855       debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
856     /* With no tls_verify_certificates, we ignore tls_crl too */
857     return OK;
858     }
859   }
860 else
861   {
862   DEBUG(D_tls)
863     debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
864   return OK;
865   }
866
867 if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
868   {
869   log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
870       "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
871       strerror(errno));
872   return DEFER;
873   }
874
875 /* The test suite passes in /dev/null; we could check for that path explicitly,
876 but who knows if someone has some weird FIFO which always dumps some certs, or
877 other weirdness.  The thing we really want to check is that it's not a
878 directory, since while OpenSSL supports that, GnuTLS does not.
879 So s/!S_ISREG/S_ISDIR/ and change some messsaging ... */
880 if (S_ISDIR(statbuf.st_mode))
881   {
882   DEBUG(D_tls)
883     debug_printf("verify certificates path is a dir: \"%s\"\n",
884         state->exp_tls_verify_certificates);
885   log_write(0, LOG_MAIN|LOG_PANIC,
886       "tls_verify_certificates \"%s\" is a directory",
887       state->exp_tls_verify_certificates);
888   return DEFER;
889   }
890
891 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
892         state->exp_tls_verify_certificates, statbuf.st_size);
893
894 if (statbuf.st_size == 0)
895   {
896   DEBUG(D_tls)
897     debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
898   return OK;
899   }
900
901 cert_count = gnutls_certificate_set_x509_trust_file(state->x509_cred,
902     CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
903 if (cert_count < 0)
904   {
905   rc = cert_count;
906   exim_gnutls_err_check(US"gnutls_certificate_set_x509_trust_file");
907   }
908 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n", cert_count);
909
910 if (state->tls_crl && *state->tls_crl &&
911     state->exp_tls_crl && *state->exp_tls_crl)
912   {
913   DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
914   cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
915       CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM);
916   if (cert_count < 0)
917     {
918     rc = cert_count;
919     exim_gnutls_err_check(US"gnutls_certificate_set_x509_crl_file");
920     }
921   DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
922   }
923
924 return OK;
925 }
926
927
928
929
930 /*************************************************
931 *          Set X.509 state variables             *
932 *************************************************/
933
934 /* In GnuTLS, the registered cert/key are not replaced by a later
935 set of a cert/key, so for SNI support we need a whole new x509_cred
936 structure.  Which means various other non-re-expanded pieces of state
937 need to be re-set in the new struct, so the setting logic is pulled
938 out to this.
939
940 Arguments:
941   state           exim_gnutls_state_st *
942
943 Returns:          OK/DEFER/FAIL
944 */
945
946 static int
947 tls_set_remaining_x509(exim_gnutls_state_st *state)
948 {
949 int rc;
950 const host_item *host = state->host;  /* macro should be reconsidered? */
951
952 /* Create D-H parameters, or read them from the cache file. This function does
953 its own SMTP error messaging. This only happens for the server, TLS D-H ignores
954 client-side params. */
955
956 if (!state->host)
957   {
958   if (!dh_server_params)
959     {
960     rc = init_server_dh();
961     if (rc != OK) return rc;
962     }
963   gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
964   }
965
966 /* Link the credentials to the session. */
967
968 rc = gnutls_credentials_set(state->session, GNUTLS_CRD_CERTIFICATE, state->x509_cred);
969 exim_gnutls_err_check(US"gnutls_credentials_set");
970
971 return OK;
972 }
973
974 /*************************************************
975 *            Initialize for GnuTLS               *
976 *************************************************/
977
978 /* Called from both server and client code. In the case of a server, errors
979 before actual TLS negotiation return DEFER.
980
981 Arguments:
982   host            connected host, if client; NULL if server
983   certificate     certificate file
984   privatekey      private key file
985   sni             TLS SNI to send, sometimes when client; else NULL
986   cas             CA certs file
987   crl             CRL file
988   require_ciphers tls_require_ciphers setting
989   caller_state    returned state-info structure
990
991 Returns:          OK/DEFER/FAIL
992 */
993
994 static int
995 tls_init(
996     const host_item *host,
997     const uschar *certificate,
998     const uschar *privatekey,
999     const uschar *sni,
1000     const uschar *cas,
1001     const uschar *crl,
1002     const uschar *require_ciphers,
1003     exim_gnutls_state_st **caller_state)
1004 {
1005 exim_gnutls_state_st *state;
1006 int rc;
1007 size_t sz;
1008 const char *errpos;
1009 uschar *p;
1010 BOOL want_default_priorities;
1011
1012 if (!exim_gnutls_base_init_done)
1013   {
1014   DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1015
1016 #ifdef HAVE_GNUTLS_PKCS11
1017   /* By default, gnutls_global_init will init PKCS11 support in auto mode,
1018   which loads modules from a config file, which sounds good and may be wanted
1019   by some sysadmin, but also means in common configurations that GNOME keyring
1020   environment variables are used and so breaks for users calling mailq.
1021   To prevent this, we init PKCS11 first, which is the documented approach. */
1022   if (!gnutls_allow_auto_pkcs11)
1023     {
1024     rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
1025     exim_gnutls_err_check(US"gnutls_pkcs11_init");
1026     }
1027 #endif
1028
1029   rc = gnutls_global_init();
1030   exim_gnutls_err_check(US"gnutls_global_init");
1031
1032 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1033   DEBUG(D_tls)
1034     {
1035     gnutls_global_set_log_function(exim_gnutls_logger_cb);
1036     /* arbitrarily chosen level; bump upto 9 for more */
1037     gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
1038     }
1039 #endif
1040
1041   exim_gnutls_base_init_done = TRUE;
1042   }
1043
1044 if (host)
1045   {
1046   state = &state_client;
1047   memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1048   state->tlsp = &tls_out;
1049   DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1050   rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1051   }
1052 else
1053   {
1054   state = &state_server;
1055   memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1056   state->tlsp = &tls_in;
1057   DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1058   rc = gnutls_init(&state->session, GNUTLS_SERVER);
1059   }
1060 exim_gnutls_err_check(US"gnutls_init");
1061
1062 state->host = host;
1063
1064 state->tls_certificate = certificate;
1065 state->tls_privatekey = privatekey;
1066 state->tls_require_ciphers = require_ciphers;
1067 state->tls_sni = sni;
1068 state->tls_verify_certificates = cas;
1069 state->tls_crl = crl;
1070
1071 /* This handles the variables that might get re-expanded after TLS SNI;
1072 that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
1073
1074 DEBUG(D_tls)
1075   debug_printf("Expanding various TLS configuration options for session credentials.\n");
1076 rc = tls_expand_session_files(state);
1077 if (rc != OK) return rc;
1078
1079 /* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1080 requires a new structure afterwards. */
1081
1082 rc = tls_set_remaining_x509(state);
1083 if (rc != OK) return rc;
1084
1085 /* set SNI in client, only */
1086 if (host)
1087   {
1088   if (!expand_check(sni, US"tls_out_sni", &state->tlsp->sni))
1089     return DEFER;
1090   if (state->tlsp->sni && *state->tlsp->sni)
1091     {
1092     DEBUG(D_tls)
1093       debug_printf("Setting TLS client SNI to \"%s\"\n", state->tlsp->sni);
1094     sz = Ustrlen(state->tlsp->sni);
1095     rc = gnutls_server_name_set(state->session,
1096         GNUTLS_NAME_DNS, state->tlsp->sni, sz);
1097     exim_gnutls_err_check(US"gnutls_server_name_set");
1098     }
1099   }
1100 else if (state->tls_sni)
1101   DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
1102       "have an SNI set for a client [%s]\n", state->tls_sni);
1103
1104 /* This is the priority string support,
1105 http://www.gnutls.org/manual/html_node/Priority-Strings.html
1106 and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1107 This was backwards incompatible, but means Exim no longer needs to track
1108 all algorithms and provide string forms for them. */
1109
1110 want_default_priorities = TRUE;
1111
1112 if (state->tls_require_ciphers && *state->tls_require_ciphers)
1113   {
1114   if (!expand_check_tlsvar(tls_require_ciphers))
1115     return DEFER;
1116   if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
1117     {
1118     DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n",
1119         state->exp_tls_require_ciphers);
1120
1121     rc = gnutls_priority_init(&state->priority_cache,
1122         CS state->exp_tls_require_ciphers, &errpos);
1123     want_default_priorities = FALSE;
1124     p = state->exp_tls_require_ciphers;
1125     }
1126   }
1127 if (want_default_priorities)
1128   {
1129   DEBUG(D_tls)
1130     debug_printf("GnuTLS using default session cipher/priority \"%s\"\n",
1131         exim_default_gnutls_priority);
1132   rc = gnutls_priority_init(&state->priority_cache,
1133       exim_default_gnutls_priority, &errpos);
1134   p = US exim_default_gnutls_priority;
1135   }
1136
1137 exim_gnutls_err_check(string_sprintf(
1138       "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1139       p, errpos - CS p, errpos));
1140
1141 rc = gnutls_priority_set(state->session, state->priority_cache);
1142 exim_gnutls_err_check(US"gnutls_priority_set");
1143
1144 gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1145
1146 /* Reduce security in favour of increased compatibility, if the admin
1147 decides to make that trade-off. */
1148 if (gnutls_compat_mode)
1149   {
1150 #if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1151   DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1152   gnutls_session_enable_compatibility_mode(state->session);
1153 #else
1154   DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1155 #endif
1156   }
1157
1158 *caller_state = state;
1159 return OK;
1160 }
1161
1162
1163
1164 /*************************************************
1165 *            Extract peer information            *
1166 *************************************************/
1167
1168 /* Called from both server and client code.
1169 Only this is allowed to set state->peerdn and state->have_set_peerdn
1170 and we use that to detect double-calls.
1171
1172 NOTE: the state blocks last while the TLS connection is up, which is fine
1173 for logging in the server side, but for the client side, we log after teardown
1174 in src/deliver.c.  While the session is up, we can twist about states and
1175 repoint tls_* globals, but those variables used for logging or other variable
1176 expansion that happens _after_ delivery need to have a longer life-time.
1177
1178 So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1179 doing this more than once per generation of a state context.  We set them in
1180 the state context, and repoint tls_* to them.  After the state goes away, the
1181 tls_* copies of the pointers remain valid and client delivery logging is happy.
1182
1183 tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1184 don't apply.
1185
1186 Arguments:
1187   state           exim_gnutls_state_st *
1188
1189 Returns:          OK/DEFER/FAIL
1190 */
1191
1192 static int
1193 peer_status(exim_gnutls_state_st *state)
1194 {
1195 uschar cipherbuf[256];
1196 const gnutls_datum *cert_list;
1197 int old_pool, rc;
1198 unsigned int cert_list_size = 0;
1199 gnutls_protocol_t protocol;
1200 gnutls_cipher_algorithm_t cipher;
1201 gnutls_kx_algorithm_t kx;
1202 gnutls_mac_algorithm_t mac;
1203 gnutls_certificate_type_t ct;
1204 gnutls_x509_crt_t crt;
1205 uschar *p, *dn_buf;
1206 size_t sz;
1207
1208 if (state->have_set_peerdn)
1209   return OK;
1210 state->have_set_peerdn = TRUE;
1211
1212 state->peerdn = NULL;
1213
1214 /* tls_cipher */
1215 cipher = gnutls_cipher_get(state->session);
1216 protocol = gnutls_protocol_get_version(state->session);
1217 mac = gnutls_mac_get(state->session);
1218 kx = gnutls_kx_get(state->session);
1219
1220 string_format(cipherbuf, sizeof(cipherbuf),
1221     "%s:%s:%d",
1222     gnutls_protocol_get_name(protocol),
1223     gnutls_cipher_suite_get_name(kx, cipher, mac),
1224     (int) gnutls_cipher_get_key_size(cipher) * 8);
1225
1226 /* I don't see a way that spaces could occur, in the current GnuTLS
1227 code base, but it was a concern in the old code and perhaps older GnuTLS
1228 releases did return "TLS 1.0"; play it safe, just in case. */
1229 for (p = cipherbuf; *p != '\0'; ++p)
1230   if (isspace(*p))
1231     *p = '-';
1232 old_pool = store_pool;
1233 store_pool = POOL_PERM;
1234 state->ciphersuite = string_copy(cipherbuf);
1235 store_pool = old_pool;
1236 state->tlsp->cipher = state->ciphersuite;
1237
1238 /* tls_peerdn */
1239 cert_list = gnutls_certificate_get_peers(state->session, &cert_list_size);
1240
1241 if (cert_list == NULL || cert_list_size == 0)
1242   {
1243   DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1244       cert_list, cert_list_size);
1245   if (state->verify_requirement >= VERIFY_REQUIRED)
1246     return tls_error(US"certificate verification failed",
1247         "no certificate received from peer", state->host);
1248   return OK;
1249   }
1250
1251 ct = gnutls_certificate_type_get(state->session);
1252 if (ct != GNUTLS_CRT_X509)
1253   {
1254   const char *ctn = gnutls_certificate_type_get_name(ct);
1255   DEBUG(D_tls)
1256     debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
1257   if (state->verify_requirement >= VERIFY_REQUIRED)
1258     return tls_error(US"certificate verification not possible, unhandled type",
1259         ctn, state->host);
1260   return OK;
1261   }
1262
1263 #define exim_gnutls_peer_err(Label) \
1264   do { \
1265     if (rc != GNUTLS_E_SUCCESS) \
1266       { \
1267       DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", \
1268         (Label), gnutls_strerror(rc)); \
1269       if (state->verify_requirement >= VERIFY_REQUIRED) \
1270         return tls_error((Label), gnutls_strerror(rc), state->host); \
1271       return OK; \
1272       } \
1273     } while (0)
1274
1275 rc = import_cert(&cert_list[0], &crt);
1276 exim_gnutls_peer_err(US"cert 0");
1277
1278 state->tlsp->peercert = state->peercert = crt;
1279
1280 sz = 0;
1281 rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1282 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
1283   {
1284   exim_gnutls_peer_err(US"getting size for cert DN failed");
1285   return FAIL; /* should not happen */
1286   }
1287 dn_buf = store_get_perm(sz);
1288 rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1289 exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
1290
1291 state->peerdn = dn_buf;
1292
1293 return OK;
1294 #undef exim_gnutls_peer_err
1295 }
1296
1297
1298
1299
1300 /*************************************************
1301 *            Verify peer certificate             *
1302 *************************************************/
1303
1304 /* Called from both server and client code.
1305 *Should* be using a callback registered with
1306 gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1307 the peer information, but that's too new for some OSes.
1308
1309 Arguments:
1310   state           exim_gnutls_state_st *
1311   error           where to put an error message
1312
1313 Returns:
1314   FALSE     if the session should be rejected
1315   TRUE      if the cert is okay or we just don't care
1316 */
1317
1318 static BOOL
1319 verify_certificate(exim_gnutls_state_st *state, const char **error)
1320 {
1321 int rc;
1322 unsigned int verify;
1323
1324 *error = NULL;
1325
1326 if ((rc = peer_status(state)) != OK)
1327   {
1328   verify = GNUTLS_CERT_INVALID;
1329   *error = "certificate not supplied";
1330   }
1331 else
1332   rc = gnutls_certificate_verify_peers2(state->session, &verify);
1333
1334 /* Handle the result of verification. INVALID seems to be set as well
1335 as REVOKED, but leave the test for both. */
1336
1337 if (rc < 0 ||
1338     verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED)
1339    )
1340   {
1341   state->peer_cert_verified = FALSE;
1342   if (!*error)
1343     *error = verify & GNUTLS_CERT_REVOKED
1344       ? "certificate revoked" : "certificate invalid";
1345
1346   DEBUG(D_tls)
1347     debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
1348         *error, state->peerdn ? state->peerdn : US"<unset>");
1349
1350   if (state->verify_requirement >= VERIFY_REQUIRED)
1351     {
1352     gnutls_alert_send(state->session,
1353       GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1354     return FALSE;
1355     }
1356   DEBUG(D_tls)
1357     debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
1358   }
1359
1360 else
1361   {
1362 #ifdef EXPERIMENTAL_CERTNAMES
1363   if (state->verify_requirement == VERIFY_WITHHOST)
1364     {
1365     int sep = 0;
1366     uschar * list = state->exp_tls_verify_cert_hostnames;
1367     uschar * name;
1368     while (name = string_nextinlist(&list, &sep, NULL, 0))
1369       if (gnutls_x509_crt_check_hostname(state->tlsp->peercert, CS name))
1370         break;
1371     if (!name)
1372       {
1373       DEBUG(D_tls)
1374         debug_printf("TLS certificate verification failed: cert name mismatch\n");
1375       gnutls_alert_send(state->session,
1376         GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1377       return FALSE;
1378       }
1379     }
1380 #endif
1381   state->peer_cert_verified = TRUE;
1382   DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
1383       state->peerdn ? state->peerdn : US"<unset>");
1384   }
1385
1386 state->tlsp->peerdn = state->peerdn;
1387
1388 return TRUE;
1389 }
1390
1391
1392
1393
1394 /* ------------------------------------------------------------------------ */
1395 /* Callbacks */
1396
1397 /* Logging function which can be registered with
1398  *   gnutls_global_set_log_function()
1399  *   gnutls_global_set_log_level() 0..9
1400  */
1401 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1402 static void
1403 exim_gnutls_logger_cb(int level, const char *message)
1404 {
1405   size_t len = strlen(message);
1406   if (len < 1)
1407     {
1408     DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1409     return;
1410     }
1411   DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1412       message[len-1] == '\n' ? "" : "\n");
1413 }
1414 #endif
1415
1416
1417 /* Called after client hello, should handle SNI work.
1418 This will always set tls_sni (state->received_sni) if available,
1419 and may trigger presenting different certificates,
1420 if state->trigger_sni_changes is TRUE.
1421
1422 Should be registered with
1423   gnutls_handshake_set_post_client_hello_function()
1424
1425 "This callback must return 0 on success or a gnutls error code to terminate the
1426 handshake.".
1427
1428 For inability to get SNI information, we return 0.
1429 We only return non-zero if re-setup failed.
1430 Only used for server-side TLS.
1431 */
1432
1433 static int
1434 exim_sni_handling_cb(gnutls_session_t session)
1435 {
1436 char sni_name[MAX_HOST_LEN];
1437 size_t data_len = MAX_HOST_LEN;
1438 exim_gnutls_state_st *state = &state_server;
1439 unsigned int sni_type;
1440 int rc, old_pool;
1441
1442 rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1443 if (rc != GNUTLS_E_SUCCESS)
1444   {
1445   DEBUG(D_tls) {
1446     if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1447       debug_printf("TLS: no SNI presented in handshake.\n");
1448     else
1449       debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1450         gnutls_strerror(rc), rc);
1451   };
1452   return 0;
1453   }
1454
1455 if (sni_type != GNUTLS_NAME_DNS)
1456   {
1457   DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1458   return 0;
1459   }
1460
1461 /* We now have a UTF-8 string in sni_name */
1462 old_pool = store_pool;
1463 store_pool = POOL_PERM;
1464 state->received_sni = string_copyn(US sni_name, data_len);
1465 store_pool = old_pool;
1466
1467 /* We set this one now so that variable expansions below will work */
1468 state->tlsp->sni = state->received_sni;
1469
1470 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1471     state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1472
1473 if (!state->trigger_sni_changes)
1474   return 0;
1475
1476 rc = tls_expand_session_files(state);
1477 if (rc != OK)
1478   {
1479   /* If the setup of certs/etc failed before handshake, TLS would not have
1480   been offered.  The best we can do now is abort. */
1481   return GNUTLS_E_APPLICATION_ERROR_MIN;
1482   }
1483
1484 rc = tls_set_remaining_x509(state);
1485 if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1486
1487 return 0;
1488 }
1489
1490
1491
1492 #ifndef DISABLE_OCSP
1493
1494 static int
1495 server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1496   gnutls_datum_t * ocsp_response)
1497 {
1498 int ret;
1499
1500 if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1501   {
1502   DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
1503                               (char *)ptr);
1504   tls_in.ocsp = OCSP_NOT_RESP;
1505   return GNUTLS_E_NO_CERTIFICATE_STATUS;
1506   }
1507
1508 tls_in.ocsp = OCSP_VFY_NOT_TRIED;
1509 return 0;
1510 }
1511
1512 #endif
1513
1514
1515
1516
1517
1518 /* ------------------------------------------------------------------------ */
1519 /* Exported functions */
1520
1521
1522
1523
1524 /*************************************************
1525 *       Start a TLS session in a server          *
1526 *************************************************/
1527
1528 /* This is called when Exim is running as a server, after having received
1529 the STARTTLS command. It must respond to that command, and then negotiate
1530 a TLS session.
1531
1532 Arguments:
1533   require_ciphers  list of allowed ciphers or NULL
1534
1535 Returns:           OK on success
1536                    DEFER for errors before the start of the negotiation
1537                    FAIL for errors during the negotation; the server can't
1538                      continue running.
1539 */
1540
1541 int
1542 tls_server_start(const uschar *require_ciphers)
1543 {
1544 int rc;
1545 const char *error;
1546 exim_gnutls_state_st *state = NULL;
1547
1548 /* Check for previous activation */
1549 if (tls_in.active >= 0)
1550   {
1551   tls_error(US"STARTTLS received after TLS started", "", NULL);
1552   smtp_printf("554 Already in TLS\r\n");
1553   return FAIL;
1554   }
1555
1556 /* Initialize the library. If it fails, it will already have logged the error
1557 and sent an SMTP response. */
1558
1559 DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
1560
1561 rc = tls_init(NULL, tls_certificate, tls_privatekey,
1562     NULL, tls_verify_certificates, tls_crl,
1563     require_ciphers, &state);
1564 if (rc != OK) return rc;
1565
1566 /* If this is a host for which certificate verification is mandatory or
1567 optional, set up appropriately. */
1568
1569 if (verify_check_host(&tls_verify_hosts) == OK)
1570   {
1571   DEBUG(D_tls)
1572     debug_printf("TLS: a client certificate will be required.\n");
1573   state->verify_requirement = VERIFY_REQUIRED;
1574   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1575   }
1576 else if (verify_check_host(&tls_try_verify_hosts) == OK)
1577   {
1578   DEBUG(D_tls)
1579     debug_printf("TLS: a client certificate will be requested but not required.\n");
1580   state->verify_requirement = VERIFY_OPTIONAL;
1581   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1582   }
1583 else
1584   {
1585   DEBUG(D_tls)
1586     debug_printf("TLS: a client certificate will not be requested.\n");
1587   state->verify_requirement = VERIFY_NONE;
1588   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1589   }
1590
1591 /* Register SNI handling; always, even if not in tls_certificate, so that the
1592 expansion variable $tls_sni is always available. */
1593
1594 gnutls_handshake_set_post_client_hello_function(state->session,
1595     exim_sni_handling_cb);
1596
1597 /* Set context and tell client to go ahead, except in the case of TLS startup
1598 on connection, where outputting anything now upsets the clients and tends to
1599 make them disconnect. We need to have an explicit fflush() here, to force out
1600 the response. Other smtp_printf() calls do not need it, because in non-TLS
1601 mode, the fflush() happens when smtp_getc() is called. */
1602
1603 if (!state->tlsp->on_connect)
1604   {
1605   smtp_printf("220 TLS go ahead\r\n");
1606   fflush(smtp_out);
1607   }
1608
1609 /* Now negotiate the TLS session. We put our own timer on it, since it seems
1610 that the GnuTLS library doesn't. */
1611
1612 gnutls_transport_set_ptr2(state->session,
1613     (gnutls_transport_ptr)(long) fileno(smtp_in),
1614     (gnutls_transport_ptr)(long) fileno(smtp_out));
1615 state->fd_in = fileno(smtp_in);
1616 state->fd_out = fileno(smtp_out);
1617
1618 sigalrm_seen = FALSE;
1619 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1620 do
1621   {
1622   rc = gnutls_handshake(state->session);
1623   } while ((rc == GNUTLS_E_AGAIN) ||
1624       (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
1625 alarm(0);
1626
1627 if (rc != GNUTLS_E_SUCCESS)
1628   {
1629   tls_error(US"gnutls_handshake",
1630       sigalrm_seen ? "timed out" : gnutls_strerror(rc), NULL);
1631   /* It seems that, except in the case of a timeout, we have to close the
1632   connection right here; otherwise if the other end is running OpenSSL it hangs
1633   until the server times out. */
1634
1635   if (!sigalrm_seen)
1636     {
1637     (void)fclose(smtp_out);
1638     (void)fclose(smtp_in);
1639     }
1640
1641   return FAIL;
1642   }
1643
1644 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1645
1646 /* Verify after the fact */
1647
1648 if (  state->verify_requirement != VERIFY_NONE
1649    && !verify_certificate(state, &error))
1650   {
1651   if (state->verify_requirement != VERIFY_OPTIONAL)
1652     {
1653     tls_error(US"certificate verification failed", error, NULL);
1654     return FAIL;
1655     }
1656   DEBUG(D_tls)
1657     debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
1658         error);
1659   }
1660
1661 /* Figure out peer DN, and if authenticated, etc. */
1662
1663 rc = peer_status(state);
1664 if (rc != OK) return rc;
1665
1666 /* Sets various Exim expansion variables; always safe within server */
1667
1668 extract_exim_vars_from_tls_state(state);
1669
1670 /* TLS has been set up. Adjust the input functions to read via TLS,
1671 and initialize appropriately. */
1672
1673 state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
1674
1675 receive_getc = tls_getc;
1676 receive_ungetc = tls_ungetc;
1677 receive_feof = tls_feof;
1678 receive_ferror = tls_ferror;
1679 receive_smtp_buffered = tls_smtp_buffered;
1680
1681 return OK;
1682 }
1683
1684
1685
1686
1687 /*************************************************
1688 *    Start a TLS session in a client             *
1689 *************************************************/
1690
1691 /* Called from the smtp transport after STARTTLS has been accepted.
1692
1693 Arguments:
1694   fd                the fd of the connection
1695   host              connected host (for messages)
1696   addr              the first address (not used)
1697   ob                smtp transport options
1698
1699 Returns:            OK/DEFER/FAIL (because using common functions),
1700                     but for a client, DEFER and FAIL have the same meaning
1701 */
1702
1703 int
1704 tls_client_start(int fd, host_item *host,
1705     address_item *addr ARG_UNUSED,
1706     void *v_ob)
1707 {
1708 smtp_transport_options_block *ob = v_ob;
1709 int rc;
1710 const char *error;
1711 exim_gnutls_state_st *state = NULL;
1712 #ifndef DISABLE_OCSP
1713 BOOL require_ocsp = verify_check_this_host(&ob->hosts_require_ocsp,
1714   NULL, host->name, host->address, NULL) == OK;
1715 BOOL request_ocsp = require_ocsp ? TRUE
1716   : verify_check_this_host(&ob->hosts_request_ocsp,
1717       NULL, host->name, host->address, NULL) == OK;
1718 #endif
1719
1720 DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
1721
1722 if ((rc = tls_init(host, ob->tls_certificate, ob->tls_privatekey,
1723     ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
1724     ob->tls_require_ciphers, &state)) != OK)
1725   return rc;
1726
1727   {
1728   int dh_min_bits = ob->tls_dh_min_bits;
1729   if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
1730     {
1731     DEBUG(D_tls)
1732       debug_printf("WARNING: tls_dh_min_bits far too low,"
1733                     " clamping %d up to %d\n",
1734           dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
1735     dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
1736     }
1737
1738   DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
1739                     " acceptable bits to %d\n",
1740       dh_min_bits);
1741   gnutls_dh_set_prime_bits(state->session, dh_min_bits);
1742   }
1743
1744 /* Stick to the old behaviour for compatibility if tls_verify_certificates is 
1745 set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
1746 the specified host patterns if one of them is defined */
1747
1748 if ((  state->exp_tls_verify_certificates
1749     && !ob->tls_verify_hosts
1750     && !ob->tls_try_verify_hosts
1751     )
1752     ||
1753     verify_check_host(&ob->tls_verify_hosts) == OK
1754    )
1755   {
1756 #ifdef EXPERIMENTAL_CERTNAMES
1757   if (ob->tls_verify_cert_hostnames)
1758     {
1759     DEBUG(D_tls)
1760       debug_printf("TLS: server cert incl. hostname verification required.\n");
1761     state->verify_requirement = VERIFY_WITHHOST;
1762     if (!expand_check(ob->tls_verify_cert_hostnames,
1763                       US"tls_verify_cert_hostnames",
1764                       &state->exp_tls_verify_cert_hostnames))
1765       return FAIL;
1766     if (state->exp_tls_verify_cert_hostnames)
1767       DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
1768                       state->exp_tls_verify_cert_hostnames);
1769     }
1770   else
1771 #endif
1772     {
1773     DEBUG(D_tls)
1774       debug_printf("TLS: server certificate verification required.\n");
1775     state->verify_requirement = VERIFY_REQUIRED;
1776     }
1777   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1778   }
1779 else if (verify_check_host(&ob->tls_try_verify_hosts) == OK)
1780   {
1781   DEBUG(D_tls)
1782     debug_printf("TLS: server certificate verification optional.\n");
1783   state->verify_requirement = VERIFY_OPTIONAL;
1784   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1785   }
1786 else
1787   {
1788   DEBUG(D_tls)
1789     debug_printf("TLS: server certificate verification not required.\n");
1790   state->verify_requirement = VERIFY_NONE;
1791   gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1792   }
1793
1794 #ifndef DISABLE_OCSP
1795                         /* supported since GnuTLS 3.1.3 */
1796 if (request_ocsp)
1797   {
1798   DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
1799   if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
1800                     NULL, 0, NULL)) != OK)
1801     return tls_error(US"cert-status-req",
1802                     gnutls_strerror(rc), state->host);
1803   tls_out.ocsp = OCSP_NOT_RESP;
1804   }
1805 #endif
1806
1807 gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr)(long) fd);
1808 state->fd_in = fd;
1809 state->fd_out = fd;
1810
1811 DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
1812 /* There doesn't seem to be a built-in timeout on connection. */
1813
1814 sigalrm_seen = FALSE;
1815 alarm(ob->command_timeout);
1816 do
1817   {
1818   rc = gnutls_handshake(state->session);
1819   } while ((rc == GNUTLS_E_AGAIN) ||
1820       (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
1821 alarm(0);
1822
1823 if (rc != GNUTLS_E_SUCCESS)
1824   return tls_error(US"gnutls_handshake",
1825       sigalrm_seen ? "timed out" : gnutls_strerror(rc), state->host);
1826
1827 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1828
1829 /* Verify late */
1830
1831 if (state->verify_requirement != VERIFY_NONE &&
1832     !verify_certificate(state, &error))
1833   return tls_error(US"certificate verification failed", error, state->host);
1834
1835 #ifndef DISABLE_OCSP
1836 if (require_ocsp)
1837   {
1838   DEBUG(D_tls)
1839     {
1840     gnutls_datum_t stapling;
1841     gnutls_ocsp_resp_t resp;
1842     gnutls_datum_t printed;
1843     if (  (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
1844        && (rc= gnutls_ocsp_resp_init(&resp)) == 0
1845        && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
1846        && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
1847        )
1848       {
1849       debug_printf("%.4096s", printed.data);
1850       gnutls_free(printed.data);
1851       }
1852     else
1853       (void) tls_error(US"ocsp decode", gnutls_strerror(rc), state->host);
1854     }
1855
1856   if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
1857     {
1858     tls_out.ocsp = OCSP_FAILED;
1859     return tls_error(US"certificate status check failed", NULL, state->host);
1860     }
1861   DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
1862   tls_out.ocsp = OCSP_VFIED;
1863   }
1864 #endif
1865
1866 /* Figure out peer DN, and if authenticated, etc. */
1867
1868 if ((rc = peer_status(state)) != OK)
1869   return rc;
1870
1871 /* Sets various Exim expansion variables; may need to adjust for ACL callouts */
1872
1873 extract_exim_vars_from_tls_state(state);
1874
1875 return OK;
1876 }
1877
1878
1879
1880
1881 /*************************************************
1882 *         Close down a TLS session               *
1883 *************************************************/
1884
1885 /* This is also called from within a delivery subprocess forked from the
1886 daemon, to shut down the TLS library, without actually doing a shutdown (which
1887 would tamper with the TLS session in the parent process).
1888
1889 Arguments:   TRUE if gnutls_bye is to be called
1890 Returns:     nothing
1891 */
1892
1893 void
1894 tls_close(BOOL is_server, BOOL shutdown)
1895 {
1896 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
1897
1898 if (!state->tlsp || state->tlsp->active < 0) return;  /* TLS was not active */
1899
1900 if (shutdown)
1901   {
1902   DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
1903   gnutls_bye(state->session, GNUTLS_SHUT_WR);
1904   }
1905
1906 gnutls_deinit(state->session);
1907
1908 state->tlsp->active = -1;
1909 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1910
1911 if ((state_server.session == NULL) && (state_client.session == NULL))
1912   {
1913   gnutls_global_deinit();
1914   exim_gnutls_base_init_done = FALSE;
1915   }
1916
1917 }
1918
1919
1920
1921
1922 /*************************************************
1923 *            TLS version of getc                 *
1924 *************************************************/
1925
1926 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
1927 it refills the buffer via the GnuTLS reading function.
1928 Only used by the server-side TLS.
1929
1930 This feeds DKIM and should be used for all message-body reads.
1931
1932 Arguments:  none
1933 Returns:    the next character or EOF
1934 */
1935
1936 int
1937 tls_getc(void)
1938 {
1939 exim_gnutls_state_st *state = &state_server;
1940 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
1941   {
1942   ssize_t inbytes;
1943
1944   DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
1945     state->session, state->xfer_buffer, ssl_xfer_buffer_size);
1946
1947   if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1948   inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
1949     ssl_xfer_buffer_size);
1950   alarm(0);
1951
1952   /* A zero-byte return appears to mean that the TLS session has been
1953      closed down, not that the socket itself has been closed down. Revert to
1954      non-TLS handling. */
1955
1956   if (inbytes == 0)
1957     {
1958     DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1959
1960     receive_getc = smtp_getc;
1961     receive_ungetc = smtp_ungetc;
1962     receive_feof = smtp_feof;
1963     receive_ferror = smtp_ferror;
1964     receive_smtp_buffered = smtp_buffered;
1965
1966     gnutls_deinit(state->session);
1967     state->session = NULL;
1968     state->tlsp->active = -1;
1969     state->tlsp->bits = 0;
1970     state->tlsp->certificate_verified = FALSE;
1971     tls_channelbinding_b64 = NULL;
1972     state->tlsp->cipher = NULL;
1973     state->tlsp->peercert = NULL;
1974     state->tlsp->peerdn = NULL;
1975
1976     return smtp_getc();
1977     }
1978
1979   /* Handle genuine errors */
1980
1981   else if (inbytes < 0)
1982     {
1983     record_io_error(state, (int) inbytes, US"recv", NULL);
1984     state->xfer_error = 1;
1985     return EOF;
1986     }
1987 #ifndef DISABLE_DKIM
1988   dkim_exim_verify_feed(state->xfer_buffer, inbytes);
1989 #endif
1990   state->xfer_buffer_hwm = (int) inbytes;
1991   state->xfer_buffer_lwm = 0;
1992   }
1993
1994 /* Something in the buffer; return next uschar */
1995
1996 return state->xfer_buffer[state->xfer_buffer_lwm++];
1997 }
1998
1999
2000
2001
2002 /*************************************************
2003 *          Read bytes from TLS channel           *
2004 *************************************************/
2005
2006 /* This does not feed DKIM, so if the caller uses this for reading message body,
2007 then the caller must feed DKIM.
2008
2009 Arguments:
2010   buff      buffer of data
2011   len       size of buffer
2012
2013 Returns:    the number of bytes read
2014             -1 after a failed read
2015 */
2016
2017 int
2018 tls_read(BOOL is_server, uschar *buff, size_t len)
2019 {
2020 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2021 ssize_t inbytes;
2022
2023 if (len > INT_MAX)
2024   len = INT_MAX;
2025
2026 if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
2027   DEBUG(D_tls)
2028     debug_printf("*** PROBABLY A BUG *** " \
2029         "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
2030         state->xfer_buffer_hwm - state->xfer_buffer_lwm);
2031
2032 DEBUG(D_tls)
2033   debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
2034       state->session, buff, len);
2035
2036 inbytes = gnutls_record_recv(state->session, buff, len);
2037 if (inbytes > 0) return inbytes;
2038 if (inbytes == 0)
2039   {
2040   DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2041   }
2042 else record_io_error(state, (int)inbytes, US"recv", NULL);
2043
2044 return -1;
2045 }
2046
2047
2048
2049
2050 /*************************************************
2051 *         Write bytes down TLS channel           *
2052 *************************************************/
2053
2054 /*
2055 Arguments:
2056   is_server channel specifier
2057   buff      buffer of data
2058   len       number of bytes
2059
2060 Returns:    the number of bytes after a successful write,
2061             -1 after a failed write
2062 */
2063
2064 int
2065 tls_write(BOOL is_server, const uschar *buff, size_t len)
2066 {
2067 ssize_t outbytes;
2068 size_t left = len;
2069 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2070
2071 DEBUG(D_tls) debug_printf("tls_do_write(%p, " SIZE_T_FMT ")\n", buff, left);
2072 while (left > 0)
2073   {
2074   DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
2075       buff, left);
2076   outbytes = gnutls_record_send(state->session, buff, left);
2077
2078   DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
2079   if (outbytes < 0)
2080     {
2081     record_io_error(state, outbytes, US"send", NULL);
2082     return -1;
2083     }
2084   if (outbytes == 0)
2085     {
2086     record_io_error(state, 0, US"send", US"TLS channel closed on write");
2087     return -1;
2088     }
2089
2090   left -= outbytes;
2091   buff += outbytes;
2092   }
2093
2094 if (len > INT_MAX)
2095   {
2096   DEBUG(D_tls)
2097     debug_printf("Whoops!  Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
2098         len);
2099   len = INT_MAX;
2100   }
2101
2102 return (int) len;
2103 }
2104
2105
2106
2107
2108 /*************************************************
2109 *            Random number generation            *
2110 *************************************************/
2111
2112 /* Pseudo-random number generation.  The result is not expected to be
2113 cryptographically strong but not so weak that someone will shoot themselves
2114 in the foot using it as a nonce in input in some email header scheme or
2115 whatever weirdness they'll twist this into.  The result should handle fork()
2116 and avoid repeating sequences.  OpenSSL handles that for us.
2117
2118 Arguments:
2119   max       range maximum
2120 Returns     a random number in range [0, max-1]
2121 */
2122
2123 #ifdef HAVE_GNUTLS_RND
2124 int
2125 vaguely_random_number(int max)
2126 {
2127 unsigned int r;
2128 int i, needed_len;
2129 uschar *p;
2130 uschar smallbuf[sizeof(r)];
2131
2132 if (max <= 1)
2133   return 0;
2134
2135 needed_len = sizeof(r);
2136 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
2137  * asked for a number less than 10. */
2138 for (r = max, i = 0; r; ++i)
2139   r >>= 1;
2140 i = (i + 7) / 8;
2141 if (i < needed_len)
2142   needed_len = i;
2143
2144 i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2145 if (i < 0)
2146   {
2147   DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2148   return vaguely_random_number_fallback(max);
2149   }
2150 r = 0;
2151 for (p = smallbuf; needed_len; --needed_len, ++p)
2152   {
2153   r *= 256;
2154   r += *p;
2155   }
2156
2157 /* We don't particularly care about weighted results; if someone wants
2158  * smooth distribution and cares enough then they should submit a patch then. */
2159 return r % max;
2160 }
2161 #else /* HAVE_GNUTLS_RND */
2162 int
2163 vaguely_random_number(int max)
2164 {
2165   return vaguely_random_number_fallback(max);
2166 }
2167 #endif /* HAVE_GNUTLS_RND */
2168
2169
2170
2171
2172 /*************************************************
2173 *  Let tls_require_ciphers be checked at startup *
2174 *************************************************/
2175
2176 /* The tls_require_ciphers option, if set, must be something which the
2177 library can parse.
2178
2179 Returns:     NULL on success, or error message
2180 */
2181
2182 uschar *
2183 tls_validate_require_cipher(void)
2184 {
2185 int rc;
2186 uschar *expciphers = NULL;
2187 gnutls_priority_t priority_cache;
2188 const char *errpos;
2189
2190 #define validate_check_rc(Label) do { \
2191   if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
2192   return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
2193 #define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
2194
2195 if (exim_gnutls_base_init_done)
2196   log_write(0, LOG_MAIN|LOG_PANIC,
2197       "already initialised GnuTLS, Exim developer bug");
2198
2199 #ifdef HAVE_GNUTLS_PKCS11
2200 if (!gnutls_allow_auto_pkcs11)
2201   {
2202   rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
2203   validate_check_rc(US"gnutls_pkcs11_init");
2204   }
2205 #endif
2206 rc = gnutls_global_init();
2207 validate_check_rc(US"gnutls_global_init()");
2208 exim_gnutls_base_init_done = TRUE;
2209
2210 if (!(tls_require_ciphers && *tls_require_ciphers))
2211   return_deinit(NULL);
2212
2213 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers))
2214   return_deinit(US"failed to expand tls_require_ciphers");
2215
2216 if (!(expciphers && *expciphers))
2217   return_deinit(NULL);
2218
2219 DEBUG(D_tls)
2220   debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2221
2222 rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
2223 validate_check_rc(string_sprintf(
2224       "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
2225       expciphers, errpos - CS expciphers, errpos));
2226
2227 #undef return_deinit
2228 #undef validate_check_rc
2229 gnutls_global_deinit();
2230
2231 return NULL;
2232 }
2233
2234
2235
2236
2237 /*************************************************
2238 *         Report the library versions.           *
2239 *************************************************/
2240
2241 /* See a description in tls-openssl.c for an explanation of why this exists.
2242
2243 Arguments:   a FILE* to print the results to
2244 Returns:     nothing
2245 */
2246
2247 void
2248 tls_version_report(FILE *f)
2249 {
2250 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
2251            "                         Runtime: %s\n",
2252            LIBGNUTLS_VERSION,
2253            gnutls_check_version(NULL));
2254 }
2255
2256 /* vi: aw ai sw=2
2257 */
2258 /* End of tls-gnu.c */