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