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