tidying
[exim.git] / src / src / tls.c
CommitLineData
059ec3d9
PH
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
f9ba5e22 5/* Copyright (c) University of Cambridge 1995 - 2018 */
059ec3d9
PH
6/* See the file NOTICE for conditions of use and distribution. */
7
8/* This module provides TLS (aka SSL) support for Exim. The code for OpenSSL is
9based on a patch that was originally contributed by Steve Haslam. It was
10adapted from stunnel, a GPL program by Michal Trojnara. The code for GNU TLS is
6aa6fc9c 11based on a patch contributed by Nikos Mavrogiannopoulos. Because these packages
059ec3d9
PH
12are so very different, the functions for each are kept in separate files. The
13relevant file is #included as required, after any any common functions.
14
15No cryptographic code is included in Exim. All this module does is to call
16functions from the OpenSSL or GNU TLS libraries. */
17
18
19#include "exim.h"
65867078 20#include "transports/smtp.h"
059ec3d9 21
de517fd3
JH
22#if !defined(DISABLE_TLS) && !defined(USE_OPENSSL) && !defined(USE_GNUTLS)
23# error One of USE_OPENSSL or USE_GNUTLS must be defined for a TLS build
24#endif
25
26
01603eec 27#if defined(MACRO_PREDEF) && !defined(DISABLE_TLS)
b10c87b3
JH
28# include "macro_predef.h"
29# ifdef USE_GNUTLS
30# include "tls-gnu.c"
31# else
8442641e
JH
32# include "tls-openssl.c"
33# endif
34#endif
35
36#ifndef MACRO_PREDEF
37
059ec3d9
PH
38/* This module is compiled only when it is specifically requested in the
39build-time configuration. However, some compilers don't like compiling empty
40modules, so keep them happy with a dummy when skipping the rest. Make it
41reference itself to stop picky compilers complaining that it is unused, and put
42in a dummy argument to stop even pickier compilers complaining about infinite
43loops. */
44
01603eec 45#ifdef DISABLE_TLS
059ec3d9
PH
46static void dummy(int x) { dummy(x-1); }
47#else
48
49/* Static variables that are used for buffering data by both sets of
4fe99a6c 50functions and the common functions below.
059ec3d9 51
4fe99a6c
PP
52We're moving away from this; GnuTLS is already using a state, which
53can switch, so we can do TLS callouts during ACLs. */
059ec3d9 54
17c76198 55static const int ssl_xfer_buffer_size = 4096;
de517fd3 56#ifdef USE_OPENSSL
4fe99a6c 57static uschar *ssl_xfer_buffer = NULL;
059ec3d9
PH
58static int ssl_xfer_buffer_lwm = 0;
59static int ssl_xfer_buffer_hwm = 0;
8b77d27a
JH
60static int ssl_xfer_eof = FALSE;
61static BOOL ssl_xfer_error = FALSE;
4fe99a6c 62#endif
059ec3d9 63
059ec3d9
PH
64
65/*************************************************
66* Expand string; give error on failure *
67*************************************************/
68
69/* If expansion is forced to fail, set the result NULL and return TRUE.
70Other failures return FALSE. For a server, an SMTP response is given.
71
72Arguments:
73 s the string to expand; if NULL just return TRUE
74 name name of string being expanded (for error)
75 result where to put the result
76
77Returns: TRUE if OK; result may still be NULL after forced failure
78*/
79
80static BOOL
cf0c6164 81expand_check(const uschar *s, const uschar *name, uschar **result, uschar ** errstr)
059ec3d9 82{
cf0c6164
JH
83if (!s)
84 *result = NULL;
85else if ( !(*result = expand_string(US s)) /* need to clean up const more */
8768d548 86 && !f.expand_string_forcedfail
cf0c6164 87 )
059ec3d9 88 {
cf0c6164
JH
89 *errstr = US"Internal error";
90 log_write(0, LOG_MAIN|LOG_PANIC, "expansion of %s failed: %s", name,
91 expand_string_message);
92 return FALSE;
059ec3d9
PH
93 }
94return TRUE;
95}
96
97
e9477a08
JH
98/*************************************************
99* Timezone environment flipping *
100*************************************************/
101
102static uschar *
103to_tz(uschar * tz)
104{
dfe7d917
JH
105uschar * old = US getenv("TZ");
106(void) setenv("TZ", CCS tz, 1);
271019bd 107tzset();
dfe7d917 108return old;
e9477a08 109}
dfe7d917 110
e9477a08
JH
111static void
112restore_tz(uschar * tz)
113{
dfe7d917
JH
114if (tz)
115 (void) setenv("TZ", CCS tz, 1);
116else
93a680e4 117 (void) os_unsetenv(US"TZ");
271019bd 118tzset();
e9477a08
JH
119}
120
059ec3d9
PH
121/*************************************************
122* Many functions are package-specific *
123*************************************************/
124
125#ifdef USE_GNUTLS
27f19eb4
JH
126# include "tls-gnu.c"
127# include "tlscert-gnu.c"
27f19eb4
JH
128# define ssl_xfer_buffer (state_server.xfer_buffer)
129# define ssl_xfer_buffer_lwm (state_server.xfer_buffer_lwm)
130# define ssl_xfer_buffer_hwm (state_server.xfer_buffer_hwm)
131# define ssl_xfer_eof (state_server.xfer_eof)
132# define ssl_xfer_error (state_server.xfer_error)
de517fd3 133#endif
4fe99a6c 134
de517fd3 135#ifdef USE_OPENSSL
27f19eb4
JH
136# include "tls-openssl.c"
137# include "tlscert-openssl.c"
059ec3d9
PH
138#endif
139
140
141
142/*************************************************
143* TLS version of ungetc *
144*************************************************/
145
146/* Puts a character back in the input buffer. Only ever
147called once.
389ca47a 148Only used by the server-side TLS.
059ec3d9
PH
149
150Arguments:
151 ch the character
152
153Returns: the character
154*/
155
156int
157tls_ungetc(int ch)
158{
159ssl_xfer_buffer[--ssl_xfer_buffer_lwm] = ch;
160return ch;
161}
162
163
164
165/*************************************************
166* TLS version of feof *
167*************************************************/
168
169/* Tests for a previous EOF
389ca47a 170Only used by the server-side TLS.
059ec3d9
PH
171
172Arguments: none
173Returns: non-zero if the eof flag is set
174*/
175
176int
177tls_feof(void)
178{
8b77d27a 179return (int)ssl_xfer_eof;
059ec3d9
PH
180}
181
182
183
184/*************************************************
185* TLS version of ferror *
186*************************************************/
187
188/* Tests for a previous read error, and returns with errno
189restored to what it was when the error was detected.
389ca47a 190Only used by the server-side TLS.
059ec3d9
PH
191
192>>>>> Hmm. Errno not handled yet. Where do we get it from? >>>>>
193
194Arguments: none
195Returns: non-zero if the error flag is set
196*/
197
198int
199tls_ferror(void)
200{
8b77d27a 201return (int)ssl_xfer_error;
059ec3d9
PH
202}
203
58eb016e
PH
204
205/*************************************************
206* TLS version of smtp_buffered *
207*************************************************/
208
209/* Tests for unused chars in the TLS input buffer.
389ca47a 210Only used by the server-side TLS.
58eb016e
PH
211
212Arguments: none
213Returns: TRUE/FALSE
214*/
215
216BOOL
217tls_smtp_buffered(void)
218{
219return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm;
220}
221
222
01603eec 223#endif /*DISABLE_TLS*/
059ec3d9 224
35aba663
JH
225void
226tls_modify_variables(tls_support * dest_tsp)
227{
228modify_variable(US"tls_bits", &dest_tsp->bits);
229modify_variable(US"tls_certificate_verified", &dest_tsp->certificate_verified);
230modify_variable(US"tls_cipher", &dest_tsp->cipher);
231modify_variable(US"tls_peerdn", &dest_tsp->peerdn);
de517fd3 232#ifdef USE_OPENSSL
35aba663
JH
233modify_variable(US"tls_sni", &dest_tsp->sni);
234#endif
235}
236
417bfce4 237
01603eec 238#ifndef DISABLE_TLS
812a6045
JH
239/************************************************
240* TLS certificate name operations *
241************************************************/
242
243/* Convert an rfc4514 DN to an exim comma-sep list.
244Backslashed commas need to be replaced by doublecomma
245for Exim's list quoting. We modify the given string
246inplace.
247*/
248
249static void
250dn_to_list(uschar * dn)
251{
d7978c0f 252for (uschar * cp = dn; *cp; cp++)
812a6045
JH
253 if (cp[0] == '\\' && cp[1] == ',')
254 *cp++ = ',';
255}
256
257
258/* Extract fields of a given type from an RFC4514-
259format Distinguished Name. Return an Exim list.
260NOTE: We modify the supplied dn string during operation.
261
262Arguments:
263 dn Distinguished Name string
bfbad1dd 264 mod list containing optional output list-sep and
812a6045
JH
265 field selector match, comma-separated
266Return:
267 allocated string with list of matching fields,
268 field type stripped
269*/
270
271uschar *
55414b25 272tls_field_from_dn(uschar * dn, const uschar * mod)
812a6045
JH
273{
274int insep = ',';
275uschar outsep = '\n';
276uschar * ele;
277uschar * match = NULL;
278int len;
acec9514 279gstring * list = NULL;
812a6045 280
7437665e 281while ((ele = string_nextinlist(&mod, &insep, NULL, 0)))
812a6045
JH
282 if (ele[0] != '>')
283 match = ele; /* field tag to match */
284 else if (ele[1])
bfbad1dd 285 outsep = ele[1]; /* nondefault output separator */
812a6045
JH
286
287dn_to_list(dn);
288insep = ',';
bfbad1dd 289len = match ? Ustrlen(match) : -1;
55414b25 290while ((ele = string_nextinlist(CUSS &dn, &insep, NULL, 0)))
bfbad1dd
JH
291 if ( !match
292 || Ustrncmp(ele, match, len) == 0 && ele[len] == '='
293 )
acec9514
JH
294 list = string_append_listele(list, outsep, ele+len+1);
295return string_from_gstring(list);
812a6045
JH
296}
297
298
e51c7be2
JH
299/* Compare a domain name with a possibly-wildcarded name. Wildcards
300are restricted to a single one, as the first element of patterns
301having at least three dot-separated elements. Case-independent.
302Return TRUE for a match
303*/
304static BOOL
305is_name_match(const uschar * name, const uschar * pat)
306{
307uschar * cp;
308return *pat == '*' /* possible wildcard match */
309 ? *++pat == '.' /* starts star, dot */
310 && !Ustrchr(++pat, '*') /* has no more stars */
311 && Ustrchr(pat, '.') /* and has another dot. */
312 && (cp = Ustrchr(name, '.'))/* The name has at least one dot */
313 && strcmpic(++cp, pat) == 0 /* and we only compare after it. */
314 : !Ustrchr(pat+1, '*')
315 && strcmpic(name, pat) == 0;
316}
317
318/* Compare a list of names with the dnsname elements
319of the Subject Alternate Name, if any, and the
320Subject otherwise.
321
322Arguments:
323 namelist names to compare
324 cert certificate
325
326Returns:
327 TRUE/FALSE
328*/
329
330BOOL
55414b25 331tls_is_name_for_cert(const uschar * namelist, void * cert)
e51c7be2
JH
332{
333uschar * altnames = tls_cert_subject_altname(cert, US"dns");
334uschar * subjdn;
335uschar * certname;
336int cmp_sep = 0;
337uschar * cmpname;
338
339if ((altnames = tls_cert_subject_altname(cert, US"dns")))
340 {
341 int alt_sep = '\n';
7437665e 342 while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0)))
e51c7be2 343 {
55414b25 344 const uschar * an = altnames;
7437665e 345 while ((certname = string_nextinlist(&an, &alt_sep, NULL, 0)))
e51c7be2
JH
346 if (is_name_match(cmpname, certname))
347 return TRUE;
348 }
349 }
350
351else if ((subjdn = tls_cert_subject(cert, NULL)))
352 {
353 int sn_sep = ',';
e51c7be2
JH
354
355 dn_to_list(subjdn);
67791ce4 356 while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0)))
e51c7be2 357 {
55414b25 358 const uschar * sn = subjdn;
7437665e 359 while ((certname = string_nextinlist(&sn, &sn_sep, NULL, 0)))
e51c7be2
JH
360 if ( *certname++ == 'C'
361 && *certname++ == 'N'
362 && *certname++ == '='
363 && is_name_match(cmpname, certname)
364 )
365 return TRUE;
366 }
367 }
368return FALSE;
369}
6b5cbf74
JH
370
371
2e5d9e71
JH
372/* Environment cleanup: The GnuTLS library uses SSLKEYLOGFILE in the environment
373and writes a file by that name. Our OpenSSL code does the same, using keying
374info from the library API.
375The GnuTLS support only works if exim is run by root, not taking advantage of
376the setuid bit.
377You can use either the external environment (modulo the keep_environment config)
378or the add_environment config option for SSLKEYLOGFILE; the latter takes
379precedence.
6b5cbf74
JH
380
381If the path is absolute, require it starts with the spooldir; otherwise delete
382the env variable. If relative, prefix the spooldir.
383*/
384void
385tls_clean_env(void)
386{
387uschar * path = US getenv("SSLKEYLOGFILE");
388if (path)
389 if (!*path)
390 unsetenv("SSLKEYLOGFILE");
391 else if (*path != '/')
392 {
393 DEBUG(D_tls)
394 debug_printf("prepending spooldir to env SSLKEYLOGFILE\n");
395 setenv("SSLKEYLOGFILE", CCS string_sprintf("%s/%s", spool_directory, path), 1);
396 }
397 else if (Ustrncmp(path, spool_directory, Ustrlen(spool_directory)) != 0)
398 {
399 DEBUG(D_tls)
86ede124 400 debug_printf("removing env SSLKEYLOGFILE=%s: not under spooldir\n", path);
6b5cbf74
JH
401 unsetenv("SSLKEYLOGFILE");
402 }
403}
d85cdeb5
JH
404
405/*************************************************
406* Drop privs for checking TLS config *
407*************************************************/
408
409/* We want to validate TLS options during readconf, but do not want to be
410root when we call into the TLS library, in case of library linkage errors
411which cause segfaults; before this check, those were always done as the Exim
412runtime user and it makes sense to continue with that.
413
414Assumes: tls_require_ciphers has been set, if it will be
415 exim_user has been set, if it will be
416 exim_group has been set, if it will be
417
418Returns: bool for "okay"; false will cause caller to immediately exit.
419*/
420
421BOOL
422tls_dropprivs_validate_require_cipher(BOOL nowarn)
423{
424const uschar *errmsg;
425pid_t pid;
426int rc, status;
427void (*oldsignal)(int);
428
429/* If TLS will never be used, no point checking ciphers */
430
431if ( !tls_advertise_hosts
432 || !*tls_advertise_hosts
433 || Ustrcmp(tls_advertise_hosts, ":") == 0
434 )
435 return TRUE;
436else if (!nowarn && !tls_certificate)
437 log_write(0, LOG_MAIN,
438 "Warning: No server certificate defined; will use a selfsigned one.\n"
439 " Suggested action: either install a certificate or change tls_advertise_hosts option");
440
441oldsignal = signal(SIGCHLD, SIG_DFL);
442
443fflush(NULL);
444if ((pid = fork()) < 0)
445 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "fork failed for TLS check");
446
447if (pid == 0)
448 {
449 /* in some modes, will have dropped privilege already */
450 if (!geteuid())
451 exim_setugid(exim_uid, exim_gid, FALSE,
452 US"calling tls_validate_require_cipher");
453
454 if ((errmsg = tls_validate_require_cipher()))
455 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
456 "tls_require_ciphers invalid: %s", errmsg);
457 fflush(NULL);
458 exim_underbar_exit(0);
459 }
460
461do {
462 rc = waitpid(pid, &status, 0);
463} while (rc < 0 && errno == EINTR);
464
465DEBUG(D_tls)
466 debug_printf("tls_validate_require_cipher child %d ended: status=0x%x\n",
467 (int)pid, status);
468
469signal(SIGCHLD, oldsignal);
470
471return status == 0;
472}
473
474
475
476
01603eec 477#endif /*!DISABLE_TLS*/
8442641e 478#endif /*!MACRO_PREDEF*/
812a6045
JH
479
480/* vi: aw ai sw=2
481*/
059ec3d9 482/* End of tls.c */