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"
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 */
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 = (sslsockdata *) safe_calloc (1, sizeof (sslsockdata));
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 ()))) {
89 dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL_CTX\n"));
93 ssl_get_client_cert (ssldata, conn);
95 if (!(ssldata->ssl = SSL_new (ssldata->ctx))) {
96 dprint (1, (debugfile, "mutt_ssl_starttls: Error allocating SSL\n"));
100 if (SSL_set_fd (ssldata->ssl, conn->fd) != 1) {
101 dprint (1, (debugfile, "mutt_ssl_starttls: Error setting fd\n"));
105 if (ssl_negotiate (ssldata))
108 /* hmm. watch out if we're starting TLS over any method other than raw. */
109 conn->sockdata = ssldata;
110 conn->conn_read = ssl_socket_read;
111 conn->conn_write = ssl_socket_write;
112 conn->conn_close = tls_close;
114 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
120 FREE (&ssldata->ssl);
122 FREE (&ssldata->ctx);
130 * OpenSSL library needs to be fed with sufficient entropy. On systems
131 * with /dev/urandom, this is done transparently by the library itself,
132 * on other systems we need to fill the entropy pool ourselves.
134 * Even though only OpenSSL 0.9.5 and later will complain about the
135 * lack of entropy, we try to our best and fill the pool with older
136 * versions also. (That's the reason for the ugly #ifdefs and macros,
137 * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
141 char path[_POSIX_PATH_MAX];
142 static unsigned char init_complete = 0;
147 if (!HAVE_ENTROPY ()) {
148 /* load entropy from files */
149 add_entropy (SslEntropyFile);
150 add_entropy (RAND_file_name (path, sizeof (path)));
152 /* load entropy from egd sockets */
154 add_entropy (getenv ("EGDSOCKET"));
155 snprintf (path, sizeof (path), "%s/.entropy", NONULL (Homedir));
157 add_entropy ("/tmp/entropy");
160 /* shuffle $RANDFILE (or ~/.rnd if unset) */
161 RAND_write_file (RAND_file_name (path, sizeof (path)));
163 if (!HAVE_ENTROPY ()) {
164 mutt_error (_("Failed to find enough entropy on your system"));
170 /* I don't think you can do this just before reading the error. The call
171 * itself might clobber the last SSL error. */
172 SSL_load_error_strings ();
178 static int add_entropy (const char *file)
186 if (stat (file, &st) == -1)
187 return errno == ENOENT ? 0 : -1;
189 mutt_message (_("Filling entropy pool: %s...\n"), file);
191 /* check that the file permissions are secure */
192 if (st.st_uid != getuid () ||
193 ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
194 ((st.st_mode & (S_IWOTH | S_IROTH)) != 0)) {
195 mutt_error (_("%s has insecure permissions!"), file);
204 n = RAND_load_file (file, -1);
206 #ifndef HAVE_RAND_STATUS
208 entropy_byte_count += n;
213 static int ssl_socket_open_err (CONNECTION * conn)
215 mutt_error (_("SSL disabled due the lack of entropy"));
221 int ssl_socket_setup (CONNECTION * conn)
223 if (ssl_init () < 0) {
224 conn->conn_open = ssl_socket_open_err;
228 conn->conn_open = ssl_socket_open;
229 conn->conn_read = ssl_socket_read;
230 conn->conn_write = ssl_socket_write;
231 conn->conn_close = ssl_socket_close;
236 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len)
238 sslsockdata *data = conn->sockdata;
240 return SSL_read (data->ssl, buf, len);
243 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len)
245 sslsockdata *data = conn->sockdata;
247 return SSL_write (data->ssl, buf, len);
250 static int ssl_socket_open (CONNECTION * conn)
255 if (raw_socket_open (conn) < 0)
258 data = (sslsockdata *) safe_calloc (1, sizeof (sslsockdata));
259 conn->sockdata = data;
261 data->ctx = SSL_CTX_new (SSLv23_client_method ());
263 /* disable SSL protocols as needed */
264 if (!option (OPTTLSV1)) {
265 SSL_CTX_set_options (data->ctx, SSL_OP_NO_TLSv1);
267 if (!option (OPTSSLV2)) {
268 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv2);
270 if (!option (OPTSSLV3)) {
271 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv3);
274 ssl_get_client_cert (data, conn);
276 data->ssl = SSL_new (data->ctx);
277 SSL_set_fd (data->ssl, conn->fd);
279 if (ssl_negotiate (data)) {
280 mutt_socket_close (conn);
284 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
290 /* ssl_negotiate: After SSL state has been initialised, attempt to negotiate
291 * SSL over the wire, including certificate checks. */
292 static int ssl_negotiate (sslsockdata * ssldata)
297 #if OPENSSL_VERSION_NUMBER >= 0x00906000L
298 /* This only exists in 0.9.6 and above. Without it we may get interrupted
299 * reads or writes. Bummer. */
300 SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY);
303 if ((err = SSL_connect (ssldata->ssl)) != 1) {
304 switch (SSL_get_error (ssldata->ssl, err)) {
305 case SSL_ERROR_SYSCALL:
306 errmsg = _("I/O error");
309 errmsg = ERR_error_string (ERR_get_error (), NULL);
312 errmsg = _("unknown error");
315 mutt_error (_("SSL failed: %s"), errmsg);
321 ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
322 if (!ssldata->cert) {
323 mutt_error (_("Unable to get certificate from peer"));
328 if (!ssl_check_certificate (ssldata))
331 mutt_message (_("SSL connection using %s (%s)"),
332 SSL_get_cipher_version (ssldata->ssl),
333 SSL_get_cipher_name (ssldata->ssl));
339 static int ssl_socket_close (CONNECTION * conn)
341 sslsockdata *data = conn->sockdata;
344 SSL_shutdown (data->ssl);
346 X509_free (data->cert);
347 SSL_free (data->ssl);
348 SSL_CTX_free (data->ctx);
349 FREE (&conn->sockdata);
352 return raw_socket_close (conn);
355 static int tls_close (CONNECTION * conn)
359 rc = ssl_socket_close (conn);
360 conn->conn_read = raw_socket_read;
361 conn->conn_write = raw_socket_write;
362 conn->conn_close = raw_socket_close;
367 static char *x509_get_part (char *line, const char *ndx)
369 static char ret[SHORT_STRING];
372 strfcpy (ret, _("Unknown"), sizeof (ret));
374 c = strstr (line, ndx);
376 c += mutt_strlen (ndx);
377 c2 = strchr (c, '/');
380 strfcpy (ret, c, sizeof (ret));
388 static void x509_fingerprint (char *s, int l, X509 * cert)
390 unsigned char md[EVP_MAX_MD_SIZE];
394 if (!X509_digest (cert, EVP_md5 (), md, &n)) {
395 snprintf (s, l, "%s", _("[unable to calculate]"));
398 for (j = 0; j < (int) n; j++) {
401 snprintf (ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
402 safe_strcat (s, l, ch);
407 static char *asn1time_to_string (ASN1_UTCTIME * tm)
412 strfcpy (buf, _("[invalid date]"), sizeof (buf));
414 bio = BIO_new (BIO_s_mem ());
416 if (ASN1_TIME_print (bio, tm))
417 (void) BIO_read (bio, buf, sizeof (buf));
424 static int check_certificate_by_signer (X509 * peercert)
430 ctx = X509_STORE_new ();
434 if (option (OPTSSLSYSTEMCERTS)) {
435 if (X509_STORE_set_default_paths (ctx))
438 dprint (2, (debugfile, "X509_STORE_set_default_paths failed\n"));
441 if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
444 dprint (2, (debugfile, "X509_STORE_load_locations_failed\n"));
448 X509_STORE_free (ctx);
452 X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
454 pass = (X509_verify_cert (&xsc) > 0);
457 char buf[SHORT_STRING];
460 err = X509_STORE_CTX_get_error (&xsc);
461 snprintf (buf, sizeof (buf), "%s (%d)",
462 X509_verify_cert_error_string (err), err);
463 dprint (2, (debugfile, "X509_verify_cert: %s\n", buf));
466 X509_STORE_CTX_cleanup (&xsc);
467 X509_STORE_free (ctx);
472 static int check_certificate_by_digest (X509 * peercert)
474 unsigned char peermd[EVP_MAX_MD_SIZE];
475 unsigned int peermdlen;
480 /* expiration check */
481 if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0) {
482 dprint (2, (debugfile, "Server certificate is not yet valid\n"));
483 mutt_error (_("Server certificate is not yet valid"));
487 if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0) {
488 dprint (2, (debugfile, "Server certificate has expired"));
489 mutt_error (_("Server certificate has expired"));
494 if ((fp = fopen (SslCertFile, "rt")) == NULL)
497 if (!X509_digest (peercert, EVP_sha1 (), peermd, &peermdlen)) {
502 while ((cert = READ_X509_KEY (fp, &cert)) != NULL) {
503 unsigned char md[EVP_MAX_MD_SIZE];
506 /* Avoid CPU-intensive digest calculation if the certificates are
507 * not even remotely equal.
509 if (X509_subject_name_cmp (cert, peercert) != 0 ||
510 X509_issuer_name_cmp (cert, peercert) != 0)
513 if (!X509_digest (cert, EVP_sha1 (), md, &mdlen) || peermdlen != mdlen)
516 if (memcmp (peermd, md, mdlen) != 0)
528 static int ssl_check_certificate (sslsockdata * data)
530 char *part[] = { "/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C=" };
531 char helpstr[SHORT_STRING];
532 char buf[SHORT_STRING];
536 char *name = NULL, *c;
538 if (check_certificate_by_signer (data->cert)) {
539 dprint (1, (debugfile, "ssl_check_certificate: signer check passed\n"));
543 /* automatic check from user's database */
544 if (SslCertFile && check_certificate_by_digest (data->cert)) {
545 dprint (1, (debugfile, "ssl_check_certificate: digest check passed\n"));
549 /* interactive check from user */
550 menu = mutt_new_menu ();
552 menu->dialog = (char **) safe_calloc (1, menu->max * sizeof (char *));
553 for (i = 0; i < menu->max; i++)
554 menu->dialog[i] = (char *) safe_calloc (1, SHORT_STRING * sizeof (char));
557 strfcpy (menu->dialog[row], _("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++], SHORT_STRING, " %s", c);
568 strfcpy (menu->dialog[row], _("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++], SHORT_STRING, " %s", c);
579 snprintf (menu->dialog[row++], SHORT_STRING, "%s",
580 _("This certificate is valid"));
581 snprintf (menu->dialog[row++], SHORT_STRING, _(" from %s"),
582 asn1time_to_string (X509_get_notBefore (data->cert)));
583 snprintf (menu->dialog[row++], SHORT_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++], SHORT_STRING, _("Fingerprint: %s"), buf);
591 menu->title = _("SSL Certificate check");
593 menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
594 menu->keys = _("roa");
597 menu->prompt = _("(r)eject, accept (o)nce");
598 menu->keys = _("ro");
602 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_GENERIC, OP_EXIT);
603 safe_strcat (helpstr, sizeof (helpstr), buf);
604 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
605 safe_strcat (helpstr, sizeof (helpstr), buf);
606 menu->help = helpstr;
609 set_option (OPTUNBUFFEREDINPUT);
611 switch (mutt_menuLoop (menu)) {
613 case OP_MAX + 1: /* reject */
617 case OP_MAX + 3: /* accept always */
619 if ((fp = fopen (SslCertFile, "a"))) {
620 if (PEM_write_X509 (fp, data->cert))
625 mutt_error (_("Warning: Couldn't save certificate"));
629 mutt_message (_("Certificate saved"));
633 case OP_MAX + 2: /* accept once */
638 unset_option (OPTUNBUFFEREDINPUT);
639 mutt_menuDestroy (&menu);
643 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn)
646 dprint (2, (debugfile, "Using client certificate %s\n", SslClientCert));
647 SSL_CTX_set_default_passwd_cb_userdata (ssldata->ctx, &conn->account);
648 SSL_CTX_set_default_passwd_cb (ssldata->ctx, ssl_passwd_cb);
649 SSL_CTX_use_certificate_file (ssldata->ctx, SslClientCert,
651 SSL_CTX_use_PrivateKey_file (ssldata->ctx, SslClientCert,
656 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata)
658 ACCOUNT *account = (ACCOUNT *) userdata;
660 if (mutt_account_getuser (account))
663 dprint (2, (debugfile, "ssl_passwd_cb: getting password for %s@%s:%u\n",
664 account->user, account->host, account->port));
666 if (mutt_account_getpass (account))
669 return snprintf (buf, size, "%s", account->pass);