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_check_certificate (sslsockdata * data);
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 int ssl_negotiate (sslsockdata*);
79 /* mutt_ssl_starttls: Negotiate TLS over an already opened connection.
80 * TODO: Merge this code better with ssl_socket_open. */
81 int mutt_ssl_starttls (CONNECTION* conn)
89 ssldata = (sslsockdata*) safe_calloc (1, sizeof (sslsockdata));
90 /* the ssl_use_xxx protocol options don't apply. We must use TLS in TLS. */
91 if (! (ssldata->ctx = SSL_CTX_new (TLSv1_client_method ())))
93 dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL_CTX\n"));
97 if (! (ssldata->ssl = SSL_new (ssldata->ctx)))
99 dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL\n"));
103 if (SSL_set_fd (ssldata->ssl, conn->fd) != 1)
105 dprint (1, (debugfile, "mutt_ssl_starttls: Error setting fd\n"));
109 if (ssl_negotiate (ssldata))
112 /* hmm. watch out if we're starting TLS over any method other than raw. */
113 conn->sockdata = ssldata;
114 conn->read = ssl_socket_read;
115 conn->write = ssl_socket_write;
116 conn->close = tls_close;
118 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
124 FREE (&ssldata->ssl);
126 FREE (&ssldata->ctx);
134 * OpenSSL library needs to be fed with sufficient entropy. On systems
135 * with /dev/urandom, this is done transparently by the library itself,
136 * on other systems we need to fill the entropy pool ourselves.
138 * Even though only OpenSSL 0.9.5 and later will complain about the
139 * lack of entropy, we try to our best and fill the pool with older
140 * versions also. (That's the reason for the ugly #ifdefs and macros,
141 * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
145 char path[_POSIX_PATH_MAX];
146 static unsigned char init_complete = 0;
151 if (! HAVE_ENTROPY())
153 /* load entropy from files */
154 add_entropy (SslEntropyFile);
155 add_entropy (RAND_file_name (path, sizeof (path)));
157 /* load entropy from egd sockets */
159 add_entropy (getenv ("EGDSOCKET"));
160 snprintf (path, sizeof(path), "%s/.entropy", NONULL(Homedir));
162 add_entropy ("/tmp/entropy");
165 /* shuffle $RANDFILE (or ~/.rnd if unset) */
166 RAND_write_file (RAND_file_name (path, sizeof (path)));
168 if (! HAVE_ENTROPY())
170 mutt_error (_("Failed to find enough entropy on your system"));
176 /* I don't think you can do this just before reading the error. The call
177 * itself might clobber the last SSL error. */
178 SSL_load_error_strings();
184 static int add_entropy (const char *file)
191 if (stat (file, &st) == -1)
192 return errno == ENOENT ? 0 : -1;
194 mutt_message (_("Filling entropy pool: %s...\n"),
197 /* check that the file permissions are secure */
198 if (st.st_uid != getuid () ||
199 ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
200 ((st.st_mode & (S_IWOTH | S_IROTH)) != 0))
202 mutt_error (_("%s has insecure permissions!"), file);
211 n = RAND_load_file (file, -1);
213 #ifndef HAVE_RAND_STATUS
214 if (n > 0) entropy_byte_count += n;
219 static int ssl_socket_open_err (CONNECTION *conn)
221 mutt_error (_("SSL disabled due the lack of entropy"));
227 int ssl_socket_setup (CONNECTION * conn)
231 conn->open = ssl_socket_open_err;
235 conn->open = ssl_socket_open;
236 conn->read = ssl_socket_read;
237 conn->write = ssl_socket_write;
238 conn->close = ssl_socket_close;
243 static int ssl_socket_read (CONNECTION* conn, char* buf, size_t len)
245 sslsockdata *data = conn->sockdata;
246 return SSL_read (data->ssl, buf, len);
249 static int ssl_socket_write (CONNECTION* conn, const char* buf, size_t len)
251 sslsockdata *data = conn->sockdata;
252 return SSL_write (data->ssl, buf, len);
255 static int ssl_socket_open (CONNECTION * conn)
260 if (raw_socket_open (conn) < 0)
263 data = (sslsockdata *) safe_calloc (1, sizeof (sslsockdata));
264 conn->sockdata = data;
266 data->ctx = SSL_CTX_new (SSLv23_client_method ());
268 /* disable SSL protocols as needed */
269 if (!option(OPTTLSV1))
271 SSL_CTX_set_options(data->ctx, SSL_OP_NO_TLSv1);
273 if (!option(OPTSSLV2))
275 SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv2);
277 if (!option(OPTSSLV3))
279 SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv3);
282 data->ssl = SSL_new (data->ctx);
283 SSL_set_fd (data->ssl, conn->fd);
285 if (ssl_negotiate(data))
287 mutt_socket_close (conn);
291 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
297 /* ssl_negotiate: After SSL state has been initialised, attempt to negotiate
298 * SSL over the wire, including certificate checks. */
299 int ssl_negotiate (sslsockdata* ssldata)
304 #if OPENSSL_VERSION_NUMBER >= 0x00906000L
305 /* This only exists in 0.9.6 and above. Without it we may get interrupted
306 * reads or writes. Bummer. */
307 SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY);
310 if ((err = SSL_connect (ssldata->ssl)) != 1)
312 switch (SSL_get_error (ssldata->ssl, err))
314 case SSL_ERROR_SYSCALL:
315 errmsg = _("I/O error");
318 errmsg = _("unspecified protocol error");
321 errmsg = _("unknown error");
324 mutt_error (_("SSL failed: %s"), errmsg);
330 ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
333 mutt_error (_("Unable to get certificate from peer"));
338 if (!ssl_check_certificate (ssldata))
341 mutt_message (_("SSL connection using %s (%s)"),
342 SSL_get_cipher_version (ssldata->ssl), SSL_get_cipher_name (ssldata->ssl));
348 static int ssl_socket_close (CONNECTION * conn)
350 sslsockdata *data = conn->sockdata;
353 SSL_shutdown (data->ssl);
355 X509_free (data->cert);
356 SSL_free (data->ssl);
357 SSL_CTX_free (data->ctx);
358 FREE (&conn->sockdata);
361 return raw_socket_close (conn);
364 static int tls_close (CONNECTION* conn)
368 rc = ssl_socket_close (conn);
369 conn->read = raw_socket_read;
370 conn->write = raw_socket_write;
371 conn->close = raw_socket_close;
376 static char *x509_get_part (char *line, const char *ndx)
378 static char ret[SHORT_STRING];
381 strfcpy (ret, _("Unknown"), sizeof (ret));
383 c = strstr (line, ndx);
387 c2 = strchr (c, '/');
390 strfcpy (ret, c, sizeof (ret));
398 static void x509_fingerprint (char *s, int l, X509 * cert)
400 unsigned char md[EVP_MAX_MD_SIZE];
404 if (!X509_digest (cert, EVP_md5 (), md, &n))
406 snprintf (s, l, "%s", _("[unable to calculate]"));
410 for (j = 0; j < (int) n; j++)
413 snprintf (ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
419 static char *asn1time_to_string (ASN1_UTCTIME *tm)
424 strfcpy (buf, _("[invalid date]"), sizeof (buf));
426 bio = BIO_new (BIO_s_mem());
429 if (ASN1_TIME_print (bio, tm))
430 (void) BIO_read (bio, buf, sizeof (buf));
437 static int check_certificate_by_signer (X509 *peercert)
443 ctx = X509_STORE_new ();
444 if (ctx == NULL) return 0;
446 if (option (OPTSSLSYSTEMCERTS))
448 if (X509_STORE_set_default_paths (ctx))
451 dprint (2, (debugfile, "X509_STORE_set_default_paths failed\n"));
454 if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
457 dprint (2, (debugfile, "X509_STORE_load_locations_failed\n"));
462 X509_STORE_free (ctx);
466 X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
468 pass = (X509_verify_cert (&xsc) > 0);
472 char buf[SHORT_STRING];
475 err = X509_STORE_CTX_get_error (&xsc);
476 snprintf (buf, sizeof (buf), "%s (%d)",
477 X509_verify_cert_error_string(err), err);
478 dprint (2, (debugfile, "X509_verify_cert: %s\n", buf));
481 X509_STORE_CTX_cleanup (&xsc);
482 X509_STORE_free (ctx);
487 static int check_certificate_by_digest (X509 *peercert)
489 unsigned char peermd[EVP_MAX_MD_SIZE];
490 unsigned int peermdlen;
495 /* expiration check */
496 if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0)
498 dprint (2, (debugfile, "Server certificate is not yet valid\n"));
499 mutt_error (_("Server certificate is not yet valid"));
503 if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0)
505 dprint (2, (debugfile, "Server certificate has expired"));
506 mutt_error (_("Server certificate has expired"));
511 if ((fp = fopen (SslCertFile, "rt")) == NULL)
514 if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
520 while ((cert = READ_X509_KEY (fp, &cert)) != NULL)
522 unsigned char md[EVP_MAX_MD_SIZE];
525 /* Avoid CPU-intensive digest calculation if the certificates are
526 * not even remotely equal.
528 if (X509_subject_name_cmp (cert, peercert) != 0 ||
529 X509_issuer_name_cmp (cert, peercert) != 0)
532 if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
535 if (memcmp(peermd, md, mdlen) != 0)
547 static int ssl_check_certificate (sslsockdata * data)
550 {"/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C="};
551 char helpstr[SHORT_STRING];
552 char buf[SHORT_STRING];
556 char *name = NULL, *c;
558 if (check_certificate_by_signer (data->cert))
560 dprint (1, (debugfile, "ssl_check_certificate: signer check passed\n"));
564 /* automatic check from user's database */
565 if (SslCertFile && check_certificate_by_digest (data->cert))
567 dprint (1, (debugfile, "ssl_check_certificate: digest check passed\n"));
571 /* interactive check from user */
572 menu = mutt_new_menu ();
574 menu->dialog = (char **) safe_calloc (1, menu->max * sizeof (char *));
575 for (i = 0; i < menu->max; i++)
576 menu->dialog[i] = (char *) safe_calloc (1, SHORT_STRING * sizeof (char));
579 strfcpy (menu->dialog[row], _("This certificate belongs to:"), SHORT_STRING);
581 name = X509_NAME_oneline (X509_get_subject_name (data->cert),
583 for (i = 0; i < 5; i++)
585 c = x509_get_part (name, part[i]);
586 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
590 strfcpy (menu->dialog[row], _("This certificate was issued by:"), SHORT_STRING);
592 name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
594 for (i = 0; i < 5; i++)
596 c = x509_get_part (name, part[i]);
597 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
601 snprintf (menu->dialog[row++], SHORT_STRING, "%s", _("This certificate is valid"));
602 snprintf (menu->dialog[row++], SHORT_STRING, _(" from %s"),
603 asn1time_to_string (X509_get_notBefore (data->cert)));
604 snprintf (menu->dialog[row++], SHORT_STRING, _(" to %s"),
605 asn1time_to_string (X509_get_notAfter (data->cert)));
609 x509_fingerprint (buf, sizeof (buf), data->cert);
610 snprintf (menu->dialog[row++], SHORT_STRING, _("Fingerprint: %s"), buf);
612 menu->title = _("SSL Certificate check");
615 menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
616 menu->keys = _("roa");
620 menu->prompt = _("(r)eject, accept (o)nce");
621 menu->keys = _("ro");
625 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_GENERIC, OP_EXIT);
626 strncat (helpstr, buf, sizeof (helpstr));
627 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
628 strncat (helpstr, buf, sizeof (helpstr));
629 menu->help = helpstr;
632 set_option(OPTUNBUFFEREDINPUT);
635 switch (mutt_menuLoop (menu))
638 case OP_MAX + 1: /* reject */
642 case OP_MAX + 3: /* accept always */
644 if ((fp = fopen (SslCertFile, "a")))
646 if (PEM_write_X509 (fp, data->cert))
652 mutt_error (_("Warning: Couldn't save certificate"));
657 mutt_message (_("Certificate saved"));
661 case OP_MAX + 2: /* accept once */
666 unset_option(OPTUNBUFFEREDINPUT);
667 mutt_menuDestroy (&menu);