1 /* ========================================================================
2 * Copyright 1988-2008 University of Washington
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
11 * ========================================================================
15 * Program: SSL authentication/encryption module
17 * Author: Mark Crispin
18 * Networks and Distributed Computing
19 * Computing & Communications
20 * University of Washington
21 * Administration Building, AG-44
23 * Internet: MRC@CAC.Washington.EDU
25 * Date: 22 September 1998
26 * Last Edited: 13 January 2007
29 #define crypt ssl_private_crypt
40 #define SSLBUFLEN 8192
41 #define SSLCIPHERLIST "ALL:!LOW"
46 typedef struct ssl_stream {
47 TCPSTREAM *tcpstream; /* TCP stream */
48 SSL_CTX *context; /* SSL context */
49 SSL *con; /* SSL connection */
50 int ictr; /* input counter */
51 char *iptr; /* input pointer */
52 char ibuf[SSLBUFLEN]; /* input buffer */
57 /* Function prototypes */
59 static SSLSTREAM *ssl_start(TCPSTREAM *tstream,char *host,unsigned long flags);
60 static char *ssl_start_work (SSLSTREAM *stream,char *host,unsigned long flags);
61 static int ssl_open_verify (int ok,X509_STORE_CTX *ctx);
62 static char *ssl_validate_cert (X509 *cert,char *host);
63 static long ssl_compare_hostnames (unsigned char *s,unsigned char *pat);
64 static char *ssl_getline_work (SSLSTREAM *stream,unsigned long *size,
66 static long ssl_abort (SSLSTREAM *stream);
67 static RSA *ssl_genkey (SSL *con,int export,int keylength);
70 /* Secure Sockets Layer network driver dispatch */
72 static struct ssl_driver ssldriver = {
73 ssl_open, /* open connection */
74 ssl_aopen, /* open preauthenticated connection */
75 ssl_getline, /* get a line */
76 ssl_getbuffer, /* get a buffer */
77 ssl_soutr, /* output pushed data */
78 ssl_sout, /* output string */
79 ssl_close, /* close connection */
80 ssl_host, /* return host name */
81 ssl_remotehost, /* return remote host name */
82 ssl_port, /* return port number */
83 ssl_localhost /* return local host name */
85 /* non-NIL if doing SSL primary I/O */
86 static SSLSTDIOSTREAM *sslstdio = NIL;
87 static char *start_tls = NIL; /* non-NIL if start TLS requested */
89 /* One-time SSL initialization */
91 static int sslonceonly = 0;
93 void ssl_onceonlyinit (void)
95 if (!sslonceonly++) { /* only need to call it once */
99 /* if system doesn't have /dev/urandom */
100 if (stat ("/dev/urandom",&sbuf)) {
101 while ((fd = open (tmpnam (tmp),O_WRONLY|O_CREAT|O_EXCL,0600)) < 0)
103 unlink (tmp); /* don't need the file */
104 fstat (fd,&sbuf); /* get information about the file */
105 close (fd); /* flush descriptor */
106 /* not great but it'll have to do */
107 sprintf (tmp + strlen (tmp),"%.80s%lx%.80s%lx%lx%lx%lx%lx",
108 tcp_serveraddr (),(unsigned long) tcp_serverport (),
109 tcp_clientaddr (),(unsigned long) tcp_clientport (),
110 (unsigned long) sbuf.st_ino,(unsigned long) time (0),
111 (unsigned long) gethostid (),(unsigned long) getpid ());
112 RAND_seed (tmp,strlen (tmp));
114 /* apply runtime linkage */
115 mail_parameters (NIL,SET_SSLDRIVER,(void *) &ssldriver);
116 mail_parameters (NIL,SET_SSLSTART,(void *) ssl_start);
117 SSL_library_init (); /* add all algorithms */
123 * contact service name
124 * contact port number
125 * Returns: SSL stream if success else NIL
128 SSLSTREAM *ssl_open (char *host,char *service,unsigned long port)
130 TCPSTREAM *stream = tcp_open (host,service,port);
131 return stream ? ssl_start (stream,host,port) : NIL;
135 /* SSL authenticated open
138 * returned user name buffer
139 * Returns: SSL stream if success else NIL
142 SSLSTREAM *ssl_aopen (NETMBX *mb,char *service,char *usrbuf)
144 return NIL; /* don't use this mechanism with SSL */
147 /* Start SSL/TLS negotiations
148 * Accepts: open TCP stream of session
151 * Returns: SSL stream if success else NIL
154 static SSLSTREAM *ssl_start (TCPSTREAM *tstream,char *host,unsigned long flags)
156 char *reason,tmp[MAILTMPLEN];
157 sslfailure_t sf = (sslfailure_t) mail_parameters (NIL,GET_SSLFAILURE,NIL);
158 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
159 void *data = (*bn) (BLOCK_SENSITIVE,NIL);
160 SSLSTREAM *stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0,
162 stream->tcpstream = tstream; /* bind TCP stream */
164 reason = ssl_start_work (stream,host,flags);
165 (*bn) (BLOCK_NONSENSITIVE,data);
166 if (reason) { /* failed? */
167 ssl_close (stream); /* failed to do SSL */
168 stream = NIL; /* no stream returned */
169 switch (*reason) { /* analyze reason */
170 case '*': /* certificate failure */
171 ++reason; /* skip over certificate failure indication */
172 /* pass to error callback */
173 if (sf) (*sf) (host,reason,flags);
174 else { /* no error callback, build error message */
175 sprintf (tmp,"Certificate failure for %.80s: %.512s",host,reason);
178 case '\0': /* user answered no to certificate callback */
179 if (flags & NET_TRYSSL) /* return dummy stream to stop tryssl */
180 stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0,
183 default: /* non-certificate failure */
184 if (flags & NET_TRYSSL); /* no error output if tryssl */
185 /* pass to error callback */
186 else if (sf) (*sf) (host,reason,flags);
187 else { /* no error callback, build error message */
188 sprintf (tmp,"TLS/SSL failure for %.80s: %.512s",host,reason);
197 /* Start SSL/TLS negotiations worker routine
198 * Accepts: SSL stream
201 * Returns: NIL if success, else error reason
204 /* evil but I had no choice */
205 static char *ssl_last_error = NIL;
206 static char *ssl_last_host = NIL;
208 static char *ssl_start_work (SSLSTREAM *stream,char *host,unsigned long flags)
213 char *s,*t,*err,tmp[MAILTMPLEN];
214 sslcertificatequery_t scq =
215 (sslcertificatequery_t) mail_parameters (NIL,GET_SSLCERTIFICATEQUERY,NIL);
216 sslclientcert_t scc =
217 (sslclientcert_t) mail_parameters (NIL,GET_SSLCLIENTCERT,NIL);
219 (sslclientkey_t) mail_parameters (NIL,GET_SSLCLIENTKEY,NIL);
220 if (ssl_last_error) fs_give ((void **) &ssl_last_error);
221 ssl_last_host = host;
222 if (!(stream->context = SSL_CTX_new ((flags & NET_TLSCLIENT) ?
223 TLSv1_client_method () :
224 SSLv23_client_method ())))
225 return "SSL context failed";
227 if (flags & NET_FORCE_LOWER_TLS_VERSION)
228 SSL_CTX_set_options(stream->context, SSL_OP_NO_SSLv2|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
230 SSL_CTX_set_options (stream->context,0);
232 /* disable certificate validation? */
233 if (flags & NET_NOVALIDATECERT)
234 SSL_CTX_set_verify (stream->context,SSL_VERIFY_NONE,NIL);
235 else SSL_CTX_set_verify (stream->context,SSL_VERIFY_PEER,ssl_open_verify);
236 /* set default paths to CAs... */
237 SSL_CTX_set_default_verify_paths (stream->context);
238 /* ...unless a non-standard path desired */
239 if (s = (char *) mail_parameters (NIL,GET_SSLCAPATH,NIL))
240 SSL_CTX_load_verify_locations (stream->context,NIL,s);
241 /* want to send client certificate? */
242 if (scc && (s = (*scc) ()) && (sl = strlen (s))) {
243 if (cert = PEM_read_bio_X509 (bio = BIO_new_mem_buf (s,sl),NIL,NIL,NIL)) {
244 SSL_CTX_use_certificate (stream->context,cert);
248 if (!cert) return "SSL client certificate failed";
249 /* want to supply private key? */
250 if ((t = (sck ? (*sck) () : s)) && (tl = strlen (t))) {
252 if (key = PEM_read_bio_PrivateKey (bio = BIO_new_mem_buf (t,tl),
254 SSL_CTX_use_PrivateKey (stream->context,key);
258 memset (t,0,tl); /* erase key */
260 if (s != t) memset (s,0,sl);/* erase certificate if different from key */
263 /* create connection */
264 if (!(stream->con = (SSL *) SSL_new (stream->context)))
265 return "SSL connection failed";
266 bio = BIO_new_socket (stream->tcpstream->tcpsi,BIO_NOCLOSE);
267 SSL_set_bio (stream->con,bio,bio);
268 SSL_set_connect_state (stream->con);
269 if (SSL_in_init (stream->con)) SSL_total_renegotiations (stream->con);
270 /* now negotiate SSL */
271 if (SSL_write (stream->con,"",0) < 0)
272 return ssl_last_error ? ssl_last_error : "SSL negotiation failed";
273 /* need to validate host names? */
274 if (!(flags & NET_NOVALIDATECERT) &&
275 (err = ssl_validate_cert (cert = SSL_get_peer_certificate (stream->con),
277 /* application callback */
278 if (scq) return (*scq) (err,host,cert ? cert->name : "???") ? NIL : "";
279 /* error message to return via mm_log() */
280 sprintf (tmp,"*%.128s: %.255s",err,cert ? cert->name : "???");
281 return ssl_last_error = cpystr (tmp);
286 /* SSL certificate verification callback
287 * Accepts: error flag
289 * Returns: error flag
292 static int ssl_open_verify (int ok,X509_STORE_CTX *ctx)
294 char *err,cert[256],tmp[MAILTMPLEN];
295 sslcertificatequery_t scq =
296 (sslcertificatequery_t) mail_parameters (NIL,GET_SSLCERTIFICATEQUERY,NIL);
297 if (!ok) { /* in case failure */
298 err = (char *) X509_verify_cert_error_string
299 (X509_STORE_CTX_get_error (ctx));
300 X509_NAME_oneline (X509_get_subject_name
301 (X509_STORE_CTX_get_current_cert (ctx)),cert,255);
302 if (!scq) { /* mm_log() error message if no callback */
303 sprintf (tmp,"*%.128s: %.255s",err,cert);
304 ssl_last_error = cpystr (tmp);
306 /* ignore error if application says to */
307 else if ((*scq) (err,ssl_last_host,cert)) ok = T;
308 /* application wants punt */
309 else ssl_last_error = cpystr ("");
315 /* SSL validate certificate
316 * Accepts: certificate
317 * host to validate against
318 * Returns: NIL if validated, else string of error message
321 static char *ssl_validate_cert (X509 *cert,char *host)
327 /* make sure have a certificate */
328 if (!cert) ret = "No certificate from server";
329 /* and that it has a name */
330 else if (!cert->name) ret = "No name in certificate";
332 else if (s = strstr (cert->name,"/CN=")) {
333 if (t = strchr (s += 4,'/')) *t = '\0';
334 /* host name matches pattern? */
335 ret = ssl_compare_hostnames (host,s) ? NIL :
336 "Server name does not match certificate";
337 if (t) *t = '/'; /* restore smashed delimiter */
338 /* if mismatch, see if in extensions */
339 if (ret && (ext = X509_get_ext_d2i (cert,NID_subject_alt_name,NIL,NIL)) &&
340 (n = sk_GENERAL_NAME_num (ext)))
341 /* older versions of OpenSSL use "ia5" instead of dNSName */
342 for (i = 0; ret && (i < n); i++)
343 if ((name = sk_GENERAL_NAME_value (ext,i)) &&
344 (name->type = GEN_DNS) && (s = name->d.ia5->data) &&
345 ssl_compare_hostnames (host,s)) ret = NIL;
347 else ret = "Unable to locate common name in certificate";
351 /* Case-independent wildcard pattern match
352 * Accepts: base string
354 * Returns: T if pattern matches base, else NIL
357 static long ssl_compare_hostnames (unsigned char *s,unsigned char *pat)
361 case '*': /* wildcard */
362 if (pat[1]) { /* there must be a pattern suffix */
363 /* there is, scan base against it */
364 do if (ssl_compare_hostnames (s,pat+1)) ret = LONGT;
365 while (!ret && (*s != '.') && *s++);
368 case '\0': /* end of pattern */
369 if (!*s) ret = LONGT; /* success if base is also at end */
371 default: /* non-wildcard, recurse if match */
372 if (!compare_uchar (*pat,*s)) ret = ssl_compare_hostnames (s+1,pat+1);
379 * Accepts: SSL stream
380 * Returns: text line string or NIL if failure
383 char *ssl_getline (SSLSTREAM *stream)
385 unsigned long n,contd;
386 char *ret = ssl_getline_work (stream,&n,&contd);
387 if (ret && contd) { /* got a line needing continuation? */
388 STRINGLIST *stl = mail_newstringlist ();
389 STRINGLIST *stc = stl;
390 do { /* collect additional lines */
391 stc->text.data = (unsigned char *) ret;
393 stc = stc->next = mail_newstringlist ();
394 ret = ssl_getline_work (stream,&n,&contd);
395 } while (ret && contd);
396 if (ret) { /* stash final part of line on list */
397 stc->text.data = (unsigned char *) ret;
399 /* determine how large a buffer we need */
400 for (n = 0, stc = stl; stc; stc = stc->next) n += stc->text.size;
401 ret = fs_get (n + 1); /* copy parts into buffer */
402 for (n = 0, stc = stl; stc; n += stc->text.size, stc = stc->next)
403 memcpy (ret + n,stc->text.data,stc->text.size);
406 mail_free_stringlist (&stl);/* either way, done with list */
411 /* SSL receive line or partial line
412 * Accepts: SSL stream
413 * pointer to return size
414 * pointer to return continuation flag
415 * Returns: text line string, size and continuation flag, or NIL if failure
418 static char *ssl_getline_work (SSLSTREAM *stream,unsigned long *size,
423 *contd = NIL; /* assume no continuation */
424 /* make sure have data */
425 if (!ssl_getdata (stream)) return NIL;
426 for (s = stream->iptr, n = 0, c = '\0'; stream->ictr--; n++, c = d) {
427 d = *stream->iptr++; /* slurp another character */
428 if ((c == '\015') && (d == '\012')) {
429 ret = (char *) fs_get (n--);
430 memcpy (ret,s,*size = n); /* copy into a free storage string */
431 ret[n] = '\0'; /* tie off string with null */
435 /* copy partial string from buffer */
436 memcpy ((ret = (char *) fs_get (n)),s,*size = n);
437 /* get more data from the net */
438 if (!ssl_getdata (stream)) fs_give ((void **) &ret);
439 /* special case of newline broken by buffer */
440 else if ((c == '\015') && (*stream->iptr == '\012')) {
441 stream->iptr++; /* eat the line feed */
443 ret[*size = --n] = '\0'; /* tie off string with null */
445 else *contd = LONGT; /* continuation needed */
449 /* SSL receive buffer
450 * Accepts: SSL stream
452 * buffer to read into
453 * Returns: T if success, NIL otherwise
456 long ssl_getbuffer (SSLSTREAM *stream,unsigned long size,char *buffer)
459 while (size > 0) { /* until request satisfied */
460 if (!ssl_getdata (stream)) return NIL;
461 n = min (size,stream->ictr);/* number of bytes to transfer */
463 memcpy (buffer,stream->iptr,n);
464 buffer += n; /* update pointer */
466 size -= n; /* update # of bytes to do */
469 buffer[0] = '\0'; /* tie off string */
474 * Accepts: TCP/IP stream
475 * Returns: T if success, NIL otherwise
478 long ssl_getdata (SSLSTREAM *stream)
483 tcptimeout_t tmoh = (tcptimeout_t) mail_parameters (NIL,GET_TIMEOUT,NIL);
484 long ttmo_read = (long) mail_parameters (NIL,GET_READTIMEOUT,NIL);
486 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
487 if (!stream->con || ((sock = SSL_get_fd (stream->con)) < 0)) return NIL;
488 /* tcp_unix should have prevented this */
489 if (sock >= FD_SETSIZE) fatal ("unselectable socket in ssl_getdata()");
490 (*bn) (BLOCK_TCPREAD,NIL);
491 while (stream->ictr < 1) { /* if nothing in the buffer */
492 time_t tl = time (0); /* start of request */
494 int ti = ttmo_read ? now + ttmo_read : 0;
495 if (SSL_pending (stream->con)) i = 1;
497 if (tcpdebug) mm_log ("Reading SSL data",TCPDEBUG);
499 FD_ZERO (&fds); /* initialize selection vector */
500 FD_ZERO (&efds); /* handle errors too */
501 FD_SET (sock,&fds); /* set bit in selection vector */
502 FD_SET (sock,&efds); /* set bit in error selection vector */
503 errno = NIL; /* block and read */
504 do { /* block under timeout */
505 tmo.tv_sec = ti ? ti - now : 0;
506 i = select (sock+1,&fds,0,&efds,ti ? &tmo : 0);
507 now = time (0); /* fake timeout if interrupt & time expired */
508 if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
509 } while ((i < 0) && (errno == EINTR));
511 if (i) { /* non-timeout result from select? */
512 errno = 0; /* just in case */
513 if (i > 0) /* read what we can */
514 while (((i = SSL_read (stream->con,stream->ibuf,SSLBUFLEN)) < 0) &&
516 (SSL_get_error (stream->con,i) == SSL_ERROR_WANT_READ)));
517 if (i <= 0) { /* error seen? */
519 char *s,tmp[MAILTMPLEN];
520 if (i) sprintf (s = tmp,"SSL data read I/O error %d SSL error %d",
521 errno,SSL_get_error (stream->con,i));
522 else s = "SSL data read end of file";
525 return ssl_abort (stream);
527 stream->iptr = stream->ibuf;/* point at TCP buffer */
528 stream->ictr = i; /* set new byte count */
529 if (tcpdebug) mm_log ("Successfully read SSL data",TCPDEBUG);
531 /* timeout, punt unless told not to */
532 else if (!tmoh || !(*tmoh) (now - t,now - tl)) {
533 if (tcpdebug) mm_log ("SSL data read timeout",TCPDEBUG);
534 return ssl_abort (stream);
537 (*bn) (BLOCK_NONE,NIL);
541 /* SSL send string as record
542 * Accepts: SSL stream
544 * Returns: T if success else NIL
547 long ssl_soutr (SSLSTREAM *stream,char *string)
549 return ssl_sout (stream,string,(unsigned long) strlen (string));
554 * Accepts: SSL stream
557 * Returns: T if success else NIL
560 long ssl_sout (SSLSTREAM *stream,char *string,unsigned long size)
563 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
564 if (!stream->con) return NIL;
565 (*bn) (BLOCK_TCPWRITE,NIL);
566 if (tcpdebug) mm_log ("Writing to SSL",TCPDEBUG);
567 /* until request satisfied */
568 for (i = 0; size > 0; string += i,size -= i)
569 /* write as much as we can */
570 if ((i = SSL_write (stream->con,string,(int) min (SSLBUFLEN,size))) < 0) {
572 char tmp[MAILTMPLEN];
573 sprintf (tmp,"SSL data write I/O error %d SSL error %d",
574 errno,SSL_get_error (stream->con,i));
575 mm_log (tmp,TCPDEBUG);
577 return ssl_abort (stream);/* write failed */
579 if (tcpdebug) mm_log ("successfully wrote to TCP",TCPDEBUG);
580 (*bn) (BLOCK_NONE,NIL);
581 return LONGT; /* all done */
585 * Accepts: SSL stream
588 void ssl_close (SSLSTREAM *stream)
590 ssl_abort (stream); /* nuke the stream */
591 fs_give ((void **) &stream); /* flush the stream */
596 * Accepts: SSL stream
597 * Returns: NIL always
600 static long ssl_abort (SSLSTREAM *stream)
602 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
603 if (stream->con) { /* close SSL connection */
604 SSL_shutdown (stream->con);
605 SSL_free (stream->con);
608 if (stream->context) { /* clean up context */
609 SSL_CTX_free (stream->context);
610 stream->context = NIL;
612 if (stream->tcpstream) { /* close TCP stream */
613 tcp_close (stream->tcpstream);
614 stream->tcpstream = NIL;
616 (*bn) (BLOCK_NONE,NIL);
621 * Accepts: SSL stream
622 * Returns: host name for this stream
625 char *ssl_host (SSLSTREAM *stream)
627 return tcp_host (stream->tcpstream);
631 /* SSL get remote host name
632 * Accepts: SSL stream
633 * Returns: host name for this stream
636 char *ssl_remotehost (SSLSTREAM *stream)
638 return tcp_remotehost (stream->tcpstream);
642 /* SSL return port for this stream
643 * Accepts: SSL stream
644 * Returns: port number for this stream
647 unsigned long ssl_port (SSLSTREAM *stream)
649 return tcp_port (stream->tcpstream);
653 /* SSL get local host name
654 * Accepts: SSL stream
655 * Returns: local host name
658 char *ssl_localhost (SSLSTREAM *stream)
660 return tcp_localhost (stream->tcpstream);
664 * Accepts: /etc/services service name
665 * Returns: cpystr'd error string if TLS failed, else NIL for success
668 char *ssl_start_tls (char *server)
670 char tmp[MAILTMPLEN];
672 if (sslstdio) return cpystr ("Already in an SSL session");
673 if (start_tls) return cpystr ("TLS already started");
674 if (server) { /* build specific certificate/key file name */
675 sprintf (tmp,"%s/%s-%s.pem",SSL_CERT_DIRECTORY,server,tcp_serveraddr ());
676 if (stat (tmp,&sbuf)) { /* use non-specific name if no specific file */
677 sprintf (tmp,"%s/%s.pem",SSL_CERT_DIRECTORY,server);
678 if (stat (tmp,&sbuf)) return cpystr ("Server certificate not installed");
680 start_tls = server; /* switch to STARTTLS mode */
685 /* Init server for SSL
686 * Accepts: server name
689 void ssl_server_init (char *server)
691 char cert[MAILTMPLEN],key[MAILTMPLEN];
694 SSLSTREAM *stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0,
696 ssl_onceonlyinit (); /* make sure algorithms added */
697 ERR_load_crypto_strings ();
698 SSL_load_error_strings ();
699 /* build specific certificate/key file names */
700 sprintf (cert,"%s/%s-%s.pem",SSL_CERT_DIRECTORY,server,tcp_serveraddr ());
701 sprintf (key,"%s/%s-%s.pem",SSL_KEY_DIRECTORY,server,tcp_serveraddr ());
702 /* use non-specific name if no specific cert */
703 if (stat (cert,&sbuf)) sprintf (cert,"%s/%s.pem",SSL_CERT_DIRECTORY,server);
704 if (stat (key,&sbuf)) { /* use non-specific name if no specific key */
705 sprintf (key,"%s/%s.pem",SSL_KEY_DIRECTORY,server);
706 /* use cert file as fallback for key */
707 if (stat (key,&sbuf)) strcpy (key,cert);
710 if (!(stream->context = SSL_CTX_new (start_tls ?
711 TLSv1_server_method () :
712 SSLv23_server_method ())))
713 syslog (LOG_ALERT,"Unable to create SSL context, host=%.80s",
715 else { /* set context options */
716 SSL_CTX_set_options (stream->context,SSL_OP_ALL);
717 /* set cipher list */
718 if (!SSL_CTX_set_cipher_list (stream->context,SSLCIPHERLIST))
719 syslog (LOG_ALERT,"Unable to set cipher list %.80s, host=%.80s",
720 SSLCIPHERLIST,tcp_clienthost ());
721 /* load certificate */
722 else if (!SSL_CTX_use_certificate_chain_file (stream->context,cert))
723 syslog (LOG_ALERT,"Unable to load certificate from %.80s, host=%.80s",
724 cert,tcp_clienthost ());
726 else if (!(SSL_CTX_use_RSAPrivateKey_file (stream->context,key,
728 syslog (LOG_ALERT,"Unable to load private key from %.80s, host=%.80s",
729 key,tcp_clienthost ());
731 else { /* generate key if needed */
732 if (SSL_CTX_need_tmp_RSA (stream->context))
733 SSL_CTX_set_tmp_rsa_callback (stream->context,ssl_genkey);
734 /* create new SSL connection */
735 if (!(stream->con = SSL_new (stream->context)))
736 syslog (LOG_ALERT,"Unable to create SSL connection, host=%.80s",
738 else { /* set file descriptor */
739 SSL_set_fd (stream->con,0);
740 /* all OK if accepted */
741 if (SSL_accept (stream->con) < 0)
742 syslog (LOG_INFO,"Unable to accept SSL connection, host=%.80s",
744 else { /* server set up */
745 sslstdio = (SSLSTDIOSTREAM *)
746 memset (fs_get (sizeof(SSLSTDIOSTREAM)),0,sizeof (SSLSTDIOSTREAM));
747 sslstdio->sslstream = stream;
748 /* available space in output buffer */
749 sslstdio->octr = SSLBUFLEN;
750 /* current output buffer pointer */
751 sslstdio->optr = sslstdio->obuf;
752 /* allow plaintext if disable value was 2 */
753 if ((long) mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL) > 1)
754 mail_parameters (NIL,SET_DISABLEPLAINTEXT,NIL);
755 /* unhide PLAIN SASL authenticator */
756 mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"PLAIN");
757 mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"LOGIN");
763 while (i = ERR_get_error ()) /* SSL failure */
764 syslog (LOG_ERR,"SSL error status: %.80s",ERR_error_string (i,NIL));
765 ssl_close (stream); /* punt stream */
766 exit (1); /* punt this program too */
769 /* Generate one-time key for server
770 * Accepts: SSL connection
773 * Returns: generated key, always
776 static RSA *ssl_genkey (SSL *con,int export,int keylength)
779 static RSA *key = NIL;
780 if (!key) { /* if don't have a key already */
782 if (!(key = RSA_generate_key (export ? keylength : 1024,RSA_F4,NIL,NIL))) {
783 syslog (LOG_ALERT,"Unable to generate temp key, host=%.80s",
785 while (i = ERR_get_error ())
786 syslog (LOG_ALERT,"SSL error status: %s",ERR_error_string (i,NIL));
793 /* Wait for stdin input
794 * Accepts: timeout in seconds
795 * Returns: T if have input on stdin, else NIL
798 long ssl_server_input_wait (long seconds)
804 if (!sslstdio) return server_input_wait (seconds);
805 /* input available in buffer */
806 if (((stream = sslstdio->sslstream)->ictr > 0) ||
807 !stream->con || ((sock = SSL_get_fd (stream->con)) < 0)) return LONGT;
808 /* sock ought to be 0 always */
809 if (sock >= FD_SETSIZE) fatal ("unselectable socket in ssl_getdata()");
810 /* input available from SSL */
811 if (SSL_pending (stream->con) &&
812 ((i = SSL_read (stream->con,stream->ibuf,SSLBUFLEN)) > 0)) {
813 stream->iptr = stream->ibuf;/* point at TCP buffer */
814 stream->ictr = i; /* set new byte count */
817 FD_ZERO (&fds); /* initialize selection vector */
818 FD_ZERO (&efd); /* initialize selection vector */
819 FD_SET (sock,&fds); /* set bit in selection vector */
820 FD_SET (sock,&efd); /* set bit in selection vector */
821 tmo.tv_sec = seconds; tmo.tv_usec = 0;
822 /* see if input available from the socket */
823 return select (sock+1,&fds,0,&efd,&tmo) ? LONGT : NIL;
826 #include "sslstdio.c"