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