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>
25 #include <lib-lib/mem.h>
28 #include "mutt_socket.h"
29 #include "mutt_menu.h"
30 #include "mutt_curses.h"
35 #include "lib/debug.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;
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 {
67 /* local prototypes */
68 static int ssl_init (void);
69 static int add_entropy (const char *file);
70 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len);
71 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len);
72 static int ssl_socket_open (CONNECTION * conn);
73 static int ssl_socket_close (CONNECTION * conn);
74 static int tls_close (CONNECTION * conn);
75 static int ssl_check_certificate (sslsockdata * data);
76 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn);
77 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata);
78 static int ssl_negotiate (sslsockdata *);
80 /* mutt_ssl_starttls: Negotiate TLS over an already opened connection.
81 * TODO: Merge this code better with ssl_socket_open. */
82 int mutt_ssl_starttls (CONNECTION * conn)
90 ssldata = p_new(sslsockdata, 1);
91 /* the ssl_use_xxx protocol options don't apply. We must use TLS in TLS. */
92 if (!(ssldata->ctx = SSL_CTX_new (TLSv1_client_method ()))) {
93 debug_print (1, ("Error allocating SSL_CTX\n"));
97 ssl_get_client_cert (ssldata, conn);
99 if (!(ssldata->ssl = SSL_new (ssldata->ctx))) {
100 debug_print (1, ("Error allocating SSL\n"));
104 if (SSL_set_fd (ssldata->ssl, conn->fd) != 1) {
105 debug_print (1, ("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->conn_read = ssl_socket_read;
115 conn->conn_write = ssl_socket_write;
116 conn->conn_close = tls_close;
118 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
124 p_delete(&ssldata->ssl);
126 p_delete(&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)
143 static int ssl_init (void)
145 char path[_POSIX_PATH_MAX];
146 static unsigned char init_complete = 0;
151 if (!HAVE_ENTROPY ()) {
152 /* load entropy from files */
153 add_entropy (SslEntropyFile);
154 add_entropy (RAND_file_name (path, sizeof (path)));
156 /* load entropy from egd sockets */
158 add_entropy (getenv ("EGDSOCKET"));
159 snprintf (path, sizeof (path), "%s/.entropy", NONULL (Homedir));
161 add_entropy ("/tmp/entropy");
164 /* shuffle $RANDFILE (or ~/.rnd if unset) */
165 RAND_write_file (RAND_file_name (path, sizeof (path)));
167 if (!HAVE_ENTROPY ()) {
168 mutt_error (_("Failed to find enough entropy on your system"));
174 /* I don't think you can do this just before reading the error. The call
175 * itself might clobber the last SSL error. */
176 SSL_load_error_strings ();
182 static int add_entropy (const char *file)
190 if (stat (file, &st) == -1)
191 return errno == ENOENT ? 0 : -1;
193 mutt_message (_("Filling entropy pool: %s...\n"), file);
195 /* check that the file permissions are secure */
196 if (st.st_uid != getuid () ||
197 ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
198 ((st.st_mode & (S_IWOTH | S_IROTH)) != 0)) {
199 mutt_error (_("%s has insecure permissions!"), file);
208 n = RAND_load_file (file, -1);
210 #ifndef HAVE_RAND_STATUS
212 entropy_byte_count += n;
217 static int ssl_socket_open_err (CONNECTION * conn)
219 mutt_error (_("SSL disabled due the lack of entropy"));
225 int mutt_ssl_socket_setup (CONNECTION * conn)
227 if (ssl_init () < 0) {
228 conn->conn_open = ssl_socket_open_err;
232 conn->conn_open = ssl_socket_open;
233 conn->conn_read = ssl_socket_read;
234 conn->conn_write = ssl_socket_write;
235 conn->conn_close = ssl_socket_close;
240 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len)
242 sslsockdata *data = conn->sockdata;
244 return SSL_read (data->ssl, buf, len);
247 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len)
249 sslsockdata *data = conn->sockdata;
251 return SSL_write (data->ssl, buf, len);
254 static int ssl_socket_open (CONNECTION * conn)
259 if (raw_socket_open (conn) < 0)
262 data = p_new(sslsockdata, 1);
263 conn->sockdata = data;
265 data->ctx = SSL_CTX_new (SSLv23_client_method ());
267 /* disable SSL protocols as needed */
268 if (!option (OPTTLSV1)) {
269 SSL_CTX_set_options (data->ctx, SSL_OP_NO_TLSv1);
271 if (!option (OPTSSLV2)) {
272 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv2);
274 if (!option (OPTSSLV3)) {
275 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv3);
278 ssl_get_client_cert (data, conn);
280 data->ssl = SSL_new (data->ctx);
281 SSL_set_fd (data->ssl, conn->fd);
283 if (ssl_negotiate (data)) {
284 mutt_socket_close (conn);
288 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
294 /* ssl_negotiate: After SSL state has been initialised, attempt to negotiate
295 * SSL over the wire, including certificate checks. */
296 static int ssl_negotiate (sslsockdata * ssldata)
301 #if OPENSSL_VERSION_NUMBER >= 0x00906000L
302 /* This only exists in 0.9.6 and above. Without it we may get interrupted
303 * reads or writes. Bummer. */
304 SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY);
307 if ((err = SSL_connect (ssldata->ssl)) != 1) {
308 switch (SSL_get_error (ssldata->ssl, err)) {
309 case SSL_ERROR_SYSCALL:
310 errmsg = _("I/O error");
313 errmsg = ERR_error_string (ERR_get_error (), NULL);
316 errmsg = _("unknown error");
319 mutt_error (_("SSL failed: %s"), errmsg);
325 ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
326 if (!ssldata->cert) {
327 mutt_error (_("Unable to get certificate from peer"));
332 if (!ssl_check_certificate (ssldata))
335 mutt_message (_("SSL connection using %s (%s)"),
336 SSL_get_cipher_version (ssldata->ssl),
337 SSL_get_cipher_name (ssldata->ssl));
343 static int ssl_socket_close (CONNECTION * conn)
345 sslsockdata *data = conn->sockdata;
348 SSL_shutdown (data->ssl);
350 X509_free (data->cert);
352 SSL_free (data->ssl);
353 SSL_CTX_free (data->ctx);
354 p_delete(&conn->sockdata);
357 return raw_socket_close (conn);
360 static int compare_certificates (X509 *cert, X509 *peercert,
361 unsigned char *peermd,
362 unsigned int peermdlen) {
363 unsigned char md[EVP_MAX_MD_SIZE];
366 /* Avoid CPU-intensive digest calculation if the certificates are
367 * not even remotely equal.
369 if (X509_subject_name_cmp (cert, peercert) != 0 ||
370 X509_issuer_name_cmp (cert, peercert) != 0)
373 if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
376 if (memcmp(peermd, md, mdlen) != 0)
382 static int check_certificate_cache (X509 *peercert) {
383 unsigned char peermd[EVP_MAX_MD_SIZE];
384 unsigned int peermdlen;
388 if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
391 for (scert = SslSessionCerts; scert; scert = scert->next) {
392 cert = *(X509**)scert->data;
393 if (!compare_certificates (cert, peercert, peermd, peermdlen)) {
400 static int tls_close (CONNECTION * conn)
404 rc = ssl_socket_close (conn);
405 conn->conn_read = raw_socket_read;
406 conn->conn_write = raw_socket_write;
407 conn->conn_close = raw_socket_close;
412 static char *x509_get_part (char *line, const char *ndx)
414 static char ret[SHORT_STRING];
417 strfcpy (ret, _("Unknown"), sizeof (ret));
419 c = strstr (line, ndx);
422 c2 = strchr (c, '/');
425 strfcpy (ret, c, sizeof (ret));
433 static void x509_fingerprint (char *s, int l, X509 * cert)
435 unsigned char md[EVP_MAX_MD_SIZE];
439 if (!X509_digest (cert, EVP_md5 (), md, &n)) {
440 snprintf (s, l, "%s", _("[unable to calculate]"));
443 for (j = 0; j < (int) n; j++) {
446 snprintf (ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
452 static char *asn1time_to_string (ASN1_UTCTIME * tm)
457 strfcpy (buf, _("[invalid date]"), sizeof (buf));
459 bio = BIO_new (BIO_s_mem ());
461 if (ASN1_TIME_print (bio, tm))
462 (void) BIO_read (bio, buf, sizeof (buf));
469 static int check_certificate_by_signer (X509 * peercert)
475 ctx = X509_STORE_new ();
479 if (option (OPTSSLSYSTEMCERTS)) {
480 if (X509_STORE_set_default_paths (ctx))
483 debug_print (2, ("X509_STORE_set_default_paths failed\n"));
486 if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
489 debug_print (2, ("X509_STORE_load_locations_failed\n"));
493 X509_STORE_free (ctx);
497 X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
499 pass = (X509_verify_cert (&xsc) > 0);
502 char buf[SHORT_STRING];
505 err = X509_STORE_CTX_get_error (&xsc);
506 snprintf (buf, sizeof (buf), "%s (%d)",
507 X509_verify_cert_error_string (err), err);
508 debug_print (2, ("X509_verify_cert: %s\n", buf));
511 X509_STORE_CTX_cleanup (&xsc);
512 X509_STORE_free (ctx);
517 static int check_certificate_by_digest (X509 * peercert)
519 unsigned char peermd[EVP_MAX_MD_SIZE];
520 unsigned int peermdlen;
525 /* expiration check */
526 if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0) {
527 debug_print (2, ("Server certificate is not yet valid\n"));
528 mutt_error (_("Server certificate is not yet valid"));
532 if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0) {
533 debug_print (2, ("Server certificate has expired\n"));
534 mutt_error (_("Server certificate has expired"));
539 if ((fp = fopen (SslCertFile, "rt")) == NULL)
542 if (!X509_digest (peercert, EVP_sha1 (), peermd, &peermdlen)) {
547 while ((cert = READ_X509_KEY (fp, &cert)) != NULL) {
548 pass = compare_certificates (cert, peercert, peermd, peermdlen) ? 0 : 1;
558 static int ssl_check_certificate (sslsockdata * data)
560 char *part[] = { "/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C=" };
561 char helpstr[SHORT_STRING];
562 char buf[SHORT_STRING];
566 char *name = NULL, *c;
568 /* check session cache first */
569 if (check_certificate_cache (data->cert)) {
570 debug_print (1, ("ssl_check_certificate: using cached certificate\n"));
574 if (check_certificate_by_signer (data->cert)) {
575 debug_print (1, ("signer check passed\n"));
579 /* automatic check from user's database */
580 if (SslCertFile && check_certificate_by_digest (data->cert)) {
581 debug_print (1, ("digest check passed\n"));
585 /* interactive check from user */
586 menu = mutt_new_menu ();
588 menu->dialog = p_new(char *, menu->max);
589 for (i = 0; i < menu->max; i++)
590 menu->dialog[i] = p_new(char, SHORT_STRING);
593 strfcpy (menu->dialog[row], _("This certificate belongs to:"),
596 name = X509_NAME_oneline (X509_get_subject_name (data->cert),
598 for (i = 0; i < 5; i++) {
599 c = x509_get_part (name, part[i]);
600 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
604 strfcpy (menu->dialog[row], _("This certificate was issued by:"),
607 name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
609 for (i = 0; i < 5; i++) {
610 c = x509_get_part (name, part[i]);
611 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
615 snprintf (menu->dialog[row++], SHORT_STRING, "%s",
616 _("This certificate is valid"));
617 snprintf (menu->dialog[row++], SHORT_STRING, _(" from %s"),
618 asn1time_to_string (X509_get_notBefore (data->cert)));
619 snprintf (menu->dialog[row++], SHORT_STRING, _(" to %s"),
620 asn1time_to_string (X509_get_notAfter (data->cert)));
624 x509_fingerprint (buf, sizeof (buf), data->cert);
625 snprintf (menu->dialog[row++], SHORT_STRING, _("Fingerprint: %s"), buf);
627 menu->title = _("SSL Certificate check");
629 if (SslCertFile && X509_cmp_current_time (X509_get_notAfter (data->cert)) >= 0
630 && X509_cmp_current_time (X509_get_notBefore (data->cert)) < 0) {
631 menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
632 menu->keys = _("roa");
635 menu->prompt = _("(r)eject, accept (o)nce");
636 menu->keys = _("ro");
640 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_GENERIC, OP_EXIT);
641 str_cat (helpstr, sizeof (helpstr), buf);
642 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
643 str_cat (helpstr, sizeof (helpstr), buf);
644 menu->help = helpstr;
647 set_option (OPTUNBUFFEREDINPUT);
649 switch (mutt_menuLoop (menu)) {
651 case OP_MAX + 1: /* reject */
655 case OP_MAX + 3: /* accept always */
657 if ((fp = fopen (SslCertFile, "a"))) {
658 if (PEM_write_X509 (fp, data->cert))
663 mutt_error (_("Warning: Couldn't save certificate"));
667 mutt_message (_("Certificate saved"));
671 case OP_MAX + 2: /* accept once */
673 /* keep a handle on accepted certificates in case we want to
674 * open up another connection to the same server in this session */
675 SslSessionCerts = mutt_add_list_n (SslSessionCerts, &data->cert,
680 unset_option (OPTUNBUFFEREDINPUT);
681 mutt_menuDestroy (&menu);
685 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn)
688 debug_print (2, ("Using client certificate %s\n", SslClientCert));
689 SSL_CTX_set_default_passwd_cb_userdata (ssldata->ctx, &conn->account);
690 SSL_CTX_set_default_passwd_cb (ssldata->ctx, ssl_passwd_cb);
691 SSL_CTX_use_certificate_file (ssldata->ctx, SslClientCert,
693 SSL_CTX_use_PrivateKey_file (ssldata->ctx, SslClientCert,
698 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata)
700 ACCOUNT *account = (ACCOUNT *) userdata;
702 if (mutt_account_getuser (account))
705 debug_print (2, ("getting password for %s@%s:%u\n",
706 account->user, account->host, account->port));
708 if (mutt_account_getpass (account))
711 return snprintf (buf, size, "%s", account->pass);