imapext-2007

view src/osdep/unix/ssl_unix.c @ 0:ada5e610ab86

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

UW-IMAP'd extensions by yuuji