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/mem.h>
24 #include <lib-lib/str.h>
25 #include <lib-lib/macros.h>
26 #include <lib-lib/debug.h>
28 #include <lib-ui/curses.h>
29 #include <lib-ui/menu.h>
32 #include "mutt_socket.h"
36 #if OPENSSL_VERSION_NUMBER >= 0x00904000L
37 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL, NULL)
39 #define READ_X509_KEY(fp, key) PEM_read_X509(fp, key, NULL)
42 /* Just in case OpenSSL doesn't define DEVRANDOM */
44 #define DEVRANDOM "/dev/urandom"
47 /* This is ugly, but as RAND_status came in on OpenSSL version 0.9.5
48 * and the code has to support older versions too, this is seemed to
49 * be cleaner way compared to having even uglier #ifdefs all around.
51 #ifdef HAVE_RAND_STATUS
52 #define HAVE_ENTROPY() (RAND_status() == 1)
54 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 {
66 /* local prototypes */
67 static int ssl_init (void);
68 static int add_entropy (const char *file);
69 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len);
70 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len);
71 static int ssl_socket_open (CONNECTION * conn);
72 static int ssl_socket_close (CONNECTION * conn);
73 static int tls_close (CONNECTION * conn);
74 static int ssl_check_certificate (sslsockdata * data);
75 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn);
76 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata);
77 static 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 = p_new(sslsockdata, 1);
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 ()))) {
92 debug_print (1, ("Error allocating SSL_CTX\n"));
96 ssl_get_client_cert (ssldata, conn);
98 if (!(ssldata->ssl = SSL_new (ssldata->ctx))) {
99 debug_print (1, ("Error allocating SSL\n"));
103 if (SSL_set_fd (ssldata->ssl, conn->fd) != 1) {
104 debug_print (1, ("Error setting fd\n"));
108 if (ssl_negotiate (ssldata))
111 /* hmm. watch out if we're starting TLS over any method other than raw. */
112 conn->sockdata = ssldata;
113 conn->conn_read = ssl_socket_read;
114 conn->conn_write = ssl_socket_write;
115 conn->conn_close = tls_close;
117 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssldata->ssl),
123 p_delete(&ssldata->ssl);
125 p_delete(&ssldata->ctx);
133 * OpenSSL library needs to be fed with sufficient entropy. On systems
134 * with /dev/urandom, this is done transparently by the library itself,
135 * on other systems we need to fill the entropy pool ourselves.
137 * Even though only OpenSSL 0.9.5 and later will complain about the
138 * lack of entropy, we try to our best and fill the pool with older
139 * versions also. (That's the reason for the ugly #ifdefs and macros,
140 * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
142 static int ssl_init (void)
144 char path[_POSIX_PATH_MAX];
145 static unsigned char init_complete = 0;
150 if (!HAVE_ENTROPY ()) {
151 /* load entropy from files */
152 add_entropy (SslEntropyFile);
153 add_entropy (RAND_file_name (path, sizeof (path)));
155 /* load entropy from egd sockets */
157 add_entropy (getenv ("EGDSOCKET"));
158 snprintf (path, sizeof (path), "%s/.entropy", NONULL (Homedir));
160 add_entropy ("/tmp/entropy");
163 /* shuffle $RANDFILE (or ~/.rnd if unset) */
164 RAND_write_file (RAND_file_name (path, sizeof (path)));
166 if (!HAVE_ENTROPY ()) {
167 mutt_error (_("Failed to find enough entropy on your system"));
173 /* I don't think you can do this just before reading the error. The call
174 * itself might clobber the last SSL error. */
175 SSL_load_error_strings ();
181 static int add_entropy (const char *file)
189 if (stat (file, &st) == -1)
190 return errno == ENOENT ? 0 : -1;
192 mutt_message (_("Filling entropy pool: %s...\n"), file);
194 /* check that the file permissions are secure */
195 if (st.st_uid != getuid () ||
196 ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
197 ((st.st_mode & (S_IWOTH | S_IROTH)) != 0)) {
198 mutt_error (_("%s has insecure permissions!"), file);
207 n = RAND_load_file (file, -1);
209 #ifndef HAVE_RAND_STATUS
211 entropy_byte_count += n;
216 static int ssl_socket_open_err (CONNECTION * conn)
218 mutt_error (_("SSL disabled due the lack of entropy"));
224 int mutt_ssl_socket_setup (CONNECTION * conn)
226 if (ssl_init () < 0) {
227 conn->conn_open = ssl_socket_open_err;
231 conn->conn_open = ssl_socket_open;
232 conn->conn_read = ssl_socket_read;
233 conn->conn_write = ssl_socket_write;
234 conn->conn_close = ssl_socket_close;
239 static int ssl_socket_read (CONNECTION * conn, char *buf, size_t len)
241 sslsockdata *data = conn->sockdata;
243 return SSL_read (data->ssl, buf, len);
246 static int ssl_socket_write (CONNECTION * conn, const char *buf, size_t len)
248 sslsockdata *data = conn->sockdata;
250 return SSL_write (data->ssl, buf, len);
253 static int ssl_socket_open (CONNECTION * conn)
258 if (raw_socket_open (conn) < 0)
261 data = p_new(sslsockdata, 1);
262 conn->sockdata = data;
264 data->ctx = SSL_CTX_new (SSLv23_client_method ());
266 /* disable SSL protocols as needed */
267 if (!option (OPTTLSV1)) {
268 SSL_CTX_set_options (data->ctx, SSL_OP_NO_TLSv1);
270 if (!option (OPTSSLV2)) {
271 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv2);
273 if (!option (OPTSSLV3)) {
274 SSL_CTX_set_options (data->ctx, SSL_OP_NO_SSLv3);
277 ssl_get_client_cert (data, conn);
279 data->ssl = SSL_new (data->ctx);
280 SSL_set_fd (data->ssl, conn->fd);
282 if (ssl_negotiate (data)) {
283 mutt_socket_close (conn);
287 conn->ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (data->ssl),
293 /* ssl_negotiate: After SSL state has been initialised, attempt to negotiate
294 * SSL over the wire, including certificate checks. */
295 static int ssl_negotiate (sslsockdata * ssldata)
300 #if OPENSSL_VERSION_NUMBER >= 0x00906000L
301 /* This only exists in 0.9.6 and above. Without it we may get interrupted
302 * reads or writes. Bummer. */
303 SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY);
306 if ((err = SSL_connect (ssldata->ssl)) != 1) {
307 switch (SSL_get_error (ssldata->ssl, err)) {
308 case SSL_ERROR_SYSCALL:
309 errmsg = _("I/O error");
312 errmsg = ERR_error_string (ERR_get_error (), NULL);
315 errmsg = _("unknown error");
318 mutt_error (_("SSL failed: %s"), errmsg);
324 ssldata->cert = SSL_get_peer_certificate (ssldata->ssl);
325 if (!ssldata->cert) {
326 mutt_error (_("Unable to get certificate from peer"));
331 if (!ssl_check_certificate (ssldata))
334 mutt_message (_("SSL connection using %s (%s)"),
335 SSL_get_cipher_version (ssldata->ssl),
336 SSL_get_cipher_name (ssldata->ssl));
342 static int ssl_socket_close (CONNECTION * conn)
344 sslsockdata *data = conn->sockdata;
347 SSL_shutdown (data->ssl);
349 X509_free (data->cert);
351 SSL_free (data->ssl);
352 SSL_CTX_free (data->ctx);
353 p_delete(&conn->sockdata);
356 return raw_socket_close (conn);
359 static int compare_certificates (X509 *cert, X509 *peercert,
360 unsigned char *peermd,
361 unsigned int peermdlen) {
362 unsigned char md[EVP_MAX_MD_SIZE];
365 /* Avoid CPU-intensive digest calculation if the certificates are
366 * not even remotely equal.
368 if (X509_subject_name_cmp (cert, peercert) != 0 ||
369 X509_issuer_name_cmp (cert, peercert) != 0)
372 if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
375 if (memcmp(peermd, md, mdlen) != 0)
381 static int check_certificate_cache (X509 *peercert) {
382 unsigned char peermd[EVP_MAX_MD_SIZE];
383 unsigned int peermdlen;
387 if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
390 for (scert = SslSessionCerts; scert; scert = scert->next) {
391 cert = *(X509**)scert->data;
392 if (!compare_certificates (cert, peercert, peermd, peermdlen)) {
399 static int tls_close (CONNECTION * conn)
403 rc = ssl_socket_close (conn);
404 conn->conn_read = raw_socket_read;
405 conn->conn_write = raw_socket_write;
406 conn->conn_close = raw_socket_close;
411 static char *x509_get_part (char *line, const char *ndx)
413 static char ret[SHORT_STRING];
416 m_strcpy(ret, sizeof(ret), _("Unknown"));
418 c = strstr (line, ndx);
421 c2 = strchr (c, '/');
424 m_strcpy(ret, sizeof(ret), c);
432 static void x509_fingerprint (char *s, int l, X509 * cert)
434 unsigned char md[EVP_MAX_MD_SIZE];
438 if (!X509_digest (cert, EVP_md5 (), md, &n)) {
439 m_strcpy(s, l, _("[unable to calculate]"));
442 for (j = 0; j < (int) n; j++) {
445 snprintf(ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
451 static char *asn1time_to_string (ASN1_UTCTIME * tm)
456 m_strcpy(buf, sizeof(buf), _("[invalid date]"));
458 bio = BIO_new (BIO_s_mem ());
460 if (ASN1_TIME_print (bio, tm))
461 (void) BIO_read (bio, buf, sizeof (buf));
468 static int check_certificate_by_signer (X509 * peercert)
474 ctx = X509_STORE_new ();
478 if (option (OPTSSLSYSTEMCERTS)) {
479 if (X509_STORE_set_default_paths (ctx))
482 debug_print (2, ("X509_STORE_set_default_paths failed\n"));
485 if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
488 debug_print (2, ("X509_STORE_load_locations_failed\n"));
492 X509_STORE_free (ctx);
496 X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);
498 pass = (X509_verify_cert (&xsc) > 0);
501 char buf[SHORT_STRING];
504 err = X509_STORE_CTX_get_error (&xsc);
505 snprintf (buf, sizeof (buf), "%s (%d)",
506 X509_verify_cert_error_string (err), err);
507 debug_print (2, ("X509_verify_cert: %s\n", buf));
510 X509_STORE_CTX_cleanup (&xsc);
511 X509_STORE_free (ctx);
516 static int check_certificate_by_digest (X509 * peercert)
518 unsigned char peermd[EVP_MAX_MD_SIZE];
519 unsigned int peermdlen;
524 /* expiration check */
525 if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0) {
526 debug_print (2, ("Server certificate is not yet valid\n"));
527 mutt_error (_("Server certificate is not yet valid"));
531 if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0) {
532 debug_print (2, ("Server certificate has expired\n"));
533 mutt_error (_("Server certificate has expired"));
538 if ((fp = fopen (SslCertFile, "rt")) == NULL)
541 if (!X509_digest (peercert, EVP_sha1 (), peermd, &peermdlen)) {
546 while ((cert = READ_X509_KEY (fp, &cert)) != NULL) {
547 pass = compare_certificates (cert, peercert, peermd, peermdlen) ? 0 : 1;
557 static int ssl_check_certificate (sslsockdata * data)
559 char *part[] = { "/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C=" };
560 char helpstr[SHORT_STRING];
561 char buf[SHORT_STRING];
565 char *name = NULL, *c;
567 /* check session cache first */
568 if (check_certificate_cache (data->cert)) {
569 debug_print (1, ("ssl_check_certificate: using cached certificate\n"));
573 if (check_certificate_by_signer (data->cert)) {
574 debug_print (1, ("signer check passed\n"));
578 /* automatic check from user's database */
579 if (SslCertFile && check_certificate_by_digest (data->cert)) {
580 debug_print (1, ("digest check passed\n"));
584 /* interactive check from user */
585 menu = mutt_new_menu ();
587 menu->dialog = p_new(char *, menu->max);
588 for (i = 0; i < menu->max; i++)
589 menu->dialog[i] = p_new(char, SHORT_STRING);
592 m_strcpy(menu->dialog[row], SHORT_STRING,
593 _("This certificate belongs to:"));
595 name = X509_NAME_oneline (X509_get_subject_name (data->cert),
597 for (i = 0; i < 5; i++) {
598 c = x509_get_part (name, part[i]);
599 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
603 m_strcpy(menu->dialog[row], SHORT_STRING,
604 _("This certificate was issued by:"));
606 name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
608 for (i = 0; i < 5; i++) {
609 c = x509_get_part (name, part[i]);
610 snprintf (menu->dialog[row++], SHORT_STRING, " %s", c);
614 snprintf (menu->dialog[row++], SHORT_STRING, "%s",
615 _("This certificate is valid"));
616 snprintf (menu->dialog[row++], SHORT_STRING, _(" from %s"),
617 asn1time_to_string (X509_get_notBefore (data->cert)));
618 snprintf (menu->dialog[row++], SHORT_STRING, _(" to %s"),
619 asn1time_to_string (X509_get_notAfter (data->cert)));
623 x509_fingerprint (buf, sizeof (buf), data->cert);
624 snprintf (menu->dialog[row++], SHORT_STRING, _("Fingerprint: %s"), buf);
626 menu->title = _("SSL Certificate check");
628 if (SslCertFile && X509_cmp_current_time (X509_get_notAfter (data->cert)) >= 0
629 && X509_cmp_current_time (X509_get_notBefore (data->cert)) < 0) {
630 menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
631 menu->keys = _("roa");
634 menu->prompt = _("(r)eject, accept (o)nce");
635 menu->keys = _("ro");
639 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_GENERIC, OP_EXIT);
640 m_strcat(helpstr, sizeof(helpstr), buf);
641 mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
642 m_strcat(helpstr, sizeof(helpstr), buf);
643 menu->help = helpstr;
646 set_option (OPTUNBUFFEREDINPUT);
648 switch (mutt_menuLoop (menu)) {
650 case OP_MAX + 1: /* reject */
654 case OP_MAX + 3: /* accept always */
656 if ((fp = fopen (SslCertFile, "a"))) {
657 if (PEM_write_X509 (fp, data->cert))
662 mutt_error (_("Warning: Couldn't save certificate"));
666 mutt_message (_("Certificate saved"));
670 case OP_MAX + 2: /* accept once */
672 /* keep a handle on accepted certificates in case we want to
673 * open up another connection to the same server in this session */
674 SslSessionCerts = mutt_add_list_n (SslSessionCerts, &data->cert,
679 unset_option (OPTUNBUFFEREDINPUT);
680 mutt_menuDestroy (&menu);
684 static void ssl_get_client_cert (sslsockdata * ssldata, CONNECTION * conn)
687 debug_print (2, ("Using client certificate %s\n", SslClientCert));
688 SSL_CTX_set_default_passwd_cb_userdata (ssldata->ctx, &conn->account);
689 SSL_CTX_set_default_passwd_cb (ssldata->ctx, ssl_passwd_cb);
690 SSL_CTX_use_certificate_file (ssldata->ctx, SslClientCert,
692 SSL_CTX_use_PrivateKey_file (ssldata->ctx, SslClientCert,
697 static int ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata)
699 ACCOUNT *account = (ACCOUNT *) userdata;
701 if (mutt_account_getuser (account))
704 debug_print (2, ("getting password for %s@%s:%u\n",
705 account->user, account->host, account->port));
707 if (mutt_account_getpass (account))
710 return snprintf (buf, size, "%s", account->pass);