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.
16 #include <openssl/ssl.h>
17 #include <openssl/x509.h>
18 #include <openssl/err.h>
19 #include <openssl/rand.h>
23 #include <lib-lib/lib-lib.h>
25 #include <lib-ui/curses.h>
26 #include <lib-ui/menu.h>
29 #include "mutt_socket.h"
33 #if OPENSSL_VERSION_NUMBER >= 0x00904000L
34 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL, NULL)
36 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL)
39 /* Just in case OpenSSL doesn't define DEVRANDOM */
41 #define DEVRANDOM "/dev/urandom"
44 /* This is ugly, but as RAND_status came in on OpenSSL version 0.9.5
45 * and the code has to support older versions too, this is seemed to
46 * be cleaner way compared to having even uglier #ifdefs all around.
48 #ifdef HAVE_RAND_STATUS
49 #define HAVE_ENTROPY() (RAND_status() == 1)
51 static int entropy_byte_count = 0;
53 /* OpenSSL fills the entropy pool from /dev/urandom if it exists */
54 #define HAVE_ENTROPY() (!access(DEVRANDOM, R_OK) || entropy_byte_count >= 16)
57 typedef struct _sslsockdata {
63 /* local prototypes */
64 static int ssl_init (void);
65 static int add_entropy (const char *file);
66 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len);
67 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len);
68 static int ssl_socket_open (CONNECTION * conn);
69 static int ssl_socket_close (CONNECTION * conn);
70 static int tls_close (CONNECTION * conn);
71 static int ssl_check_certificate (sslsockdata * data);
72 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn);
73 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata);
74 static int ssl_negotiate (sslsockdata *);
76 /* mutt_ssl_starttls: Negotiate TLS over an already opened connection.
77 * TODO: Merge this code better with ssl_socket_open. */
78 int mutt_ssl_starttls (CONNECTION * conn)
86 ssldata = p_new(sslsockdata, 1);
87 /* the ssl_use_xxx protocol options don't apply. We must use TLS in TLS. */
88 if (!(ssldata->ctx = SSL_CTX_new (TLSv1_client_method ()))) {
92 ssl_get_client_cert (ssldata, conn);
94 if (!(ssldata->ssl = SSL_new (ssldata->ctx))) {
98 if (SSL_set_fd (ssldata->ssl, conn->fd) != 1) {
102 if (ssl_negotiate (ssldata))
105 /* hmm. watch out if we're starting TLS over any method other than raw. */
106 conn->sockdata = ssldata;
107 conn->conn_read = ssl_socket_read;
108 conn->conn_write = ssl_socket_write;
109 conn->conn_close = tls_close;
111 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
117 p_delete(&ssldata->ssl);
119 p_delete(&ssldata->ctx);
127 * OpenSSL library needs to be fed with sufficient entropy. On systems
128 * with /dev/urandom, this is done transparently by the library itself,
129 * on other systems we need to fill the entropy pool ourselves.
131 * Even though only OpenSSL 0.9.5 and later will complain about the
132 * lack of entropy, we try to our best and fill the pool with older
133 * versions also. (That's the reason for the ugly #ifdefs and macros,
134 * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
136 static int ssl_init (void)
138 char path[_POSIX_PATH_MAX];
139 static unsigned char init_complete = 0;
144 if (!HAVE_ENTROPY ()) {
145 /* load entropy from files */
146 add_entropy (SslEntropyFile);
147 add_entropy (RAND_file_name (path, sizeof (path)));
149 /* load entropy from egd sockets */
151 add_entropy (getenv ("EGDSOCKET"));
152 snprintf (path, sizeof (path), "%s/.entropy", NONULL (Homedir));
154 add_entropy ("/tmp/entropy");
157 /* shuffle $RANDFILE (or ~/.rnd if unset) */
158 RAND_write_file (RAND_file_name (path, sizeof (path)));
160 if (!HAVE_ENTROPY ()) {
161 mutt_error (_("Failed to find enough entropy on your system"));
167 /* I don't think you can do this just before reading the error. The call
168 * itself might clobber the last SSL error. */
169 SSL_load_error_strings ();
175 static int add_entropy (const char *file)
183 if (stat (file, &st) == -1)
184 return errno == ENOENT ? 0 : -1;
186 mutt_message (_("Filling entropy pool: %s...\n"), file);
188 /* check that the file permissions are secure */
189 if (st.st_uid != getuid () ||
190 ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
191 ((st.st_mode & (S_IWOTH | S_IROTH)) != 0)) {
192 mutt_error (_("%s has insecure permissions!"), file);
201 n = RAND_load_file (file, -1);
203 #ifndef HAVE_RAND_STATUS
205 entropy_byte_count += n;
210 static int ssl_socket_open_err (CONNECTION * conn)
212 mutt_error (_("SSL disabled due the lack of entropy"));
218 int mutt_ssl_socket_setup (CONNECTION * conn)
220 if (ssl_init () < 0) {
221 conn->conn_open = ssl_socket_open_err;
225 conn->conn_open = ssl_socket_open;
226 conn->conn_read = ssl_socket_read;
227 conn->conn_write = ssl_socket_write;
228 conn->conn_close = ssl_socket_close;
233 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len)
235 sslsockdata *data = conn->sockdata;
237 return SSL_read (data->ssl, buf, len);
240 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len)
242 sslsockdata *data = conn->sockdata;
244 return SSL_write (data->ssl, buf, len);
247 static int ssl_socket_open (CONNECTION * conn)
252 if (raw_socket_open (conn) < 0)
255 data = p_new(sslsockdata, 1);
256 conn->sockdata = data;
258 data->ctx = SSL_CTX_new (SSLv23_client_method ());
260 /* disable SSL protocols as needed */
261 if (!option (OPTTLSV1)) {
262 SSL_CTX_set_options (data->ctx, SSL_OP_NO_TLSv1);
264 if (!option (OPTSSLV2)) {
265 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv2);
267 if (!option (OPTSSLV3)) {
268 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv3);
271 ssl_get_client_cert (data, conn);
273 data->ssl = SSL_new (data->ctx);
274 SSL_set_fd (data->ssl, conn->fd);
276 if (ssl_negotiate (data)) {
277 mutt_socket_close (conn);
281 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
287 /* ssl_negotiate: After SSL state has been initialised, attempt to negotiate
288 * SSL over the wire, including certificate checks. */
289 static int ssl_negotiate (sslsockdata * ssldata)
294 #if OPENSSL_VERSION_NUMBER >= 0x00906000L
295 /* This only exists in 0.9.6 and above. Without it we may get interrupted
296 * reads or writes. Bummer. */
297 SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY);
300 if ((err = SSL_connect (ssldata->ssl)) != 1) {
301 switch (SSL_get_error (ssldata->ssl, err)) {
302 case SSL_ERROR_SYSCALL:
303 errmsg = _("I/O error");
306 errmsg = ERR_error_string (ERR_get_error (), NULL);
309 errmsg = _("unknown error");
312 mutt_error (_("SSL failed: %s"), errmsg);
318 ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
319 if (!ssldata->cert) {
320 mutt_error (_("Unable to get certificate from peer"));
325 if (!ssl_check_certificate (ssldata))
328 mutt_message (_("SSL connection using %s (%s)"),
329 SSL_get_cipher_version (ssldata->ssl),
330 SSL_get_cipher_name (ssldata->ssl));
336 static int ssl_socket_close (CONNECTION * conn)
338 sslsockdata *data = conn->sockdata;
341 SSL_shutdown (data->ssl);
343 X509_free (data->cert);
345 SSL_free (data->ssl);
346 SSL_CTX_free (data->ctx);
347 p_delete(&conn->sockdata);
350 return raw_socket_close (conn);
353 static int compare_certificates (X509 *cert, X509 *peercert,
354 unsigned char *peermd,
355 unsigned int peermdlen) {
356 unsigned char md[EVP_MAX_MD_SIZE];
359 /* Avoid CPU-intensive digest calculation if the certificates are
360 * not even remotely equal.
362 if (X509_subject_name_cmp (cert, peercert) != 0 ||
363 X509_issuer_name_cmp (cert, peercert) != 0)
366 if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
369 if (memcmp(peermd, md, mdlen) != 0)
375 static int check_certificate_cache (X509 *peercert) {
376 unsigned char peermd[EVP_MAX_MD_SIZE];
377 unsigned int peermdlen;
379 string_list_t *scert;
381 if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
384 for (scert = SslSessionCerts; scert; scert = scert->next) {
385 cert = *(X509**)scert->data;
386 if (!compare_certificates (cert, peercert, peermd, peermdlen)) {
393 static int tls_close (CONNECTION * conn)
397 rc = ssl_socket_close (conn);
398 conn->conn_read = raw_socket_read;
399 conn->conn_write = raw_socket_write;
400 conn->conn_close = raw_socket_close;
405 static char *x509_get_part (char *line, const char *ndx)
407 static char ret[SHORT_STRING];
410 m_strcpy(ret, sizeof(ret), _("Unknown"));
412 c = strstr (line, ndx);
415 c2 = strchr (c, '/');
418 m_strcpy(ret, sizeof(ret), c);
426 static void x509_fingerprint (char *s, int l, X509 * cert)
428 unsigned char md[EVP_MAX_MD_SIZE];
432 if (!X509_digest (cert, EVP_md5 (), md, &n)) {
433 m_strcpy(s, l, _("[unable to calculate]"));
436 for (j = 0; j < (int) n; j++) {
439 snprintf(ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
445 static char *asn1time_to_string (ASN1_UTCTIME * tm)
450 m_strcpy(buf, sizeof(buf), _("[invalid date]"));
452 bio = BIO_new (BIO_s_mem ());
454 if (ASN1_TIME_print (bio, tm))
455 (void) BIO_read (bio, buf, sizeof (buf));
462 static int check_certificate_by_signer (X509 * peercert)
468 ctx = X509_STORE_new ();
472 if (option (OPTSSLSYSTEMCERTS)) {
473 if (X509_STORE_set_default_paths (ctx))
477 if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
482 X509_STORE_free (ctx);
486 X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
488 pass = (X509_verify_cert (&xsc) > 0);
489 X509_STORE_CTX_cleanup (&xsc);
490 X509_STORE_free (ctx);
495 static int check_certificate_by_digest (X509 * peercert)
497 unsigned char peermd[EVP_MAX_MD_SIZE];
498 unsigned int peermdlen;
503 /* expiration check */
504 if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0) {
505 mutt_error (_("Server certificate is not yet valid"));
509 if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0) {
510 mutt_error (_("Server certificate has expired"));
515 if ((fp = fopen (SslCertFile, "rt")) == NULL)
518 if (!X509_digest (peercert, EVP_sha1 (), peermd, &peermdlen)) {
523 while ((cert = READ_X509_KEY (fp, &cert)) != NULL) {
524 pass = compare_certificates (cert, peercert, peermd, peermdlen) ? 0 : 1;
534 static int ssl_check_certificate (sslsockdata * data)
536 char *part[] = { "/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C=" };
537 char helpstr[SHORT_STRING];
538 char buf[SHORT_STRING];
542 char *name = NULL, *c;
544 /* check session cache first */
545 if (check_certificate_cache (data->cert)) {
549 if (check_certificate_by_signer (data->cert)) {
553 /* automatic check from user's database */
554 if (SslCertFile && check_certificate_by_digest (data->cert)) {
558 /* interactive check from user */
559 menu = mutt_new_menu ();
561 menu->dialog = p_new(char *, menu->max);
562 for (i = 0; i < menu->max; i++)
563 menu->dialog[i] = p_new(char, SHORT_STRING);
566 m_strcpy(menu->dialog[row], SHORT_STRING,
567 _("This certificate belongs to:"));
569 name = X509_NAME_oneline (X509_get_subject_name (data->cert),
571 for (i = 0; i < 5; i++) {
572 c = x509_get_part (name, part[i]);
573 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
577 m_strcpy(menu->dialog[row], SHORT_STRING,
578 _("This certificate was issued by:"));
580 name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
582 for (i = 0; i < 5; i++) {
583 c = x509_get_part (name, part[i]);
584 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
588 snprintf (menu->dialog[row++], SHORT_STRING, "%s",
589 _("This certificate is valid"));
590 snprintf (menu->dialog[row++], SHORT_STRING, _(" from %s"),
591 asn1time_to_string (X509_get_notBefore (data->cert)));
592 snprintf (menu->dialog[row++], SHORT_STRING, _(" to %s"),
593 asn1time_to_string (X509_get_notAfter (data->cert)));
597 x509_fingerprint (buf, sizeof (buf), data->cert);
598 snprintf (menu->dialog[row++], SHORT_STRING, _("Fingerprint: %s"), buf);
600 menu->title = _("SSL Certificate check");
602 if (SslCertFile && X509_cmp_current_time (X509_get_notAfter (data->cert)) >= 0
603 && X509_cmp_current_time (X509_get_notBefore (data->cert)) < 0) {
604 menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
605 menu->keys = _("roa");
608 menu->prompt = _("(r)eject, accept (o)nce");
609 menu->keys = _("ro");
613 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_GENERIC, OP_EXIT);
614 m_strcat(helpstr, sizeof(helpstr), buf);
615 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
616 m_strcat(helpstr, sizeof(helpstr), buf);
617 menu->help = helpstr;
620 set_option (OPTUNBUFFEREDINPUT);
622 switch (mutt_menuLoop (menu)) {
624 case OP_MAX + 1: /* reject */
628 case OP_MAX + 3: /* accept always */
630 if ((fp = fopen (SslCertFile, "a"))) {
631 if (PEM_write_X509 (fp, data->cert))
636 mutt_error (_("Warning: Couldn't save certificate"));
640 mutt_message (_("Certificate saved"));
644 case OP_MAX + 2: /* accept once */
646 /* keep a handle on accepted certificates in case we want to
647 * open up another connection to the same server in this session */
648 SslSessionCerts = mutt_add_list_n (SslSessionCerts, &data->cert,
653 unset_option (OPTUNBUFFEREDINPUT);
654 mutt_menuDestroy (&menu);
658 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn)
661 SSL_CTX_set_default_passwd_cb_userdata (ssldata->ctx, &conn->account);
662 SSL_CTX_set_default_passwd_cb (ssldata->ctx, ssl_passwd_cb);
663 SSL_CTX_use_certificate_file (ssldata->ctx, SslClientCert,
665 SSL_CTX_use_PrivateKey_file (ssldata->ctx, SslClientCert,
670 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata)
672 ACCOUNT *account = (ACCOUNT *) userdata;
674 if (mutt_account_getuser (account))
677 if (mutt_account_getpass (account))
680 return snprintf (buf, size, "%s", account->pass);