Andreas Krennmair:
[apps/madmutt.git] / mutt_ssl.c
1 /*
2  * Copyright (C) 1999-2001 Tommi Komulainen <Tommi.Komulainen@iki.fi>
3  * 
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  * 
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  * 
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 #if HAVE_CONFIG_H
20 # include "config.h"
21 #endif
22
23 #include <openssl/ssl.h>
24 #include <openssl/x509.h>
25 #include <openssl/err.h>
26 #include <openssl/rand.h>
27
28 #undef _
29
30 #include <string.h>
31
32 #include "mutt.h"
33 #include "mutt_socket.h"
34 #include "mutt_menu.h"
35 #include "mutt_curses.h"
36 #include "mutt_ssl.h"
37
38 #if OPENSSL_VERSION_NUMBER >= 0x00904000L
39 #define READ_X509_KEY(fp, key)  PEM_read_X509(fp, key, NULL, NULL)
40 #else
41 #define READ_X509_KEY(fp, key)  PEM_read_X509(fp, key, NULL)
42 #endif
43
44 /* Just in case OpenSSL doesn't define DEVRANDOM */
45 #ifndef DEVRANDOM
46 #define DEVRANDOM "/dev/urandom"
47 #endif
48
49 /* This is ugly, but as RAND_status came in on OpenSSL version 0.9.5
50  * and the code has to support older versions too, this is seemed to
51  * be cleaner way compared to having even uglier #ifdefs all around.
52  */
53 #ifdef HAVE_RAND_STATUS
54 #define HAVE_ENTROPY()  (RAND_status() == 1)
55 #else
56 static int entropy_byte_count = 0;
57 /* OpenSSL fills the entropy pool from /dev/urandom if it exists */
58 #define HAVE_ENTROPY()  (!access(DEVRANDOM, R_OK) || entropy_byte_count >= 16)
59 #endif
60
61 typedef struct _sslsockdata
62 {
63   SSL_CTX *ctx;
64   SSL *ssl;
65   X509 *cert;
66 }
67 sslsockdata;
68
69 /* local prototypes */
70 int ssl_init (void);
71 static int add_entropy (const char *file);
72 static int ssl_socket_read (CONNECTION* conn, char* buf, size_t len);
73 static int ssl_socket_write (CONNECTION* conn, const char* buf, size_t len);
74 static int ssl_socket_open (CONNECTION * conn);
75 static int ssl_socket_close (CONNECTION * conn);
76 static int tls_close (CONNECTION* conn);
77 static int ssl_check_certificate (sslsockdata * data);
78 static void ssl_get_client_cert(sslsockdata *ssldata, CONNECTION *conn);
79 static int ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
80 static int ssl_negotiate (sslsockdata*);
81
82 /* mutt_ssl_starttls: Negotiate TLS over an already opened connection.
83  *   TODO: Merge this code better with ssl_socket_open. */
84 int mutt_ssl_starttls (CONNECTION* conn)
85 {
86   sslsockdata* ssldata;
87   int maxbits;
88
89   if (ssl_init())
90     goto bail;
91
92   ssldata = (sslsockdata*) safe_calloc (1, sizeof (sslsockdata));
93   /* the ssl_use_xxx protocol options don't apply. We must use TLS in TLS. */
94   if (! (ssldata->ctx = SSL_CTX_new (TLSv1_client_method ())))
95   {
96     dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL_CTX\n"));
97     goto bail_ssldata;
98   }
99
100   ssl_get_client_cert(ssldata, conn);
101
102   if (! (ssldata->ssl = SSL_new (ssldata->ctx)))
103   {
104     dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL\n"));
105     goto bail_ctx;
106   }
107
108   if (SSL_set_fd (ssldata->ssl, conn->fd) != 1)
109   {
110     dprint (1, (debugfile, "mutt_ssl_starttls: Error setting fd\n"));
111     goto bail_ssl;
112   }
113
114   if (ssl_negotiate (ssldata))
115     goto bail_ssl;
116
117   /* hmm. watch out if we're starting TLS over any method other than raw. */
118   conn->sockdata = ssldata;
119   conn->read = ssl_socket_read;
120   conn->write = ssl_socket_write;
121   conn->close = tls_close;
122
123   conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
124     &maxbits);
125
126   return 0;
127
128  bail_ssl:
129   FREE (&ssldata->ssl);
130  bail_ctx:
131   FREE (&ssldata->ctx);
132  bail_ssldata:
133   FREE (&ssldata);
134  bail:
135   return -1;
136 }
137
138 /* 
139  * OpenSSL library needs to be fed with sufficient entropy. On systems
140  * with /dev/urandom, this is done transparently by the library itself,
141  * on other systems we need to fill the entropy pool ourselves.
142  *
143  * Even though only OpenSSL 0.9.5 and later will complain about the
144  * lack of entropy, we try to our best and fill the pool with older
145  * versions also. (That's the reason for the ugly #ifdefs and macros,
146  * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
147  */
148 int ssl_init (void)
149 {
150   char path[_POSIX_PATH_MAX];
151   static unsigned char init_complete = 0;
152
153   if (init_complete)
154     return 0;
155
156   if (! HAVE_ENTROPY())
157   {
158     /* load entropy from files */
159     add_entropy (SslEntropyFile);
160     add_entropy (RAND_file_name (path, sizeof (path)));
161   
162     /* load entropy from egd sockets */
163 #ifdef HAVE_RAND_EGD
164     add_entropy (getenv ("EGDSOCKET"));
165     snprintf (path, sizeof(path), "%s/.entropy", NONULL(Homedir));
166     add_entropy (path);
167     add_entropy ("/tmp/entropy");
168 #endif
169
170     /* shuffle $RANDFILE (or ~/.rnd if unset) */
171     RAND_write_file (RAND_file_name (path, sizeof (path)));
172     mutt_clear_error ();
173     if (! HAVE_ENTROPY())
174     {
175       mutt_error (_("Failed to find enough entropy on your system"));
176       mutt_sleep (2);
177       return -1;
178     }
179   }
180
181   /* I don't think you can do this just before reading the error. The call
182    * itself might clobber the last SSL error. */
183   SSL_load_error_strings();
184   SSL_library_init();
185   init_complete = 1;
186   return 0;
187 }
188
189 static int add_entropy (const char *file)
190 {
191   struct stat st;
192   int n = -1;
193
194   if (!file) return 0;
195
196   if (stat (file, &st) == -1)
197     return errno == ENOENT ? 0 : -1;
198
199   mutt_message (_("Filling entropy pool: %s...\n"),
200                 file);
201   
202   /* check that the file permissions are secure */
203   if (st.st_uid != getuid () || 
204       ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
205       ((st.st_mode & (S_IWOTH | S_IROTH)) != 0))
206   {
207     mutt_error (_("%s has insecure permissions!"), file);
208     mutt_sleep (2);
209     return -1;
210   }
211
212 #ifdef HAVE_RAND_EGD
213   n = RAND_egd (file);
214 #endif
215   if (n <= 0)
216     n = RAND_load_file (file, -1);
217
218 #ifndef HAVE_RAND_STATUS
219   if (n > 0) entropy_byte_count += n;
220 #endif
221   return n;
222 }
223
224 static int ssl_socket_open_err (CONNECTION *conn)
225 {
226   mutt_error (_("SSL disabled due the lack of entropy"));
227   mutt_sleep (2);
228   return -1;
229 }
230
231
232 int ssl_socket_setup (CONNECTION * conn)
233 {
234   if (ssl_init() < 0)
235   {
236     conn->open = ssl_socket_open_err;
237     return -1;
238   }
239
240   conn->open    = ssl_socket_open;
241   conn->read    = ssl_socket_read;
242   conn->write   = ssl_socket_write;
243   conn->close   = ssl_socket_close;
244
245   return 0;
246 }
247
248 static int ssl_socket_read (CONNECTION* conn, char* buf, size_t len)
249 {
250   sslsockdata *data = conn->sockdata;
251   return SSL_read (data->ssl, buf, len);
252 }
253
254 static int ssl_socket_write (CONNECTION* conn, const char* buf, size_t len)
255 {
256   sslsockdata *data = conn->sockdata;
257   return SSL_write (data->ssl, buf, len);
258 }
259
260 static int ssl_socket_open (CONNECTION * conn)
261 {
262   sslsockdata *data;
263   int maxbits;
264
265   if (raw_socket_open (conn) < 0)
266     return -1;
267
268   data = (sslsockdata *) safe_calloc (1, sizeof (sslsockdata));
269   conn->sockdata = data;
270
271   data->ctx = SSL_CTX_new (SSLv23_client_method ());
272
273   /* disable SSL protocols as needed */
274   if (!option(OPTTLSV1)) 
275   {
276     SSL_CTX_set_options(data->ctx, SSL_OP_NO_TLSv1);
277   }
278   if (!option(OPTSSLV2)) 
279   {
280     SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv2);
281   }
282   if (!option(OPTSSLV3)) 
283   {
284     SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv3);
285   }
286
287   ssl_get_client_cert(data, conn);
288
289   data->ssl = SSL_new (data->ctx);
290   SSL_set_fd (data->ssl, conn->fd);
291
292   if (ssl_negotiate(data))
293   {
294     mutt_socket_close (conn);
295     return -1;
296   }
297   
298   conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
299     &maxbits);
300
301   return 0;
302 }
303
304 /* ssl_negotiate: After SSL state has been initialised, attempt to negotiate
305  *   SSL over the wire, including certificate checks. */
306 static int ssl_negotiate (sslsockdata* ssldata)
307 {
308   int err;
309   const char* errmsg;
310
311 #if OPENSSL_VERSION_NUMBER >= 0x00906000L
312   /* This only exists in 0.9.6 and above. Without it we may get interrupted
313    *   reads or writes. Bummer. */
314   SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY);
315 #endif
316
317   if ((err = SSL_connect (ssldata->ssl)) != 1)
318   {
319     switch (SSL_get_error (ssldata->ssl, err))
320     {
321     case SSL_ERROR_SYSCALL:
322       errmsg = _("I/O error");
323       break;
324     case SSL_ERROR_SSL:
325       errmsg = ERR_error_string (ERR_get_error (), NULL);
326       break;
327     default:
328       errmsg = _("unknown error");
329     }
330     
331     mutt_error (_("SSL failed: %s"), errmsg);
332     mutt_sleep (1);
333
334     return -1;
335   }
336
337   ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
338   if (!ssldata->cert)
339   {
340     mutt_error (_("Unable to get certificate from peer"));
341     mutt_sleep (1);
342     return -1;
343   }
344
345   if (!ssl_check_certificate (ssldata))
346     return -1;
347
348   mutt_message (_("SSL connection using %s (%s)"), 
349     SSL_get_cipher_version (ssldata->ssl), SSL_get_cipher_name (ssldata->ssl));
350   mutt_sleep (0);
351
352   return 0;
353 }
354
355 static int ssl_socket_close (CONNECTION * conn)
356 {
357   sslsockdata *data = conn->sockdata;
358   if (data)
359   {
360     SSL_shutdown (data->ssl);
361
362     X509_free (data->cert);
363     SSL_free (data->ssl);
364     SSL_CTX_free (data->ctx);
365     FREE (&conn->sockdata);
366   }
367
368   return raw_socket_close (conn);
369 }
370
371 static int tls_close (CONNECTION* conn)
372 {
373   int rc;
374
375   rc = ssl_socket_close (conn);
376   conn->read = raw_socket_read;
377   conn->write = raw_socket_write;
378   conn->close = raw_socket_close;
379
380   return rc;
381 }
382
383 static char *x509_get_part (char *line, const char *ndx)
384 {
385   static char ret[SHORT_STRING];
386   char *c, *c2;
387
388   strfcpy (ret, _("Unknown"), sizeof (ret));
389
390   c = strstr (line, ndx);
391   if (c)
392   {
393     c += strlen (ndx);
394     c2 = strchr (c, '/');
395     if (c2)
396       *c2 = '\0';
397     strfcpy (ret, c, sizeof (ret));
398     if (c2)
399       *c2 = '/';
400   }
401
402   return ret;
403 }
404
405 static void x509_fingerprint (char *s, int l, X509 * cert)
406 {
407   unsigned char md[EVP_MAX_MD_SIZE];
408   unsigned int n;
409   int j;
410
411   if (!X509_digest (cert, EVP_md5 (), md, &n))
412   {
413     snprintf (s, l, "%s", _("[unable to calculate]"));
414   }
415   else
416   {
417     for (j = 0; j < (int) n; j++)
418     {
419       char ch[8];
420       snprintf (ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
421       safe_strcat (s, l, ch);
422     }
423   }
424 }
425
426 static char *asn1time_to_string (ASN1_UTCTIME *tm)
427 {
428   static char buf[64];
429   BIO *bio;
430
431   strfcpy (buf, _("[invalid date]"), sizeof (buf));
432   
433   bio = BIO_new (BIO_s_mem());
434   if (bio)
435   {
436     if (ASN1_TIME_print (bio, tm))
437       (void) BIO_read (bio, buf, sizeof (buf));
438     BIO_free (bio);
439   }
440
441   return buf;
442 }
443
444 static int check_certificate_by_signer (X509 *peercert)
445 {
446   X509_STORE_CTX xsc;
447   X509_STORE *ctx;
448   int pass = 0;
449
450   ctx = X509_STORE_new ();
451   if (ctx == NULL) return 0;
452
453   if (option (OPTSSLSYSTEMCERTS))
454   {
455     if (X509_STORE_set_default_paths (ctx))
456       pass++;
457     else
458       dprint (2, (debugfile, "X509_STORE_set_default_paths failed\n"));
459   }
460
461   if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
462     pass++;
463   else
464     dprint (2, (debugfile, "X509_STORE_load_locations_failed\n"));
465
466   if (pass == 0)
467   {
468     /* nothing to do */
469     X509_STORE_free (ctx);
470     return 0;
471   }
472
473   X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
474
475   pass = (X509_verify_cert (&xsc) > 0);
476 #ifdef DEBUG
477   if (! pass)
478   {
479     char buf[SHORT_STRING];
480     int err;
481
482     err = X509_STORE_CTX_get_error (&xsc);
483     snprintf (buf, sizeof (buf), "%s (%d)", 
484         X509_verify_cert_error_string(err), err);
485     dprint (2, (debugfile, "X509_verify_cert: %s\n", buf));
486   }
487 #endif
488   X509_STORE_CTX_cleanup (&xsc);
489   X509_STORE_free (ctx);
490
491   return pass;
492 }
493
494 static int check_certificate_by_digest (X509 *peercert)
495 {
496   unsigned char peermd[EVP_MAX_MD_SIZE];
497   unsigned int peermdlen;
498   X509 *cert = NULL;
499   int pass = 0;
500   FILE *fp;
501
502   /* expiration check */
503   if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0)
504   {
505     dprint (2, (debugfile, "Server certificate is not yet valid\n"));
506     mutt_error (_("Server certificate is not yet valid"));
507     mutt_sleep (2);
508     return 0;
509   }
510   if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0)
511   {
512     dprint (2, (debugfile, "Server certificate has expired"));
513     mutt_error (_("Server certificate has expired"));
514     mutt_sleep (2);
515     return 0;
516   }
517
518   if ((fp = fopen (SslCertFile, "rt")) == NULL)
519     return 0;
520
521   if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
522   {
523     fclose (fp);
524     return 0;
525   }
526   
527   while ((cert = READ_X509_KEY (fp, &cert)) != NULL)
528   {
529     unsigned char md[EVP_MAX_MD_SIZE];
530     unsigned int mdlen;
531
532     /* Avoid CPU-intensive digest calculation if the certificates are
533      * not even remotely equal.
534      */
535     if (X509_subject_name_cmp (cert, peercert) != 0 ||
536         X509_issuer_name_cmp (cert, peercert) != 0)
537       continue;
538
539     if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
540       continue;
541     
542     if (memcmp(peermd, md, mdlen) != 0)
543       continue;
544
545     pass = 1;
546     break;
547   }
548   X509_free (cert);
549   fclose (fp);
550
551   return pass;
552 }
553
554 static int ssl_check_certificate (sslsockdata * data)
555 {
556   char *part[] =
557   {"/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C="};
558   char helpstr[SHORT_STRING];
559   char buf[SHORT_STRING];
560   MUTTMENU *menu;
561   int done, row, i;
562   FILE *fp;
563   char *name = NULL, *c;
564
565   if (check_certificate_by_signer (data->cert))
566   {
567     dprint (1, (debugfile, "ssl_check_certificate: signer check passed\n"));
568     return 1;
569   }
570
571   /* automatic check from user's database */
572   if (SslCertFile && check_certificate_by_digest (data->cert))
573   {
574     dprint (1, (debugfile, "ssl_check_certificate: digest check passed\n"));
575     return 1;
576   }
577
578   /* interactive check from user */
579   menu = mutt_new_menu ();
580   menu->max = 19;
581   menu->dialog = (char **) safe_calloc (1, menu->max * sizeof (char *));
582   for (i = 0; i < menu->max; i++)
583     menu->dialog[i] = (char *) safe_calloc (1, SHORT_STRING * sizeof (char));
584
585   row = 0;
586   strfcpy (menu->dialog[row], _("This certificate belongs to:"), SHORT_STRING);
587   row++;
588   name = X509_NAME_oneline (X509_get_subject_name (data->cert),
589                             buf, sizeof (buf));
590   for (i = 0; i < 5; i++)
591   {
592     c = x509_get_part (name, part[i]);
593     snprintf (menu->dialog[row++], SHORT_STRING, "   %s", c);
594   }
595
596   row++;
597   strfcpy (menu->dialog[row], _("This certificate was issued by:"), SHORT_STRING);
598   row++;
599   name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
600                             buf, sizeof (buf));
601   for (i = 0; i < 5; i++)
602   {
603     c = x509_get_part (name, part[i]);
604     snprintf (menu->dialog[row++], SHORT_STRING, "   %s", c);
605   }
606
607   row++;
608   snprintf (menu->dialog[row++], SHORT_STRING, "%s", _("This certificate is valid"));
609   snprintf (menu->dialog[row++], SHORT_STRING, _("   from %s"), 
610       asn1time_to_string (X509_get_notBefore (data->cert)));
611   snprintf (menu->dialog[row++], SHORT_STRING, _("     to %s"), 
612       asn1time_to_string (X509_get_notAfter (data->cert)));
613
614   row++;
615   buf[0] = '\0';
616   x509_fingerprint (buf, sizeof (buf), data->cert);
617   snprintf (menu->dialog[row++], SHORT_STRING, _("Fingerprint: %s"), buf);
618
619   menu->title = _("SSL Certificate check");
620   if (SslCertFile)
621   {
622     menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
623     menu->keys = _("roa");
624   }
625   else
626   {
627     menu->prompt = _("(r)eject, accept (o)nce");
628     menu->keys = _("ro");
629   }
630   
631   helpstr[0] = '\0';
632   mutt_make_help (buf, sizeof (buf), _("Exit  "), MENU_GENERIC, OP_EXIT);
633   safe_strcat (helpstr, sizeof (helpstr), buf);
634   mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
635   safe_strcat (helpstr, sizeof (helpstr), buf);
636   menu->help = helpstr;
637
638   done = 0;
639   set_option(OPTUNBUFFEREDINPUT);
640   while (!done)
641   {
642     switch (mutt_menuLoop (menu))
643     {
644       case -1:                  /* abort */
645       case OP_MAX + 1:          /* reject */
646       case OP_EXIT:
647         done = 1;
648         break;
649       case OP_MAX + 3:          /* accept always */
650         done = 0;
651         if ((fp = fopen (SslCertFile, "a")))
652         {
653           if (PEM_write_X509 (fp, data->cert))
654             done = 1;
655           fclose (fp);
656         }
657         if (!done)
658         {
659           mutt_error (_("Warning: Couldn't save certificate"));
660           mutt_sleep (2);
661         }
662         else
663         {
664           mutt_message (_("Certificate saved"));
665           mutt_sleep (0);
666         }
667         /* fall through */
668       case OP_MAX + 2:          /* accept once */
669         done = 2;
670         break;
671     }
672   }
673   unset_option(OPTUNBUFFEREDINPUT);
674   mutt_menuDestroy (&menu);
675   return (done == 2);
676 }
677
678 static void ssl_get_client_cert(sslsockdata *ssldata, CONNECTION *conn)
679 {
680   if (SslClientCert)
681   {
682     dprint (2, (debugfile, "Using client certificate %s\n", SslClientCert));
683     SSL_CTX_set_default_passwd_cb_userdata(ssldata->ctx, &conn->account);
684     SSL_CTX_set_default_passwd_cb(ssldata->ctx, ssl_passwd_cb);
685     SSL_CTX_use_certificate_file(ssldata->ctx, SslClientCert, SSL_FILETYPE_PEM);
686     SSL_CTX_use_PrivateKey_file(ssldata->ctx, SslClientCert, SSL_FILETYPE_PEM);
687   }
688 }
689
690 static int ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
691 {
692   ACCOUNT *account = (ACCOUNT*)userdata;
693
694   if (mutt_account_getuser (account))
695     return 0;
696
697   dprint (2, (debugfile, "ssl_passwd_cb: getting password for %s@%s:%u\n",
698               account->user, account->host, account->port));
699   
700   if (mutt_account_getpass (account))
701     return 0;
702
703   return snprintf(buf, size, "%s", account->pass);
704 }