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.
23 #include <openssl/ssl.h>
24 #include <openssl/x509.h>
25 #include <openssl/err.h>
26 #include <openssl/rand.h>
33 #include "mutt_socket.h"
34 #include "mutt_menu.h"
35 #include "mutt_curses.h"
38 #if OPENSSL_VERSION_NUMBER >= 0x00904000L
39 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL, NULL)
41 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL)
44 /* Just in case OpenSSL doesn't define DEVRANDOM */
46 #define DEVRANDOM "/dev/urandom"
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.
53 #ifdef HAVE_RAND_STATUS
54 #define HAVE_ENTROPY() (RAND_status() == 1)
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)
61 typedef struct _sslsockdata
69 /* local prototypes */
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*);
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)
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 ())))
96 dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL_CTX\n"));
100 ssl_get_client_cert(ssldata, conn);
102 if (! (ssldata->ssl = SSL_new (ssldata->ctx)))
104 dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL\n"));
108 if (SSL_set_fd (ssldata->ssl, conn->fd) != 1)
110 dprint (1, (debugfile, "mutt_ssl_starttls: Error setting fd\n"));
114 if (ssl_negotiate (ssldata))
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;
123 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
129 FREE (&ssldata->ssl);
131 FREE (&ssldata->ctx);
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.
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)
150 char path[_POSIX_PATH_MAX];
151 static unsigned char init_complete = 0;
156 if (! HAVE_ENTROPY())
158 /* load entropy from files */
159 add_entropy (SslEntropyFile);
160 add_entropy (RAND_file_name (path, sizeof (path)));
162 /* load entropy from egd sockets */
164 add_entropy (getenv ("EGDSOCKET"));
165 snprintf (path, sizeof(path), "%s/.entropy", NONULL(Homedir));
167 add_entropy ("/tmp/entropy");
170 /* shuffle $RANDFILE (or ~/.rnd if unset) */
171 RAND_write_file (RAND_file_name (path, sizeof (path)));
173 if (! HAVE_ENTROPY())
175 mutt_error (_("Failed to find enough entropy on your system"));
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();
189 static int add_entropy (const char *file)
196 if (stat (file, &st) == -1)
197 return errno == ENOENT ? 0 : -1;
199 mutt_message (_("Filling entropy pool: %s...\n"),
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))
207 mutt_error (_("%s has insecure permissions!"), file);
216 n = RAND_load_file (file, -1);
218 #ifndef HAVE_RAND_STATUS
219 if (n > 0) entropy_byte_count += n;
224 static int ssl_socket_open_err (CONNECTION *conn)
226 mutt_error (_("SSL disabled due the lack of entropy"));
232 int ssl_socket_setup (CONNECTION * conn)
236 conn->open = ssl_socket_open_err;
240 conn->open = ssl_socket_open;
241 conn->read = ssl_socket_read;
242 conn->write = ssl_socket_write;
243 conn->close = ssl_socket_close;
248 static int ssl_socket_read (CONNECTION* conn, char* buf, size_t len)
250 sslsockdata *data = conn->sockdata;
251 return SSL_read (data->ssl, buf, len);
254 static int ssl_socket_write (CONNECTION* conn, const char* buf, size_t len)
256 sslsockdata *data = conn->sockdata;
257 return SSL_write (data->ssl, buf, len);
260 static int ssl_socket_open (CONNECTION * conn)
265 if (raw_socket_open (conn) < 0)
268 data = (sslsockdata *) safe_calloc (1, sizeof (sslsockdata));
269 conn->sockdata = data;
271 data->ctx = SSL_CTX_new (SSLv23_client_method ());
273 /* disable SSL protocols as needed */
274 if (!option(OPTTLSV1))
276 SSL_CTX_set_options(data->ctx, SSL_OP_NO_TLSv1);
278 if (!option(OPTSSLV2))
280 SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv2);
282 if (!option(OPTSSLV3))
284 SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv3);
287 ssl_get_client_cert(data, conn);
289 data->ssl = SSL_new (data->ctx);
290 SSL_set_fd (data->ssl, conn->fd);
292 if (ssl_negotiate(data))
294 mutt_socket_close (conn);
298 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
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)
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);
317 if ((err = SSL_connect (ssldata->ssl)) != 1)
319 switch (SSL_get_error (ssldata->ssl, err))
321 case SSL_ERROR_SYSCALL:
322 errmsg = _("I/O error");
325 errmsg = ERR_error_string (ERR_get_error (), NULL);
328 errmsg = _("unknown error");
331 mutt_error (_("SSL failed: %s"), errmsg);
337 ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
340 mutt_error (_("Unable to get certificate from peer"));
345 if (!ssl_check_certificate (ssldata))
348 mutt_message (_("SSL connection using %s (%s)"),
349 SSL_get_cipher_version (ssldata->ssl), SSL_get_cipher_name (ssldata->ssl));
355 static int ssl_socket_close (CONNECTION * conn)
357 sslsockdata *data = conn->sockdata;
360 SSL_shutdown (data->ssl);
362 X509_free (data->cert);
363 SSL_free (data->ssl);
364 SSL_CTX_free (data->ctx);
365 FREE (&conn->sockdata);
368 return raw_socket_close (conn);
371 static int tls_close (CONNECTION* conn)
375 rc = ssl_socket_close (conn);
376 conn->read = raw_socket_read;
377 conn->write = raw_socket_write;
378 conn->close = raw_socket_close;
383 static char *x509_get_part (char *line, const char *ndx)
385 static char ret[SHORT_STRING];
388 strfcpy (ret, _("Unknown"), sizeof (ret));
390 c = strstr (line, ndx);
394 c2 = strchr (c, '/');
397 strfcpy (ret, c, sizeof (ret));
405 static void x509_fingerprint (char *s, int l, X509 * cert)
407 unsigned char md[EVP_MAX_MD_SIZE];
411 if (!X509_digest (cert, EVP_md5 (), md, &n))
413 snprintf (s, l, "%s", _("[unable to calculate]"));
417 for (j = 0; j < (int) n; j++)
420 snprintf (ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
421 safe_strcat (s, l, ch);
426 static char *asn1time_to_string (ASN1_UTCTIME *tm)
431 strfcpy (buf, _("[invalid date]"), sizeof (buf));
433 bio = BIO_new (BIO_s_mem());
436 if (ASN1_TIME_print (bio, tm))
437 (void) BIO_read (bio, buf, sizeof (buf));
444 static int check_certificate_by_signer (X509 *peercert)
450 ctx = X509_STORE_new ();
451 if (ctx == NULL) return 0;
453 if (option (OPTSSLSYSTEMCERTS))
455 if (X509_STORE_set_default_paths (ctx))
458 dprint (2, (debugfile, "X509_STORE_set_default_paths failed\n"));
461 if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
464 dprint (2, (debugfile, "X509_STORE_load_locations_failed\n"));
469 X509_STORE_free (ctx);
473 X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
475 pass = (X509_verify_cert (&xsc) > 0);
479 char buf[SHORT_STRING];
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));
488 X509_STORE_CTX_cleanup (&xsc);
489 X509_STORE_free (ctx);
494 static int check_certificate_by_digest (X509 *peercert)
496 unsigned char peermd[EVP_MAX_MD_SIZE];
497 unsigned int peermdlen;
502 /* expiration check */
503 if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0)
505 dprint (2, (debugfile, "Server certificate is not yet valid\n"));
506 mutt_error (_("Server certificate is not yet valid"));
510 if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0)
512 dprint (2, (debugfile, "Server certificate has expired"));
513 mutt_error (_("Server certificate has expired"));
518 if ((fp = fopen (SslCertFile, "rt")) == NULL)
521 if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
527 while ((cert = READ_X509_KEY (fp, &cert)) != NULL)
529 unsigned char md[EVP_MAX_MD_SIZE];
532 /* Avoid CPU-intensive digest calculation if the certificates are
533 * not even remotely equal.
535 if (X509_subject_name_cmp (cert, peercert) != 0 ||
536 X509_issuer_name_cmp (cert, peercert) != 0)
539 if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
542 if (memcmp(peermd, md, mdlen) != 0)
554 static int ssl_check_certificate (sslsockdata * data)
557 {"/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C="};
558 char helpstr[SHORT_STRING];
559 char buf[SHORT_STRING];
563 char *name = NULL, *c;
565 if (check_certificate_by_signer (data->cert))
567 dprint (1, (debugfile, "ssl_check_certificate: signer check passed\n"));
571 /* automatic check from user's database */
572 if (SslCertFile && check_certificate_by_digest (data->cert))
574 dprint (1, (debugfile, "ssl_check_certificate: digest check passed\n"));
578 /* interactive check from user */
579 menu = mutt_new_menu ();
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));
586 strfcpy (menu->dialog[row], _("This certificate belongs to:"), SHORT_STRING);
588 name = X509_NAME_oneline (X509_get_subject_name (data->cert),
590 for (i = 0; i < 5; i++)
592 c = x509_get_part (name, part[i]);
593 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
597 strfcpy (menu->dialog[row], _("This certificate was issued by:"), SHORT_STRING);
599 name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
601 for (i = 0; i < 5; i++)
603 c = x509_get_part (name, part[i]);
604 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
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)));
616 x509_fingerprint (buf, sizeof (buf), data->cert);
617 snprintf (menu->dialog[row++], SHORT_STRING, _("Fingerprint: %s"), buf);
619 menu->title = _("SSL Certificate check");
622 menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
623 menu->keys = _("roa");
627 menu->prompt = _("(r)eject, accept (o)nce");
628 menu->keys = _("ro");
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;
639 set_option(OPTUNBUFFEREDINPUT);
642 switch (mutt_menuLoop (menu))
645 case OP_MAX + 1: /* reject */
649 case OP_MAX + 3: /* accept always */
651 if ((fp = fopen (SslCertFile, "a")))
653 if (PEM_write_X509 (fp, data->cert))
659 mutt_error (_("Warning: Couldn't save certificate"));
664 mutt_message (_("Certificate saved"));
668 case OP_MAX + 2: /* accept once */
673 unset_option(OPTUNBUFFEREDINPUT);
674 mutt_menuDestroy (&menu);
678 static void ssl_get_client_cert(sslsockdata *ssldata, CONNECTION *conn)
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);
690 static int ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
692 ACCOUNT *account = (ACCOUNT*)userdata;
694 if (mutt_account_getuser (account))
697 dprint (2, (debugfile, "ssl_passwd_cb: getting password for %s@%s:%u\n",
698 account->user, account->host, account->port));
700 if (mutt_account_getpass (account))
703 return snprintf(buf, size, "%s", account->pass);