Compiler quietening. Bug 907
[exim.git] / src / src / tls-gnu.c
CommitLineData
059ec3d9
PH
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
5a66c31b 5/* Copyright (c) University of Cambridge 1995 - 2014 */
059ec3d9
PH
6/* See the file NOTICE for conditions of use and distribution. */
7
17c76198 8/* Copyright (c) Phil Pennock 2012 */
059ec3d9 9
17c76198
PP
10/* This file provides TLS/SSL support for Exim using the GnuTLS library,
11one of the available supported implementations. This file is #included into
12tls.c when USE_GNUTLS has been set.
059ec3d9 13
17c76198
PP
14The code herein is a revamp of GnuTLS integration using the current APIs; the
15original tls-gnu.c was based on a patch which was contributed by Nikos
16Mavroyanopoulos. The revamp is partially a rewrite, partially cut&paste as
17appropriate.
059ec3d9 18
17c76198
PP
19APIs current as of GnuTLS 2.12.18; note that the GnuTLS manual is for GnuTLS 3,
20which is not widely deployed by OS vendors. Will note issues below, which may
21assist in updating the code in the future. Another sources of hints is
22mod_gnutls for Apache (SNI callback registration and handling).
059ec3d9 23
17c76198
PP
24Keeping client and server variables more split than before and is currently
25the norm, in anticipation of TLS in ACL callouts.
059ec3d9 26
17c76198
PP
27I wanted to switch to gnutls_certificate_set_verify_function() so that
28certificate rejection could happen during handshake where it belongs, rather
29than 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.
059ec3d9 31
17c76198
PP
32(I wasn't looking for libraries quite that old, when updating to get rid of
33compiler warnings of deprecated APIs. If it turns out that a lot of the rest
34require current GnuTLS, then we'll drop support for the ancient libraries).
35*/
b5aea5e1 36
17c76198
PP
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>
a5f239e4
PP
42/* needed to disable PKCS11 autoload unless requested */
43#if GNUTLS_VERSION_NUMBER >= 0x020c00
44# include <gnutls/pkcs11.h>
45#endif
2b4a568d
JH
46#ifdef EXPERIMENTAL_OCSP
47# include <gnutls/ocsp.h>
48#endif
059ec3d9 49
17c76198 50/* GnuTLS 2 vs 3
059ec3d9 51
17c76198
PP
52GnuTLS 3 only:
53 gnutls_global_set_audit_log_function()
059ec3d9 54
17c76198
PP
55Changes:
56 gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
57*/
059ec3d9 58
17c76198 59/* Local static variables for GnuTLS */
059ec3d9 60
17c76198 61/* Values for verify_requirement */
059ec3d9 62
e51c7be2
JH
63enum peer_verify_requirement
64 { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED
65#ifdef EXPERIMENTAL_CERTNAMES
66 ,VERIFY_WITHHOST
67#endif
68 };
059ec3d9 69
17c76198
PP
70/* This holds most state for server or client; with this, we can set up an
71outbound TLS-enabled connection in an ACL callout, while not stomping all
72over the TLS variables available for expansion.
059ec3d9 73
17c76198
PP
74Some of these correspond to variables in globals.c; those variables will
75be set to point to content in one of these instances, as appropriate for
76the stage of the process lifetime.
059ec3d9 77
389ca47a 78Not handled here: global tls_channelbinding_b64.
17c76198 79*/
059ec3d9 80
17c76198 81typedef struct exim_gnutls_state {
9d1c15ef 82 gnutls_session_t session;
17c76198 83 gnutls_certificate_credentials_t x509_cred;
9d1c15ef 84 gnutls_priority_t priority_cache;
17c76198 85 enum peer_verify_requirement verify_requirement;
9d1c15ef
JH
86 int fd_in;
87 int fd_out;
88 BOOL peer_cert_verified;
89 BOOL trigger_sni_changes;
90 BOOL have_set_peerdn;
17c76198 91 const struct host_item *host;
9d1c15ef
JH
92 gnutls_x509_crt_t peercert;
93 uschar *peerdn;
94 uschar *ciphersuite;
95 uschar *received_sni;
17c76198
PP
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;
e51c7be2 103
17c76198
PP
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;
44662487 110 uschar *exp_tls_ocsp_file;
e51c7be2
JH
111#ifdef EXPERIMENTAL_CERTNAMES
112 uschar *exp_tls_verify_cert_hostnames;
113#endif
17c76198 114
389ca47a 115 tls_support *tlsp; /* set in tls_init() */
817d9f57 116
17c76198
PP
117 uschar *xfer_buffer;
118 int xfer_buffer_lwm;
119 int xfer_buffer_hwm;
120 int xfer_eof;
121 int xfer_error;
17c76198
PP
122} exim_gnutls_state_st;
123
124static const exim_gnutls_state_st exim_gnutls_state_init = {
4fe99a6c 125 NULL, NULL, NULL, VERIFY_NONE, -1, -1, FALSE, FALSE, FALSE,
75fe387d 126 NULL, NULL, NULL, NULL,
17c76198 127 NULL, NULL, NULL, NULL, NULL, NULL,
44662487 128 NULL, NULL, NULL, NULL, NULL, NULL, NULL,
e51c7be2
JH
129#ifdef EXPERIMENTAL_CERTNAMES
130 NULL,
131#endif
817d9f57 132 NULL,
17c76198 133 NULL, 0, 0, 0, 0,
17c76198 134};
83da1223 135
17c76198
PP
136/* Not only do we have our own APIs which don't pass around state, assuming
137it's held in globals, GnuTLS doesn't appear to let us register callback data
138for callbacks, or as part of the session, so we have to keep a "this is the
139context we're currently dealing with" pointer and rely upon being
140single-threaded to keep from processing data on an inbound TLS connection while
141talking to another TLS connection for an outbound check. This does mean that
142there's no way for heart-beats to be responded to, for the duration of the
143second connection. */
059ec3d9 144
17c76198 145static exim_gnutls_state_st state_server, state_client;
059ec3d9 146
17c76198
PP
147/* dh_params are initialised once within the lifetime of a process using TLS;
148if we used TLS in a long-lived daemon, we'd have to reconsider this. But we
149don't want to repeat this. */
83da1223 150
17c76198 151static gnutls_dh_params_t dh_server_params = NULL;
059ec3d9 152
17c76198 153/* No idea how this value was chosen; preserving it. Default is 3600. */
059ec3d9 154
17c76198 155static const int ssl_session_timeout = 200;
059ec3d9 156
17c76198 157static const char * const exim_default_gnutls_priority = "NORMAL";
83da1223 158
17c76198 159/* Guard library core initialisation */
83da1223 160
17c76198 161static BOOL exim_gnutls_base_init_done = FALSE;
059ec3d9 162
059ec3d9 163
17c76198
PP
164/* ------------------------------------------------------------------------ */
165/* macros */
83da1223 166
17c76198 167#define MAX_HOST_LEN 255
83da1223 168
17c76198
PP
169/* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
170the library logging; a value less than 0 disables the calls to set up logging
171callbacks. */
2c17bb02 172#ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
17c76198 173#define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
2c17bb02 174#endif
83da1223 175
2c17bb02 176#ifndef EXIM_CLIENT_DH_MIN_BITS
bba74fc6 177#define EXIM_CLIENT_DH_MIN_BITS 1024
2c17bb02 178#endif
83da1223 179
af3498d6
PP
180/* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
181can ask for a bit-strength. Without that, we stick to the constant we had
182before, for now. */
2c17bb02 183#ifndef EXIM_SERVER_DH_BITS_PRE2_12
af3498d6 184#define EXIM_SERVER_DH_BITS_PRE2_12 1024
2c17bb02 185#endif
af3498d6 186
17c76198
PP
187#define exim_gnutls_err_check(Label) do { \
188 if (rc != GNUTLS_E_SUCCESS) { return tls_error((Label), gnutls_strerror(rc), host); } } while (0)
059ec3d9 189
17c76198 190#define expand_check_tlsvar(Varname) expand_check(state->Varname, US #Varname, &state->exp_##Varname)
83da1223 191
17c76198 192#if GNUTLS_VERSION_NUMBER >= 0x020c00
e51c7be2
JH
193# define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
194# define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
195# define HAVE_GNUTLS_RND
2519e60d
TL
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 */
e51c7be2
JH
202# ifndef AVOID_GNUTLS_PKCS11
203# define HAVE_GNUTLS_PKCS11
204# endif /* AVOID_GNUTLS_PKCS11 */
17c76198 205#endif
83da1223 206
af3498d6
PP
207
208
209
210/* ------------------------------------------------------------------------ */
211/* Callback declarations */
212
213#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
214static void exim_gnutls_logger_cb(int level, const char *message);
215#endif
216
217static int exim_sni_handling_cb(gnutls_session_t session);
218
44662487
JH
219#ifdef EXPERIMENTAL_OCSP
220static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
221 gnutls_datum_t * ocsp_response);
222#endif
af3498d6
PP
223
224
225
17c76198
PP
226/* ------------------------------------------------------------------------ */
227/* Static functions */
059ec3d9
PH
228
229/*************************************************
230* Handle TLS error *
231*************************************************/
232
233/* Called from lots of places when errors occur before actually starting to do
234the TLS handshake, that is, while the session is still in clear. Always returns
235DEFER for a server and FAIL for a client so that most calls can use "return
236tls_error(...)" to do this processing and then give an appropriate return. A
237single function is used for both server and client, because it is called from
238some shared functions.
239
240Argument:
241 prefix text to include in the logged error
7199e1ee
TF
242 msg additional error string (may be NULL)
243 usually obtained from gnutls_strerror()
17c76198
PP
244 host NULL if setting up a server;
245 the connected host if setting up a client
059ec3d9
PH
246
247Returns: OK/DEFER/FAIL
248*/
249
250static int
17c76198 251tls_error(const uschar *prefix, const char *msg, const host_item *host)
059ec3d9 252{
17c76198
PP
253if (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 }
259else
059ec3d9 260 {
7199e1ee 261 uschar *conn_info = smtp_get_connection_info();
17c76198 262 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0)
7199e1ee
TF
263 conn_info += 5;
264 log_write(0, LOG_MAIN, "TLS error on %s (%s)%s%s",
17c76198 265 conn_info, prefix, msg ? ": " : "", msg ? msg : "");
059ec3d9
PH
266 return DEFER;
267 }
059ec3d9
PH
268}
269
270
271
17c76198 272
059ec3d9 273/*************************************************
17c76198 274* Deal with logging errors during I/O *
059ec3d9
PH
275*************************************************/
276
17c76198 277/* We have to get the identity of the peer from saved data.
059ec3d9 278
17c76198
PP
279Argument:
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
059ec3d9 284
17c76198 285Returns: nothing
059ec3d9
PH
286*/
287
17c76198
PP
288static void
289record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
059ec3d9 290{
17c76198 291const char *msg;
059ec3d9 292
17c76198
PP
293if (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)));
296else
297 msg = gnutls_strerror(rc);
059ec3d9 298
17c76198
PP
299tls_error(when, msg, state->host);
300}
059ec3d9 301
059ec3d9 302
059ec3d9 303
059ec3d9 304
17c76198
PP
305/*************************************************
306* Set various Exim expansion vars *
307*************************************************/
059ec3d9 308
e51c7be2
JH
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)
9d1c15ef
JH
319
320static int
321import_cert(const gnutls_datum * cert, gnutls_x509_crt_t * crtp)
322{
323int rc;
324
325rc = gnutls_x509_crt_init(crtp);
326exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
327
328rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
329exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
330
331return rc;
332}
333
334#undef exim_gnutls_cert_err
335
336
17c76198
PP
337/* We set various Exim global variables from the state, once a session has
338been established. With TLS callouts, may need to change this to stack
339variables, or just re-call it with the server state after client callout
340has finished.
059ec3d9 341
9d1c15ef 342Make sure anything set here is unset in tls_getc().
17c76198
PP
343
344Sets:
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
9d1c15ef 350 tls_peercert pointer to library internal
17c76198
PP
351 tls_peerdn a string
352 tls_sni a (UTF-8) string
9d1c15ef 353 tls_ourcert pointer to library internal
17c76198
PP
354
355Argument:
356 state the relevant exim_gnutls_state_st *
357*/
358
359static void
9d1c15ef 360extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
17c76198 361{
17c76198 362gnutls_cipher_algorithm_t cipher;
17c76198
PP
363#ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
364int old_pool;
365int rc;
366gnutls_datum_t channel;
367#endif
9d1c15ef 368tls_support * tlsp = state->tlsp;
17c76198 369
9d1c15ef 370tlsp->active = state->fd_out;
17c76198
PP
371
372cipher = gnutls_cipher_get(state->session);
373/* returns size in "bytes" */
9d1c15ef 374tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
17c76198 375
9d1c15ef 376tlsp->cipher = state->ciphersuite;
17c76198 377
817d9f57 378DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
17c76198 379
9d1c15ef 380tlsp->certificate_verified = state->peer_cert_verified;
059ec3d9 381
17c76198
PP
382/* note that tls_channelbinding_b64 is not saved to the spool file, since it's
383only available for use for authenticators while this TLS session is running. */
384
385tls_channelbinding_b64 = NULL;
386#ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
387channel.data = NULL;
388channel.size = 0;
389rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel);
390if (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
9d1c15ef
JH
401/* peercert is set in peer_status() */
402tlsp->peerdn = state->peerdn;
403tlsp->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 }
059ec3d9
PH
412}
413
414
415
17c76198 416
059ec3d9 417/*************************************************
575643cd 418* Setup up DH parameters *
059ec3d9
PH
419*************************************************/
420
575643cd 421/* Generating the D-H parameters may take a long time. They only need to
059ec3d9
PH
422be re-generated every so often, depending on security policy. What we do is to
423keep these parameters in a file in the spool directory. If the file does not
424exist, we generate them. This means that it is easy to cause a regeneration.
425
426The new file is written as a temporary file and renamed, so that an incomplete
427file is never present. If two processes both compute some new parameters, you
428waste a bit of effort, but it doesn't seem worth messing around with locking to
429prevent this.
430
059ec3d9
PH
431Returns: OK/DEFER/FAIL
432*/
433
434static int
17c76198 435init_server_dh(void)
059ec3d9 436{
17c76198
PP
437int fd, rc;
438unsigned int dh_bits;
b5aea5e1 439gnutls_datum m;
a799883d
PP
440uschar filename_buf[PATH_MAX];
441uschar *filename = NULL;
17c76198 442size_t sz;
a799883d
PP
443uschar *exp_tls_dhparam;
444BOOL use_file_in_spool = FALSE;
445BOOL use_fixed_file = FALSE;
17c76198 446host_item *host = NULL; /* dummy for macros */
059ec3d9 447
17c76198 448DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
059ec3d9 449
17c76198
PP
450rc = gnutls_dh_params_init(&dh_server_params);
451exim_gnutls_err_check(US"gnutls_dh_params_init");
059ec3d9 452
a799883d
PP
453m.data = NULL;
454m.size = 0;
455
456if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam))
457 return DEFER;
458
459if (!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 }
465else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
466 use_file_in_spool = TRUE;
467else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
468 {
469 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
470 return OK;
471 }
472else 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 }
479else
480 {
481 use_fixed_file = TRUE;
482 filename = exp_tls_dhparam;
483 }
484
485if (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
af3498d6
PP
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
17c76198
PP
495different filename and ensure we have sufficient bits. */
496dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
497if (!dh_bits)
498 return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL);
af3498d6 499DEBUG(D_tls)
b34fc30c 500 debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
af3498d6
PP
501 dh_bits);
502#else
503dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
504DEBUG(D_tls)
505 debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
506 dh_bits);
507#endif
059ec3d9 508
3375e053
PP
509/* Some clients have hard-coded limits. */
510if (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
a799883d
PP
518if (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 }
059ec3d9 525
b5aea5e1 526/* Open the cache file for reading and if successful, read it and set up the
575643cd 527parameters. */
059ec3d9
PH
528
529fd = Uopen(filename, O_RDONLY, 0);
b5aea5e1 530if (fd >= 0)
059ec3d9 531 {
b5aea5e1 532 struct stat statbuf;
17c76198
PP
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))
b5aea5e1
PH
543 {
544 (void)close(fd);
17c76198
PP
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);
b5aea5e1 554 }
059ec3d9 555
b5aea5e1
PH
556 m.size = statbuf.st_size;
557 m.data = malloc(m.size);
558 if (m.data == NULL)
17c76198
PP
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);
b5aea5e1 572
17c76198 573 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
b5aea5e1 574 free(m.data);
17c76198
PP
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);
b5aea5e1
PH
577 }
578
579/* If the file does not exist, fall through to compute new data and cache it.
580If there was any other opening error, it is serious. */
581
182ad5cf
PH
582else if (errno == ENOENT)
583 {
17c76198 584 rc = -1;
182ad5cf 585 DEBUG(D_tls)
17c76198 586 debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
182ad5cf
PH
587 }
588else
17c76198
PP
589 return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
590 NULL, NULL);
b5aea5e1
PH
591
592/* If ret < 0, either the cache file does not exist, or the data it contains
593is not useful. One particular case of this is when upgrading from an older
594release of Exim in which the data was stored in a different format. We don't
595try to be clever and support both formats; we just regenerate new data in this
596case. */
597
17c76198 598if (rc < 0)
b5aea5e1 599 {
17c76198 600 uschar *temp_fn;
201f5254 601 unsigned int dh_bits_gen = dh_bits;
059ec3d9 602
17c76198
PP
603 if ((PATH_MAX - Ustrlen(filename)) < 10)
604 return tls_error(US"Filename too long to generate replacement",
605 CS filename, NULL);
059ec3d9 606
17c76198
PP
607 temp_fn = string_copy(US "%s.XXXXXXX");
608 fd = mkstemp(CS temp_fn); /* modifies temp_fn */
059ec3d9 609 if (fd < 0)
17c76198 610 return tls_error(US"Unable to open temp file", strerror(errno), NULL);
059ec3d9
PH
611 (void)fchown(fd, exim_uid, exim_gid); /* Probably not necessary */
612
201f5254
PP
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 */
cae6e576 621 if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
201f5254
PP
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);
17c76198
PP
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;
b5aea5e1
PH
646 m.data = malloc(m.size);
647 if (m.data == NULL)
17c76198 648 return tls_error(US"memory allocation failed", strerror(errno), NULL);
1f00591e 649 /* this will return a size 1 less than the allocation size above */
17c76198 650 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
1f00591e 651 m.data, &sz);
17c76198
PP
652 if (rc != GNUTLS_E_SUCCESS)
653 {
654 free(m.data);
655 exim_gnutls_err_check(US"gnutls_dh_params_export_pkcs3() real");
656 }
1f00591e 657 m.size = sz; /* shrink by 1, probably */
059ec3d9 658
17c76198
PP
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 }
b5aea5e1 666 free(m.data);
17c76198
PP
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);
059ec3d9 676
17c76198
PP
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);
059ec3d9 680
17c76198 681 DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
059ec3d9
PH
682 }
683
17c76198 684DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
059ec3d9
PH
685return OK;
686}
687
688
689
690
691/*************************************************
17c76198 692* Variables re-expanded post-SNI *
059ec3d9
PH
693*************************************************/
694
17c76198
PP
695/* Called from both server and client code, via tls_init(), and also from
696the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
697
698We can tell the two apart by state->received_sni being non-NULL in callback.
699
700The callback should not call us unless state->trigger_sni_changes is true,
701which we are responsible for setting on the first pass through.
059ec3d9
PH
702
703Arguments:
17c76198 704 state exim_gnutls_state_st *
059ec3d9
PH
705
706Returns: OK/DEFER/FAIL
707*/
708
709static int
17c76198 710tls_expand_session_files(exim_gnutls_state_st *state)
059ec3d9 711{
1365611d 712struct stat statbuf;
059ec3d9 713int rc;
17c76198
PP
714const host_item *host = state->host; /* macro should be reconsidered? */
715uschar *saved_tls_certificate = NULL;
716uschar *saved_tls_privatekey = NULL;
717uschar *saved_tls_verify_certificates = NULL;
718uschar *saved_tls_crl = NULL;
719int cert_count;
720
721/* We check for tls_sni *before* expansion. */
2b4a568d 722if (!host) /* server */
17c76198
PP
723 {
724 if (!state->received_sni)
725 {
d9b2312b
JH
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 ))
17c76198
PP
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 {
1365611d 738 /* useful for debugging */
17c76198
PP
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 }
059ec3d9 745
1365611d
PP
746rc = gnutls_certificate_allocate_credentials(&state->x509_cred);
747exim_gnutls_err_check(US"gnutls_certificate_allocate_credentials");
748
17c76198
PP
749/* remember: expand_check_tlsvar() is expand_check() but fiddling with
750state members, assuming consistent naming; and expand_check() returns
751false if expansion failed, unless expansion was forced to fail. */
059ec3d9 752
17c76198
PP
753/* check if we at least have a certificate, before doing expensive
754D-H generation. */
059ec3d9 755
17c76198
PP
756if (!expand_check_tlsvar(tls_certificate))
757 return DEFER;
059ec3d9 758
17c76198 759/* certificate is mandatory in server, optional in client */
059ec3d9 760
17c76198
PP
761if ((state->exp_tls_certificate == NULL) ||
762 (*state->exp_tls_certificate == '\0'))
763 {
2b4a568d 764 if (!host)
17c76198
PP
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 }
059ec3d9 769
17c76198 770if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey))
059ec3d9
PH
771 return DEFER;
772
17c76198
PP
773/* tls_privatekey is optional, defaulting to same file as certificate */
774
775if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
059ec3d9 776 {
17c76198
PP
777 state->tls_privatekey = state->tls_certificate;
778 state->exp_tls_privatekey = state->exp_tls_certificate;
059ec3d9 779 }
c91535f3 780
059ec3d9 781
17c76198 782if (state->exp_tls_certificate && *state->exp_tls_certificate)
059ec3d9
PH
783 {
784 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
17c76198
PP
785 state->exp_tls_certificate, state->exp_tls_privatekey);
786
787 if (state->received_sni)
de365ded 788 {
17c76198
PP
789 if ((Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0) &&
790 (Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0))
791 {
b34fc30c 792 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
17c76198
PP
793 }
794 else
795 {
b34fc30c 796 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
17c76198 797 }
8e669ac1 798 }
059ec3d9 799
1365611d
PP
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");
b34fc30c 807 } /* tls_certificate */
059ec3d9 808
2b4a568d
JH
809
810/* Set the OCSP stapling server info */
811
812#ifdef EXPERIMENTAL_OCSP
813if ( !host /* server */
814 && tls_ocsp_file
815 )
816 {
44662487
JH
817 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file",
818 &state->exp_tls_ocsp_file))
2b4a568d
JH
819 return DEFER;
820
44662487
JH
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);
2b4a568d 827
44662487 828 DEBUG(D_tls) debug_printf("Set OCSP response file %s\n", &state->exp_tls_ocsp_file);
2b4a568d
JH
829 }
830#endif
831
832
059ec3d9
PH
833/* Set the trusted CAs file if one is provided, and then add the CRL if one is
834provided. Experiment shows that, if the certificate file is empty, an unhelpful
835error message is provided. However, if we just refrain from setting anything up
836in that case, certificate verification fails, which seems to be the correct
837behaviour. */
838
17c76198 839if (state->tls_verify_certificates && *state->tls_verify_certificates)
059ec3d9 840 {
17c76198 841 if (!expand_check_tlsvar(tls_verify_certificates))
059ec3d9 842 return DEFER;
17c76198
PP
843 if (state->tls_crl && *state->tls_crl)
844 if (!expand_check_tlsvar(tls_crl))
845 return DEFER;
059ec3d9 846
1365611d
PP
847 if (!(state->exp_tls_verify_certificates &&
848 *state->exp_tls_verify_certificates))
b34fc30c
PP
849 {
850 DEBUG(D_tls)
1365611d
PP
851 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
852 /* With no tls_verify_certificates, we ignore tls_crl too */
17c76198 853 return OK;
b34fc30c 854 }
1365611d 855 }
83e2f8a2
PP
856else
857 {
858 DEBUG(D_tls)
859 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
860 return OK;
861 }
17c76198 862
1365611d
PP
863if (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 }
17c76198 870
619b2b25
PP
871/* The test suite passes in /dev/null; we could check for that path explicitly,
872but who knows if someone has some weird FIFO which always dumps some certs, or
873other weirdness. The thing we really want to check is that it's not a
874directory, since while OpenSSL supports that, GnuTLS does not.
875So s/!S_ISREG/S_ISDIR/ and change some messsaging ... */
876if (S_ISDIR(statbuf.st_mode))
1365611d
PP
877 {
878 DEBUG(D_tls)
619b2b25
PP
879 debug_printf("verify certificates path is a dir: \"%s\"\n",
880 state->exp_tls_verify_certificates);
1365611d 881 log_write(0, LOG_MAIN|LOG_PANIC,
619b2b25 882 "tls_verify_certificates \"%s\" is a directory",
1365611d
PP
883 state->exp_tls_verify_certificates);
884 return DEFER;
885 }
059ec3d9 886
1365611d
PP
887DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
888 state->exp_tls_verify_certificates, statbuf.st_size);
059ec3d9 889
1365611d
PP
890if (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 }
059ec3d9 896
1365611d
PP
897cert_count = gnutls_certificate_set_x509_trust_file(state->x509_cred,
898 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
899if (cert_count < 0)
900 {
901 rc = cert_count;
902 exim_gnutls_err_check(US"gnutls_certificate_set_x509_trust_file");
903 }
904DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n", cert_count);
059ec3d9 905
5c8cda3a
PP
906if (state->tls_crl && *state->tls_crl &&
907 state->exp_tls_crl && *state->exp_tls_crl)
1365611d 908 {
5c8cda3a
PP
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)
1365611d 913 {
5c8cda3a 914 rc = cert_count;
1365611d
PP
915 exim_gnutls_err_check(US"gnutls_certificate_set_x509_crl_file");
916 }
5c8cda3a 917 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
1365611d 918 }
059ec3d9 919
059ec3d9
PH
920return OK;
921}
922
923
924
925
1365611d
PP
926/*************************************************
927* Set X.509 state variables *
928*************************************************/
929
930/* In GnuTLS, the registered cert/key are not replaced by a later
931set of a cert/key, so for SNI support we need a whole new x509_cred
932structure. Which means various other non-re-expanded pieces of state
933need to be re-set in the new struct, so the setting logic is pulled
934out to this.
935
936Arguments:
937 state exim_gnutls_state_st *
938
939Returns: OK/DEFER/FAIL
940*/
941
942static int
943tls_set_remaining_x509(exim_gnutls_state_st *state)
944{
945int rc;
946const 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
949its own SMTP error messaging. This only happens for the server, TLS D-H ignores
950client-side params. */
951
952if (!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
964rc = gnutls_credentials_set(state->session, GNUTLS_CRD_CERTIFICATE, state->x509_cred);
965exim_gnutls_err_check(US"gnutls_credentials_set");
966
967return OK;
968}
969
059ec3d9 970/*************************************************
17c76198 971* Initialize for GnuTLS *
059ec3d9
PH
972*************************************************/
973
17c76198
PP
974/* Called from both server and client code. In the case of a server, errors
975before actual TLS negotiation return DEFER.
059ec3d9
PH
976
977Arguments:
17c76198
PP
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
817d9f57 985 caller_state returned state-info structure
059ec3d9 986
17c76198 987Returns: OK/DEFER/FAIL
059ec3d9
PH
988*/
989
17c76198
PP
990static int
991tls_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)
059ec3d9 1000{
17c76198
PP
1001exim_gnutls_state_st *state;
1002int rc;
1003size_t sz;
1004const char *errpos;
1005uschar *p;
1006BOOL want_default_priorities;
1007
1008if (!exim_gnutls_base_init_done)
059ec3d9 1009 {
17c76198
PP
1010 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1011
a5f239e4
PP
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. */
2519e60d 1018 if (!gnutls_allow_auto_pkcs11)
a5f239e4
PP
1019 {
1020 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
1021 exim_gnutls_err_check(US"gnutls_pkcs11_init");
1022 }
1023#endif
1024
17c76198
PP
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)
059ec3d9 1030 {
17c76198
PP
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);
059ec3d9 1034 }
17c76198
PP
1035#endif
1036
1037 exim_gnutls_base_init_done = TRUE;
059ec3d9 1038 }
059ec3d9 1039
17c76198
PP
1040if (host)
1041 {
1042 state = &state_client;
1043 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
817d9f57 1044 state->tlsp = &tls_out;
17c76198
PP
1045 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1046 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1047 }
1048else
1049 {
1050 state = &state_server;
1051 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
817d9f57 1052 state->tlsp = &tls_in;
17c76198
PP
1053 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1054 rc = gnutls_init(&state->session, GNUTLS_SERVER);
1055 }
1056exim_gnutls_err_check(US"gnutls_init");
059ec3d9 1057
17c76198 1058state->host = host;
059ec3d9 1059
17c76198
PP
1060state->tls_certificate = certificate;
1061state->tls_privatekey = privatekey;
5779e6aa 1062state->tls_require_ciphers = require_ciphers;
17c76198
PP
1063state->tls_sni = sni;
1064state->tls_verify_certificates = cas;
1065state->tls_crl = crl;
059ec3d9 1066
17c76198
PP
1067/* This handles the variables that might get re-expanded after TLS SNI;
1068that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
059ec3d9 1069
17c76198
PP
1070DEBUG(D_tls)
1071 debug_printf("Expanding various TLS configuration options for session credentials.\n");
1072rc = tls_expand_session_files(state);
1073if (rc != OK) return rc;
059ec3d9 1074
1365611d
PP
1075/* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1076requires a new structure afterwards. */
83da1223 1077
1365611d
PP
1078rc = tls_set_remaining_x509(state);
1079if (rc != OK) return rc;
83da1223 1080
17c76198
PP
1081/* set SNI in client, only */
1082if (host)
1083 {
a5f239e4 1084 if (!expand_check(state->tlsp->sni, US"tls_out_sni", &state->exp_tls_sni))
17c76198
PP
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 }
1096else 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);
83da1223 1099
17c76198 1100/* This is the priority string support,
42bfef1e 1101http://www.gnutls.org/manual/html_node/Priority-Strings.html
17c76198
PP
1102and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1103This was backwards incompatible, but means Exim no longer needs to track
1104all algorithms and provide string forms for them. */
83da1223 1105
17c76198 1106want_default_priorities = TRUE;
83da1223 1107
17c76198 1108if (state->tls_require_ciphers && *state->tls_require_ciphers)
83da1223 1109 {
17c76198
PP
1110 if (!expand_check_tlsvar(tls_require_ciphers))
1111 return DEFER;
1112 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
83da1223 1113 {
17c76198
PP
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;
83da1223
PH
1121 }
1122 }
17c76198
PP
1123if (want_default_priorities)
1124 {
83e2f8a2
PP
1125 DEBUG(D_tls)
1126 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n",
1127 exim_default_gnutls_priority);
17c76198
PP
1128 rc = gnutls_priority_init(&state->priority_cache,
1129 exim_default_gnutls_priority, &errpos);
1130 p = US exim_default_gnutls_priority;
1131 }
83da1223 1132
17c76198
PP
1133exim_gnutls_err_check(string_sprintf(
1134 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1135 p, errpos - CS p, errpos));
1136
1137rc = gnutls_priority_set(state->session, state->priority_cache);
1138exim_gnutls_err_check(US"gnutls_priority_set");
1139
1140gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1141
1142/* Reduce security in favour of increased compatibility, if the admin
1143decides to make that trade-off. */
1144if (gnutls_compat_mode)
83da1223 1145 {
17c76198
PP
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
83da1223
PH
1152 }
1153
17c76198 1154*caller_state = state;
17c76198 1155return OK;
83da1223
PH
1156}
1157
1158
1159
059ec3d9 1160/*************************************************
17c76198 1161* Extract peer information *
059ec3d9
PH
1162*************************************************/
1163
17c76198 1164/* Called from both server and client code.
4fe99a6c
PP
1165Only this is allowed to set state->peerdn and state->have_set_peerdn
1166and we use that to detect double-calls.
059ec3d9 1167
75fe387d
PP
1168NOTE: the state blocks last while the TLS connection is up, which is fine
1169for logging in the server side, but for the client side, we log after teardown
1170in src/deliver.c. While the session is up, we can twist about states and
1171repoint tls_* globals, but those variables used for logging or other variable
1172expansion that happens _after_ delivery need to have a longer life-time.
1173
1174So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1175doing this more than once per generation of a state context. We set them in
1176the state context, and repoint tls_* to them. After the state goes away, the
1177tls_* copies of the pointers remain valid and client delivery logging is happy.
1178
1179tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1180don't apply.
1181
059ec3d9 1182Arguments:
17c76198 1183 state exim_gnutls_state_st *
059ec3d9 1184
17c76198 1185Returns: OK/DEFER/FAIL
059ec3d9
PH
1186*/
1187
17c76198
PP
1188static int
1189peer_status(exim_gnutls_state_st *state)
059ec3d9 1190{
75fe387d 1191uschar cipherbuf[256];
17c76198 1192const gnutls_datum *cert_list;
75fe387d 1193int old_pool, rc;
17c76198 1194unsigned int cert_list_size = 0;
4fe99a6c
PP
1195gnutls_protocol_t protocol;
1196gnutls_cipher_algorithm_t cipher;
1197gnutls_kx_algorithm_t kx;
1198gnutls_mac_algorithm_t mac;
17c76198
PP
1199gnutls_certificate_type_t ct;
1200gnutls_x509_crt_t crt;
4fe99a6c 1201uschar *p, *dn_buf;
17c76198 1202size_t sz;
059ec3d9 1203
4fe99a6c 1204if (state->have_set_peerdn)
17c76198 1205 return OK;
4fe99a6c 1206state->have_set_peerdn = TRUE;
059ec3d9 1207
4fe99a6c 1208state->peerdn = NULL;
059ec3d9 1209
4fe99a6c
PP
1210/* tls_cipher */
1211cipher = gnutls_cipher_get(state->session);
1212protocol = gnutls_protocol_get_version(state->session);
1213mac = gnutls_mac_get(state->session);
1214kx = gnutls_kx_get(state->session);
1215
75fe387d 1216string_format(cipherbuf, sizeof(cipherbuf),
4fe99a6c
PP
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
1223code base, but it was a concern in the old code and perhaps older GnuTLS
1224releases did return "TLS 1.0"; play it safe, just in case. */
75fe387d 1225for (p = cipherbuf; *p != '\0'; ++p)
4fe99a6c
PP
1226 if (isspace(*p))
1227 *p = '-';
75fe387d
PP
1228old_pool = store_pool;
1229store_pool = POOL_PERM;
1230state->ciphersuite = string_copy(cipherbuf);
1231store_pool = old_pool;
817d9f57 1232state->tlsp->cipher = state->ciphersuite;
4fe99a6c
PP
1233
1234/* tls_peerdn */
17c76198 1235cert_list = gnutls_certificate_get_peers(state->session, &cert_list_size);
83da1223 1236
17c76198
PP
1237if (cert_list == NULL || cert_list_size == 0)
1238 {
17c76198
PP
1239 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1240 cert_list, cert_list_size);
e51c7be2 1241 if (state->verify_requirement >= VERIFY_REQUIRED)
17c76198
PP
1242 return tls_error(US"certificate verification failed",
1243 "no certificate received from peer", state->host);
1244 return OK;
1245 }
059ec3d9 1246
17c76198
PP
1247ct = gnutls_certificate_type_get(state->session);
1248if (ct != GNUTLS_CRT_X509)
059ec3d9 1249 {
17c76198 1250 const char *ctn = gnutls_certificate_type_get_name(ct);
17c76198
PP
1251 DEBUG(D_tls)
1252 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
e51c7be2 1253 if (state->verify_requirement >= VERIFY_REQUIRED)
17c76198
PP
1254 return tls_error(US"certificate verification not possible, unhandled type",
1255 ctn, state->host);
1256 return OK;
83da1223 1257 }
059ec3d9 1258
e51c7be2
JH
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)
17c76198 1270
9d1c15ef
JH
1271rc = import_cert(&cert_list[0], &crt);
1272exim_gnutls_peer_err(US"cert 0");
1273
1274state->tlsp->peercert = state->peercert = crt;
17c76198 1275
17c76198
PP
1276sz = 0;
1277rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1278if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
83da1223 1279 {
17c76198
PP
1280 exim_gnutls_peer_err(US"getting size for cert DN failed");
1281 return FAIL; /* should not happen */
059ec3d9 1282 }
17c76198
PP
1283dn_buf = store_get_perm(sz);
1284rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1285exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
9d1c15ef 1286
17c76198
PP
1287state->peerdn = dn_buf;
1288
1289return OK;
1290#undef exim_gnutls_peer_err
1291}
059ec3d9 1292
059ec3d9 1293
059ec3d9 1294
059ec3d9 1295
17c76198
PP
1296/*************************************************
1297* Verify peer certificate *
1298*************************************************/
059ec3d9 1299
17c76198
PP
1300/* Called from both server and client code.
1301*Should* be using a callback registered with
1302gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1303the peer information, but that's too new for some OSes.
059ec3d9 1304
17c76198
PP
1305Arguments:
1306 state exim_gnutls_state_st *
1307 error where to put an error message
059ec3d9 1308
17c76198
PP
1309Returns:
1310 FALSE if the session should be rejected
1311 TRUE if the cert is okay or we just don't care
1312*/
059ec3d9 1313
17c76198
PP
1314static BOOL
1315verify_certificate(exim_gnutls_state_st *state, const char **error)
1316{
1317int rc;
1318unsigned int verify;
1319
1320*error = NULL;
1321
0a92f87f 1322if ((rc = peer_status(state)) != OK)
e6060e2c 1323 {
17c76198 1324 verify = GNUTLS_CERT_INVALID;
0a92f87f 1325 *error = "certificate not supplied";
17c76198
PP
1326 }
1327else
17c76198 1328 rc = gnutls_certificate_verify_peers2(state->session, &verify);
e6060e2c 1329
17c76198
PP
1330/* Handle the result of verification. INVALID seems to be set as well
1331as REVOKED, but leave the test for both. */
059ec3d9 1332
e51c7be2
JH
1333if (rc < 0 ||
1334 verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED)
1335 )
17c76198
PP
1336 {
1337 state->peer_cert_verified = FALSE;
0a92f87f
JH
1338 if (!*error)
1339 *error = verify & GNUTLS_CERT_REVOKED
1340 ? "certificate revoked" : "certificate invalid";
059ec3d9 1341
17c76198 1342 DEBUG(D_tls)
e51c7be2 1343 debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
4fe99a6c 1344 *error, state->peerdn ? state->peerdn : US"<unset>");
059ec3d9 1345
e51c7be2 1346 if (state->verify_requirement >= VERIFY_REQUIRED)
17c76198 1347 {
e51c7be2
JH
1348 gnutls_alert_send(state->session,
1349 GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
17c76198
PP
1350 return FALSE;
1351 }
1352 DEBUG(D_tls)
4789da3a 1353 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
17c76198 1354 }
e51c7be2 1355
17c76198
PP
1356else
1357 {
e51c7be2
JH
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
17c76198 1377 state->peer_cert_verified = TRUE;
e51c7be2 1378 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
4fe99a6c 1379 state->peerdn ? state->peerdn : US"<unset>");
17c76198 1380 }
059ec3d9 1381
817d9f57 1382state->tlsp->peerdn = state->peerdn;
059ec3d9 1383
17c76198
PP
1384return TRUE;
1385}
059ec3d9 1386
17c76198
PP
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 */
af3498d6 1397#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
059ec3d9 1398static void
17c76198 1399exim_gnutls_logger_cb(int level, const char *message)
059ec3d9 1400{
8c79eebf
PP
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");
17c76198 1409}
af3498d6 1410#endif
059ec3d9 1411
059ec3d9 1412
17c76198
PP
1413/* Called after client hello, should handle SNI work.
1414This will always set tls_sni (state->received_sni) if available,
1415and may trigger presenting different certificates,
1416if state->trigger_sni_changes is TRUE.
059ec3d9 1417
17c76198
PP
1418Should be registered with
1419 gnutls_handshake_set_post_client_hello_function()
059ec3d9 1420
17c76198
PP
1421"This callback must return 0 on success or a gnutls error code to terminate the
1422handshake.".
059ec3d9 1423
17c76198
PP
1424For inability to get SNI information, we return 0.
1425We only return non-zero if re-setup failed.
817d9f57 1426Only used for server-side TLS.
17c76198 1427*/
44bbabb5 1428
17c76198
PP
1429static int
1430exim_sni_handling_cb(gnutls_session_t session)
1431{
1432char sni_name[MAX_HOST_LEN];
1433size_t data_len = MAX_HOST_LEN;
817d9f57 1434exim_gnutls_state_st *state = &state_server;
17c76198
PP
1435unsigned int sni_type;
1436int rc, old_pool;
1437
1438rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
b34fc30c
PP
1439if (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
17c76198
PP
1451if (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 }
44bbabb5 1456
17c76198
PP
1457/* We now have a UTF-8 string in sni_name */
1458old_pool = store_pool;
1459store_pool = POOL_PERM;
1460state->received_sni = string_copyn(US sni_name, data_len);
1461store_pool = old_pool;
1462
1463/* We set this one now so that variable expansions below will work */
817d9f57 1464state->tlsp->sni = state->received_sni;
17c76198
PP
1465
1466DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1467 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1468
1469if (!state->trigger_sni_changes)
1470 return 0;
1471
1472rc = tls_expand_session_files(state);
1473if (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
1365611d
PP
1480rc = tls_set_remaining_x509(state);
1481if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1482
1483return 0;
059ec3d9
PH
1484}
1485
1486
1487
44662487
JH
1488#ifdef EXPERIMENTAL_OCSP
1489
1490static int
1491server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1492 gnutls_datum_t * ocsp_response)
1493{
1494int ret;
1495
44662487
JH
1496if ((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);
018058b2 1500 tls_in.ocsp = OCSP_NOT_RESP;
44662487
JH
1501 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1502 }
1503
018058b2 1504tls_in.ocsp = OCSP_VFY_NOT_TRIED;
44662487
JH
1505return 0;
1506}
1507
1508#endif
1509
1510
1511
1512
17c76198
PP
1513
1514/* ------------------------------------------------------------------------ */
1515/* Exported functions */
1516
1517
1518
1519
059ec3d9
PH
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
1525the STARTTLS command. It must respond to that command, and then negotiate
1526a TLS session.
1527
1528Arguments:
83da1223 1529 require_ciphers list of allowed ciphers or NULL
059ec3d9
PH
1530
1531Returns: 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
1537int
17c76198 1538tls_server_start(const uschar *require_ciphers)
059ec3d9
PH
1539{
1540int rc;
7199e1ee 1541const char *error;
17c76198 1542exim_gnutls_state_st *state = NULL;
059ec3d9
PH
1543
1544/* Check for previous activation */
817d9f57 1545if (tls_in.active >= 0)
059ec3d9 1546 {
17c76198 1547 tls_error(US"STARTTLS received after TLS started", "", NULL);
059ec3d9
PH
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
1553and sent an SMTP response. */
1554
17c76198 1555DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
059ec3d9 1556
17c76198
PP
1557rc = tls_init(NULL, tls_certificate, tls_privatekey,
1558 NULL, tls_verify_certificates, tls_crl,
1559 require_ciphers, &state);
059ec3d9
PH
1560if (rc != OK) return rc;
1561
059ec3d9
PH
1562/* If this is a host for which certificate verification is mandatory or
1563optional, set up appropriately. */
1564
059ec3d9 1565if (verify_check_host(&tls_verify_hosts) == OK)
17c76198 1566 {
e51c7be2
JH
1567 DEBUG(D_tls)
1568 debug_printf("TLS: a client certificate will be required.\n");
17c76198
PP
1569 state->verify_requirement = VERIFY_REQUIRED;
1570 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1571 }
059ec3d9 1572else if (verify_check_host(&tls_try_verify_hosts) == OK)
17c76198 1573 {
e51c7be2
JH
1574 DEBUG(D_tls)
1575 debug_printf("TLS: a client certificate will be requested but not required.\n");
17c76198
PP
1576 state->verify_requirement = VERIFY_OPTIONAL;
1577 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1578 }
1579else
1580 {
e51c7be2
JH
1581 DEBUG(D_tls)
1582 debug_printf("TLS: a client certificate will not be requested.\n");
17c76198
PP
1583 state->verify_requirement = VERIFY_NONE;
1584 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1585 }
059ec3d9 1586
17c76198
PP
1587/* Register SNI handling; always, even if not in tls_certificate, so that the
1588expansion variable $tls_sni is always available. */
059ec3d9 1589
17c76198
PP
1590gnutls_handshake_set_post_client_hello_function(state->session,
1591 exim_sni_handling_cb);
059ec3d9
PH
1592
1593/* Set context and tell client to go ahead, except in the case of TLS startup
1594on connection, where outputting anything now upsets the clients and tends to
1595make them disconnect. We need to have an explicit fflush() here, to force out
1596the response. Other smtp_printf() calls do not need it, because in non-TLS
1597mode, the fflush() happens when smtp_getc() is called. */
1598
817d9f57 1599if (!state->tlsp->on_connect)
059ec3d9
PH
1600 {
1601 smtp_printf("220 TLS go ahead\r\n");
9d1c15ef 1602 fflush(smtp_out);
059ec3d9
PH
1603 }
1604
1605/* Now negotiate the TLS session. We put our own timer on it, since it seems
1606that the GnuTLS library doesn't. */
1607
17c76198 1608gnutls_transport_set_ptr2(state->session,
44662487
JH
1609 (gnutls_transport_ptr)(long) fileno(smtp_in),
1610 (gnutls_transport_ptr)(long) fileno(smtp_out));
17c76198
PP
1611state->fd_in = fileno(smtp_in);
1612state->fd_out = fileno(smtp_out);
059ec3d9
PH
1613
1614sigalrm_seen = FALSE;
1615if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
17c76198
PP
1616do
1617 {
1618 rc = gnutls_handshake(state->session);
619b2b25
PP
1619 } while ((rc == GNUTLS_E_AGAIN) ||
1620 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
059ec3d9
PH
1621alarm(0);
1622
17c76198 1623if (rc != GNUTLS_E_SUCCESS)
059ec3d9 1624 {
17c76198
PP
1625 tls_error(US"gnutls_handshake",
1626 sigalrm_seen ? "timed out" : gnutls_strerror(rc), NULL);
059ec3d9
PH
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 {
f1e894f3
PH
1633 (void)fclose(smtp_out);
1634 (void)fclose(smtp_in);
059ec3d9
PH
1635 }
1636
1637 return FAIL;
1638 }
1639
1640DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1641
17c76198
PP
1642/* Verify after the fact */
1643
9d1c15ef
JH
1644if ( state->verify_requirement != VERIFY_NONE
1645 && !verify_certificate(state, &error))
059ec3d9 1646 {
9d1c15ef 1647 if (state->verify_requirement != VERIFY_OPTIONAL)
17c76198 1648 {
9d1c15ef
JH
1649 tls_error(US"certificate verification failed", error, NULL);
1650 return FAIL;
17c76198 1651 }
9d1c15ef
JH
1652 DEBUG(D_tls)
1653 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
1654 error);
059ec3d9
PH
1655 }
1656
17c76198
PP
1657/* Figure out peer DN, and if authenticated, etc. */
1658
1659rc = peer_status(state);
1660if (rc != OK) return rc;
1661
1662/* Sets various Exim expansion variables; always safe within server */
1663
9d1c15ef 1664extract_exim_vars_from_tls_state(state);
059ec3d9
PH
1665
1666/* TLS has been set up. Adjust the input functions to read via TLS,
1667and initialize appropriately. */
1668
17c76198 1669state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
059ec3d9
PH
1670
1671receive_getc = tls_getc;
1672receive_ungetc = tls_ungetc;
1673receive_feof = tls_feof;
1674receive_ferror = tls_ferror;
58eb016e 1675receive_smtp_buffered = tls_smtp_buffered;
059ec3d9 1676
059ec3d9
PH
1677return 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
1689Arguments:
1690 fd the fd of the connection
1691 host connected host (for messages)
83da1223 1692 addr the first address (not used)
65867078 1693 ob smtp transport options
059ec3d9
PH
1694
1695Returns: OK/DEFER/FAIL (because using common functions),
1696 but for a client, DEFER and FAIL have the same meaning
1697*/
1698
1699int
17c76198 1700tls_client_start(int fd, host_item *host,
f5d78688 1701 address_item *addr ARG_UNUSED,
65867078 1702 void *v_ob)
059ec3d9 1703{
65867078 1704smtp_transport_options_block *ob = v_ob;
059ec3d9 1705int rc;
17c76198
PP
1706const char *error;
1707exim_gnutls_state_st *state = NULL;
2b4a568d 1708#ifdef EXPERIMENTAL_OCSP
65867078 1709BOOL require_ocsp = verify_check_this_host(&ob->hosts_require_ocsp,
2b4a568d 1710 NULL, host->name, host->address, NULL) == OK;
44662487
JH
1711BOOL request_ocsp = require_ocsp ? TRUE
1712 : verify_check_this_host(&ob->hosts_request_ocsp,
1713 NULL, host->name, host->address, NULL) == OK;
2b4a568d 1714#endif
059ec3d9 1715
17c76198 1716DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
059ec3d9 1717
65867078
JH
1718if ((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)
2b4a568d 1721 return rc;
059ec3d9 1722
54c90be1 1723 {
65867078
JH
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 }
54c90be1 1733
65867078
JH
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 }
83da1223 1739
2b4a568d
JH
1740/* Stick to the old behaviour for compatibility if tls_verify_certificates is
1741set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
1742the specified host patterns if one of them is defined */
1743
1744if (( state->exp_tls_verify_certificates
65867078
JH
1745 && !ob->tls_verify_hosts
1746 && !ob->tls_try_verify_hosts
2b4a568d
JH
1747 )
1748 ||
65867078 1749 verify_check_host(&ob->tls_verify_hosts) == OK
2b4a568d 1750 )
17c76198 1751 {
e51c7be2
JH
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 }
52f93eed
WB
1773 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1774 }
65867078 1775else if (verify_check_host(&ob->tls_try_verify_hosts) == OK)
52f93eed 1776 {
e51c7be2
JH
1777 DEBUG(D_tls)
1778 debug_printf("TLS: server certificate verification optional.\n");
52f93eed 1779 state->verify_requirement = VERIFY_OPTIONAL;
17c76198
PP
1780 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1781 }
1782else
1783 {
e51c7be2
JH
1784 DEBUG(D_tls)
1785 debug_printf("TLS: server certificate verification not required.\n");
52f93eed
WB
1786 state->verify_requirement = VERIFY_NONE;
1787 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
17c76198 1788 }
059ec3d9 1789
2b4a568d 1790#ifdef EXPERIMENTAL_OCSP /* since GnuTLS 3.1.3 */
44662487 1791if (request_ocsp)
9d1c15ef
JH
1792 {
1793 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
65867078
JH
1794 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
1795 NULL, 0, NULL)) != OK)
9d1c15ef
JH
1796 return tls_error(US"cert-status-req",
1797 gnutls_strerror(rc), state->host);
44662487 1798 tls_out.ocsp = OCSP_NOT_RESP;
9d1c15ef 1799 }
2b4a568d
JH
1800#endif
1801
44662487 1802gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr)(long) fd);
17c76198
PP
1803state->fd_in = fd;
1804state->fd_out = fd;
059ec3d9 1805
9d1c15ef 1806DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
059ec3d9
PH
1807/* There doesn't seem to be a built-in timeout on connection. */
1808
1809sigalrm_seen = FALSE;
65867078 1810alarm(ob->command_timeout);
17c76198
PP
1811do
1812 {
1813 rc = gnutls_handshake(state->session);
619b2b25
PP
1814 } while ((rc == GNUTLS_E_AGAIN) ||
1815 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
059ec3d9
PH
1816alarm(0);
1817
4fe99a6c
PP
1818if (rc != GNUTLS_E_SUCCESS)
1819 return tls_error(US"gnutls_handshake",
1820 sigalrm_seen ? "timed out" : gnutls_strerror(rc), state->host);
1821
17c76198 1822DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
059ec3d9 1823
17c76198 1824/* Verify late */
059ec3d9 1825
17c76198
PP
1826if (state->verify_requirement != VERIFY_NONE &&
1827 !verify_certificate(state, &error))
1828 return tls_error(US"certificate verification failed", error, state->host);
059ec3d9 1829
2b4a568d
JH
1830#ifdef EXPERIMENTAL_OCSP
1831if (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 {
65867078 1844 debug_printf("%.4096s", printed.data);
2b4a568d
JH
1845 gnutls_free(printed.data);
1846 }
1847 else
1848 (void) tls_error(US"ocsp decode", gnutls_strerror(rc), state->host);
1849 }
1850
2b4a568d 1851 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
018058b2
JH
1852 {
1853 tls_out.ocsp = OCSP_FAILED;
2b4a568d 1854 return tls_error(US"certificate status check failed", NULL, state->host);
018058b2 1855 }
2b4a568d 1856 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
44662487 1857 tls_out.ocsp = OCSP_VFIED;
2b4a568d
JH
1858 }
1859#endif
1860
17c76198 1861/* Figure out peer DN, and if authenticated, etc. */
059ec3d9 1862
2b4a568d
JH
1863if ((rc = peer_status(state)) != OK)
1864 return rc;
059ec3d9 1865
4fe99a6c 1866/* Sets various Exim expansion variables; may need to adjust for ACL callouts */
059ec3d9 1867
9d1c15ef 1868extract_exim_vars_from_tls_state(state);
059ec3d9 1869
059ec3d9
PH
1870return OK;
1871}
1872
1873
1874
17c76198 1875
059ec3d9 1876/*************************************************
17c76198 1877* Close down a TLS session *
059ec3d9
PH
1878*************************************************/
1879
17c76198
PP
1880/* This is also called from within a delivery subprocess forked from the
1881daemon, to shut down the TLS library, without actually doing a shutdown (which
1882would tamper with the TLS session in the parent process).
059ec3d9 1883
17c76198
PP
1884Arguments: TRUE if gnutls_bye is to be called
1885Returns: nothing
059ec3d9
PH
1886*/
1887
17c76198 1888void
817d9f57 1889tls_close(BOOL is_server, BOOL shutdown)
059ec3d9 1890{
817d9f57 1891exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
059ec3d9 1892
389ca47a 1893if (!state->tlsp || state->tlsp->active < 0) return; /* TLS was not active */
17c76198
PP
1894
1895if (shutdown)
1896 {
1897 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
1898 gnutls_bye(state->session, GNUTLS_SHUT_WR);
1899 }
1900
1901gnutls_deinit(state->session);
1902
389ca47a 1903state->tlsp->active = -1;
17c76198
PP
1904memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1905
1906if ((state_server.session == NULL) && (state_client.session == NULL))
1907 {
1908 gnutls_global_deinit();
1909 exim_gnutls_base_init_done = FALSE;
1910 }
7199e1ee 1911
059ec3d9
PH
1912}
1913
1914
1915
17c76198 1916
059ec3d9
PH
1917/*************************************************
1918* TLS version of getc *
1919*************************************************/
1920
1921/* This gets the next byte from the TLS input buffer. If the buffer is empty,
1922it refills the buffer via the GnuTLS reading function.
817d9f57 1923Only used by the server-side TLS.
059ec3d9 1924
17c76198
PP
1925This feeds DKIM and should be used for all message-body reads.
1926
059ec3d9
PH
1927Arguments: none
1928Returns: the next character or EOF
1929*/
1930
1931int
1932tls_getc(void)
1933{
817d9f57 1934exim_gnutls_state_st *state = &state_server;
17c76198 1935if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
059ec3d9 1936 {
17c76198 1937 ssize_t inbytes;
059ec3d9 1938
17c76198
PP
1939 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
1940 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
059ec3d9
PH
1941
1942 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
17c76198 1943 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
059ec3d9
PH
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;
58eb016e 1959 receive_smtp_buffered = smtp_buffered;
059ec3d9 1960
17c76198
PP
1961 gnutls_deinit(state->session);
1962 state->session = NULL;
817d9f57
JH
1963 state->tlsp->active = -1;
1964 state->tlsp->bits = 0;
1965 state->tlsp->certificate_verified = FALSE;
9d1c15ef 1966 tls_channelbinding_b64 = NULL;
817d9f57 1967 state->tlsp->cipher = NULL;
9d1c15ef 1968 state->tlsp->peercert = NULL;
817d9f57 1969 state->tlsp->peerdn = NULL;
059ec3d9
PH
1970
1971 return smtp_getc();
1972 }
1973
1974 /* Handle genuine errors */
1975
1976 else if (inbytes < 0)
1977 {
17c76198
PP
1978 record_io_error(state, (int) inbytes, US"recv", NULL);
1979 state->xfer_error = 1;
059ec3d9
PH
1980 return EOF;
1981 }
80a47a2c 1982#ifndef DISABLE_DKIM
17c76198 1983 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
80a47a2c 1984#endif
17c76198
PP
1985 state->xfer_buffer_hwm = (int) inbytes;
1986 state->xfer_buffer_lwm = 0;
059ec3d9
PH
1987 }
1988
059ec3d9
PH
1989/* Something in the buffer; return next uschar */
1990
17c76198 1991return state->xfer_buffer[state->xfer_buffer_lwm++];
059ec3d9
PH
1992}
1993
1994
1995
17c76198 1996
059ec3d9
PH
1997/*************************************************
1998* Read bytes from TLS channel *
1999*************************************************/
2000
17c76198
PP
2001/* This does not feed DKIM, so if the caller uses this for reading message body,
2002then the caller must feed DKIM.
817d9f57 2003
059ec3d9
PH
2004Arguments:
2005 buff buffer of data
2006 len size of buffer
2007
2008Returns: the number of bytes read
2009 -1 after a failed read
2010*/
2011
2012int
817d9f57 2013tls_read(BOOL is_server, uschar *buff, size_t len)
059ec3d9 2014{
817d9f57 2015exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
17c76198 2016ssize_t inbytes;
059ec3d9 2017
17c76198
PP
2018if (len > INT_MAX)
2019 len = INT_MAX;
059ec3d9 2020
17c76198
PP
2021if (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
2027DEBUG(D_tls)
2028 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
2029 state->session, buff, len);
2030
2031inbytes = gnutls_record_recv(state->session, buff, len);
059ec3d9
PH
2032if (inbytes > 0) return inbytes;
2033if (inbytes == 0)
2034 {
2035 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2036 }
17c76198 2037else record_io_error(state, (int)inbytes, US"recv", NULL);
059ec3d9
PH
2038
2039return -1;
2040}
2041
2042
2043
17c76198 2044
059ec3d9
PH
2045/*************************************************
2046* Write bytes down TLS channel *
2047*************************************************/
2048
2049/*
2050Arguments:
817d9f57 2051 is_server channel specifier
059ec3d9
PH
2052 buff buffer of data
2053 len number of bytes
2054
2055Returns: the number of bytes after a successful write,
2056 -1 after a failed write
2057*/
2058
2059int
817d9f57 2060tls_write(BOOL is_server, const uschar *buff, size_t len)
059ec3d9 2061{
17c76198
PP
2062ssize_t outbytes;
2063size_t left = len;
817d9f57 2064exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
059ec3d9 2065
17c76198 2066DEBUG(D_tls) debug_printf("tls_do_write(%p, " SIZE_T_FMT ")\n", buff, left);
059ec3d9
PH
2067while (left > 0)
2068 {
17c76198
PP
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);
059ec3d9 2072
17c76198 2073 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
059ec3d9
PH
2074 if (outbytes < 0)
2075 {
17c76198 2076 record_io_error(state, outbytes, US"send", NULL);
059ec3d9
PH
2077 return -1;
2078 }
2079 if (outbytes == 0)
2080 {
17c76198 2081 record_io_error(state, 0, US"send", US"TLS channel closed on write");
059ec3d9
PH
2082 return -1;
2083 }
2084
2085 left -= outbytes;
2086 buff += outbytes;
2087 }
2088
17c76198
PP
2089if (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
2097return (int) len;
059ec3d9
PH
2098}
2099
2100
2101
17c76198 2102
059ec3d9 2103/*************************************************
17c76198 2104* Random number generation *
059ec3d9
PH
2105*************************************************/
2106
17c76198
PP
2107/* Pseudo-random number generation. The result is not expected to be
2108cryptographically strong but not so weak that someone will shoot themselves
2109in the foot using it as a nonce in input in some email header scheme or
2110whatever weirdness they'll twist this into. The result should handle fork()
2111and avoid repeating sequences. OpenSSL handles that for us.
059ec3d9 2112
17c76198
PP
2113Arguments:
2114 max range maximum
2115Returns a random number in range [0, max-1]
059ec3d9
PH
2116*/
2117
af3498d6 2118#ifdef HAVE_GNUTLS_RND
17c76198
PP
2119int
2120vaguely_random_number(int max)
059ec3d9 2121{
17c76198
PP
2122unsigned int r;
2123int i, needed_len;
2124uschar *p;
2125uschar smallbuf[sizeof(r)];
2126
2127if (max <= 1)
2128 return 0;
2129
2130needed_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. */
2133for (r = max, i = 0; r; ++i)
2134 r >>= 1;
2135i = (i + 7) / 8;
2136if (i < needed_len)
2137 needed_len = i;
2138
2139i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2140if (i < 0)
059ec3d9 2141 {
17c76198
PP
2142 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2143 return vaguely_random_number_fallback(max);
2144 }
2145r = 0;
2146for (p = smallbuf; needed_len; --needed_len, ++p)
2147 {
2148 r *= 256;
2149 r += *p;
059ec3d9
PH
2150 }
2151
17c76198
PP
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. */
2154return r % max;
059ec3d9 2155}
af3498d6
PP
2156#else /* HAVE_GNUTLS_RND */
2157int
2158vaguely_random_number(int max)
2159{
2160 return vaguely_random_number_fallback(max);
2161}
2162#endif /* HAVE_GNUTLS_RND */
059ec3d9 2163
36f12725
NM
2164
2165
2166
3375e053
PP
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
2172library can parse.
2173
2174Returns: NULL on success, or error message
2175*/
2176
2177uschar *
2178tls_validate_require_cipher(void)
2179{
2180int rc;
2181uschar *expciphers = NULL;
2182gnutls_priority_t priority_cache;
2183const 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
2190if (exim_gnutls_base_init_done)
2191 log_write(0, LOG_MAIN|LOG_PANIC,
2192 "already initialised GnuTLS, Exim developer bug");
2193
a5f239e4 2194#ifdef HAVE_GNUTLS_PKCS11
2519e60d 2195if (!gnutls_allow_auto_pkcs11)
a5f239e4
PP
2196 {
2197 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
2198 validate_check_rc(US"gnutls_pkcs11_init");
2199 }
2200#endif
3375e053
PP
2201rc = gnutls_global_init();
2202validate_check_rc(US"gnutls_global_init()");
2203exim_gnutls_base_init_done = TRUE;
2204
2205if (!(tls_require_ciphers && *tls_require_ciphers))
2206 return_deinit(NULL);
2207
2208if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers))
2209 return_deinit(US"failed to expand tls_require_ciphers");
2210
2211if (!(expciphers && *expciphers))
2212 return_deinit(NULL);
2213
2214DEBUG(D_tls)
2215 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2216
2217rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
2218validate_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
2224gnutls_global_deinit();
2225
2226return NULL;
2227}
2228
2229
2230
2231
36f12725
NM
2232/*************************************************
2233* Report the library versions. *
2234*************************************************/
2235
2236/* See a description in tls-openssl.c for an explanation of why this exists.
2237
2238Arguments: a FILE* to print the results to
2239Returns: nothing
2240*/
2241
2242void
2243tls_version_report(FILE *f)
2244{
754a0503
PP
2245fprintf(f, "Library version: GnuTLS: Compile: %s\n"
2246 " Runtime: %s\n",
2247 LIBGNUTLS_VERSION,
2248 gnutls_check_version(NULL));
36f12725
NM
2249}
2250
2b4a568d
JH
2251/* vi: aw ai sw=2
2252*/
059ec3d9 2253/* End of tls-gnu.c */