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.
10 #include <lib-lib/lib-lib.h>
14 #include <openssl/ssl.h>
15 #include <openssl/x509.h>
16 #include <openssl/err.h>
17 #include <openssl/rand.h>
19 #include <lib-ui/curses.h>
20 #include <lib-ui/menu.h>
23 #include "mutt_socket.h"
27 #if OPENSSL_VERSION_NUMBER >= 0x00904000L
28 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL, NULL)
30 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL)
33 /* Just in case OpenSSL doesn't define DEVRANDOM */
35 #define DEVRANDOM "/dev/urandom"
38 /* This is ugly, but as RAND_status came in on OpenSSL version 0.9.5
39 * and the code has to support older versions too, this is seemed to
40 * be cleaner way compared to having even uglier #ifdefs all around.
42 #ifdef HAVE_RAND_STATUS
43 #define HAVE_ENTROPY() (RAND_status() == 1)
45 static int entropy_byte_count = 0;
47 /* OpenSSL fills the entropy pool from /dev/urandom if it exists */
48 #define HAVE_ENTROPY() (!access(DEVRANDOM, R_OK) || entropy_byte_count >= 16)
51 typedef struct _sslsockdata {
57 /* local prototypes */
58 static int ssl_init (void);
59 static int add_entropy (const char *file);
60 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len);
61 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len);
62 static int ssl_socket_open (CONNECTION * conn);
63 static int ssl_socket_close (CONNECTION * conn);
64 static int tls_close (CONNECTION * conn);
65 static int ssl_check_certificate (sslsockdata * data);
66 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn);
67 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata);
68 static int ssl_negotiate (sslsockdata *);
70 /* mutt_ssl_starttls: Negotiate TLS over an already opened connection.
71 * TODO: Merge this code better with ssl_socket_open. */
72 int mutt_ssl_starttls (CONNECTION * conn)
80 ssldata = p_new(sslsockdata, 1);
81 /* the ssl_use_xxx protocol options don't apply. We must use TLS in TLS. */
82 if (!(ssldata->ctx = SSL_CTX_new (TLSv1_client_method ()))) {
86 ssl_get_client_cert (ssldata, conn);
88 if (!(ssldata->ssl = SSL_new (ssldata->ctx))) {
92 if (SSL_set_fd (ssldata->ssl, conn->fd) != 1) {
96 if (ssl_negotiate (ssldata))
99 /* hmm. watch out if we're starting TLS over any method other than raw. */
100 conn->sockdata = ssldata;
101 conn->conn_read = ssl_socket_read;
102 conn->conn_write = ssl_socket_write;
103 conn->conn_close = tls_close;
105 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
111 p_delete(&ssldata->ssl);
113 p_delete(&ssldata->ctx);
121 * OpenSSL library needs to be fed with sufficient entropy. On systems
122 * with /dev/urandom, this is done transparently by the library itself,
123 * on other systems we need to fill the entropy pool ourselves.
125 * Even though only OpenSSL 0.9.5 and later will complain about the
126 * lack of entropy, we try to our best and fill the pool with older
127 * versions also. (That's the reason for the ugly #ifdefs and macros,
128 * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
130 static int ssl_init (void)
132 char path[_POSIX_PATH_MAX];
133 static unsigned char init_complete = 0;
138 if (!HAVE_ENTROPY ()) {
139 /* load entropy from files */
140 add_entropy (SslEntropyFile);
141 add_entropy (RAND_file_name (path, sizeof (path)));
143 /* load entropy from egd sockets */
145 add_entropy (getenv ("EGDSOCKET"));
146 snprintf (path, sizeof (path), "%s/.entropy", NONULL (Homedir));
148 add_entropy ("/tmp/entropy");
151 /* shuffle $RANDFILE (or ~/.rnd if unset) */
152 RAND_write_file (RAND_file_name (path, sizeof (path)));
154 if (!HAVE_ENTROPY ()) {
155 mutt_error (_("Failed to find enough entropy on your system"));
161 /* I don't think you can do this just before reading the error. The call
162 * itself might clobber the last SSL error. */
163 SSL_load_error_strings ();
169 static int add_entropy (const char *file)
177 if (stat (file, &st) == -1)
178 return errno == ENOENT ? 0 : -1;
180 mutt_message (_("Filling entropy pool: %s...\n"), file);
182 /* check that the file permissions are secure */
183 if (st.st_uid != getuid () ||
184 ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
185 ((st.st_mode & (S_IWOTH | S_IROTH)) != 0)) {
186 mutt_error (_("%s has insecure permissions!"), file);
195 n = RAND_load_file (file, -1);
197 #ifndef HAVE_RAND_STATUS
199 entropy_byte_count += n;
204 static int ssl_socket_open_err (CONNECTION * conn)
206 mutt_error (_("SSL disabled due the lack of entropy"));
212 int mutt_ssl_socket_setup (CONNECTION * conn)
214 if (ssl_init () < 0) {
215 conn->conn_open = ssl_socket_open_err;
219 conn->conn_open = ssl_socket_open;
220 conn->conn_read = ssl_socket_read;
221 conn->conn_write = ssl_socket_write;
222 conn->conn_close = ssl_socket_close;
227 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len)
229 sslsockdata *data = conn->sockdata;
231 return SSL_read (data->ssl, buf, len);
234 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len)
236 sslsockdata *data = conn->sockdata;
238 return SSL_write (data->ssl, buf, len);
241 static int ssl_socket_open (CONNECTION * conn)
246 if (raw_socket_open (conn) < 0)
249 data = p_new(sslsockdata, 1);
250 conn->sockdata = data;
252 data->ctx = SSL_CTX_new (SSLv23_client_method ());
254 /* disable SSL protocols as needed */
255 if (!option (OPTTLSV1)) {
256 SSL_CTX_set_options (data->ctx, SSL_OP_NO_TLSv1);
258 if (!option (OPTSSLV2)) {
259 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv2);
261 if (!option (OPTSSLV3)) {
262 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv3);
265 ssl_get_client_cert (data, conn);
267 data->ssl = SSL_new (data->ctx);
268 SSL_set_fd (data->ssl, conn->fd);
270 if (ssl_negotiate (data)) {
271 mutt_socket_close (conn);
275 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
281 /* ssl_negotiate: After SSL state has been initialised, attempt to negotiate
282 * SSL over the wire, including certificate checks. */
283 static int ssl_negotiate (sslsockdata * ssldata)
288 #if OPENSSL_VERSION_NUMBER >= 0x00906000L
289 /* This only exists in 0.9.6 and above. Without it we may get interrupted
290 * reads or writes. Bummer. */
291 SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY);
294 if ((err = SSL_connect (ssldata->ssl)) != 1) {
295 switch (SSL_get_error (ssldata->ssl, err)) {
296 case SSL_ERROR_SYSCALL:
297 errmsg = _("I/O error");
300 errmsg = ERR_error_string (ERR_get_error (), NULL);
303 errmsg = _("unknown error");
306 mutt_error (_("SSL failed: %s"), errmsg);
312 ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
313 if (!ssldata->cert) {
314 mutt_error (_("Unable to get certificate from peer"));
319 if (!ssl_check_certificate (ssldata))
322 mutt_message (_("SSL connection using %s (%s)"),
323 SSL_get_cipher_version (ssldata->ssl),
324 SSL_get_cipher_name (ssldata->ssl));
330 static int ssl_socket_close (CONNECTION * conn)
332 sslsockdata *data = conn->sockdata;
335 SSL_shutdown (data->ssl);
336 SSL_free (data->ssl);
337 SSL_CTX_free (data->ctx);
338 p_delete(&conn->sockdata);
341 return raw_socket_close (conn);
344 static int compare_certificates (X509 *cert, X509 *peercert,
345 unsigned char *peermd,
346 unsigned int peermdlen) {
347 unsigned char md[EVP_MAX_MD_SIZE];
350 /* Avoid CPU-intensive digest calculation if the certificates are
351 * not even remotely equal.
353 if (X509_subject_name_cmp (cert, peercert) != 0 ||
354 X509_issuer_name_cmp (cert, peercert) != 0)
357 if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
360 if (memcmp(peermd, md, mdlen) != 0)
366 static int check_certificate_cache (X509 *peercert) {
367 unsigned char peermd[EVP_MAX_MD_SIZE];
368 unsigned int peermdlen;
370 string_list_t *scert;
372 if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
375 for (scert = SslSessionCerts; scert; scert = scert->next) {
376 cert = *(X509**)scert->data;
377 if (!compare_certificates (cert, peercert, peermd, peermdlen)) {
384 static int tls_close (CONNECTION * conn)
388 rc = ssl_socket_close (conn);
389 conn->conn_read = raw_socket_read;
390 conn->conn_write = raw_socket_write;
391 conn->conn_close = raw_socket_close;
396 static char *x509_get_part (char *line, const char *ndx)
398 static char ret[STRING];
401 m_strcpy(ret, sizeof(ret), _("Unknown"));
403 c = strstr (line, ndx);
406 c2 = strchr (c, '/');
409 m_strcpy(ret, sizeof(ret), c);
417 static void x509_fingerprint (char *s, int l, X509 * cert)
419 unsigned char md[EVP_MAX_MD_SIZE];
423 if (!X509_digest (cert, EVP_md5 (), md, &n)) {
424 m_strcpy(s, l, _("[unable to calculate]"));
427 for (j = 0; j < (int) n; j++) {
430 snprintf(ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
436 static char *asn1time_to_string (ASN1_UTCTIME * tm)
441 m_strcpy(buf, sizeof(buf), _("[invalid date]"));
443 bio = BIO_new (BIO_s_mem ());
445 if (ASN1_TIME_print (bio, tm))
446 (void) BIO_read (bio, buf, sizeof (buf));
453 static int check_certificate_by_signer (X509 * peercert)
459 ctx = X509_STORE_new ();
463 if (option (OPTSSLSYSTEMCERTS)) {
464 if (X509_STORE_set_default_paths (ctx))
468 if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
473 X509_STORE_free (ctx);
477 X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
479 pass = (X509_verify_cert (&xsc) > 0);
480 X509_STORE_CTX_cleanup (&xsc);
481 X509_STORE_free (ctx);
486 static int check_certificate_by_digest (X509 * peercert)
488 unsigned char peermd[EVP_MAX_MD_SIZE];
489 unsigned int peermdlen;
494 /* expiration check */
495 if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0) {
496 mutt_error (_("Server certificate is not yet valid"));
500 if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0) {
501 mutt_error (_("Server certificate has expired"));
506 if ((fp = fopen (SslCertFile, "rt")) == NULL)
509 if (!X509_digest (peercert, EVP_sha1 (), peermd, &peermdlen)) {
514 while ((cert = READ_X509_KEY (fp, &cert)) != NULL) {
515 pass = compare_certificates (cert, peercert, peermd, peermdlen) ? 0 : 1;
525 static int ssl_check_certificate (sslsockdata * data)
527 char *part[] = { "/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C=" };
528 char helpstr[STRING];
533 char *name = NULL, *c;
535 /* check session cache first */
536 if (check_certificate_cache (data->cert)) {
540 if (check_certificate_by_signer (data->cert)) {
544 /* automatic check from user's database */
545 if (SslCertFile && check_certificate_by_digest (data->cert)) {
549 /* interactive check from user */
550 menu = mutt_new_menu ();
552 menu->dialog = p_new(char *, menu->max);
553 for (i = 0; i < menu->max; i++)
554 menu->dialog[i] = p_new(char, STRING);
557 m_strcpy(menu->dialog[row], STRING,
558 _("This certificate belongs to:"));
560 name = X509_NAME_oneline (X509_get_subject_name (data->cert),
562 for (i = 0; i < 5; i++) {
563 c = x509_get_part (name, part[i]);
564 snprintf (menu->dialog[row++], STRING, " %s", c);
568 m_strcpy(menu->dialog[row], STRING,
569 _("This certificate was issued by:"));
571 name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
573 for (i = 0; i < 5; i++) {
574 c = x509_get_part (name, part[i]);
575 snprintf (menu->dialog[row++], STRING, " %s", c);
579 snprintf (menu->dialog[row++], STRING, "%s",
580 _("This certificate is valid"));
581 snprintf (menu->dialog[row++], STRING, _(" from %s"),
582 asn1time_to_string (X509_get_notBefore (data->cert)));
583 snprintf (menu->dialog[row++], STRING, _(" to %s"),
584 asn1time_to_string (X509_get_notAfter (data->cert)));
588 x509_fingerprint (buf, sizeof (buf), data->cert);
589 snprintf (menu->dialog[row++], STRING, _("Fingerprint: %s"), buf);
591 menu->title = _("SSL Certificate check");
593 if (SslCertFile && X509_cmp_current_time (X509_get_notAfter (data->cert)) >= 0
594 && X509_cmp_current_time (X509_get_notBefore (data->cert)) < 0) {
595 menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
596 menu->keys = _("roa");
599 menu->prompt = _("(r)eject, accept (o)nce");
600 menu->keys = _("ro");
604 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_GENERIC, OP_EXIT);
605 m_strcat(helpstr, sizeof(helpstr), buf);
606 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
607 m_strcat(helpstr, sizeof(helpstr), buf);
608 menu->help = helpstr;
611 set_option (OPTUNBUFFEREDINPUT);
613 switch (mutt_menuLoop (menu)) {
615 case OP_MAX + 1: /* reject */
619 case OP_MAX + 3: /* accept always */
621 if ((fp = fopen (SslCertFile, "a"))) {
622 if (PEM_write_X509 (fp, data->cert))
627 mutt_error (_("Warning: Couldn't save certificate"));
631 mutt_message (_("Certificate saved"));
635 case OP_MAX + 2: /* accept once */
637 /* keep a handle on accepted certificates in case we want to
638 * open up another connection to the same server in this session */
639 SslSessionCerts = mutt_add_list_n (SslSessionCerts, &data->cert,
644 unset_option (OPTUNBUFFEREDINPUT);
645 mutt_menuDestroy (&menu);
649 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn)
652 SSL_CTX_set_default_passwd_cb_userdata (ssldata->ctx, &conn->account);
653 SSL_CTX_set_default_passwd_cb (ssldata->ctx, ssl_passwd_cb);
654 SSL_CTX_use_certificate_file (ssldata->ctx, SslClientCert,
656 SSL_CTX_use_PrivateKey_file (ssldata->ctx, SslClientCert,
661 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata)
663 ACCOUNT *account = (ACCOUNT *) userdata;
665 if (mutt_account_getuser (account))
668 if (mutt_account_getpass (account))
671 return snprintf (buf, size, "%s", account->pass);