34#include <openssl/asn1.h>
35#include <openssl/bio.h>
36#include <openssl/err.h>
37#include <openssl/evp.h>
38#include <openssl/obj_mac.h>
39#include <openssl/opensslv.h>
40#include <openssl/ossl_typ.h>
41#include <openssl/pem.h>
42#include <openssl/rand.h>
43#include <openssl/safestack.h>
44#include <openssl/ssl.h>
45#include <openssl/x509.h>
46#include <openssl/x509v3.h>
69#if (defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER < 0x10100000L)) || \
70 (defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER < 0x2070000fL))
71#define X509_get0_notBefore X509_get_notBefore
72#define X509_get0_notAfter X509_get_notAfter
73#define X509_getm_notBefore X509_get_notBefore
74#define X509_getm_notAfter X509_get_notAfter
75#define X509_STORE_CTX_get0_chain X509_STORE_CTX_get_chain
76#define SSL_has_pending SSL_pending
80#if (defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER >= 0x2070000fL))
81#define SSL_has_pending SSL_pending
104 unsigned char isopen;
124 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
127 store = X509_STORE_new();
128 SSL_CTX_set_cert_store(ctx, store);
137 while (NULL != PEM_read_X509(fp, &cert, NULL, NULL))
139 if ((X509_cmp_current_time(X509_get0_notBefore(cert)) >= 0) ||
140 (X509_cmp_current_time(X509_get0_notAfter(cert)) <= 0))
142 char buf[256] = { 0 };
144 X509_NAME_oneline(X509_get_subject_name(cert), buf,
sizeof(buf)));
148 X509_STORE_add_cert(store, cert);
152 if (ERR_GET_REASON(ERR_peek_last_error()) != PEM_R_NO_START_LINE)
171#ifdef HAVE_SSL_PARTIAL_CHAIN
172 X509_VERIFY_PARAM *param = NULL;
175 if (c_ssl_verify_partial_chains)
177 param = X509_VERIFY_PARAM_new();
180 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_PARTIAL_CHAIN);
181 if (SSL_CTX_set1_param(ctx, param) == 0)
186 X509_VERIFY_PARAM_free(param);
209 struct stat st = { 0 };
212 if (stat(file, &st) == -1)
213 return (errno == ENOENT) ? 0 : -1;
218 if ((st.st_uid != getuid()) || ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
219 ((st.st_mode & (S_IWOTH | S_IROTH)) != 0))
221 mutt_error(
_(
"%s has insecure permissions"), file);
229 n = RAND_load_file(file, -1);
239static void ssl_err(
struct SslSockData *data,
int err)
241 int e = SSL_get_error(data->ssl, err);
246 case SSL_ERROR_ZERO_RETURN:
249 case SSL_ERROR_SYSCALL:
254 const char *errmsg = NULL;
255 unsigned long sslerr;
259 case SSL_ERROR_SYSCALL:
260 errmsg =
"I/O error";
262 case SSL_ERROR_WANT_ACCEPT:
263 errmsg =
"retry accept";
265 case SSL_ERROR_WANT_CONNECT:
266 errmsg =
"retry connect";
268 case SSL_ERROR_WANT_READ:
269 errmsg =
"retry read";
271 case SSL_ERROR_WANT_WRITE:
272 errmsg =
"retry write";
274 case SSL_ERROR_WANT_X509_LOOKUP:
275 errmsg =
"retry x509 lookup";
277 case SSL_ERROR_ZERO_RETURN:
278 errmsg =
"SSL connection closed";
281 sslerr = ERR_get_error();
291 errmsg = strerror(errno);
295 errmsg = ERR_error_string(sslerr, NULL);
299 errmsg =
"unknown error";
310 BIO *bio = BIO_new(BIO_s_mem());
313 ERR_print_errors(bio);
316 long buflen = BIO_get_mem_data(bio, &buf);
320 memcpy(output, buf, buflen);
321 output[buflen] =
'\0';
349 return snprintf(buf, buflen,
"%s", cac->
pass);
358 mutt_error(
_(
"SSL disabled due to the lack of entropy"));
372 static char data[128];
374 if (!name || (X509_NAME_get_text_by_NID(name, nid, data,
sizeof(data)) < 0))
388 unsigned char md[EVP_MAX_MD_SIZE];
391 if (X509_digest(cert, hashfunc(), md, &n) == 0)
397 for (
unsigned int i = 0; i < n; i++)
402 if (((i % 2) == 1) && (i < (n - 1)))
421 bio = BIO_new(BIO_s_mem());
424 if (ASN1_TIME_print(bio, tm))
425 (void) BIO_read(bio, buf,
sizeof(buf));
442 unsigned char *peermd,
unsigned int peermdlen)
444 unsigned char md[EVP_MAX_MD_SIZE];
449 if ((X509_subject_name_cmp(cert, peercert) != 0) ||
450 (X509_issuer_name_cmp(cert, peercert) != 0))
455 if (!X509_digest(cert, EVP_sha256(), md, &mdlen) || (peermdlen != mdlen))
458 if (memcmp(peermd, md, mdlen) != 0)
474 if (c_ssl_verify_dates ==
MUTT_NO)
477 if (X509_cmp_current_time(X509_get0_notBefore(peercert)) >= 0)
482 mutt_error(
_(
"Server certificate is not yet valid"));
487 if (X509_cmp_current_time(X509_get0_notAfter(peercert)) <= 0)
508 const char *cmp1 = NULL, *cmp2 = NULL;
513 cmp2 = strchr(hostname,
'.');
525 if ((*cmp1 ==
'\0') || (*cmp2 ==
'\0'))
530 if (strcasecmp(cmp1, cmp2) != 0)
554 static bool init_complete =
false;
559 if (RAND_status() != 1)
576 RAND_write_file(RAND_file_name(path->
data, path->
dsize));
580 if (RAND_status() != 1)
582 mutt_error(
_(
"Failed to find enough entropy on your system"));
589#if (defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER < 0x10100000L)) || \
590 (defined(LIBRESSL_VERSION_NUMBER))
593 SSL_load_error_strings();
596 init_complete =
true;
608 if (!c_ssl_client_cert)
612 SSL_CTX_set_default_passwd_cb_userdata(ssldata->sctx, &conn->
account);
614 SSL_CTX_use_certificate_file(ssldata->sctx, c_ssl_client_cert, SSL_FILETYPE_PEM);
615 SSL_CTX_use_PrivateKey_file(ssldata->sctx, c_ssl_client_cert, SSL_FILETYPE_PEM);
639 unsigned char peermd[EVP_MAX_MD_SIZE];
640 unsigned int peermdlen;
643 if (!X509_digest(peercert, EVP_sha256(), peermd, &peermdlen) || !SslSessionCerts)
648 for (
int i = sk_X509_num(SslSessionCerts); i-- > 0;)
650 cert = sk_X509_value(SslSessionCerts, i);
668 unsigned char peermd[EVP_MAX_MD_SIZE];
669 unsigned int peermdlen;
679 if (!X509_digest(peercert, EVP_sha256(), peermd, &peermdlen))
685 while (PEM_read_X509(fp, &cert, NULL, NULL))
712static int check_host(X509 *x509cert,
const char *hostname,
char *err,
size_t errlen)
716 char *hostname_ascii = NULL;
718 X509_NAME *x509_subject = NULL;
722 STACK_OF(GENERAL_NAME) * subj_alt_names;
723 int subj_alt_names_count;
724 GENERAL_NAME *subj_alt_name = NULL;
742 subj_alt_names = X509_get_ext_d2i(x509cert, NID_subject_alt_name, NULL, NULL);
745 subj_alt_names_count = sk_GENERAL_NAME_num(subj_alt_names);
746 for (
int i = 0; i < subj_alt_names_count; i++)
748 subj_alt_name = sk_GENERAL_NAME_value(subj_alt_names, i);
749 if (subj_alt_name->type == GEN_DNS)
751 if ((subj_alt_name->d.ia5->length >= 0) &&
753 (
size_t) subj_alt_name->d.ia5->length) &&
755 (
char *) (subj_alt_name->d.ia5->data))))
761 GENERAL_NAMES_free(subj_alt_names);
767 x509_subject = X509_get_subject_name(x509cert);
776 bufsize = X509_NAME_get_text_by_NID(x509_subject, NID_commonName, NULL, 0);
780 mutt_str_copy(err,
_(
"can't get certificate common name"), errlen);
785 if (X509_NAME_get_text_by_NID(x509_subject, NID_commonName, buf, bufsize) == -1)
788 mutt_str_copy(err,
_(
"can't get certificate common name"), errlen);
802 snprintf(err, errlen,
_(
"certificate owner does not match hostname %s"), hostname);
810 FREE(&hostname_ascii);
835 if (!SslSessionCerts)
836 SslSessionCerts = sk_X509_new_null();
837 return sk_X509_push(SslSessionCerts, X509_dup(c));
847static void add_cert(
const char *title, X509 *cert,
bool issuer,
struct CertArray *carr)
849 static const int part[] = {
851 NID_pkcs9_emailAddress,
852 NID_organizationName,
853 NID_organizationalUnitName,
855 NID_stateOrProvinceName,
859 X509_NAME *x509 = NULL;
861 x509 = X509_get_issuer_name(cert);
863 x509 = X509_get_subject_name(cert);
903 add_cert(
_(
"This certificate belongs to:"), cert,
false, &carr);
905 add_cert(
_(
"This certificate was issued by:"), cert,
true, &carr);
920 buf->
data[39] =
'\0';
927 bool allow_skip =
false;
929#ifdef HAVE_SSL_PARTIAL_CHAIN
931 if ((idx != 0) && c_ssl_verify_partial_chains)
935 char title[256] = { 0 };
936 snprintf(title,
sizeof(title),
937 _(
"SSL Certificate check (certificate %zu of %zu in chain)"), len - idx, len);
944 allow_always = allow_always && c_certificate_file &&
948 if ((rc == 3) && !allow_always)
965 if (PEM_write_X509(fp, cert))
973 mutt_error(
_(
"Warning: Couldn't save certificate"));
1003 char buf[256] = { 0 };
1005 SSL *ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1025 X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
1026 int pos = X509_STORE_CTX_get_error_depth(ctx);
1027 size_t len = sk_X509_num(X509_STORE_CTX_get0_chain(ctx));
1030 X509_NAME_oneline(X509_get_subject_name(cert), buf,
sizeof(buf)),
1031 preverify_ok, skip_mode);
1033#ifdef HAVE_SSL_PARTIAL_CHAIN
1038 if (c_ssl_verify_partial_chains)
1040 static int last_pos = 0;
1041 static X509 *last_cert = NULL;
1042 if (skip_mode && preverify_ok && (pos == last_pos) && last_cert)
1044 unsigned char last_cert_md[EVP_MAX_MD_SIZE];
1045 unsigned int last_cert_mdlen;
1046 if (X509_digest(last_cert, EVP_sha256(), last_cert_md, &last_cert_mdlen) &&
1056 X509_free(last_cert);
1057 last_cert = X509_dup(cert);
1072 if ((pos == 0) && (c_ssl_verify_host !=
MUTT_NO))
1074 if (
check_host(cert, host, buf,
sizeof(buf)) == 0)
1076 mutt_error(
_(
"Certificate host check failed: %s"), buf);
1084 if (!preverify_ok || skip_mode)
1096 int err = X509_STORE_CTX_get_error(ctx);
1097 snprintf(buf,
sizeof(buf),
"%s (%d)", X509_verify_cert_error_string(err), err);
1120 const char *errmsg = NULL;
1149 SSL_set_mode(ssldata->ssl, SSL_MODE_AUTO_RETRY);
1151 if (!SSL_set_tlsext_host_name(ssldata->ssl, conn->
account.
host))
1156 mutt_error(
_(
"Warning: unable to set TLS SNI host name"));
1162 err = SSL_connect(ssldata->ssl);
1166 if (BIO_should_retry(SSL_get_rbio(ssldata->ssl)))
1169 switch (SSL_get_error(ssldata->ssl, err))
1171 case SSL_ERROR_SYSCALL:
1172 errmsg =
_(
"I/O error");
1175 errmsg = ERR_error_string(ERR_get_error(), NULL);
1178 errmsg =
_(
"unknown error");
1211 sockdata(conn)->sctx = SSL_CTX_new(SSLv23_client_method());
1223#ifdef SSL_OP_NO_TLSv1_3
1225 if (!c_ssl_use_tlsv1_3)
1226 SSL_CTX_set_options(
sockdata(conn)->sctx, SSL_OP_NO_TLSv1_3);
1229#ifdef SSL_OP_NO_TLSv1_2
1231 if (!c_ssl_use_tlsv1_2)
1232 SSL_CTX_set_options(
sockdata(conn)->sctx, SSL_OP_NO_TLSv1_2);
1235#ifdef SSL_OP_NO_TLSv1_1
1237 if (!c_ssl_use_tlsv1_1)
1238 SSL_CTX_set_options(
sockdata(conn)->sctx, SSL_OP_NO_TLSv1_1);
1241#ifdef SSL_OP_NO_TLSv1
1243 if (!c_ssl_use_tlsv1)
1244 SSL_CTX_set_options(
sockdata(conn)->sctx, SSL_OP_NO_TLSv1);
1248 if (!c_ssl_use_sslv3)
1249 SSL_CTX_set_options(
sockdata(conn)->sctx, SSL_OP_NO_SSLv3);
1252 if (!c_ssl_use_sslv2)
1253 SSL_CTX_set_options(
sockdata(conn)->sctx, SSL_OP_NO_SSLv2);
1256 if (c_ssl_use_system_certs)
1258 if (!SSL_CTX_set_default_verify_paths(
sockdata(conn)->sctx))
1274 SSL_CTX_set_cipher_list(
sockdata(conn)->sctx, c_ssl_ciphers);
1279 mutt_error(
_(
"Warning: error enabling ssl_verify_partial_chains"));
1289 conn->
ssf = SSL_CIPHER_get_bits(SSL_get_current_cipher(
sockdata(conn)->ssl), &maxbits);
1297 SSL_CTX_free(
sockdata(conn)->sctx);
1313 if (SSL_has_pending(
sockdata(conn)->ssl))
1339 struct SslSockData *data =
sockdata(conn);
1343 rc = SSL_read(data->ssl, buf, count);
1348 if (
SigInt && (errno == EINTR))
1352 else if (BIO_should_retry(SSL_get_rbio(data->ssl)))
1368 if (!conn || !conn->
sockdata || !buf || (count == 0))
1371 struct SslSockData *data =
sockdata(conn);
1375 rc = SSL_write(data->ssl, buf, count);
1380 if (
SigInt && (errno == EINTR))
1384 else if (BIO_should_retry(SSL_get_wbio(data->ssl)))
1399 struct SslSockData *data =
sockdata(conn);
1404 SSL_shutdown(data->ssl);
1406 SSL_free(data->ssl);
1408 SSL_CTX_free(data->sctx);
#define ARRAY_ADD(head, elem)
Add an element at the end of the array.
#define ARRAY_HEAD_INITIALIZER
Static initializer for arrays.
int buf_printf(struct Buffer *buf, const char *fmt,...)
Format a string overwriting a Buffer.
int buf_add_printf(struct Buffer *buf, const char *fmt,...)
Format a string appending a Buffer.
size_t buf_addch(struct Buffer *buf, char c)
Add a single character to a Buffer.
size_t buf_strcpy(struct Buffer *buf, const char *s)
Copy a string into a Buffer.
static const char * buf_string(const struct Buffer *buf)
Convert a buffer to a const char * "string".
const char * cs_subset_string(const struct ConfigSubset *sub, const char *name)
Get a string config item by name.
const char * cs_subset_path(const struct ConfigSubset *sub, const char *name)
Get a path config item by name.
bool cs_subset_bool(const struct ConfigSubset *sub, const char *name)
Get a boolean config item by name.
Convenience wrapper for the config headers.
char * HomeDir
User's home directory.
int mutt_account_getpass(struct ConnAccount *cac)
Fetch password into ConnAccount, if necessary.
int mutt_account_getuser(struct ConnAccount *cac)
Retrieve username into ConnAccount, if necessary.
An open network connection (socket)
Convenience wrapper for the core headers.
void cert_array_clear(struct CertArray *carr)
Free all memory of a CertArray.
#define mutt_file_fclose(FP)
#define mutt_file_fopen(PATH, MODE)
bool OptNoCurses
(pseudo) when sending in batch mode
static int ssl_socket_close_and_restore(struct Connection *conn)
Close an SSL Connection and restore Connection callbacks - Implements Connection::close() -.
int raw_socket_close(struct Connection *conn)
Close a socket - Implements Connection::close() -.
static int ssl_socket_close(struct Connection *conn)
Close an SSL connection - Implements Connection::close() -.
int raw_socket_open(struct Connection *conn)
Open a socket - Implements Connection::open() -.
static int ssl_socket_open_err(struct Connection *conn)
Error callback for opening an SSL connection - Implements Connection::open() -.
static int ssl_socket_open(struct Connection *conn)
Open an SSL socket - Implements Connection::open() -.
static int ssl_socket_poll(struct Connection *conn, time_t wait_secs)
Check if any data is waiting on a socket - Implements Connection::poll() -.
int raw_socket_poll(struct Connection *conn, time_t wait_secs)
Check if any data is waiting on a socket - Implements Connection::poll() -.
static int ssl_socket_read(struct Connection *conn, char *buf, size_t count)
Read data from an SSL socket - Implements Connection::read() -.
int raw_socket_read(struct Connection *conn, char *buf, size_t len)
Read data from a socket - Implements Connection::read() -.
static int ssl_socket_write(struct Connection *conn, const char *buf, size_t count)
Write data to an SSL socket - Implements Connection::write() -.
int raw_socket_write(struct Connection *conn, const char *buf, size_t count)
Write data to a socket - Implements Connection::write() -.
int dlg_certificate(const char *title, struct CertArray *carr, bool allow_always, bool allow_skip)
Ask the user to validate the certificate -.
#define mutt_message(...)
#define mutt_debug(LEVEL,...)
int mutt_idna_to_ascii_lz(const char *input, char **output, uint8_t flags)
Convert a domain to Punycode.
@ LL_DEBUG2
Log at debug level 2.
@ LL_DEBUG1
Log at debug level 1.
#define MUTT_MEM_CALLOC(n, type)
#define MUTT_MEM_MALLOC(n, type)
#define mutt_array_size(x)
Convenience wrapper for the library headers.
char * mutt_str_dup(const char *str)
Copy a string, safely.
int mutt_str_asprintf(char **strp, const char *fmt,...)
bool mutt_strn_equal(const char *a, const char *b, size_t num)
Check for equality of two strings (to a maximum), safely.
const char * mutt_str_getenv(const char *name)
Get an environment variable.
size_t mutt_str_len(const char *a)
Calculate the length of a string, safely.
size_t mutt_str_copy(char *dest, const char *src, size_t dsize)
Copy a string into a buffer (guaranteeing NUL-termination)
void mutt_clear_error(void)
Clear the message line (bottom line of screen)
static int check_host(X509 *x509cert, const char *hostname, char *err, size_t errlen)
Check the host on the certificate.
static int add_entropy(const char *file)
Add a source of random numbers.
static char * x509_get_part(X509_NAME *name, int nid)
Retrieve from X509 data.
static char * asn1time_to_string(ASN1_UTCTIME *tm)
Convert a time to a string.
int mutt_ssl_starttls(struct Connection *conn)
Negotiate TLS over an already opened connection.
static STACK_OF(X509)
Keep a handle on accepted certificates in case we want to open up another connection to the same serv...
static void x509_fingerprint(struct Buffer *buf, X509 *cert, const EVP_MD *(*hashfunc)(void))
Generate a fingerprint for an X509 certificate.
static int ssl_setup(struct Connection *conn)
Set up SSL on the Connection.
static bool check_certificate_cache(X509 *peercert)
Is the X509 Certificate in the cache?
static int ssl_passwd_cb(char *buf, int buflen, int rwflag, void *userdata)
Callback to get a password.
static int ssl_negotiate(struct Connection *conn, struct SslSockData *ssldata)
Attempt to negotiate SSL over the wire.
static bool certificates_equal(X509 *cert, X509 *peercert, unsigned char *peermd, unsigned int peermdlen)
Compare two X509 certificated.
static bool ssl_load_certificates(SSL_CTX *ctx)
Load certificates and filter out the expired ones.
static void ssl_dprint_err_stack(void)
Dump the SSL error stack.
static int ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
Certificate verification callback.
static struct SslSockData * sockdata(struct Connection *conn)
Get a Connection's socket data.
static int HostExDataIndex
index for storing hostname as application specific data in SSL structure
static bool ssl_set_verify_partial(SSL_CTX *ctx)
Allow verification using partial chains (with no root)
static int ssl_cache_trusted_cert(X509 *c)
Cache a trusted certificate.
static int ssl_init(void)
Initialise the SSL library.
static void ssl_err(struct SslSockData *data, int err)
Display an SSL error message.
static void ssl_get_client_cert(struct SslSockData *ssldata, struct Connection *conn)
Get the client certificate for an SSL connection.
static void add_cert(const char *title, X509 *cert, bool issuer, struct CertArray *carr)
Look up certificate info and save it to a list.
static bool check_certificate_expiration(X509 *peercert, bool silent)
Check if a certificate has expired.
static bool check_certificate_file(X509 *peercert)
Read and check a certificate file.
static bool interactive_check_cert(X509 *cert, int idx, size_t len, SSL *ssl, bool allow_always)
Ask the user if a certificate is valid.
static bool hostname_match(const char *hostname, const char *certname)
Does the hostname match the certificate.
int mutt_ssl_socket_setup(struct Connection *conn)
Set up SSL socket mulitplexor.
static int SkipModeExDataIndex
Index for storing the "skip mode" state in SSL structure.
static bool check_certificate_by_digest(X509 *peercert)
Validate a certificate by its digest.
struct Buffer * buf_pool_get(void)
Get a Buffer from the pool.
void buf_pool_release(struct Buffer **ptr)
Return a Buffer to the pool.
@ MUTT_NO
User answered 'No', or assume 'No'.
volatile sig_atomic_t SigInt
true after SIGINT is received
Handling of SSL encryption.
String manipulation buffer.
size_t dsize
Length of data.
char * data
Pointer to data.
Login details for a remote server.
char host[128]
Server to login to.
unsigned short port
Port to connect to.
void * sockdata
Backend-specific socket data.
int(* poll)(struct Connection *conn, time_t wait_secs)
int(* write)(struct Connection *conn, const char *buf, size_t count)
unsigned int ssf
Security strength factor, in bits (see notes)
int(* close)(struct Connection *conn)
struct ConnAccount account
Account details: username, password, etc.
int(* open)(struct Connection *conn)
int fd
Socket file descriptor.
int(* read)(struct Connection *conn, char *buf, size_t count)
Container for Accounts, Notifications.
struct ConfigSubset * sub
Inherited config items.