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