2 * Copyright (C) 1999-2001 Tommi Komulainen <Tommi.Komulainen@iki.fi>
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.
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.
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.
19 /* for SSL NO_* defines */
22 #include <openssl/ssl.h>
23 #include <openssl/x509.h>
24 #include <openssl/err.h>
25 #include <openssl/rand.h>
32 #include "mutt_socket.h"
33 #include "mutt_menu.h"
34 #include "mutt_curses.h"
37 #if OPENSSL_VERSION_NUMBER >= 0x00904000L
38 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL, NULL)
40 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL)
43 /* Just in case OpenSSL doesn't define DEVRANDOM */
45 #define DEVRANDOM "/dev/urandom"
48 /* This is ugly, but as RAND_status came in on OpenSSL version 0.9.5
49 * and the code has to support older versions too, this is seemed to
50 * be cleaner way compared to having even uglier #ifdefs all around.
52 #ifdef HAVE_RAND_STATUS
53 #define HAVE_ENTROPY() (RAND_status() == 1)
55 static int entropy_byte_count = 0;
56 /* OpenSSL fills the entropy pool from /dev/urandom if it exists */
57 #define HAVE_ENTROPY() (!access(DEVRANDOM, R_OK) || entropy_byte_count >= 16)
60 typedef struct _sslsockdata
68 /* local prototypes */
70 static int add_entropy (const char *file);
71 static int ssl_socket_read (CONNECTION* conn, char* buf, size_t len);
72 static int ssl_socket_write (CONNECTION* conn, const char* buf, size_t len);
73 static int ssl_socket_open (CONNECTION * conn);
74 static int ssl_socket_close (CONNECTION * conn);
75 static int tls_close (CONNECTION* conn);
76 static int ssl_check_certificate (sslsockdata * data);
77 static void ssl_get_client_cert(sslsockdata *ssldata, CONNECTION *conn);
78 static int ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
79 static int ssl_negotiate (sslsockdata*);
81 /* mutt_ssl_starttls: Negotiate TLS over an already opened connection.
82 * TODO: Merge this code better with ssl_socket_open. */
83 int mutt_ssl_starttls (CONNECTION* conn)
91 ssldata = (sslsockdata*) safe_calloc (1, sizeof (sslsockdata));
92 /* the ssl_use_xxx protocol options don't apply. We must use TLS in TLS. */
93 if (! (ssldata->ctx = SSL_CTX_new (TLSv1_client_method ())))
95 dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL_CTX\n"));
99 ssl_get_client_cert(ssldata, conn);
101 if (! (ssldata->ssl = SSL_new (ssldata->ctx)))
103 dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL\n"));
107 if (SSL_set_fd (ssldata->ssl, conn->fd) != 1)
109 dprint (1, (debugfile, "mutt_ssl_starttls: Error setting fd\n"));
113 if (ssl_negotiate (ssldata))
116 /* hmm. watch out if we're starting TLS over any method other than raw. */
117 conn->sockdata = ssldata;
118 conn->read = ssl_socket_read;
119 conn->write = ssl_socket_write;
120 conn->close = tls_close;
122 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
128 FREE (&ssldata->ssl);
130 FREE (&ssldata->ctx);
138 * OpenSSL library needs to be fed with sufficient entropy. On systems
139 * with /dev/urandom, this is done transparently by the library itself,
140 * on other systems we need to fill the entropy pool ourselves.
142 * Even though only OpenSSL 0.9.5 and later will complain about the
143 * lack of entropy, we try to our best and fill the pool with older
144 * versions also. (That's the reason for the ugly #ifdefs and macros,
145 * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
149 char path[_POSIX_PATH_MAX];
150 static unsigned char init_complete = 0;
155 if (! HAVE_ENTROPY())
157 /* load entropy from files */
158 add_entropy (SslEntropyFile);
159 add_entropy (RAND_file_name (path, sizeof (path)));
161 /* load entropy from egd sockets */
163 add_entropy (getenv ("EGDSOCKET"));
164 snprintf (path, sizeof(path), "%s/.entropy", NONULL(Homedir));
166 add_entropy ("/tmp/entropy");
169 /* shuffle $RANDFILE (or ~/.rnd if unset) */
170 RAND_write_file (RAND_file_name (path, sizeof (path)));
172 if (! HAVE_ENTROPY())
174 mutt_error (_("Failed to find enough entropy on your system"));
180 /* I don't think you can do this just before reading the error. The call
181 * itself might clobber the last SSL error. */
182 SSL_load_error_strings();
188 static int add_entropy (const char *file)
195 if (stat (file, &st) == -1)
196 return errno == ENOENT ? 0 : -1;
198 mutt_message (_("Filling entropy pool: %s...\n"),
201 /* check that the file permissions are secure */
202 if (st.st_uid != getuid () ||
203 ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
204 ((st.st_mode & (S_IWOTH | S_IROTH)) != 0))
206 mutt_error (_("%s has insecure permissions!"), file);
215 n = RAND_load_file (file, -1);
217 #ifndef HAVE_RAND_STATUS
218 if (n > 0) entropy_byte_count += n;
223 static int ssl_socket_open_err (CONNECTION *conn)
225 mutt_error (_("SSL disabled due the lack of entropy"));
231 int ssl_socket_setup (CONNECTION * conn)
235 conn->open = ssl_socket_open_err;
239 conn->open = ssl_socket_open;
240 conn->read = ssl_socket_read;
241 conn->write = ssl_socket_write;
242 conn->close = ssl_socket_close;
247 static int ssl_socket_read (CONNECTION* conn, char* buf, size_t len)
249 sslsockdata *data = conn->sockdata;
250 return SSL_read (data->ssl, buf, len);
253 static int ssl_socket_write (CONNECTION* conn, const char* buf, size_t len)
255 sslsockdata *data = conn->sockdata;
256 return SSL_write (data->ssl, buf, len);
259 static int ssl_socket_open (CONNECTION * conn)
264 if (raw_socket_open (conn) < 0)
267 data = (sslsockdata *) safe_calloc (1, sizeof (sslsockdata));
268 conn->sockdata = data;
270 data->ctx = SSL_CTX_new (SSLv23_client_method ());
272 /* disable SSL protocols as needed */
273 if (!option(OPTTLSV1))
275 SSL_CTX_set_options(data->ctx, SSL_OP_NO_TLSv1);
277 if (!option(OPTSSLV2))
279 SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv2);
281 if (!option(OPTSSLV3))
283 SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv3);
286 ssl_get_client_cert(data, conn);
288 data->ssl = SSL_new (data->ctx);
289 SSL_set_fd (data->ssl, conn->fd);
291 if (ssl_negotiate(data))
293 mutt_socket_close (conn);
297 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
303 /* ssl_negotiate: After SSL state has been initialised, attempt to negotiate
304 * SSL over the wire, including certificate checks. */
305 static int ssl_negotiate (sslsockdata* ssldata)
310 #if OPENSSL_VERSION_NUMBER >= 0x00906000L
311 /* This only exists in 0.9.6 and above. Without it we may get interrupted
312 * reads or writes. Bummer. */
313 SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY);
316 if ((err = SSL_connect (ssldata->ssl)) != 1)
318 switch (SSL_get_error (ssldata->ssl, err))
320 case SSL_ERROR_SYSCALL:
321 errmsg = _("I/O error");
324 errmsg = ERR_error_string (ERR_get_error (), NULL);
327 errmsg = _("unknown error");
330 mutt_error (_("SSL failed: %s"), errmsg);
336 ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
339 mutt_error (_("Unable to get certificate from peer"));
344 if (!ssl_check_certificate (ssldata))
347 mutt_message (_("SSL connection using %s (%s)"),
348 SSL_get_cipher_version (ssldata->ssl), SSL_get_cipher_name (ssldata->ssl));
354 static int ssl_socket_close (CONNECTION * conn)
356 sslsockdata *data = conn->sockdata;
359 SSL_shutdown (data->ssl);
361 X509_free (data->cert);
362 SSL_free (data->ssl);
363 SSL_CTX_free (data->ctx);
364 FREE (&conn->sockdata);
367 return raw_socket_close (conn);
370 static int tls_close (CONNECTION* conn)
374 rc = ssl_socket_close (conn);
375 conn->read = raw_socket_read;
376 conn->write = raw_socket_write;
377 conn->close = raw_socket_close;
382 static char *x509_get_part (char *line, const char *ndx)
384 static char ret[SHORT_STRING];
387 strfcpy (ret, _("Unknown"), sizeof (ret));
389 c = strstr (line, ndx);
393 c2 = strchr (c, '/');
396 strfcpy (ret, c, sizeof (ret));
404 static void x509_fingerprint (char *s, int l, X509 * cert)
406 unsigned char md[EVP_MAX_MD_SIZE];
410 if (!X509_digest (cert, EVP_md5 (), md, &n))
412 snprintf (s, l, "%s", _("[unable to calculate]"));
416 for (j = 0; j < (int) n; j++)
419 snprintf (ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
420 safe_strcat (s, l, ch);
425 static char *asn1time_to_string (ASN1_UTCTIME *tm)
430 strfcpy (buf, _("[invalid date]"), sizeof (buf));
432 bio = BIO_new (BIO_s_mem());
435 if (ASN1_TIME_print (bio, tm))
436 (void) BIO_read (bio, buf, sizeof (buf));
443 static int check_certificate_by_signer (X509 *peercert)
449 ctx = X509_STORE_new ();
450 if (ctx == NULL) return 0;
452 if (option (OPTSSLSYSTEMCERTS))
454 if (X509_STORE_set_default_paths (ctx))
457 dprint (2, (debugfile, "X509_STORE_set_default_paths failed\n"));
460 if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
463 dprint (2, (debugfile, "X509_STORE_load_locations_failed\n"));
468 X509_STORE_free (ctx);
472 X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
474 pass = (X509_verify_cert (&xsc) > 0);
478 char buf[SHORT_STRING];
481 err = X509_STORE_CTX_get_error (&xsc);
482 snprintf (buf, sizeof (buf), "%s (%d)",
483 X509_verify_cert_error_string(err), err);
484 dprint (2, (debugfile, "X509_verify_cert: %s\n", buf));
487 X509_STORE_CTX_cleanup (&xsc);
488 X509_STORE_free (ctx);
493 static int check_certificate_by_digest (X509 *peercert)
495 unsigned char peermd[EVP_MAX_MD_SIZE];
496 unsigned int peermdlen;
501 /* expiration check */
502 if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0)
504 dprint (2, (debugfile, "Server certificate is not yet valid\n"));
505 mutt_error (_("Server certificate is not yet valid"));
509 if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0)
511 dprint (2, (debugfile, "Server certificate has expired"));
512 mutt_error (_("Server certificate has expired"));
517 if ((fp = fopen (SslCertFile, "rt")) == NULL)
520 if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
526 while ((cert = READ_X509_KEY (fp, &cert)) != NULL)
528 unsigned char md[EVP_MAX_MD_SIZE];
531 /* Avoid CPU-intensive digest calculation if the certificates are
532 * not even remotely equal.
534 if (X509_subject_name_cmp (cert, peercert) != 0 ||
535 X509_issuer_name_cmp (cert, peercert) != 0)
538 if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
541 if (memcmp(peermd, md, mdlen) != 0)
553 static int ssl_check_certificate (sslsockdata * data)
556 {"/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C="};
557 char helpstr[SHORT_STRING];
558 char buf[SHORT_STRING];
562 char *name = NULL, *c;
564 if (check_certificate_by_signer (data->cert))
566 dprint (1, (debugfile, "ssl_check_certificate: signer check passed\n"));
570 /* automatic check from user's database */
571 if (SslCertFile && check_certificate_by_digest (data->cert))
573 dprint (1, (debugfile, "ssl_check_certificate: digest check passed\n"));
577 /* interactive check from user */
578 menu = mutt_new_menu ();
580 menu->dialog = (char **) safe_calloc (1, menu->max * sizeof (char *));
581 for (i = 0; i < menu->max; i++)
582 menu->dialog[i] = (char *) safe_calloc (1, SHORT_STRING * sizeof (char));
585 strfcpy (menu->dialog[row], _("This certificate belongs to:"), SHORT_STRING);
587 name = X509_NAME_oneline (X509_get_subject_name (data->cert),
589 for (i = 0; i < 5; i++)
591 c = x509_get_part (name, part[i]);
592 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
596 strfcpy (menu->dialog[row], _("This certificate was issued by:"), SHORT_STRING);
598 name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
600 for (i = 0; i < 5; i++)
602 c = x509_get_part (name, part[i]);
603 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
607 snprintf (menu->dialog[row++], SHORT_STRING, "%s", _("This certificate is valid"));
608 snprintf (menu->dialog[row++], SHORT_STRING, _(" from %s"),
609 asn1time_to_string (X509_get_notBefore (data->cert)));
610 snprintf (menu->dialog[row++], SHORT_STRING, _(" to %s"),
611 asn1time_to_string (X509_get_notAfter (data->cert)));
615 x509_fingerprint (buf, sizeof (buf), data->cert);
616 snprintf (menu->dialog[row++], SHORT_STRING, _("Fingerprint: %s"), buf);
618 menu->title = _("SSL Certificate check");
621 menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
622 menu->keys = _("roa");
626 menu->prompt = _("(r)eject, accept (o)nce");
627 menu->keys = _("ro");
631 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_GENERIC, OP_EXIT);
632 safe_strcat (helpstr, sizeof (helpstr), buf);
633 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
634 safe_strcat (helpstr, sizeof (helpstr), buf);
635 menu->help = helpstr;
638 set_option(OPTUNBUFFEREDINPUT);
641 switch (mutt_menuLoop (menu))
644 case OP_MAX + 1: /* reject */
648 case OP_MAX + 3: /* accept always */
650 if ((fp = fopen (SslCertFile, "a")))
652 if (PEM_write_X509 (fp, data->cert))
658 mutt_error (_("Warning: Couldn't save certificate"));
663 mutt_message (_("Certificate saved"));
667 case OP_MAX + 2: /* accept once */
672 unset_option(OPTUNBUFFEREDINPUT);
673 mutt_menuDestroy (&menu);
677 static void ssl_get_client_cert(sslsockdata *ssldata, CONNECTION *conn)
681 dprint (2, (debugfile, "Using client certificate %s\n", SslClientCert));
682 SSL_CTX_set_default_passwd_cb_userdata(ssldata->ctx, &conn->account);
683 SSL_CTX_set_default_passwd_cb(ssldata->ctx, ssl_passwd_cb);
684 SSL_CTX_use_certificate_file(ssldata->ctx, SslClientCert, SSL_FILETYPE_PEM);
685 SSL_CTX_use_PrivateKey_file(ssldata->ctx, SslClientCert, SSL_FILETYPE_PEM);
689 static int ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
691 ACCOUNT *account = (ACCOUNT*)userdata;
693 if (mutt_account_getuser (account))
696 dprint (2, (debugfile, "ssl_passwd_cb: getting password for %s@%s:%u\n",
697 account->user, account->host, account->port));
699 if (mutt_account_getpass (account))
702 return snprintf(buf, size, "%s", account->pass);