merge with latest
[external/uw-imap-toolkit.git] / imap-2007e / c-client / ssl_unix.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   if (flags & NET_FORCE_LOWER_TLS_VERSION)
227         SSL_CTX_set_options(stream->context, SSL_OP_NO_SSLv2|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
228   else
229     SSL_CTX_set_options (stream->context,0);
230                                 /* disable certificate validation? */
231   if (flags & NET_NOVALIDATECERT)
232     SSL_CTX_set_verify (stream->context,SSL_VERIFY_NONE,NIL);
233   else SSL_CTX_set_verify (stream->context,SSL_VERIFY_PEER,ssl_open_verify);
234                                 /* set default paths to CAs... */
235   SSL_CTX_set_default_verify_paths (stream->context);
236                                 /* ...unless a non-standard path desired */
237   if (s = (char *) mail_parameters (NIL,GET_SSLCAPATH,NIL))
238     SSL_CTX_load_verify_locations (stream->context,NIL,s);
239                                 /* want to send client certificate? */
240   if (scc && (s = (*scc) ()) && (sl = strlen (s))) {
241     if (cert = PEM_read_bio_X509 (bio = BIO_new_mem_buf (s,sl),NIL,NIL,NIL)) {
242       SSL_CTX_use_certificate (stream->context,cert);
243       X509_free (cert);
244     }
245     BIO_free (bio);
246     if (!cert) return "SSL client certificate failed";
247                                 /* want to supply private key? */
248     if ((t = (sck ? (*sck) () : s)) && (tl = strlen (t))) {
249       EVP_PKEY *key;
250       if (key = PEM_read_bio_PrivateKey (bio = BIO_new_mem_buf (t,tl),
251                                          NIL,NIL,"")) {
252         SSL_CTX_use_PrivateKey (stream->context,key);
253         EVP_PKEY_free (key);
254       }
255       BIO_free (bio);
256       memset (t,0,tl);          /* erase key */
257     }
258     if (s != t) memset (s,0,sl);/* erase certificate if different from key */
259   }
260 \f
261                                 /* create connection */
262   if (!(stream->con = (SSL *) SSL_new (stream->context)))
263     return "SSL connection failed";
264   bio = BIO_new_socket (stream->tcpstream->tcpsi,BIO_NOCLOSE);
265   SSL_set_bio (stream->con,bio,bio);
266   SSL_set_connect_state (stream->con);
267   if (SSL_in_init (stream->con)) SSL_total_renegotiations (stream->con);
268                                 /* now negotiate SSL */
269   if (SSL_write (stream->con,"",0) < 0)
270     return ssl_last_error ? ssl_last_error : "SSL negotiation failed";
271                                 /* need to validate host names? */
272   if (!(flags & NET_NOVALIDATECERT) &&
273       (err = ssl_validate_cert (cert = SSL_get_peer_certificate (stream->con),
274                                 host))) {
275                                 /* application callback */
276     if (scq) return (*scq) (err,host,cert ? cert->name : "???") ? NIL : "";
277                                 /* error message to return via mm_log() */
278     sprintf (tmp,"*%.128s: %.255s",err,cert ? cert->name : "???");
279     return ssl_last_error = cpystr (tmp);
280   }
281   return NIL;
282 }
283 \f
284 /* SSL certificate verification callback
285  * Accepts: error flag
286  *          X509 context
287  * Returns: error flag
288  */
289
290 static int ssl_open_verify (int ok,X509_STORE_CTX *ctx)
291 {
292   char *err,cert[256],tmp[MAILTMPLEN];
293   sslcertificatequery_t scq =
294     (sslcertificatequery_t) mail_parameters (NIL,GET_SSLCERTIFICATEQUERY,NIL);
295   if (!ok) {                    /* in case failure */
296     err = (char *) X509_verify_cert_error_string
297       (X509_STORE_CTX_get_error (ctx));
298     X509_NAME_oneline (X509_get_subject_name
299                        (X509_STORE_CTX_get_current_cert (ctx)),cert,255);
300     if (!scq) {                 /* mm_log() error message if no callback */
301       sprintf (tmp,"*%.128s: %.255s",err,cert);
302       ssl_last_error = cpystr (tmp);
303     }
304                                 /* ignore error if application says to */
305     else if ((*scq) (err,ssl_last_host,cert)) ok = T;
306                                 /* application wants punt */
307     else ssl_last_error = cpystr ("");
308   }
309   return ok;
310 }
311
312
313 /* SSL validate certificate
314  * Accepts: certificate
315  *          host to validate against
316  * Returns: NIL if validated, else string of error message
317  */
318
319 static char *ssl_validate_cert (X509 *cert,char *host)
320 {
321   int i,n;
322   char *s,*t,*ret;
323   void *ext;
324   GENERAL_NAME *name;
325                                 /* make sure have a certificate */
326   if (!cert) ret = "No certificate from server";
327                                 /* and that it has a name */
328   else if (!cert->name) ret = "No name in certificate";
329                                 /* locate CN */
330   else if (s = strstr (cert->name,"/CN=")) {
331     if (t = strchr (s += 4,'/')) *t = '\0';
332                                 /* host name matches pattern? */
333     ret = ssl_compare_hostnames (host,s) ? NIL :
334       "Server name does not match certificate";
335     if (t) *t = '/';            /* restore smashed delimiter */
336                                 /* if mismatch, see if in extensions */
337     if (ret && (ext = X509_get_ext_d2i (cert,NID_subject_alt_name,NIL,NIL)) &&
338         (n = sk_GENERAL_NAME_num (ext)))
339       /* older versions of OpenSSL use "ia5" instead of dNSName */
340       for (i = 0; ret && (i < n); i++)
341         if ((name = sk_GENERAL_NAME_value (ext,i)) &&
342             (name->type = GEN_DNS) && (s = name->d.ia5->data) &&
343             ssl_compare_hostnames (host,s)) ret = NIL;
344   }
345   else ret = "Unable to locate common name in certificate";
346   return ret;
347 }
348 \f
349 /* Case-independent wildcard pattern match
350  * Accepts: base string
351  *          pattern string
352  * Returns: T if pattern matches base, else NIL
353  */
354
355 static long ssl_compare_hostnames (unsigned char *s,unsigned char *pat)
356 {
357   long ret = NIL;
358   switch (*pat) {
359   case '*':                     /* wildcard */
360     if (pat[1]) {               /* there must be a pattern suffix */
361                                 /* there is, scan base against it */
362       do if (ssl_compare_hostnames (s,pat+1)) ret = LONGT;
363       while (!ret && (*s != '.') && *s++);
364     }
365     break;
366   case '\0':                    /* end of pattern */
367     if (!*s) ret = LONGT;       /* success if base is also at end */
368     break;
369   default:                      /* non-wildcard, recurse if match */
370     if (!compare_uchar (*pat,*s)) ret = ssl_compare_hostnames (s+1,pat+1);
371     break;
372   }
373   return ret;
374 }
375 \f
376 /* SSL receive line
377  * Accepts: SSL stream
378  * Returns: text line string or NIL if failure
379  */
380
381 char *ssl_getline (SSLSTREAM *stream)
382 {
383   unsigned long n,contd;
384   char *ret = ssl_getline_work (stream,&n,&contd);
385   if (ret && contd) {           /* got a line needing continuation? */
386     STRINGLIST *stl = mail_newstringlist ();
387     STRINGLIST *stc = stl;
388     do {                        /* collect additional lines */
389       stc->text.data = (unsigned char *) ret;
390       stc->text.size = n;
391       stc = stc->next = mail_newstringlist ();
392       ret = ssl_getline_work (stream,&n,&contd);
393     } while (ret && contd);
394     if (ret) {                  /* stash final part of line on list */
395       stc->text.data = (unsigned char *) ret;
396       stc->text.size = n;
397                                 /* determine how large a buffer we need */
398       for (n = 0, stc = stl; stc; stc = stc->next) n += stc->text.size;
399       ret = fs_get (n + 1);     /* copy parts into buffer */
400       for (n = 0, stc = stl; stc; n += stc->text.size, stc = stc->next)
401         memcpy (ret + n,stc->text.data,stc->text.size);
402       ret[n] = '\0';
403     }
404     mail_free_stringlist (&stl);/* either way, done with list */
405   }
406   return ret;
407 }
408 \f
409 /* SSL receive line or partial line
410  * Accepts: SSL stream
411  *          pointer to return size
412  *          pointer to return continuation flag
413  * Returns: text line string, size and continuation flag, or NIL if failure
414  */
415
416 static char *ssl_getline_work (SSLSTREAM *stream,unsigned long *size,
417                                long *contd)
418 {
419   unsigned long n;
420   char *s,*ret,c,d;
421   *contd = NIL;                 /* assume no continuation */
422                                 /* make sure have data */
423   if (!ssl_getdata (stream)) return NIL;
424   for (s = stream->iptr, n = 0, c = '\0'; stream->ictr--; n++, c = d) {
425     d = *stream->iptr++;        /* slurp another character */
426     if ((c == '\015') && (d == '\012')) {
427       ret = (char *) fs_get (n--);
428       memcpy (ret,s,*size = n); /* copy into a free storage string */
429       ret[n] = '\0';            /* tie off string with null */
430       return ret;
431     }
432   }
433                                 /* copy partial string from buffer */
434   memcpy ((ret = (char *) fs_get (n)),s,*size = n);
435                                 /* get more data from the net */
436   if (!ssl_getdata (stream)) fs_give ((void **) &ret);
437                                 /* special case of newline broken by buffer */
438   else if ((c == '\015') && (*stream->iptr == '\012')) {
439     stream->iptr++;             /* eat the line feed */
440     stream->ictr--;
441     ret[*size = --n] = '\0';    /* tie off string with null */
442   }
443   else *contd = LONGT;          /* continuation needed */
444   return ret;
445 }
446 \f
447 /* SSL receive buffer
448  * Accepts: SSL stream
449  *          size in bytes
450  *          buffer to read into
451  * Returns: T if success, NIL otherwise
452  */
453
454 long ssl_getbuffer (SSLSTREAM *stream,unsigned long size,char *buffer)
455 {
456   unsigned long n;
457   while (size > 0) {            /* until request satisfied */
458     if (!ssl_getdata (stream)) return NIL;
459     n = min (size,stream->ictr);/* number of bytes to transfer */
460                                 /* do the copy */
461     memcpy (buffer,stream->iptr,n);
462     buffer += n;                /* update pointer */
463     stream->iptr += n;
464     size -= n;                  /* update # of bytes to do */
465     stream->ictr -= n;
466   }
467   buffer[0] = '\0';             /* tie off string */
468   return T;
469 }
470 \f
471 /* SSL receive data
472  * Accepts: TCP/IP stream
473  * Returns: T if success, NIL otherwise
474  */
475
476 long ssl_getdata (SSLSTREAM *stream)
477 {
478   int i,sock;
479   fd_set fds,efds;
480   struct timeval tmo;
481   tcptimeout_t tmoh = (tcptimeout_t) mail_parameters (NIL,GET_TIMEOUT,NIL);
482   long ttmo_read = (long) mail_parameters (NIL,GET_READTIMEOUT,NIL);
483   time_t t = time (0);
484   blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
485   if (!stream->con || ((sock = SSL_get_fd (stream->con)) < 0)) return NIL;
486                                 /* tcp_unix should have prevented this */
487   if (sock >= FD_SETSIZE) fatal ("unselectable socket in ssl_getdata()");
488   (*bn) (BLOCK_TCPREAD,NIL);
489   while (stream->ictr < 1) {    /* if nothing in the buffer */
490     time_t tl = time (0);       /* start of request */
491     time_t now = tl;
492     int ti = ttmo_read ? now + ttmo_read : 0;
493     if (SSL_pending (stream->con)) i = 1;
494     else {
495       if (tcpdebug) mm_log ("Reading SSL data",TCPDEBUG);
496       tmo.tv_usec = 0;
497       FD_ZERO (&fds);           /* initialize selection vector */
498       FD_ZERO (&efds);          /* handle errors too */
499       FD_SET (sock,&fds);       /* set bit in selection vector */
500       FD_SET (sock,&efds);      /* set bit in error selection vector */
501       errno = NIL;              /* block and read */
502       do {                      /* block under timeout */
503         tmo.tv_sec = ti ? ti - now : 0;
504         i = select (sock+1,&fds,0,&efds,ti ? &tmo : 0);
505         now = time (0);         /* fake timeout if interrupt & time expired */
506         if ((i < 0) && (errno == EINTR) && ti && (ti <= now)) i = 0;
507       } while ((i < 0) && (errno == EINTR));
508     }
509     if (i) {                    /* non-timeout result from select? */
510       errno = 0;                /* just in case */
511       if (i > 0)                /* read what we can */
512         while (((i = SSL_read (stream->con,stream->ibuf,SSLBUFLEN)) < 0) &&
513                ((errno == EINTR) ||
514                 (SSL_get_error (stream->con,i) == SSL_ERROR_WANT_READ)));
515       if (i <= 0) {             /* error seen? */
516         if (tcpdebug) {
517           char *s,tmp[MAILTMPLEN];
518           if (i) sprintf (s = tmp,"SSL data read I/O error %d SSL error %d",
519                           errno,SSL_get_error (stream->con,i));
520           else s = "SSL data read end of file";
521           mm_log (s,TCPDEBUG);
522         }
523         return ssl_abort (stream);
524       }
525       stream->iptr = stream->ibuf;/* point at TCP buffer */
526       stream->ictr = i;         /* set new byte count */
527       if (tcpdebug) mm_log ("Successfully read SSL data",TCPDEBUG);
528     }
529                                 /* timeout, punt unless told not to */
530     else if (!tmoh || !(*tmoh) (now - t,now - tl)) {
531       if (tcpdebug) mm_log ("SSL data read timeout",TCPDEBUG);
532       return ssl_abort (stream);
533     }
534   }
535   (*bn) (BLOCK_NONE,NIL);
536   return T;
537 }
538 \f
539 /* SSL send string as record
540  * Accepts: SSL stream
541  *          string pointer
542  * Returns: T if success else NIL
543  */
544
545 long ssl_soutr (SSLSTREAM *stream,char *string)
546 {
547   return ssl_sout (stream,string,(unsigned long) strlen (string));
548 }
549
550
551 /* SSL send string
552  * Accepts: SSL stream
553  *          string pointer
554  *          byte count
555  * Returns: T if success else NIL
556  */
557
558 long ssl_sout (SSLSTREAM *stream,char *string,unsigned long size)
559 {
560   long i;
561   blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
562   if (!stream->con) return NIL;
563   (*bn) (BLOCK_TCPWRITE,NIL);
564   if (tcpdebug) mm_log ("Writing to SSL",TCPDEBUG);
565                                 /* until request satisfied */
566   for (i = 0; size > 0; string += i,size -= i)
567                                 /* write as much as we can */
568     if ((i = SSL_write (stream->con,string,(int) min (SSLBUFLEN,size))) < 0) {
569       if (tcpdebug) {
570         char tmp[MAILTMPLEN];
571         sprintf (tmp,"SSL data write I/O error %d SSL error %d",
572                  errno,SSL_get_error (stream->con,i));
573         mm_log (tmp,TCPDEBUG);
574       }
575       return ssl_abort (stream);/* write failed */
576     }
577   if (tcpdebug) mm_log ("successfully wrote to TCP",TCPDEBUG);
578   (*bn) (BLOCK_NONE,NIL);
579   return LONGT;                 /* all done */
580 }
581 \f
582 /* SSL close
583  * Accepts: SSL stream
584  */
585
586 void ssl_close (SSLSTREAM *stream)
587 {
588   ssl_abort (stream);           /* nuke the stream */
589   fs_give ((void **) &stream);  /* flush the stream */
590 }
591
592
593 /* SSL abort stream
594  * Accepts: SSL stream
595  * Returns: NIL always
596  */
597
598 static long ssl_abort (SSLSTREAM *stream)
599 {
600   blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
601   if (stream->con) {            /* close SSL connection */
602     SSL_shutdown (stream->con);
603     SSL_free (stream->con);
604     stream->con = NIL;
605   }
606   if (stream->context) {        /* clean up context */
607     SSL_CTX_free (stream->context);
608     stream->context = NIL;
609   }
610   if (stream->tcpstream) {      /* close TCP stream */
611     tcp_close (stream->tcpstream);
612     stream->tcpstream = NIL;
613   }
614   (*bn) (BLOCK_NONE,NIL);
615   return NIL;
616 }
617 \f
618 /* SSL get host name
619  * Accepts: SSL stream
620  * Returns: host name for this stream
621  */
622
623 char *ssl_host (SSLSTREAM *stream)
624 {
625   return tcp_host (stream->tcpstream);
626 }
627
628
629 /* SSL get remote host name
630  * Accepts: SSL stream
631  * Returns: host name for this stream
632  */
633
634 char *ssl_remotehost (SSLSTREAM *stream)
635 {
636   return tcp_remotehost (stream->tcpstream);
637 }
638
639
640 /* SSL return port for this stream
641  * Accepts: SSL stream
642  * Returns: port number for this stream
643  */
644
645 unsigned long ssl_port (SSLSTREAM *stream)
646 {
647   return tcp_port (stream->tcpstream);
648 }
649
650
651 /* SSL get local host name
652  * Accepts: SSL stream
653  * Returns: local host name
654  */
655
656 char *ssl_localhost (SSLSTREAM *stream)
657 {
658   return tcp_localhost (stream->tcpstream);
659 }
660 \f
661 /* Start TLS
662  * Accepts: /etc/services service name
663  * Returns: cpystr'd error string if TLS failed, else NIL for success
664  */
665
666 char *ssl_start_tls (char *server)
667 {
668   char tmp[MAILTMPLEN];
669   struct stat sbuf;
670   if (sslstdio) return cpystr ("Already in an SSL session");
671   if (start_tls) return cpystr ("TLS already started");
672   if (server) {                 /* build specific certificate/key file name */
673     sprintf (tmp,"%s/%s-%s.pem",SSL_CERT_DIRECTORY,server,tcp_serveraddr ());
674     if (stat (tmp,&sbuf)) {     /* use non-specific name if no specific file */
675       sprintf (tmp,"%s/%s.pem",SSL_CERT_DIRECTORY,server);
676       if (stat (tmp,&sbuf)) return cpystr ("Server certificate not installed");
677     }
678     start_tls = server;         /* switch to STARTTLS mode */
679   }
680   return NIL;
681 }
682 \f
683 /* Init server for SSL
684  * Accepts: server name
685  */
686
687 void ssl_server_init (char *server)
688 {
689   char cert[MAILTMPLEN],key[MAILTMPLEN];
690   unsigned long i;
691   struct stat sbuf;
692   SSLSTREAM *stream = (SSLSTREAM *) memset (fs_get (sizeof (SSLSTREAM)),0,
693                                             sizeof (SSLSTREAM));
694   ssl_onceonlyinit ();          /* make sure algorithms added */
695   ERR_load_crypto_strings ();
696   SSL_load_error_strings ();
697                                 /* build specific certificate/key file names */
698   sprintf (cert,"%s/%s-%s.pem",SSL_CERT_DIRECTORY,server,tcp_serveraddr ());
699   sprintf (key,"%s/%s-%s.pem",SSL_KEY_DIRECTORY,server,tcp_serveraddr ());
700                                 /* use non-specific name if no specific cert */
701   if (stat (cert,&sbuf)) sprintf (cert,"%s/%s.pem",SSL_CERT_DIRECTORY,server);
702   if (stat (key,&sbuf)) {       /* use non-specific name if no specific key */
703     sprintf (key,"%s/%s.pem",SSL_KEY_DIRECTORY,server);
704                                 /* use cert file as fallback for key */
705     if (stat (key,&sbuf)) strcpy (key,cert);
706   }
707                                 /* create context */
708   if (!(stream->context = SSL_CTX_new (start_tls ?
709                                        TLSv1_server_method () :
710                                        SSLv23_server_method ())))
711     syslog (LOG_ALERT,"Unable to create SSL context, host=%.80s",
712             tcp_clienthost ());
713   else {                        /* set context options */
714     SSL_CTX_set_options (stream->context,SSL_OP_ALL);
715                                 /* set cipher list */
716     if (!SSL_CTX_set_cipher_list (stream->context,SSLCIPHERLIST))
717       syslog (LOG_ALERT,"Unable to set cipher list %.80s, host=%.80s",
718               SSLCIPHERLIST,tcp_clienthost ());
719                                 /* load certificate */
720     else if (!SSL_CTX_use_certificate_chain_file (stream->context,cert))
721       syslog (LOG_ALERT,"Unable to load certificate from %.80s, host=%.80s",
722               cert,tcp_clienthost ());
723                                 /* load key */
724     else if (!(SSL_CTX_use_RSAPrivateKey_file (stream->context,key,
725                                                SSL_FILETYPE_PEM)))
726       syslog (LOG_ALERT,"Unable to load private key from %.80s, host=%.80s",
727               key,tcp_clienthost ());
728 \f
729     else {                      /* generate key if needed */
730       if (SSL_CTX_need_tmp_RSA (stream->context))
731         SSL_CTX_set_tmp_rsa_callback (stream->context,ssl_genkey);
732                                 /* create new SSL connection */
733       if (!(stream->con = SSL_new (stream->context)))
734         syslog (LOG_ALERT,"Unable to create SSL connection, host=%.80s",
735                 tcp_clienthost ());
736       else {                    /* set file descriptor */
737         SSL_set_fd (stream->con,0);
738                                 /* all OK if accepted */
739         if (SSL_accept (stream->con) < 0)
740           syslog (LOG_INFO,"Unable to accept SSL connection, host=%.80s",
741                   tcp_clienthost ());
742         else {                  /* server set up */
743           sslstdio = (SSLSTDIOSTREAM *)
744             memset (fs_get (sizeof(SSLSTDIOSTREAM)),0,sizeof (SSLSTDIOSTREAM));
745           sslstdio->sslstream = stream;
746                                 /* available space in output buffer */
747           sslstdio->octr = SSLBUFLEN;
748                                 /* current output buffer pointer */
749           sslstdio->optr = sslstdio->obuf;
750                                 /* allow plaintext if disable value was 2 */
751           if ((long) mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL) > 1)
752             mail_parameters (NIL,SET_DISABLEPLAINTEXT,NIL);
753                                 /* unhide PLAIN SASL authenticator */
754           mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"PLAIN");
755           mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"LOGIN");
756           return;
757         }
758       }
759     }  
760   }
761   while (i = ERR_get_error ())  /* SSL failure */
762     syslog (LOG_ERR,"SSL error status: %.80s",ERR_error_string (i,NIL));
763   ssl_close (stream);           /* punt stream */
764   exit (1);                     /* punt this program too */
765 }
766 \f
767 /* Generate one-time key for server
768  * Accepts: SSL connection
769  *          export flag
770  *          keylength
771  * Returns: generated key, always
772  */
773
774 static RSA *ssl_genkey (SSL *con,int export,int keylength)
775 {
776   unsigned long i;
777   static RSA *key = NIL;
778   if (!key) {                   /* if don't have a key already */
779                                 /* generate key */
780     if (!(key = RSA_generate_key (export ? keylength : 1024,RSA_F4,NIL,NIL))) {
781       syslog (LOG_ALERT,"Unable to generate temp key, host=%.80s",
782               tcp_clienthost ());
783       while (i = ERR_get_error ())
784         syslog (LOG_ALERT,"SSL error status: %s",ERR_error_string (i,NIL));
785       exit (1);
786     }
787   }
788   return key;
789 }
790 \f
791 /* Wait for stdin input
792  * Accepts: timeout in seconds
793  * Returns: T if have input on stdin, else NIL
794  */
795
796 long ssl_server_input_wait (long seconds)
797 {
798   int i,sock;
799   fd_set fds,efd;
800   struct timeval tmo;
801   SSLSTREAM *stream;
802   if (!sslstdio) return server_input_wait (seconds);
803                                 /* input available in buffer */
804   if (((stream = sslstdio->sslstream)->ictr > 0) ||
805       !stream->con || ((sock = SSL_get_fd (stream->con)) < 0)) return LONGT;
806                                 /* sock ought to be 0 always */
807   if (sock >= FD_SETSIZE) fatal ("unselectable socket in ssl_getdata()");
808                                 /* input available from SSL */
809   if (SSL_pending (stream->con) &&
810       ((i = SSL_read (stream->con,stream->ibuf,SSLBUFLEN)) > 0)) {
811     stream->iptr = stream->ibuf;/* point at TCP buffer */
812     stream->ictr = i;           /* set new byte count */
813     return LONGT;
814   }
815   FD_ZERO (&fds);               /* initialize selection vector */
816   FD_ZERO (&efd);               /* initialize selection vector */
817   FD_SET (sock,&fds);           /* set bit in selection vector */
818   FD_SET (sock,&efd);           /* set bit in selection vector */
819   tmo.tv_sec = seconds; tmo.tv_usec = 0;
820                                 /* see if input available from the socket */
821   return select (sock+1,&fds,0,&efd,&tmo) ? LONGT : NIL;
822 }
823
824 #include "sslstdio.c"