merge with latest
[external/uw-imap-toolkit.git] / imap-2007e / c-client / osdepssl.c
1 /* ========================================================================
2  * Copyright 1988-2008 University of Washington
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * 
11  * ========================================================================
12  */
13
14 /*
15  * Program:     SSL authentication/encryption module
16  *
17  * Author:      Mark Crispin
18  *              Networks and Distributed Computing
19  *              Computing & Communications
20  *              University of Washington
21  *              Administration Building, AG-44
22  *              Seattle, WA  98195
23  *              Internet: MRC@CAC.Washington.EDU
24  *
25  * Date:        22 September 1998
26  * Last Edited: 13 January 2007
27  */
28 \f
29 #define crypt ssl_private_crypt
30 #include <x509v3.h>
31 #include <ssl.h>
32 #include <err.h>
33 #include <pem.h>
34 #include <buffer.h>
35 #include <bio.h>
36 #include <crypto.h>
37 #include <rand.h>
38 #undef crypt
39
40 #define SSLBUFLEN 8192
41 #define SSLCIPHERLIST "ALL:!LOW"
42
43
44 /* SSL I/O stream */
45
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 */
53 } SSLSTREAM;
54
55 #include "sslio.h"
56 \f
57 /* Function prototypes */
58
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,
65                                long *contd);
66 static long ssl_abort (SSLSTREAM *stream);
67 static RSA *ssl_genkey (SSL *con,int export,int keylength);
68
69
70 /* Secure Sockets Layer network driver dispatch */
71
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 */
84 };
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 */
88 \f
89 /* One-time SSL initialization */
90
91 static int sslonceonly = 0;
92
93 void ssl_onceonlyinit (void)
94 {
95   if (!sslonceonly++) {         /* only need to call it once */
96     int fd;
97     char tmp[MAILTMPLEN];
98     struct stat sbuf;
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)
102         sleep (1);
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));
113     }
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 */
118   }
119 }
120 \f
121 /* SSL open
122  * Accepts: host name
123  *          contact service name
124  *          contact port number
125  * Returns: SSL stream if success else NIL
126  */
127
128 SSLSTREAM *ssl_open (char *host,char *service,unsigned long port)
129 {
130   TCPSTREAM *stream = tcp_open (host,service,port);
131   return stream ? ssl_start (stream,host,port) : NIL;
132 }
133
134
135 /* SSL authenticated open
136  * Accepts: host name
137  *          service name
138  *          returned user name buffer
139  * Returns: SSL stream if success else NIL
140  */
141
142 SSLSTREAM *ssl_aopen (NETMBX *mb,char *service,char *usrbuf)
143 {
144   return NIL;                   /* don't use this mechanism with SSL */
145 }
146 \f
147 /* Start SSL/TLS negotiations
148  * Accepts: open TCP stream of session
149  *          user's host name
150  *          flags
151  * Returns: SSL stream if success else NIL
152  */
153
154 static SSLSTREAM *ssl_start (TCPSTREAM *tstream,char *host,unsigned long flags)
155 {
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,
161                                             sizeof (SSLSTREAM));
162   stream->tcpstream = tstream;  /* bind TCP stream */
163                                 /* do the work */
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);
176         mm_log (tmp,ERROR);
177       }
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,
181                                        sizeof (SSLSTREAM));
182       break;
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);
189         mm_log (tmp,ERROR);
190       }
191       break;
192     }
193   }
194   return stream;
195 }
196 \f
197 /* Start SSL/TLS negotiations worker routine
198  * Accepts: SSL stream
199  *          user's host name
200  *          flags
201  * Returns: NIL if success, else error reason
202  */
203
204                                 /* evil but I had no choice */
205 static char *ssl_last_error = NIL;
206 static char *ssl_last_host = NIL;
207
208 static char *ssl_start_work (SSLSTREAM *stream,char *host,unsigned long flags)
209 {
210   BIO *bio;
211   X509 *cert;
212   unsigned long sl,tl;
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);
218   sslclientkey_t sck =
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";
226
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);
229   else
230     SSL_CTX_set_options (stream->context,0);
231
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);
245       X509_free (cert);
246     }
247     BIO_free (bio);
248     if (!cert) return "SSL client certificate failed";
249                                 /* want to supply private key? */
250     if ((t = (sck ? (*sck) () : s)) && (tl = strlen (t))) {
251       EVP_PKEY *key;
252       if (key = PEM_read_bio_PrivateKey (bio = BIO_new_mem_buf (t,tl),
253                                          NIL,NIL,"")) {
254         SSL_CTX_use_PrivateKey (stream->context,key);
255         EVP_PKEY_free (key);
256       }
257       BIO_free (bio);
258       memset (t,0,tl);          /* erase key */
259     }
260     if (s != t) memset (s,0,sl);/* erase certificate if different from key */
261   }
262 \f
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),
276                                 host))) {
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);
282   }
283   return NIL;
284 }
285 \f
286 /* SSL certificate verification callback
287  * Accepts: error flag
288  *          X509 context
289  * Returns: error flag
290  */
291
292 static int ssl_open_verify (int ok,X509_STORE_CTX *ctx)
293 {
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);
305     }
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 ("");
310   }
311   return ok;
312 }
313
314
315 /* SSL validate certificate
316  * Accepts: certificate
317  *          host to validate against
318  * Returns: NIL if validated, else string of error message
319  */
320
321 static char *ssl_validate_cert (X509 *cert,char *host)
322 {
323   int i,n;
324   char *s,*t,*ret;
325   void *ext;
326   GENERAL_NAME *name;
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";
331                                 /* locate CN */
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;
346   }
347   else ret = "Unable to locate common name in certificate";
348   return ret;
349 }
350 \f
351 /* Case-independent wildcard pattern match
352  * Accepts: base string
353  *          pattern string
354  * Returns: T if pattern matches base, else NIL
355  */
356
357 static long ssl_compare_hostnames (unsigned char *s,unsigned char *pat)
358 {
359   long ret = NIL;
360   switch (*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++);
366     }
367     break;
368   case '\0':                    /* end of pattern */
369     if (!*s) ret = LONGT;       /* success if base is also at end */
370     break;
371   default:                      /* non-wildcard, recurse if match */
372     if (!compare_uchar (*pat,*s)) ret = ssl_compare_hostnames (s+1,pat+1);
373     break;
374   }
375   return ret;
376 }
377 \f
378 /* SSL receive line
379  * Accepts: SSL stream
380  * Returns: text line string or NIL if failure
381  */
382
383 char *ssl_getline (SSLSTREAM *stream)
384 {
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;
392       stc->text.size = n;
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;
398       stc->text.size = n;
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);
404       ret[n] = '\0';
405     }
406     mail_free_stringlist (&stl);/* either way, done with list */
407   }
408   return ret;
409 }
410 \f
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
416  */
417
418 static char *ssl_getline_work (SSLSTREAM *stream,unsigned long *size,
419                                long *contd)
420 {
421   unsigned long n;
422   char *s,*ret,c,d;
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 */
432       return ret;
433     }
434   }
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 */
442     stream->ictr--;
443     ret[*size = --n] = '\0';    /* tie off string with null */
444   }
445   else *contd = LONGT;          /* continuation needed */
446   return ret;
447 }
448 \f
449 /* SSL receive buffer
450  * Accepts: SSL stream
451  *          size in bytes
452  *          buffer to read into
453  * Returns: T if success, NIL otherwise
454  */
455
456 long ssl_getbuffer (SSLSTREAM *stream,unsigned long size,char *buffer)
457 {
458   unsigned long n;
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 */
462                                 /* do the copy */
463     memcpy (buffer,stream->iptr,n);
464     buffer += n;                /* update pointer */
465     stream->iptr += n;
466     size -= n;                  /* update # of bytes to do */
467     stream->ictr -= n;
468   }
469   buffer[0] = '\0';             /* tie off string */
470   return T;
471 }
472 \f
473 /* SSL receive data
474  * Accepts: TCP/IP stream
475  * Returns: T if success, NIL otherwise
476  */
477
478 long ssl_getdata (SSLSTREAM *stream)
479 {
480   int i,sock;
481   fd_set fds,efds;
482   struct timeval tmo;
483   tcptimeout_t tmoh = (tcptimeout_t) mail_parameters (NIL,GET_TIMEOUT,NIL);
484   long ttmo_read = (long) mail_parameters (NIL,GET_READTIMEOUT,NIL);
485   time_t t = time (0);
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 */
493     time_t now = tl;
494     int ti = ttmo_read ? now + ttmo_read : 0;
495     if (SSL_pending (stream->con)) i = 1;
496     else {
497       if (tcpdebug) mm_log ("Reading SSL data",TCPDEBUG);
498       tmo.tv_usec = 0;
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));
510     }
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) &&
515                ((errno == EINTR) ||
516                 (SSL_get_error (stream->con,i) == SSL_ERROR_WANT_READ)));
517       if (i <= 0) {             /* error seen? */
518         if (tcpdebug) {
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";
523           mm_log (s,TCPDEBUG);
524         }
525         return ssl_abort (stream);
526       }
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);
530     }
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);
535     }
536   }
537   (*bn) (BLOCK_NONE,NIL);
538   return T;
539 }
540 \f
541 /* SSL send string as record
542  * Accepts: SSL stream
543  *          string pointer
544  * Returns: T if success else NIL
545  */
546
547 long ssl_soutr (SSLSTREAM *stream,char *string)
548 {
549   return ssl_sout (stream,string,(unsigned long) strlen (string));
550 }
551
552
553 /* SSL send string
554  * Accepts: SSL stream
555  *          string pointer
556  *          byte count
557  * Returns: T if success else NIL
558  */
559
560 long ssl_sout (SSLSTREAM *stream,char *string,unsigned long size)
561 {
562   long i;
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) {
571       if (tcpdebug) {
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);
576       }
577       return ssl_abort (stream);/* write failed */
578     }
579   if (tcpdebug) mm_log ("successfully wrote to TCP",TCPDEBUG);
580   (*bn) (BLOCK_NONE,NIL);
581   return LONGT;                 /* all done */
582 }
583 \f
584 /* SSL close
585  * Accepts: SSL stream
586  */
587
588 void ssl_close (SSLSTREAM *stream)
589 {
590   ssl_abort (stream);           /* nuke the stream */
591   fs_give ((void **) &stream);  /* flush the stream */
592 }
593
594
595 /* SSL abort stream
596  * Accepts: SSL stream
597  * Returns: NIL always
598  */
599
600 static long ssl_abort (SSLSTREAM *stream)
601 {
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);
606     stream->con = NIL;
607   }
608   if (stream->context) {        /* clean up context */
609     SSL_CTX_free (stream->context);
610     stream->context = NIL;
611   }
612   if (stream->tcpstream) {      /* close TCP stream */
613     tcp_close (stream->tcpstream);
614     stream->tcpstream = NIL;
615   }
616   (*bn) (BLOCK_NONE,NIL);
617   return NIL;
618 }
619 \f
620 /* SSL get host name
621  * Accepts: SSL stream
622  * Returns: host name for this stream
623  */
624
625 char *ssl_host (SSLSTREAM *stream)
626 {
627   return tcp_host (stream->tcpstream);
628 }
629
630
631 /* SSL get remote host name
632  * Accepts: SSL stream
633  * Returns: host name for this stream
634  */
635
636 char *ssl_remotehost (SSLSTREAM *stream)
637 {
638   return tcp_remotehost (stream->tcpstream);
639 }
640
641
642 /* SSL return port for this stream
643  * Accepts: SSL stream
644  * Returns: port number for this stream
645  */
646
647 unsigned long ssl_port (SSLSTREAM *stream)
648 {
649   return tcp_port (stream->tcpstream);
650 }
651
652
653 /* SSL get local host name
654  * Accepts: SSL stream
655  * Returns: local host name
656  */
657
658 char *ssl_localhost (SSLSTREAM *stream)
659 {
660   return tcp_localhost (stream->tcpstream);
661 }
662 \f
663 /* Start TLS
664  * Accepts: /etc/services service name
665  * Returns: cpystr'd error string if TLS failed, else NIL for success
666  */
667
668 char *ssl_start_tls (char *server)
669 {
670   char tmp[MAILTMPLEN];
671   struct stat sbuf;
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");
679     }
680     start_tls = server;         /* switch to STARTTLS mode */
681   }
682   return NIL;
683 }
684 \f
685 /* Init server for SSL
686  * Accepts: server name
687  */
688
689 void ssl_server_init (char *server)
690 {
691   char cert[MAILTMPLEN],key[MAILTMPLEN];
692   unsigned long i;
693   struct stat sbuf;
694   SSLSTREAM *stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0,
695                                             sizeof (SSLSTREAM));
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);
708   }
709                                 /* create context */
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",
714             tcp_clienthost ());
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 ());
725                                 /* load key */
726     else if (!(SSL_CTX_use_RSAPrivateKey_file (stream->context,key,
727                                                SSL_FILETYPE_PEM)))
728       syslog (LOG_ALERT,"Unable to load private key from %.80s, host=%.80s",
729               key,tcp_clienthost ());
730 \f
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",
737                 tcp_clienthost ());
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",
743                   tcp_clienthost ());
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");
758           return;
759         }
760       }
761     }  
762   }
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 */
767 }
768 \f
769 /* Generate one-time key for server
770  * Accepts: SSL connection
771  *          export flag
772  *          keylength
773  * Returns: generated key, always
774  */
775
776 static RSA *ssl_genkey (SSL *con,int export,int keylength)
777 {
778   unsigned long i;
779   static RSA *key = NIL;
780   if (!key) {                   /* if don't have a key already */
781                                 /* generate key */
782     if (!(key = RSA_generate_key (export ? keylength : 1024,RSA_F4,NIL,NIL))) {
783       syslog (LOG_ALERT,"Unable to generate temp key, host=%.80s",
784               tcp_clienthost ());
785       while (i = ERR_get_error ())
786         syslog (LOG_ALERT,"SSL error status: %s",ERR_error_string (i,NIL));
787       exit (1);
788     }
789   }
790   return key;
791 }
792 \f
793 /* Wait for stdin input
794  * Accepts: timeout in seconds
795  * Returns: T if have input on stdin, else NIL
796  */
797
798 long ssl_server_input_wait (long seconds)
799 {
800   int i,sock;
801   fd_set fds,efd;
802   struct timeval tmo;
803   SSLSTREAM *stream;
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 */
815     return LONGT;
816   }
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;
824 }
825
826 #include "sslstdio.c"