imapext-2007

view src/osdep/unix/ssl_unix.c @ 7:a5aee41f2fb9

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

UW-IMAP'd extensions by yuuji