Pull Andreas Metzler's fix for gnutls_certificate_verify_peers (bug 1095)
[exim.git] / src / src / tls-openssl.c
CommitLineData
059ec3d9
PH
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
0a49a7a4 5/* Copyright (c) University of Cambridge 1995 - 2009 */
059ec3d9
PH
6/* See the file NOTICE for conditions of use and distribution. */
7
8/* This module provides the TLS (aka SSL) support for Exim using the OpenSSL
9library. It is #included into the tls.c file when that library is used. The
10code herein is based on a patch that was originally contributed by Steve
11Haslam. It was adapted from stunnel, a GPL program by Michal Trojnara.
12
13No cryptographic code is included in Exim. All this module does is to call
14functions from the OpenSSL library. */
15
16
17/* Heading stuff */
18
19#include <openssl/lhash.h>
20#include <openssl/ssl.h>
21#include <openssl/err.h>
22#include <openssl/rand.h>
23
24/* Structure for collecting random data for seeding. */
25
26typedef struct randstuff {
9e3331ea
TK
27 struct timeval tv;
28 pid_t p;
059ec3d9
PH
29} randstuff;
30
31/* Local static variables */
32
33static BOOL verify_callback_called = FALSE;
34static const uschar *sid_ctx = US"exim";
35
36static SSL_CTX *ctx = NULL;
37static SSL *ssl = NULL;
38
39static char ssl_errstring[256];
40
41static int ssl_session_timeout = 200;
42static BOOL verify_optional = FALSE;
43
44
45
46
47
48/*************************************************
49* Handle TLS error *
50*************************************************/
51
52/* Called from lots of places when errors occur before actually starting to do
53the TLS handshake, that is, while the session is still in clear. Always returns
54DEFER for a server and FAIL for a client so that most calls can use "return
55tls_error(...)" to do this processing and then give an appropriate return. A
56single function is used for both server and client, because it is called from
57some shared functions.
58
59Argument:
60 prefix text to include in the logged error
61 host NULL if setting up a server;
62 the connected host if setting up a client
7199e1ee 63 msg error message or NULL if we should ask OpenSSL
059ec3d9
PH
64
65Returns: OK/DEFER/FAIL
66*/
67
68static int
7199e1ee 69tls_error(uschar *prefix, host_item *host, uschar *msg)
059ec3d9 70{
7199e1ee
TF
71if (msg == NULL)
72 {
73 ERR_error_string(ERR_get_error(), ssl_errstring);
5ca6d115 74 msg = (uschar *)ssl_errstring;
7199e1ee
TF
75 }
76
059ec3d9
PH
77if (host == NULL)
78 {
7199e1ee 79 uschar *conn_info = smtp_get_connection_info();
5ca6d115 80 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0)
7199e1ee
TF
81 conn_info += 5;
82 log_write(0, LOG_MAIN, "TLS error on %s (%s): %s",
83 conn_info, prefix, msg);
059ec3d9
PH
84 return DEFER;
85 }
86else
87 {
88 log_write(0, LOG_MAIN, "TLS error on connection to %s [%s] (%s): %s",
7199e1ee 89 host->name, host->address, prefix, msg);
059ec3d9
PH
90 return FAIL;
91 }
92}
93
94
95
96/*************************************************
97* Callback to generate RSA key *
98*************************************************/
99
100/*
101Arguments:
102 s SSL connection
103 export not used
104 keylength keylength
105
106Returns: pointer to generated key
107*/
108
109static RSA *
110rsa_callback(SSL *s, int export, int keylength)
111{
112RSA *rsa_key;
113export = export; /* Shut picky compilers up */
114DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
115rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL);
116if (rsa_key == NULL)
117 {
118 ERR_error_string(ERR_get_error(), ssl_errstring);
119 log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
120 ssl_errstring);
121 return NULL;
122 }
123return rsa_key;
124}
125
126
127
128
129/*************************************************
130* Callback for verification *
131*************************************************/
132
133/* The SSL library does certificate verification if set up to do so. This
134callback has the current yes/no state is in "state". If verification succeeded,
135we set up the tls_peerdn string. If verification failed, what happens depends
136on whether the client is required to present a verifiable certificate or not.
137
138If verification is optional, we change the state to yes, but still log the
139verification error. For some reason (it really would help to have proper
140documentation of OpenSSL), this callback function then gets called again, this
141time with state = 1. In fact, that's useful, because we can set up the peerdn
142value, but we must take care not to set the private verified flag on the second
143time through.
144
145Note: this function is not called if the client fails to present a certificate
146when asked. We get here only if a certificate has been received. Handling of
147optional verification for this case is done when requesting SSL to verify, by
148setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
149
150Arguments:
151 state current yes/no state as 1/0
152 x509ctx certificate information.
153
154Returns: 1 if verified, 0 if not
155*/
156
157static int
158verify_callback(int state, X509_STORE_CTX *x509ctx)
159{
160static uschar txt[256];
161
162X509_NAME_oneline(X509_get_subject_name(x509ctx->current_cert),
163 CS txt, sizeof(txt));
164
165if (state == 0)
166 {
167 log_write(0, LOG_MAIN, "SSL verify error: depth=%d error=%s cert=%s",
168 x509ctx->error_depth,
169 X509_verify_cert_error_string(x509ctx->error),
170 txt);
171 tls_certificate_verified = FALSE;
172 verify_callback_called = TRUE;
173 if (!verify_optional) return 0; /* reject */
174 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
175 "tls_try_verify_hosts)\n");
176 return 1; /* accept */
177 }
178
179if (x509ctx->error_depth != 0)
180 {
181 DEBUG(D_tls) debug_printf("SSL verify ok: depth=%d cert=%s\n",
182 x509ctx->error_depth, txt);
183 }
184else
185 {
186 DEBUG(D_tls) debug_printf("SSL%s peer: %s\n",
187 verify_callback_called? "" : " authenticated", txt);
188 tls_peerdn = txt;
189 }
190
059ec3d9
PH
191if (!verify_callback_called) tls_certificate_verified = TRUE;
192verify_callback_called = TRUE;
193
194return 1; /* accept */
195}
196
197
198
199/*************************************************
200* Information callback *
201*************************************************/
202
203/* The SSL library functions call this from time to time to indicate what they
204are doing. We copy the string to the debugging output when the level is high
205enough.
206
207Arguments:
208 s the SSL connection
209 where
210 ret
211
212Returns: nothing
213*/
214
215static void
216info_callback(SSL *s, int where, int ret)
217{
218where = where;
219ret = ret;
220DEBUG(D_tls) debug_printf("SSL info: %s\n", SSL_state_string_long(s));
221}
222
223
224
225/*************************************************
226* Initialize for DH *
227*************************************************/
228
229/* If dhparam is set, expand it, and load up the parameters for DH encryption.
230
231Arguments:
232 dhparam DH parameter file
7199e1ee 233 host connected host, if client; NULL if server
059ec3d9
PH
234
235Returns: TRUE if OK (nothing to set up, or setup worked)
236*/
237
238static BOOL
7199e1ee 239init_dh(uschar *dhparam, host_item *host)
059ec3d9
PH
240{
241BOOL yield = TRUE;
242BIO *bio;
243DH *dh;
244uschar *dhexpanded;
245
246if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded))
247 return FALSE;
248
249if (dhexpanded == NULL) return TRUE;
250
251if ((bio = BIO_new_file(CS dhexpanded, "r")) == NULL)
252 {
7199e1ee 253 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
5ca6d115 254 host, (uschar *)strerror(errno));
059ec3d9
PH
255 yield = FALSE;
256 }
257else
258 {
259 if ((dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)) == NULL)
260 {
7199e1ee
TF
261 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
262 host, NULL);
059ec3d9
PH
263 yield = FALSE;
264 }
265 else
266 {
267 SSL_CTX_set_tmp_dh(ctx, dh);
268 DEBUG(D_tls)
269 debug_printf("Diffie-Hellman initialized from %s with %d-bit key\n",
270 dhexpanded, 8*DH_size(dh));
271 DH_free(dh);
272 }
273 BIO_free(bio);
274 }
275
276return yield;
277}
278
279
280
281
282/*************************************************
283* Initialize for TLS *
284*************************************************/
285
286/* Called from both server and client code, to do preliminary initialization of
287the library.
288
289Arguments:
290 host connected host, if client; NULL if server
291 dhparam DH parameter file
292 certificate certificate file
293 privatekey private key
294 addr address if client; NULL if server (for some randomness)
295
296Returns: OK/DEFER/FAIL
297*/
298
299static int
c91535f3
PH
300tls_init(host_item *host, uschar *dhparam, uschar *certificate,
301 uschar *privatekey, address_item *addr)
059ec3d9 302{
77bb000f
PP
303long init_options;
304BOOL okay;
305
059ec3d9
PH
306SSL_load_error_strings(); /* basic set up */
307OpenSSL_add_ssl_algorithms();
308
388d6564 309#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
77bb000f 310/* SHA256 is becoming ever more popular. This makes sure it gets added to the
a0475b69
TK
311list of available digests. */
312EVP_add_digest(EVP_sha256());
cf1ef1a9 313#endif
a0475b69 314
059ec3d9
PH
315/* Create a context */
316
317ctx = SSL_CTX_new((host == NULL)?
318 SSLv23_server_method() : SSLv23_client_method());
319
7199e1ee 320if (ctx == NULL) return tls_error(US"SSL_CTX_new", host, NULL);
059ec3d9
PH
321
322/* It turns out that we need to seed the random number generator this early in
323order to get the full complement of ciphers to work. It took me roughly a day
324of work to discover this by experiment.
325
326On systems that have /dev/urandom, SSL may automatically seed itself from
327there. Otherwise, we have to make something up as best we can. Double check
328afterwards. */
329
330if (!RAND_status())
331 {
332 randstuff r;
9e3331ea 333 gettimeofday(&r.tv, NULL);
059ec3d9
PH
334 r.p = getpid();
335
336 RAND_seed((uschar *)(&r), sizeof(r));
337 RAND_seed((uschar *)big_buffer, big_buffer_size);
338 if (addr != NULL) RAND_seed((uschar *)addr, sizeof(addr));
339
340 if (!RAND_status())
7199e1ee 341 return tls_error(US"RAND_status", host,
5ca6d115 342 US"unable to seed random number generator");
059ec3d9
PH
343 }
344
345/* Set up the information callback, which outputs if debugging is at a suitable
346level. */
347
58c01c94 348SSL_CTX_set_info_callback(ctx, (void (*)())info_callback);
059ec3d9 349
77bb000f
PP
350/* Apply administrator-supplied work-arounds.
351Historically we applied just one requested option,
352SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
353moved to an administrator-controlled list of options to specify and
354grandfathered in the first one as the default value for "openssl_options".
059ec3d9 355
77bb000f
PP
356No OpenSSL version number checks: the options we accept depend upon the
357availability of the option value macros from OpenSSL. */
059ec3d9 358
77bb000f
PP
359okay = tls_openssl_options_parse(openssl_options, &init_options);
360if (!okay)
73a46702 361 return tls_error(US"openssl_options parsing failed", host, NULL);
77bb000f
PP
362
363if (init_options)
364 {
365 DEBUG(D_tls) debug_printf("setting SSL CTX options: %#lx\n", init_options);
366 if (!(SSL_CTX_set_options(ctx, init_options)))
367 return tls_error(string_sprintf(
368 "SSL_CTX_set_option(%#lx)", init_options), host, NULL);
369 }
370else
371 DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
059ec3d9
PH
372
373/* Initialize with DH parameters if supplied */
374
7199e1ee 375if (!init_dh(dhparam, host)) return DEFER;
059ec3d9
PH
376
377/* Set up certificate and key */
378
379if (certificate != NULL)
380 {
381 uschar *expanded;
382 if (!expand_check(certificate, US"tls_certificate", &expanded))
383 return DEFER;
384
385 if (expanded != NULL)
386 {
387 DEBUG(D_tls) debug_printf("tls_certificate file %s\n", expanded);
388 if (!SSL_CTX_use_certificate_chain_file(ctx, CS expanded))
d6453af2 389 return tls_error(string_sprintf(
7199e1ee 390 "SSL_CTX_use_certificate_chain_file file=%s", expanded), host, NULL);
059ec3d9
PH
391 }
392
393 if (privatekey != NULL &&
394 !expand_check(privatekey, US"tls_privatekey", &expanded))
395 return DEFER;
396
c91535f3
PH
397 /* If expansion was forced to fail, key_expanded will be NULL. If the result
398 of the expansion is an empty string, ignore it also, and assume the private
399 key is in the same file as the certificate. */
400
401 if (expanded != NULL && *expanded != 0)
059ec3d9
PH
402 {
403 DEBUG(D_tls) debug_printf("tls_privatekey file %s\n", expanded);
404 if (!SSL_CTX_use_PrivateKey_file(ctx, CS expanded, SSL_FILETYPE_PEM))
d6453af2 405 return tls_error(string_sprintf(
7199e1ee 406 "SSL_CTX_use_PrivateKey_file file=%s", expanded), host, NULL);
059ec3d9
PH
407 }
408 }
409
410/* Set up the RSA callback */
411
412SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
413
414/* Finally, set the timeout, and we are done */
415
416SSL_CTX_set_timeout(ctx, ssl_session_timeout);
417DEBUG(D_tls) debug_printf("Initialized TLS\n");
418return OK;
419}
420
421
422
423
424/*************************************************
425* Get name of cipher in use *
426*************************************************/
427
428/* The answer is left in a static buffer, and tls_cipher is set to point
429to it.
430
431Argument: pointer to an SSL structure for the connection
432Returns: nothing
433*/
434
435static void
436construct_cipher_name(SSL *ssl)
437{
438static uschar cipherbuf[256];
57b3a7f5
PP
439/* With OpenSSL 1.0.0a, this needs to be const but the documentation doesn't
440yet reflect that. It should be a safe change anyway, even 0.9.8 versions have
441the accessor functions use const in the prototype. */
442const SSL_CIPHER *c;
059ec3d9
PH
443uschar *ver;
444int bits;
445
446switch (ssl->session->ssl_version)
447 {
448 case SSL2_VERSION:
449 ver = US"SSLv2";
450 break;
451
452 case SSL3_VERSION:
453 ver = US"SSLv3";
454 break;
455
456 case TLS1_VERSION:
457 ver = US"TLSv1";
458 break;
459
460 default:
461 ver = US"UNKNOWN";
462 }
463
57b3a7f5 464c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
059ec3d9
PH
465SSL_CIPHER_get_bits(c, &bits);
466
467string_format(cipherbuf, sizeof(cipherbuf), "%s:%s:%u", ver,
468 SSL_CIPHER_get_name(c), bits);
469tls_cipher = cipherbuf;
470
471DEBUG(D_tls) debug_printf("Cipher: %s\n", cipherbuf);
472}
473
474
475
476
477
478/*************************************************
479* Set up for verifying certificates *
480*************************************************/
481
482/* Called by both client and server startup
483
484Arguments:
485 certs certs file or NULL
486 crl CRL file or NULL
487 host NULL in a server; the remote host in a client
488 optional TRUE if called from a server for a host in tls_try_verify_hosts;
489 otherwise passed as FALSE
490
491Returns: OK/DEFER/FAIL
492*/
493
494static int
495setup_certs(uschar *certs, uschar *crl, host_item *host, BOOL optional)
496{
497uschar *expcerts, *expcrl;
498
499if (!expand_check(certs, US"tls_verify_certificates", &expcerts))
500 return DEFER;
501
502if (expcerts != NULL)
503 {
504 struct stat statbuf;
505 if (!SSL_CTX_set_default_verify_paths(ctx))
7199e1ee 506 return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL);
059ec3d9
PH
507
508 if (Ustat(expcerts, &statbuf) < 0)
509 {
510 log_write(0, LOG_MAIN|LOG_PANIC,
511 "failed to stat %s for certificates", expcerts);
512 return DEFER;
513 }
514 else
515 {
516 uschar *file, *dir;
517 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
518 { file = NULL; dir = expcerts; }
519 else
520 { file = expcerts; dir = NULL; }
521
522 /* If a certificate file is empty, the next function fails with an
523 unhelpful error message. If we skip it, we get the correct behaviour (no
524 certificates are recognized, but the error message is still misleading (it
525 says no certificate was supplied.) But this is better. */
526
527 if ((file == NULL || statbuf.st_size > 0) &&
528 !SSL_CTX_load_verify_locations(ctx, CS file, CS dir))
7199e1ee 529 return tls_error(US"SSL_CTX_load_verify_locations", host, NULL);
059ec3d9
PH
530
531 if (file != NULL)
532 {
533 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CS file));
534 }
535 }
536
537 /* Handle a certificate revocation list. */
538
539 #if OPENSSL_VERSION_NUMBER > 0x00907000L
540
8b417f2c
PH
541 /* This bit of code is now the version supplied by Lars Mainka. (I have
542 * merely reformatted it into the Exim code style.)
543
544 * "From here I changed the code to add support for multiple crl's
545 * in pem format in one file or to support hashed directory entries in
546 * pem format instead of a file. This method now uses the library function
547 * X509_STORE_load_locations to add the CRL location to the SSL context.
548 * OpenSSL will then handle the verify against CA certs and CRLs by
549 * itself in the verify callback." */
550
059ec3d9
PH
551 if (!expand_check(crl, US"tls_crl", &expcrl)) return DEFER;
552 if (expcrl != NULL && *expcrl != 0)
553 {
8b417f2c
PH
554 struct stat statbufcrl;
555 if (Ustat(expcrl, &statbufcrl) < 0)
556 {
557 log_write(0, LOG_MAIN|LOG_PANIC,
558 "failed to stat %s for certificates revocation lists", expcrl);
559 return DEFER;
560 }
561 else
059ec3d9 562 {
8b417f2c
PH
563 /* is it a file or directory? */
564 uschar *file, *dir;
565 X509_STORE *cvstore = SSL_CTX_get_cert_store(ctx);
566 if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
059ec3d9 567 {
8b417f2c
PH
568 file = NULL;
569 dir = expcrl;
570 DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
059ec3d9
PH
571 }
572 else
573 {
8b417f2c
PH
574 file = expcrl;
575 dir = NULL;
576 DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
059ec3d9 577 }
8b417f2c 578 if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
7199e1ee 579 return tls_error(US"X509_STORE_load_locations", host, NULL);
8b417f2c
PH
580
581 /* setting the flags to check against the complete crl chain */
582
583 X509_STORE_set_flags(cvstore,
584 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
059ec3d9 585 }
059ec3d9
PH
586 }
587
588 #endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
589
590 /* If verification is optional, don't fail if no certificate */
591
592 SSL_CTX_set_verify(ctx,
593 SSL_VERIFY_PEER | (optional? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
594 verify_callback);
595 }
596
597return OK;
598}
599
600
601
602/*************************************************
603* Start a TLS session in a server *
604*************************************************/
605
606/* This is called when Exim is running as a server, after having received
607the STARTTLS command. It must respond to that command, and then negotiate
608a TLS session.
609
610Arguments:
611 require_ciphers allowed ciphers
83da1223
PH
612 ------------------------------------------------------
613 require_mac list of allowed MACs ) Not used
614 require_kx list of allowed key_exchange methods ) for
615 require_proto list of allowed protocols ) OpenSSL
616 ------------------------------------------------------
059ec3d9
PH
617
618Returns: OK on success
619 DEFER for errors before the start of the negotiation
620 FAIL for errors during the negotation; the server can't
621 continue running.
622*/
623
624int
83da1223
PH
625tls_server_start(uschar *require_ciphers, uschar *require_mac,
626 uschar *require_kx, uschar *require_proto)
059ec3d9
PH
627{
628int rc;
629uschar *expciphers;
630
631/* Check for previous activation */
632
633if (tls_active >= 0)
634 {
5ca6d115 635 tls_error(US"STARTTLS received after TLS started", NULL, US"");
059ec3d9
PH
636 smtp_printf("554 Already in TLS\r\n");
637 return FAIL;
638 }
639
640/* Initialize the SSL library. If it fails, it will already have logged
641the error. */
642
643rc = tls_init(NULL, tls_dhparam, tls_certificate, tls_privatekey, NULL);
644if (rc != OK) return rc;
645
646if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers))
647 return FAIL;
648
649/* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
650are separated by underscores. So that I can use either form in my tests, and
651also for general convenience, we turn underscores into hyphens here. */
652
653if (expciphers != NULL)
654 {
655 uschar *s = expciphers;
656 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
657 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
658 if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
7199e1ee 659 return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL);
059ec3d9
PH
660 }
661
662/* If this is a host for which certificate verification is mandatory or
663optional, set up appropriately. */
664
665tls_certificate_verified = FALSE;
666verify_callback_called = FALSE;
667
668if (verify_check_host(&tls_verify_hosts) == OK)
669 {
670 rc = setup_certs(tls_verify_certificates, tls_crl, NULL, FALSE);
671 if (rc != OK) return rc;
672 verify_optional = FALSE;
673 }
674else if (verify_check_host(&tls_try_verify_hosts) == OK)
675 {
676 rc = setup_certs(tls_verify_certificates, tls_crl, NULL, TRUE);
677 if (rc != OK) return rc;
678 verify_optional = TRUE;
679 }
680
681/* Prepare for new connection */
682
7199e1ee 683if ((ssl = SSL_new(ctx)) == NULL) return tls_error(US"SSL_new", NULL, NULL);
059ec3d9
PH
684SSL_clear(ssl);
685
686/* Set context and tell client to go ahead, except in the case of TLS startup
687on connection, where outputting anything now upsets the clients and tends to
688make them disconnect. We need to have an explicit fflush() here, to force out
689the response. Other smtp_printf() calls do not need it, because in non-TLS
690mode, the fflush() happens when smtp_getc() is called. */
691
692SSL_set_session_id_context(ssl, sid_ctx, Ustrlen(sid_ctx));
693if (!tls_on_connect)
694 {
695 smtp_printf("220 TLS go ahead\r\n");
696 fflush(smtp_out);
697 }
698
699/* Now negotiate the TLS session. We put our own timer on it, since it seems
700that the OpenSSL library doesn't. */
701
56f5d9bd
PH
702SSL_set_wfd(ssl, fileno(smtp_out));
703SSL_set_rfd(ssl, fileno(smtp_in));
059ec3d9
PH
704SSL_set_accept_state(ssl);
705
706DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
707
708sigalrm_seen = FALSE;
709if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
710rc = SSL_accept(ssl);
711alarm(0);
712
713if (rc <= 0)
714 {
7199e1ee 715 tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL);
77bb000f
PP
716 if (ERR_get_error() == 0)
717 log_write(0, LOG_MAIN,
a053d125 718 "TLS client disconnected cleanly (rejected our certificate?)");
059ec3d9
PH
719 return FAIL;
720 }
721
722DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
723
724/* TLS has been set up. Adjust the input functions to read via TLS,
725and initialize things. */
726
727construct_cipher_name(ssl);
728
729DEBUG(D_tls)
730 {
731 uschar buf[2048];
732 if (SSL_get_shared_ciphers(ssl, CS buf, sizeof(buf)) != NULL)
733 debug_printf("Shared ciphers: %s\n", buf);
734 }
735
736
737ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
738ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
739ssl_xfer_eof = ssl_xfer_error = 0;
740
741receive_getc = tls_getc;
742receive_ungetc = tls_ungetc;
743receive_feof = tls_feof;
744receive_ferror = tls_ferror;
58eb016e 745receive_smtp_buffered = tls_smtp_buffered;
059ec3d9
PH
746
747tls_active = fileno(smtp_out);
748return OK;
749}
750
751
752
753
754
755/*************************************************
756* Start a TLS session in a client *
757*************************************************/
758
759/* Called from the smtp transport after STARTTLS has been accepted.
760
761Argument:
762 fd the fd of the connection
763 host connected host (for messages)
83da1223 764 addr the first address
059ec3d9
PH
765 dhparam DH parameter file
766 certificate certificate file
767 privatekey private key file
768 verify_certs file for certificate verify
769 crl file containing CRL
770 require_ciphers list of allowed ciphers
83da1223
PH
771 ------------------------------------------------------
772 require_mac list of allowed MACs ) Not used
773 require_kx list of allowed key_exchange methods ) for
774 require_proto list of allowed protocols ) OpenSSL
775 ------------------------------------------------------
776 timeout startup timeout
059ec3d9
PH
777
778Returns: OK on success
779 FAIL otherwise - note that tls_error() will not give DEFER
780 because this is not a server
781*/
782
783int
784tls_client_start(int fd, host_item *host, address_item *addr, uschar *dhparam,
785 uschar *certificate, uschar *privatekey, uschar *verify_certs, uschar *crl,
83da1223
PH
786 uschar *require_ciphers, uschar *require_mac, uschar *require_kx,
787 uschar *require_proto, int timeout)
059ec3d9
PH
788{
789static uschar txt[256];
790uschar *expciphers;
791X509* server_cert;
792int rc;
793
794rc = tls_init(host, dhparam, certificate, privatekey, addr);
795if (rc != OK) return rc;
796
797tls_certificate_verified = FALSE;
798verify_callback_called = FALSE;
799
800if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers))
801 return FAIL;
802
803/* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
804are separated by underscores. So that I can use either form in my tests, and
805also for general convenience, we turn underscores into hyphens here. */
806
807if (expciphers != NULL)
808 {
809 uschar *s = expciphers;
810 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
811 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
812 if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
7199e1ee 813 return tls_error(US"SSL_CTX_set_cipher_list", host, NULL);
059ec3d9
PH
814 }
815
816rc = setup_certs(verify_certs, crl, host, FALSE);
817if (rc != OK) return rc;
818
7199e1ee 819if ((ssl = SSL_new(ctx)) == NULL) return tls_error(US"SSL_new", host, NULL);
059ec3d9
PH
820SSL_set_session_id_context(ssl, sid_ctx, Ustrlen(sid_ctx));
821SSL_set_fd(ssl, fd);
822SSL_set_connect_state(ssl);
823
824/* There doesn't seem to be a built-in timeout on connection. */
825
826DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
827sigalrm_seen = FALSE;
828alarm(timeout);
829rc = SSL_connect(ssl);
830alarm(0);
831
832if (rc <= 0)
7199e1ee 833 return tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL);
059ec3d9
PH
834
835DEBUG(D_tls) debug_printf("SSL_connect succeeded\n");
836
453a6645 837/* Beware anonymous ciphers which lead to server_cert being NULL */
059ec3d9 838server_cert = SSL_get_peer_certificate (ssl);
453a6645
PP
839if (server_cert)
840 {
841 tls_peerdn = US X509_NAME_oneline(X509_get_subject_name(server_cert),
842 CS txt, sizeof(txt));
843 tls_peerdn = txt;
844 }
845else
846 tls_peerdn = NULL;
059ec3d9
PH
847
848construct_cipher_name(ssl); /* Sets tls_cipher */
849
850tls_active = fd;
851return OK;
852}
853
854
855
856
857
858/*************************************************
859* TLS version of getc *
860*************************************************/
861
862/* This gets the next byte from the TLS input buffer. If the buffer is empty,
863it refills the buffer via the SSL reading function.
864
865Arguments: none
866Returns: the next character or EOF
867*/
868
869int
870tls_getc(void)
871{
872if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
873 {
874 int error;
875 int inbytes;
876
877 DEBUG(D_tls) debug_printf("Calling SSL_read(%lx, %lx, %u)\n", (long)ssl,
878 (long)ssl_xfer_buffer, ssl_xfer_buffer_size);
879
880 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
881 inbytes = SSL_read(ssl, CS ssl_xfer_buffer, ssl_xfer_buffer_size);
882 error = SSL_get_error(ssl, inbytes);
883 alarm(0);
884
885 /* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
886 closed down, not that the socket itself has been closed down. Revert to
887 non-SSL handling. */
888
889 if (error == SSL_ERROR_ZERO_RETURN)
890 {
891 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
892
893 receive_getc = smtp_getc;
894 receive_ungetc = smtp_ungetc;
895 receive_feof = smtp_feof;
896 receive_ferror = smtp_ferror;
58eb016e 897 receive_smtp_buffered = smtp_buffered;
059ec3d9
PH
898
899 SSL_free(ssl);
900 ssl = NULL;
901 tls_active = -1;
902 tls_cipher = NULL;
903 tls_peerdn = NULL;
904
905 return smtp_getc();
906 }
907
908 /* Handle genuine errors */
909
ba084640
PP
910 else if (error == SSL_ERROR_SSL)
911 {
912 ERR_error_string(ERR_get_error(), ssl_errstring);
89dd51cd 913 log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
ba084640
PP
914 ssl_xfer_error = 1;
915 return EOF;
916 }
917
059ec3d9
PH
918 else if (error != SSL_ERROR_NONE)
919 {
920 DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
921 ssl_xfer_error = 1;
922 return EOF;
923 }
80a47a2c
TK
924#ifndef DISABLE_DKIM
925 dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
926#endif
059ec3d9
PH
927 ssl_xfer_buffer_hwm = inbytes;
928 ssl_xfer_buffer_lwm = 0;
929 }
930
931/* Something in the buffer; return next uschar */
932
933return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
934}
935
936
937
938/*************************************************
939* Read bytes from TLS channel *
940*************************************************/
941
942/*
943Arguments:
944 buff buffer of data
945 len size of buffer
946
947Returns: the number of bytes read
948 -1 after a failed read
949*/
950
951int
952tls_read(uschar *buff, size_t len)
953{
954int inbytes;
955int error;
956
957DEBUG(D_tls) debug_printf("Calling SSL_read(%lx, %lx, %u)\n", (long)ssl,
958 (long)buff, (unsigned int)len);
959
960inbytes = SSL_read(ssl, CS buff, len);
961error = SSL_get_error(ssl, inbytes);
962
963if (error == SSL_ERROR_ZERO_RETURN)
964 {
965 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
966 return -1;
967 }
968else if (error != SSL_ERROR_NONE)
969 {
970 return -1;
971 }
972
973return inbytes;
974}
975
976
977
978
979
980/*************************************************
981* Write bytes down TLS channel *
982*************************************************/
983
984/*
985Arguments:
986 buff buffer of data
987 len number of bytes
988
989Returns: the number of bytes after a successful write,
990 -1 after a failed write
991*/
992
993int
994tls_write(const uschar *buff, size_t len)
995{
996int outbytes;
997int error;
998int left = len;
999
1000DEBUG(D_tls) debug_printf("tls_do_write(%lx, %d)\n", (long)buff, left);
1001while (left > 0)
1002 {
1003 DEBUG(D_tls) debug_printf("SSL_write(SSL, %lx, %d)\n", (long)buff, left);
1004 outbytes = SSL_write(ssl, CS buff, left);
1005 error = SSL_get_error(ssl, outbytes);
1006 DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
1007 switch (error)
1008 {
1009 case SSL_ERROR_SSL:
1010 ERR_error_string(ERR_get_error(), ssl_errstring);
1011 log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
1012 return -1;
1013
1014 case SSL_ERROR_NONE:
1015 left -= outbytes;
1016 buff += outbytes;
1017 break;
1018
1019 case SSL_ERROR_ZERO_RETURN:
1020 log_write(0, LOG_MAIN, "SSL channel closed on write");
1021 return -1;
1022
1023 default:
1024 log_write(0, LOG_MAIN, "SSL_write error %d", error);
1025 return -1;
1026 }
1027 }
1028return len;
1029}
1030
1031
1032
1033/*************************************************
1034* Close down a TLS session *
1035*************************************************/
1036
1037/* This is also called from within a delivery subprocess forked from the
1038daemon, to shut down the TLS library, without actually doing a shutdown (which
1039would tamper with the SSL session in the parent process).
1040
1041Arguments: TRUE if SSL_shutdown is to be called
1042Returns: nothing
1043*/
1044
1045void
1046tls_close(BOOL shutdown)
1047{
1048if (tls_active < 0) return; /* TLS was not active */
1049
1050if (shutdown)
1051 {
1052 DEBUG(D_tls) debug_printf("tls_close(): shutting down SSL\n");
1053 SSL_shutdown(ssl);
1054 }
1055
1056SSL_free(ssl);
1057ssl = NULL;
1058
1059tls_active = -1;
1060}
1061
36f12725
NM
1062
1063
1064
1065/*************************************************
1066* Report the library versions. *
1067*************************************************/
1068
1069/* There have historically been some issues with binary compatibility in
1070OpenSSL libraries; if Exim (like many other applications) is built against
1071one version of OpenSSL but the run-time linker picks up another version,
1072it can result in serious failures, including crashing with a SIGSEGV. So
1073report the version found by the compiler and the run-time version.
1074
1075Arguments: a FILE* to print the results to
1076Returns: nothing
1077*/
1078
1079void
1080tls_version_report(FILE *f)
1081{
754a0503
PP
1082fprintf(f, "Library version: OpenSSL: Compile: %s\n"
1083 " Runtime: %s\n",
1084 OPENSSL_VERSION_TEXT,
1085 SSLeay_version(SSLEAY_VERSION));
36f12725
NM
1086}
1087
9e3331ea
TK
1088
1089
1090
1091/*************************************************
1092* Pseudo-random number generation *
1093*************************************************/
1094
1095/* Pseudo-random number generation. The result is not expected to be
1096cryptographically strong but not so weak that someone will shoot themselves
1097in the foot using it as a nonce in input in some email header scheme or
1098whatever weirdness they'll twist this into. The result should handle fork()
1099and avoid repeating sequences. OpenSSL handles that for us.
1100
1101Arguments:
1102 max range maximum
1103Returns a random number in range [0, max-1]
1104*/
1105
1106int
1107pseudo_random_number(int max)
1108{
1109unsigned int r;
1110int i, needed_len;
1111uschar *p;
1112uschar smallbuf[sizeof(r)];
1113
1114if (max <= 1)
1115 return 0;
1116
1117/* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
1118if (!RAND_status())
1119 {
1120 randstuff r;
1121 gettimeofday(&r.tv, NULL);
1122 r.p = getpid();
1123
1124 RAND_seed((uschar *)(&r), sizeof(r));
1125 }
1126/* We're after pseudo-random, not random; if we still don't have enough data
1127in the internal PRNG then our options are limited. We could sleep and hope
1128for entropy to come along (prayer technique) but if the system is so depleted
1129in the first place then something is likely to just keep taking it. Instead,
1130we'll just take whatever little bit of pseudo-random we can still manage to
1131get. */
1132
1133needed_len = sizeof(r);
1134/* Don't take 8 times more entropy than needed if int is 8 octets and we were
1135asked for a number less than 10. */
1136for (r = max, i = 0; r; ++i)
1137 r >>= 1;
1138i = (i + 7) / 8;
1139if (i < needed_len)
1140 needed_len = i;
1141
1142/* We do not care if crypto-strong */
1143(void) RAND_pseudo_bytes(smallbuf, needed_len);
1144r = 0;
1145for (p = smallbuf; needed_len; --needed_len, ++p)
1146 {
1147 r *= 256;
1148 r += *p;
1149 }
1150
1151/* We don't particularly care about weighted results; if someone wants
1152smooth distribution and cares enough then they should submit a patch then. */
1153return r % max;
1154}
1155
77bb000f
PP
1156
1157
1158
1159/*************************************************
1160* OpenSSL option parse *
1161*************************************************/
1162
1163/* Parse one option for tls_openssl_options_parse below
1164
1165Arguments:
1166 name one option name
1167 value place to store a value for it
1168Returns success or failure in parsing
1169*/
1170
1171struct exim_openssl_option {
1172 uschar *name;
1173 long value;
1174};
1175/* We could use a macro to expand, but we need the ifdef and not all the
1176options document which version they were introduced in. Policylet: include
1177all options unless explicitly for DTLS, let the administrator choose which
1178to apply.
1179
1180This list is current as of:
c0c7b2da 1181 ==> 1.0.0c <== */
77bb000f
PP
1182static struct exim_openssl_option exim_openssl_options[] = {
1183/* KEEP SORTED ALPHABETICALLY! */
1184#ifdef SSL_OP_ALL
73a46702 1185 { US"all", SSL_OP_ALL },
77bb000f
PP
1186#endif
1187#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
73a46702 1188 { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
77bb000f
PP
1189#endif
1190#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
73a46702 1191 { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
77bb000f
PP
1192#endif
1193#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
73a46702 1194 { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
77bb000f
PP
1195#endif
1196#ifdef SSL_OP_EPHEMERAL_RSA
73a46702 1197 { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
77bb000f
PP
1198#endif
1199#ifdef SSL_OP_LEGACY_SERVER_CONNECT
73a46702 1200 { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
77bb000f
PP
1201#endif
1202#ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
73a46702 1203 { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
77bb000f
PP
1204#endif
1205#ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
73a46702 1206 { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
77bb000f
PP
1207#endif
1208#ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
73a46702 1209 { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
77bb000f
PP
1210#endif
1211#ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
73a46702 1212 { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
77bb000f
PP
1213#endif
1214#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
73a46702 1215 { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
77bb000f
PP
1216#endif
1217#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
73a46702 1218 { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
77bb000f 1219#endif
c0c7b2da
PP
1220#ifdef SSL_OP_NO_SSLv2
1221 { US"no_sslv2", SSL_OP_NO_SSLv2 },
1222#endif
1223#ifdef SSL_OP_NO_SSLv3
1224 { US"no_sslv3", SSL_OP_NO_SSLv3 },
1225#endif
1226#ifdef SSL_OP_NO_TICKET
1227 { US"no_ticket", SSL_OP_NO_TICKET },
1228#endif
1229#ifdef SSL_OP_NO_TLSv1
1230 { US"no_tlsv1", SSL_OP_NO_TLSv1 },
1231#endif
77bb000f 1232#ifdef SSL_OP_SINGLE_DH_USE
73a46702 1233 { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
77bb000f
PP
1234#endif
1235#ifdef SSL_OP_SINGLE_ECDH_USE
73a46702 1236 { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
77bb000f
PP
1237#endif
1238#ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
73a46702 1239 { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
77bb000f
PP
1240#endif
1241#ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
73a46702 1242 { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
77bb000f
PP
1243#endif
1244#ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
73a46702 1245 { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
77bb000f
PP
1246#endif
1247#ifdef SSL_OP_TLS_D5_BUG
73a46702 1248 { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
77bb000f
PP
1249#endif
1250#ifdef SSL_OP_TLS_ROLLBACK_BUG
73a46702 1251 { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
77bb000f
PP
1252#endif
1253};
1254static int exim_openssl_options_size =
1255 sizeof(exim_openssl_options)/sizeof(struct exim_openssl_option);
1256
1257static BOOL
1258tls_openssl_one_option_parse(uschar *name, long *value)
1259{
1260int first = 0;
1261int last = exim_openssl_options_size;
1262while (last > first)
1263 {
1264 int middle = (first + last)/2;
1265 int c = Ustrcmp(name, exim_openssl_options[middle].name);
1266 if (c == 0)
1267 {
1268 *value = exim_openssl_options[middle].value;
1269 return TRUE;
1270 }
1271 else if (c > 0)
1272 first = middle + 1;
1273 else
1274 last = middle;
1275 }
1276return FALSE;
1277}
1278
1279
1280
1281
1282/*************************************************
1283* OpenSSL option parsing logic *
1284*************************************************/
1285
1286/* OpenSSL has a number of compatibility options which an administrator might
1287reasonably wish to set. Interpret a list similarly to decode_bits(), so that
1288we look like log_selector.
1289
1290Arguments:
1291 option_spec the administrator-supplied string of options
1292 results ptr to long storage for the options bitmap
1293Returns success or failure
1294*/
1295
1296BOOL
1297tls_openssl_options_parse(uschar *option_spec, long *results)
1298{
1299long result, item;
1300uschar *s, *end;
1301uschar keep_c;
1302BOOL adding, item_parsed;
1303
0e944a0d 1304result = 0L;
77bb000f
PP
1305/* We grandfather in as default the one option which we used to set always. */
1306#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
0e944a0d 1307result |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
77bb000f
PP
1308#endif
1309
1310if (option_spec == NULL)
1311 {
1312 *results = result;
1313 return TRUE;
1314 }
1315
1316for (s=option_spec; *s != '\0'; /**/)
1317 {
1318 while (isspace(*s)) ++s;
1319 if (*s == '\0')
1320 break;
1321 if (*s != '+' && *s != '-')
1322 {
1323 DEBUG(D_tls) debug_printf("malformed openssl option setting: "
0e944a0d 1324 "+ or - expected but found \"%s\"\n", s);
77bb000f
PP
1325 return FALSE;
1326 }
1327 adding = *s++ == '+';
1328 for (end = s; (*end != '\0') && !isspace(*end); ++end) /**/ ;
1329 keep_c = *end;
1330 *end = '\0';
1331 item_parsed = tls_openssl_one_option_parse(s, &item);
1332 if (!item_parsed)
1333 {
0e944a0d 1334 DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
77bb000f
PP
1335 return FALSE;
1336 }
1337 DEBUG(D_tls) debug_printf("openssl option, %s from %lx: %lx (%s)\n",
1338 adding ? "adding" : "removing", result, item, s);
1339 if (adding)
1340 result |= item;
1341 else
1342 result &= ~item;
1343 *end = keep_c;
1344 s = end;
1345 }
1346
1347*results = result;
1348return TRUE;
1349}
1350
059ec3d9 1351/* End of tls-openssl.c */