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