2 * Copyright notice from original mutt:
3 * Copyright (C) 1999-2001 Tommi Komulainen <Tommi.Komulainen@iki.fi>
5 * This file is part of mutt-ng, see http://www.muttng.org/.
6 * It's licensed under the GNU General Public License,
7 * please see the file GPL in the top level source directory.
14 #include <openssl/ssl.h>
15 #include <openssl/x509.h>
16 #include <openssl/err.h>
17 #include <openssl/rand.h>
24 #include "mutt_socket.h"
25 #include "mutt_menu.h"
26 #include "mutt_curses.h"
32 #include "lib/debug.h"
34 #if OPENSSL_VERSION_NUMBER >= 0x00904000L
35 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL, NULL)
37 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL)
40 /* Just in case OpenSSL doesn't define DEVRANDOM */
42 #define DEVRANDOM "/dev/urandom"
45 /* This is ugly, but as RAND_status came in on OpenSSL version 0.9.5
46 * and the code has to support older versions too, this is seemed to
47 * be cleaner way compared to having even uglier #ifdefs all around.
49 #ifdef HAVE_RAND_STATUS
50 #define HAVE_ENTROPY() (RAND_status() == 1)
52 static int entropy_byte_count = 0;
54 /* OpenSSL fills the entropy pool from /dev/urandom if it exists */
55 #define HAVE_ENTROPY() (!access(DEVRANDOM, R_OK) || entropy_byte_count >= 16)
58 typedef struct _sslsockdata {
64 /* local prototypes */
66 static int add_entropy (const char *file);
67 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len);
68 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len);
69 static int ssl_socket_open (CONNECTION * conn);
70 static int ssl_socket_close (CONNECTION * conn);
71 static int tls_close (CONNECTION * conn);
72 static int ssl_check_certificate (sslsockdata * data);
73 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn);
74 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata);
75 static int ssl_negotiate (sslsockdata *);
77 /* mutt_ssl_starttls: Negotiate TLS over an already opened connection.
78 * TODO: Merge this code better with ssl_socket_open. */
79 int mutt_ssl_starttls (CONNECTION * conn)
87 ssldata = (sslsockdata *) mem_calloc (1, sizeof (sslsockdata));
88 /* the ssl_use_xxx protocol options don't apply. We must use TLS in TLS. */
89 if (!(ssldata->ctx = SSL_CTX_new (TLSv1_client_method ()))) {
90 debug_print (1, ("Error allocating SSL_CTX\n"));
94 ssl_get_client_cert (ssldata, conn);
96 if (!(ssldata->ssl = SSL_new (ssldata->ctx))) {
97 debug_print (1, ("Error allocating SSL\n"));
101 if (SSL_set_fd (ssldata->ssl, conn->fd) != 1) {
102 debug_print (1, ("Error setting fd\n"));
106 if (ssl_negotiate (ssldata))
109 /* hmm. watch out if we're starting TLS over any method other than raw. */
110 conn->sockdata = ssldata;
111 conn->conn_read = ssl_socket_read;
112 conn->conn_write = ssl_socket_write;
113 conn->conn_close = tls_close;
115 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
121 mem_free (&ssldata->ssl);
123 mem_free (&ssldata->ctx);
131 * OpenSSL library needs to be fed with sufficient entropy. On systems
132 * with /dev/urandom, this is done transparently by the library itself,
133 * on other systems we need to fill the entropy pool ourselves.
135 * Even though only OpenSSL 0.9.5 and later will complain about the
136 * lack of entropy, we try to our best and fill the pool with older
137 * versions also. (That's the reason for the ugly #ifdefs and macros,
138 * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
142 char path[_POSIX_PATH_MAX];
143 static unsigned char init_complete = 0;
148 if (!HAVE_ENTROPY ()) {
149 /* load entropy from files */
150 add_entropy (SslEntropyFile);
151 add_entropy (RAND_file_name (path, sizeof (path)));
153 /* load entropy from egd sockets */
155 add_entropy (getenv ("EGDSOCKET"));
156 snprintf (path, sizeof (path), "%s/.entropy", NONULL (Homedir));
158 add_entropy ("/tmp/entropy");
161 /* shuffle $RANDFILE (or ~/.rnd if unset) */
162 RAND_write_file (RAND_file_name (path, sizeof (path)));
164 if (!HAVE_ENTROPY ()) {
165 mutt_error (_("Failed to find enough entropy on your system"));
171 /* I don't think you can do this just before reading the error. The call
172 * itself might clobber the last SSL error. */
173 SSL_load_error_strings ();
179 static int add_entropy (const char *file)
187 if (stat (file, &st) == -1)
188 return errno == ENOENT ? 0 : -1;
190 mutt_message (_("Filling entropy pool: %s...\n"), file);
192 /* check that the file permissions are secure */
193 if (st.st_uid != getuid () ||
194 ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
195 ((st.st_mode & (S_IWOTH | S_IROTH)) != 0)) {
196 mutt_error (_("%s has insecure permissions!"), file);
205 n = RAND_load_file (file, -1);
207 #ifndef HAVE_RAND_STATUS
209 entropy_byte_count += n;
214 static int ssl_socket_open_err (CONNECTION * conn)
216 mutt_error (_("SSL disabled due the lack of entropy"));
222 int ssl_socket_setup (CONNECTION * conn)
224 if (ssl_init () < 0) {
225 conn->conn_open = ssl_socket_open_err;
229 conn->conn_open = ssl_socket_open;
230 conn->conn_read = ssl_socket_read;
231 conn->conn_write = ssl_socket_write;
232 conn->conn_close = ssl_socket_close;
237 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len)
239 sslsockdata *data = conn->sockdata;
241 return SSL_read (data->ssl, buf, len);
244 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len)
246 sslsockdata *data = conn->sockdata;
248 return SSL_write (data->ssl, buf, len);
251 static int ssl_socket_open (CONNECTION * conn)
256 if (raw_socket_open (conn) < 0)
259 data = (sslsockdata *) mem_calloc (1, sizeof (sslsockdata));
260 conn->sockdata = data;
262 data->ctx = SSL_CTX_new (SSLv23_client_method ());
264 /* disable SSL protocols as needed */
265 if (!option (OPTTLSV1)) {
266 SSL_CTX_set_options (data->ctx, SSL_OP_NO_TLSv1);
268 if (!option (OPTSSLV2)) {
269 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv2);
271 if (!option (OPTSSLV3)) {
272 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv3);
275 ssl_get_client_cert (data, conn);
277 data->ssl = SSL_new (data->ctx);
278 SSL_set_fd (data->ssl, conn->fd);
280 if (ssl_negotiate (data)) {
281 mutt_socket_close (conn);
285 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
291 /* ssl_negotiate: After SSL state has been initialised, attempt to negotiate
292 * SSL over the wire, including certificate checks. */
293 static int ssl_negotiate (sslsockdata * ssldata)
298 #if OPENSSL_VERSION_NUMBER >= 0x00906000L
299 /* This only exists in 0.9.6 and above. Without it we may get interrupted
300 * reads or writes. Bummer. */
301 SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY);
304 if ((err = SSL_connect (ssldata->ssl)) != 1) {
305 switch (SSL_get_error (ssldata->ssl, err)) {
306 case SSL_ERROR_SYSCALL:
307 errmsg = _("I/O error");
310 errmsg = ERR_error_string (ERR_get_error (), NULL);
313 errmsg = _("unknown error");
316 mutt_error (_("SSL failed: %s"), errmsg);
322 ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
323 if (!ssldata->cert) {
324 mutt_error (_("Unable to get certificate from peer"));
329 if (!ssl_check_certificate (ssldata))
332 mutt_message (_("SSL connection using %s (%s)"),
333 SSL_get_cipher_version (ssldata->ssl),
334 SSL_get_cipher_name (ssldata->ssl));
340 static int ssl_socket_close (CONNECTION * conn)
342 sslsockdata *data = conn->sockdata;
345 SSL_shutdown (data->ssl);
347 X509_free (data->cert);
349 SSL_free (data->ssl);
350 SSL_CTX_free (data->ctx);
351 mem_free (&conn->sockdata);
354 return raw_socket_close (conn);
357 static int compare_certificates (X509 *cert, X509 *peercert,
358 unsigned char *peermd,
359 unsigned int peermdlen) {
360 unsigned char md[EVP_MAX_MD_SIZE];
363 /* Avoid CPU-intensive digest calculation if the certificates are
364 * not even remotely equal.
366 if (X509_subject_name_cmp (cert, peercert) != 0 ||
367 X509_issuer_name_cmp (cert, peercert) != 0)
370 if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
373 if (memcmp(peermd, md, mdlen) != 0)
379 static int check_certificate_cache (X509 *peercert) {
380 unsigned char peermd[EVP_MAX_MD_SIZE];
381 unsigned int peermdlen;
385 if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
388 for (scert = SslSessionCerts; scert; scert = scert->next) {
389 cert = *(X509**)scert->data;
390 if (!compare_certificates (cert, peercert, peermd, peermdlen)) {
397 static int tls_close (CONNECTION * conn)
401 rc = ssl_socket_close (conn);
402 conn->conn_read = raw_socket_read;
403 conn->conn_write = raw_socket_write;
404 conn->conn_close = raw_socket_close;
409 static char *x509_get_part (char *line, const char *ndx)
411 static char ret[SHORT_STRING];
414 strfcpy (ret, _("Unknown"), sizeof (ret));
416 c = strstr (line, ndx);
419 c2 = strchr (c, '/');
422 strfcpy (ret, c, sizeof (ret));
430 static void x509_fingerprint (char *s, int l, X509 * cert)
432 unsigned char md[EVP_MAX_MD_SIZE];
436 if (!X509_digest (cert, EVP_md5 (), md, &n)) {
437 snprintf (s, l, "%s", _("[unable to calculate]"));
440 for (j = 0; j < (int) n; j++) {
443 snprintf (ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
449 static char *asn1time_to_string (ASN1_UTCTIME * tm)
454 strfcpy (buf, _("[invalid date]"), sizeof (buf));
456 bio = BIO_new (BIO_s_mem ());
458 if (ASN1_TIME_print (bio, tm))
459 (void) BIO_read (bio, buf, sizeof (buf));
466 static int check_certificate_by_signer (X509 * peercert)
472 ctx = X509_STORE_new ();
476 if (option (OPTSSLSYSTEMCERTS)) {
477 if (X509_STORE_set_default_paths (ctx))
480 debug_print (2, ("X509_STORE_set_default_paths failed\n"));
483 if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
486 debug_print (2, ("X509_STORE_load_locations_failed\n"));
490 X509_STORE_free (ctx);
494 X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
496 pass = (X509_verify_cert (&xsc) > 0);
499 char buf[SHORT_STRING];
502 err = X509_STORE_CTX_get_error (&xsc);
503 snprintf (buf, sizeof (buf), "%s (%d)",
504 X509_verify_cert_error_string (err), err);
505 debug_print (2, ("X509_verify_cert: %s\n", buf));
508 X509_STORE_CTX_cleanup (&xsc);
509 X509_STORE_free (ctx);
514 static int check_certificate_by_digest (X509 * peercert)
516 unsigned char peermd[EVP_MAX_MD_SIZE];
517 unsigned int peermdlen;
522 /* expiration check */
523 if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0) {
524 debug_print (2, ("Server certificate is not yet valid\n"));
525 mutt_error (_("Server certificate is not yet valid"));
529 if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0) {
530 debug_print (2, ("Server certificate has expired\n"));
531 mutt_error (_("Server certificate has expired"));
536 if ((fp = fopen (SslCertFile, "rt")) == NULL)
539 if (!X509_digest (peercert, EVP_sha1 (), peermd, &peermdlen)) {
544 while ((cert = READ_X509_KEY (fp, &cert)) != NULL) {
545 pass = compare_certificates (cert, peercert, peermd, peermdlen) ? 0 : 1;
555 static int ssl_check_certificate (sslsockdata * data)
557 char *part[] = { "/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C=" };
558 char helpstr[SHORT_STRING];
559 char buf[SHORT_STRING];
563 char *name = NULL, *c;
565 /* check session cache first */
566 if (check_certificate_cache (data->cert)) {
567 debug_print (1, ("ssl_check_certificate: using cached certificate\n"));
571 if (check_certificate_by_signer (data->cert)) {
572 debug_print (1, ("signer check passed\n"));
576 /* automatic check from user's database */
577 if (SslCertFile && check_certificate_by_digest (data->cert)) {
578 debug_print (1, ("digest check passed\n"));
582 /* interactive check from user */
583 menu = mutt_new_menu ();
585 menu->dialog = (char **) mem_calloc (1, menu->max * sizeof (char *));
586 for (i = 0; i < menu->max; i++)
587 menu->dialog[i] = (char *) mem_calloc (1, SHORT_STRING * sizeof (char));
590 strfcpy (menu->dialog[row], _("This certificate belongs to:"),
593 name = X509_NAME_oneline (X509_get_subject_name (data->cert),
595 for (i = 0; i < 5; i++) {
596 c = x509_get_part (name, part[i]);
597 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
601 strfcpy (menu->dialog[row], _("This certificate was issued by:"),
604 name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
606 for (i = 0; i < 5; i++) {
607 c = x509_get_part (name, part[i]);
608 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
612 snprintf (menu->dialog[row++], SHORT_STRING, "%s",
613 _("This certificate is valid"));
614 snprintf (menu->dialog[row++], SHORT_STRING, _(" from %s"),
615 asn1time_to_string (X509_get_notBefore (data->cert)));
616 snprintf (menu->dialog[row++], SHORT_STRING, _(" to %s"),
617 asn1time_to_string (X509_get_notAfter (data->cert)));
621 x509_fingerprint (buf, sizeof (buf), data->cert);
622 snprintf (menu->dialog[row++], SHORT_STRING, _("Fingerprint: %s"), buf);
624 menu->title = _("SSL Certificate check");
626 if (SslCertFile && X509_cmp_current_time (X509_get_notAfter (data->cert)) >= 0
627 && X509_cmp_current_time (X509_get_notBefore (data->cert)) < 0) {
628 menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
629 menu->keys = _("roa");
632 menu->prompt = _("(r)eject, accept (o)nce");
633 menu->keys = _("ro");
637 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_GENERIC, OP_EXIT);
638 str_cat (helpstr, sizeof (helpstr), buf);
639 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
640 str_cat (helpstr, sizeof (helpstr), buf);
641 menu->help = helpstr;
644 set_option (OPTUNBUFFEREDINPUT);
646 switch (mutt_menuLoop (menu)) {
648 case OP_MAX + 1: /* reject */
652 case OP_MAX + 3: /* accept always */
654 if ((fp = fopen (SslCertFile, "a"))) {
655 if (PEM_write_X509 (fp, data->cert))
660 mutt_error (_("Warning: Couldn't save certificate"));
664 mutt_message (_("Certificate saved"));
668 case OP_MAX + 2: /* accept once */
670 /* keep a handle on accepted certificates in case we want to
671 * open up another connection to the same server in this session */
672 SslSessionCerts = mutt_add_list_n (SslSessionCerts, &data->cert,
677 unset_option (OPTUNBUFFEREDINPUT);
678 mutt_menuDestroy (&menu);
682 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn)
685 debug_print (2, ("Using client certificate %s\n", SslClientCert));
686 SSL_CTX_set_default_passwd_cb_userdata (ssldata->ctx, &conn->account);
687 SSL_CTX_set_default_passwd_cb (ssldata->ctx, ssl_passwd_cb);
688 SSL_CTX_use_certificate_file (ssldata->ctx, SslClientCert,
690 SSL_CTX_use_PrivateKey_file (ssldata->ctx, SslClientCert,
695 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata)
697 ACCOUNT *account = (ACCOUNT *) userdata;
699 if (mutt_account_getuser (account))
702 debug_print (2, ("getting password for %s@%s:%u\n",
703 account->user, account->host, account->port));
705 if (mutt_account_getpass (account))
708 return snprintf (buf, size, "%s", account->pass);