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