lighttpd1.4/src/mod_openssl.c

3699 lines
130 KiB
C
Raw Normal View History

/*
* mod_openssl - openssl support for lighttpd
*
* Fully-rewritten from original
* Copyright(c) 2016 Glenn Strauss gstrauss()gluelogic.com All rights reserved
* License: BSD 3-clause (same as lighttpd)
*/
/*
* Note: If session tickets are -not- disabled with
* ssl.openssl.ssl-conf-cmd = ("Options" => "-SessionTicket")
* mod_openssl rotates server ticket encryption key (STEK) every 8 hours
* and keeps the prior two STEKs around, so ticket lifetime is 24 hours.
* This is fine for use with a single lighttpd instance, but with multiple
* lighttpd workers, no coordinated STEK (server ticket encryption key)
* rotation occurs unless ssl.stek-file is defined and maintained (preferred),
* or if some external job restarts lighttpd. Restarting lighttpd generates a
* new key that is shared by lighttpd workers for the lifetime of the new key.
* If the rotation period expires and lighttpd has not been restarted, and if
* ssl.stek-file is not in use, then lighttpd workers will generate new
* independent keys, making session tickets less effective for session
* resumption, since clients have a lower chance for future connections to
* reach the same lighttpd worker. However, things will still work, and a new
* session will be created if session resumption fails. Admins should plan to
* restart lighttpd at least every 8 hours if session tickets are enabled and
* multiple lighttpd workers are configured. Since that is likely disruptive,
* if multiple lighttpd workers are configured, ssl.stek-file should be
* defined and the file maintained externally.
*/
#include "first.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
/*(not needed)*/
/* correction; needed for:
* SSL_load_client_CA_file()
* X509_STORE_load_locations()
*/
/*#define OPENSSL_NO_STDIO*/
#ifndef USE_OPENSSL_KERBEROS
#ifndef OPENSSL_NO_KRB5
#define OPENSSL_NO_KRB5
#endif
#endif
2020-06-10 11:52:57 +00:00
#ifdef BORINGSSL_API_VERSION
#undef OPENSSL_NO_STDIO /* for X509_STORE_load_locations() */
#endif
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/tls1.h>
#ifndef OPENSSL_NO_DH
#include <openssl/dh.h>
#endif
#ifndef OPENSSL_NO_OCSP
#include <openssl/ocsp.h>
#endif
2020-06-10 11:52:57 +00:00
#ifdef BORINGSSL_API_VERSION
/* BoringSSL purports to have some OCSP support */
#undef OPENSSL_NO_OCSP
#endif
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
#ifndef OPENSSL_NO_ECDH
#include <openssl/ecdh.h>
#endif
#endif
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
#include <openssl/core_names.h>
#endif
#include "base.h"
#include "fdevent.h"
#include "http_date.h"
#include "http_header.h"
#include "http_kv.h"
#include "log.h"
#include "plugin.h"
#include "safe_memclear.h"
typedef struct {
/* SNI per host: with COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
EVP_PKEY *ssl_pemfile_pkey;
X509 *ssl_pemfile_x509;
STACK_OF(X509) *ssl_pemfile_chain;
buffer *ssl_stapling;
const buffer *ssl_pemfile;
const buffer *ssl_privkey;
const buffer *ssl_stapling_file;
time_t ssl_stapling_loadts;
time_t ssl_stapling_nextts;
char must_staple;
} plugin_cert;
typedef struct {
SSL_CTX *ssl_ctx;
} plugin_ssl_ctx;
typedef struct {
STACK_OF(X509_NAME) *names;
X509_STORE *certs;
} plugin_cacerts;
typedef struct {
SSL_CTX *ssl_ctx; /* output from network_init_ssl() */
/*(used only during startup; not patched)*/
unsigned char ssl_enabled; /* only interesting for setting up listening sockets. don't use at runtime */
unsigned char ssl_honor_cipher_order; /* determine SSL cipher in server-preferred order, not client-order */
unsigned char ssl_empty_fragments; /* whether to not set SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS */
unsigned char ssl_use_sslv2;
unsigned char ssl_use_sslv3;
const buffer *ssl_cipher_list;
const buffer *ssl_dh_file;
const buffer *ssl_ec_curve;
array *ssl_conf_cmd;
/*(copied from plugin_data for socket ssl_ctx config)*/
const plugin_cert *pc;
const plugin_cacerts *ssl_ca_file;
STACK_OF(X509_NAME) *ssl_ca_dn_file;
const buffer *ssl_ca_crl_file;
unsigned char ssl_verifyclient;
unsigned char ssl_verifyclient_enforce;
unsigned char ssl_verifyclient_depth;
unsigned char ssl_read_ahead;
unsigned char ssl_disable_client_renegotiation;
} plugin_config_socket; /*(used at startup during configuration)*/
typedef struct {
/* SNI per host: w/ COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
plugin_cert *pc;
const plugin_cacerts *ssl_ca_file;
STACK_OF(X509_NAME) *ssl_ca_dn_file;
const buffer *ssl_ca_crl_file;
unsigned char ssl_verifyclient;
unsigned char ssl_verifyclient_enforce;
unsigned char ssl_verifyclient_depth;
unsigned char ssl_verifyclient_export_cert;
unsigned char ssl_read_ahead;
unsigned char ssl_log_noise;
unsigned char ssl_disable_client_renegotiation;
const buffer *ssl_verifyclient_username;
const buffer *ssl_acme_tls_1;
} plugin_config;
typedef struct {
PLUGIN_DATA;
plugin_ssl_ctx *ssl_ctxs;
plugin_config defaults;
server *srv;
array *cafiles;
const char *ssl_stek_file;
} plugin_data;
static int ssl_is_init;
/* need assigned p->id for deep access of module handler_ctx for connection
* i.e. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id]; */
static plugin_data *plugin_data_singleton;
#define LOCAL_SEND_BUFSIZE (16 * 1024)
static char *local_send_buffer;
typedef struct {
SSL *ssl;
request_st *r;
connection *con;
short renegotiations; /* count of SSL_CB_HANDSHAKE_START */
short close_notify;
unsigned short alpn;
plugin_config conf;
buffer *tmp_buf;
log_error_st *errh;
} handler_ctx;
static handler_ctx *
handler_ctx_init (void)
{
handler_ctx *hctx = calloc(1, sizeof(*hctx));
force_assert(hctx);
return hctx;
}
static void
handler_ctx_free (handler_ctx *hctx)
{
if (hctx->ssl) SSL_free(hctx->ssl);
free(hctx);
}
#ifdef TLSEXT_TYPE_session_ticket
/* ssl/ssl_local.h */
#define TLSEXT_KEYNAME_LENGTH 16
#define TLSEXT_TICK_KEY_LENGTH 32
/* openssl has a huge number of interfaces, but not the most useful;
* construct our own session ticket encryption key structure */
typedef struct tlsext_ticket_key_st {
time_t active_ts; /* tickets not issued w/ key until activation timestamp */
time_t expire_ts; /* key not valid after expiration timestamp */
unsigned char tick_key_name[TLSEXT_KEYNAME_LENGTH];
unsigned char tick_hmac_key[TLSEXT_TICK_KEY_LENGTH];
unsigned char tick_aes_key[TLSEXT_TICK_KEY_LENGTH];
} tlsext_ticket_key_t;
static tlsext_ticket_key_t session_ticket_keys[4];
static time_t stek_rotate_ts;
static int
mod_openssl_session_ticket_key_generate (time_t active_ts, time_t expire_ts)
{
/* openssl RAND_*bytes() functions are called multiple times since the
* funcs might have a 32-byte limit on number of bytes returned each call
*
* (Note: session ticket encryption key generation is not expected to fail)
*
* 3 keys are stored in session_ticket_keys[]
* The 4th element of session_ticket_keys[] is used for STEK construction
*/
/*(RAND_priv_bytes() not in openssl 1.1.0; introduced in openssl 1.1.1)*/
2020-06-05 07:28:19 +00:00
#if OPENSSL_VERSION_NUMBER < 0x10101000L \
|| defined(LIBRESSL_VERSION_NUMBER)
#define RAND_priv_bytes(x,sz) RAND_bytes((x),(sz))
#endif
if (RAND_bytes(session_ticket_keys[3].tick_key_name,
TLSEXT_KEYNAME_LENGTH) <= 0
|| RAND_priv_bytes(session_ticket_keys[3].tick_hmac_key,
TLSEXT_TICK_KEY_LENGTH) <= 0
|| RAND_priv_bytes(session_ticket_keys[3].tick_aes_key,
TLSEXT_TICK_KEY_LENGTH) <= 0)
return 0;
session_ticket_keys[3].active_ts = active_ts;
session_ticket_keys[3].expire_ts = expire_ts;
return 1;
}
static void
mod_openssl_session_ticket_key_rotate (void)
{
/* discard oldest key (session_ticket_keys[2]) and put newest key first
* 3 keys are stored in session_ticket_keys[0], [1], [2]
* session_ticket_keys[3] is used to construct and pass new STEK */
session_ticket_keys[2] = session_ticket_keys[1];
session_ticket_keys[1] = session_ticket_keys[0];
/*memmove(session_ticket_keys+1,
session_ticket_keys+0, sizeof(tlsext_ticket_key_t)*2);*/
session_ticket_keys[0] = session_ticket_keys[3];
OPENSSL_cleanse(session_ticket_keys+3, sizeof(tlsext_ticket_key_t));
}
static tlsext_ticket_key_t *
tlsext_ticket_key_get (void)
{
const time_t cur_ts = log_epoch_secs;
const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
for (int i = 0; i < e; ++i) {
if (session_ticket_keys[i].active_ts > cur_ts) continue;
if (session_ticket_keys[i].expire_ts < cur_ts) continue;
return &session_ticket_keys[i];
}
return NULL;
}
static tlsext_ticket_key_t *
tlsext_ticket_key_find (unsigned char key_name[16], int *refresh)
{
*refresh = 0;
const time_t cur_ts = log_epoch_secs;
const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
for (int i = 0; i < e; ++i) {
if (session_ticket_keys[i].expire_ts < cur_ts) continue;
if (0 == memcmp(session_ticket_keys[i].tick_key_name, key_name, 16))
return &session_ticket_keys[i];
if (session_ticket_keys[i].active_ts <= cur_ts)
*refresh = 1; /* newer active key is available */
}
return NULL;
}
static void
tlsext_ticket_wipe_expired (const time_t cur_ts)
{
const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
for (int i = 0; i < e; ++i) {
if (session_ticket_keys[i].expire_ts != 0
&& session_ticket_keys[i].expire_ts < cur_ts)
OPENSSL_cleanse(session_ticket_keys+i, sizeof(tlsext_ticket_key_t));
}
}
#if OPENSSL_VERSION_NUMBER < 0x30000000L
/* based on reference implementation from openssl 1.1.1g man page
* man SSL_CTX_set_tlsext_ticket_key_cb
* but mod_openssl code uses EVP_aes_256_cbc() instead of EVP_aes_128_cbc()
*/
static int
ssl_tlsext_ticket_key_cb (SSL *s, unsigned char key_name[16],
unsigned char iv[EVP_MAX_IV_LENGTH],
EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)
#else /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
/* based on reference implementation from openssl 3.0.0 man page
* man SSL_CTX_set_tlsext_ticket_key_cb
*/
static int
ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16],
unsigned char *iv, EVP_CIPHER_CTX *ctx,
EVP_MAC_CTX *hctx, int enc)
#endif
{
UNUSED(s);
if (enc) { /* create new session */
tlsext_ticket_key_t *k = tlsext_ticket_key_get();
if (NULL == k)
return 0; /* current key does not exist or is not valid */
memcpy(key_name, k->tick_key_name, 16);
if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) <= 0)
return -1; /* insufficient random */
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, k->tick_aes_key, iv);
#if OPENSSL_VERSION_NUMBER < 0x30000000L
HMAC_Init_ex(hctx, k->tick_hmac_key, sizeof(k->tick_hmac_key),
EVP_sha256(), NULL);
#else
OSSL_PARAM params[] = {
OSSL_PARAM_DEFN(OSSL_MAC_PARAM_KEY, OSSL_PARAM_OCTET_STRING,
k->tick_hmac_key, sizeof(k->tick_hmac_key)),
OSSL_PARAM_DEFN(OSSL_MAC_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING,
"sha256", sizeof("sha256")),
OSSL_PARAM_END
};
EVP_MAC_CTX_set_params(hctx, params);
#endif
return 1;
}
else { /* retrieve session */
int refresh;
tlsext_ticket_key_t *k = tlsext_ticket_key_find(key_name, &refresh);
if (NULL == k)
return 0;
#if OPENSSL_VERSION_NUMBER < 0x30000000L
HMAC_Init_ex(hctx, k->tick_hmac_key, sizeof(k->tick_hmac_key),
EVP_sha256(), NULL);
#else
OSSL_PARAM params[] = {
OSSL_PARAM_DEFN(OSSL_KDF_PARAM_KEY, OSSL_PARAM_OCTET_STRING,
k->tick_hmac_key, sizeof(k->tick_hmac_key)),
OSSL_PARAM_DEFN(OSSL_MAC_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING,
"sha256", sizeof("sha256")),
OSSL_PARAM_END
};
EVP_MAC_CTX_set_params(hctx, params);
#endif
EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, k->tick_aes_key, iv);
return refresh ? 2 : 1;
/* 'refresh' will trigger issuing new ticket for session
* even though the current ticket is still valid */
}
}
static int
mod_openssl_session_ticket_key_file (const char *fn)
{
/* session ticket encryption key (STEK)
*
* STEK file should be stored in non-persistent storage,
* e.g. /dev/shm/lighttpd/stek-file (in memory)
* with appropriate permissions set to keep stek-file from being
* read by other users. Where possible, systems should also be
* configured without swap.
*
* admin should schedule an independent job to periodically
* generate new STEK up to 3 times during key lifetime
* (lighttpd stores up to 3 keys)
*
* format of binary file is:
* 4-byte - format version (always 0; for use if format changes)
* 4-byte - activation timestamp
* 4-byte - expiration timestamp
* 16-byte - session ticket key name
* 32-byte - session ticket HMAC encrpytion key
* 32-byte - session ticket AES encrpytion key
*
* STEK file can be created with a command such as:
* dd if=/dev/random bs=1 count=80 status=none | \
* perl -e 'print pack("iii",0,time()+300,time()+86400),<>' \
* > STEK-file.$$ && mv STEK-file.$$ STEK-file
*
* The above delays activation time by 5 mins (+300 sec) to allow file to
* be propagated to other machines. (admin must handle this independently)
* If STEK generation is performed immediately prior to starting lighttpd,
* admin should activate keys immediately (without +300).
*/
int buf[23]; /* 92 bytes */
int rc = 0; /*(will retry on next check interval upon any error)*/
if (0 != fdevent_load_file_bytes((char *)buf,(off_t)sizeof(buf),0,fn,NULL))
return rc;
if (buf[0] == 0) { /*(format version 0)*/
session_ticket_keys[3].active_ts = buf[1];
session_ticket_keys[3].expire_ts = buf[2];
2020-07-11 02:18:26 +00:00
#ifndef __COVERITY__ /* intentional; hide from Coverity Scan */
2020-07-10 23:35:26 +00:00
/* intentionally copy 80 bytes into consecutive arrays
* tick_key_name[], tick_hmac_key[], tick_aes_key[] */
2020-07-11 02:18:26 +00:00
memcpy(&session_ticket_keys[3].tick_key_name, buf+3, 80);
#endif
rc = 1;
}
OPENSSL_cleanse(buf, sizeof(buf));
return rc;
}
static void
mod_openssl_session_ticket_key_check (const plugin_data *p, const time_t cur_ts)
{
int rotate = 0;
if (p->ssl_stek_file) {
struct stat st;
if (0 == stat(p->ssl_stek_file, &st) && st.st_mtime > stek_rotate_ts)
rotate = mod_openssl_session_ticket_key_file(p->ssl_stek_file);
tlsext_ticket_wipe_expired(cur_ts);
}
else if (cur_ts - 28800 >= stek_rotate_ts) /*(8 hours)*/
rotate = mod_openssl_session_ticket_key_generate(cur_ts, cur_ts+86400);
if (rotate) {
mod_openssl_session_ticket_key_rotate();
stek_rotate_ts = cur_ts;
}
}
#endif /* TLSEXT_TYPE_session_ticket */
#ifndef OPENSSL_NO_OCSP
#ifndef BORINGSSL_API_VERSION /* BoringSSL suggests using different API */
static int
ssl_tlsext_status_cb(SSL *ssl, void *arg)
{
#ifdef SSL_get_tlsext_status_type
if (TLSEXT_STATUSTYPE_ocsp != SSL_get_tlsext_status_type(ssl))
return SSL_TLSEXT_ERR_NOACK; /* ignore if not client OCSP request */
#endif
handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
buffer *ssl_stapling = hctx->conf.pc->ssl_stapling;
if (NULL == ssl_stapling) return SSL_TLSEXT_ERR_NOACK;
UNUSED(arg);
int len = (int)buffer_string_length(ssl_stapling);
/* OpenSSL and LibreSSL require copy (BoringSSL, too, if using compat API)*/
uint8_t *ocsp_resp = OPENSSL_malloc(len);
if (NULL == ocsp_resp)
return SSL_TLSEXT_ERR_NOACK; /* ignore OCSP request if error occurs */
memcpy(ocsp_resp, ssl_stapling->ptr, len);
if (!SSL_set_tlsext_status_ocsp_resp(ssl, ocsp_resp, len)) {
log_error(hctx->r->conf.errh, __FILE__, __LINE__,
"SSL: failed to set OCSP response for TLS server name %s: %s",
hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
OPENSSL_free(ocsp_resp);
return SSL_TLSEXT_ERR_NOACK; /* ignore OCSP request if error occurs */
/*return SSL_TLSEXT_ERR_ALERT_FATAL;*/
}
return SSL_TLSEXT_ERR_OK;
}
#endif
#endif
INIT_FUNC(mod_openssl_init)
{
plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
return plugin_data_singleton;
}
static int mod_openssl_init_once_openssl (server *srv)
{
if (ssl_is_init) return 1;
#if OPENSSL_VERSION_NUMBER >= 0x10100000L \
&& (!defined(LIBRESSL_VERSION_NUMBER) \
|| LIBRESSL_VERSION_NUMBER >= 0x2070000fL)
OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
|OPENSSL_INIT_LOAD_CRYPTO_STRINGS,NULL);
OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
|OPENSSL_INIT_ADD_ALL_DIGESTS
|OPENSSL_INIT_LOAD_CONFIG, NULL);
#else
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
#endif
ssl_is_init = 1;
if (0 == RAND_status()) {
log_error(srv->errh, __FILE__, __LINE__,
"SSL: not enough entropy in the pool");
return 0;
}
local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
force_assert(NULL != local_send_buffer);
return 1;
}
static void mod_openssl_free_openssl (void)
{
if (!ssl_is_init) return;
#ifdef TLSEXT_TYPE_session_ticket
OPENSSL_cleanse(session_ticket_keys, sizeof(session_ticket_keys));
stek_rotate_ts = 0;
#endif
#if OPENSSL_VERSION_NUMBER >= 0x10100000L \
&& !defined(LIBRESSL_VERSION_NUMBER)
/*(OpenSSL libraries handle thread init and deinit)
* https://github.com/openssl/openssl/pull/1048 */
#else
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
ERR_remove_thread_state(NULL);
#else
ERR_remove_state(0);
#endif
EVP_cleanup();
#endif
free(local_send_buffer);
ssl_is_init = 0;
}
static void
mod_openssl_free_config (server *srv, plugin_data * const p)
{
array_free(p->cafiles);
if (NULL != p->ssl_ctxs) {
SSL_CTX * const ssl_ctx_global_scope = p->ssl_ctxs->ssl_ctx;
/* free ssl_ctx from $SERVER["socket"] (if not copy of global scope) */
for (uint32_t i = 1; i < srv->config_context->used; ++i) {
plugin_ssl_ctx * const s = p->ssl_ctxs + i;
if (s->ssl_ctx && s->ssl_ctx != ssl_ctx_global_scope)
SSL_CTX_free(s->ssl_ctx);
}
/* free ssl_ctx from global scope */
if (ssl_ctx_global_scope)
SSL_CTX_free(ssl_ctx_global_scope);
free(p->ssl_ctxs);
}
if (NULL == p->cvlist) return;
/* (init i to 0 if global context; to 1 to skip empty global context) */
for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
for (; -1 != cpv->k_id; ++cpv) {
switch (cpv->k_id) {
case 0: /* ssl.pemfile */
if (cpv->vtype == T_CONFIG_LOCAL) {
plugin_cert *pc = cpv->v.v;
EVP_PKEY_free(pc->ssl_pemfile_pkey);
X509_free(pc->ssl_pemfile_x509);
sk_X509_pop_free(pc->ssl_pemfile_chain, X509_free);
buffer_free(pc->ssl_stapling);
free(pc);
}
break;
case 2: /* ssl.ca-file */
if (cpv->vtype == T_CONFIG_LOCAL) {
plugin_cacerts *cacerts = cpv->v.v;
sk_X509_NAME_pop_free(cacerts->names, X509_NAME_free);
X509_STORE_free(cacerts->certs);
free(cacerts);
}
break;
case 3: /* ssl.ca-dn-file */
if (cpv->vtype == T_CONFIG_LOCAL)
sk_X509_NAME_pop_free(cpv->v.v, X509_NAME_free);
break;
default:
break;
}
}
}
}
/* use memory from openssl secure heap for temporary buffers, returned storage
* (pemfile might contain a private key in addition to certificate chain)
* Interfaces similar to those constructed in include/openssl/pem.h for
* PEM_read_bio_X509(), except this is named PEM_read_bio_X509_secmem().
* Similar for PEM_read_bio_X509_AUX_secmem().
*
* Supporting routine PEM_ASN1_read_bio_secmem() modified from openssl
* crypto/pem/pem_oth.c:PEM_ASN1_read_bio():
* uses PEM_bytes_read_bio_secmem() instead of PEM_bytes_read_bio()
* uses OPENSSL_secure_clear_free() instead of OPENSSL_free()
*
* 'man PEM_bytes_read_bio_secmem()' and see NOTES section for more info
* PEM_bytes_read_bio_secmem() openssl 1.1.1 or later
* OPENSSL_secure_clear_free() openssl 1.1.0g or later
* As this comment is being written, only openssl 1.1.1 is actively maintained.
* Earlier vers of openssl no longer receive security patches from openssl.org.
*/
static void *
PEM_ASN1_read_bio_secmem(d2i_of_void *d2i, const char *name, BIO *bp, void **x,
pem_password_cb *cb, void *u)
{
const unsigned char *p = NULL;
unsigned char *data = NULL;
long len = 0;
char *ret = NULL;
2020-06-05 07:28:19 +00:00
#if OPENSSL_VERSION_NUMBER >= 0x10101000L \
&& !defined(LIBRESSL_VERSION_NUMBER)
if (!PEM_bytes_read_bio_secmem(&data, &len, NULL, name, bp, cb, u))
#else
if (!PEM_bytes_read_bio(&data, &len, NULL, name, bp, cb, u))
#endif
return NULL;
p = data;
ret = d2i(x, &p, len);
2020-06-10 11:52:57 +00:00
#ifndef BORINGSSL_API_VERSION /* missing PEMerr() macro */
if (ret == NULL)
PEMerr(PEM_F_PEM_ASN1_READ_BIO, ERR_R_ASN1_LIB);
2020-06-10 11:52:57 +00:00
#endif
2020-06-05 07:28:19 +00:00
#if OPENSSL_VERSION_NUMBER >= 0x10101000L \
&& !defined(LIBRESSL_VERSION_NUMBER)
OPENSSL_secure_clear_free(data, len);
#else
OPENSSL_cleanse(data, len);
OPENSSL_free(data);
#endif
return ret;
}
static X509 *
PEM_read_bio_X509_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
{
return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509,
PEM_STRING_X509,
bp, (void **)x, cb, u);
}
static X509 *
PEM_read_bio_X509_AUX_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
{
return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509_AUX,
PEM_STRING_X509_TRUSTED,
bp, (void **)x, cb, u);
}
static int
mod_openssl_load_X509_sk (const char *file, log_error_st *errh, STACK_OF(X509) **chain, BIO *in)
{
STACK_OF(X509) *chain_sk = NULL;
for (X509 *ca; (ca = PEM_read_bio_X509_secmem(in,NULL,NULL,NULL)); ) {
if (NULL == chain_sk) /*(allocate only if it will not be empty)*/
chain_sk = sk_X509_new_null();
if (!chain_sk || !sk_X509_push(chain_sk, ca)) {
log_error(errh, __FILE__, __LINE__,
"SSL: couldn't read X509 certificates from '%s'", file);
if (chain_sk) sk_X509_pop_free(chain_sk, X509_free);
X509_free(ca);
return 0;
}
}
*chain = chain_sk;
return 1;
}
static int
mod_openssl_load_X509_STORE (const char *file, log_error_st *errh, X509_STORE **chain, BIO *in)
{
X509_STORE *chain_store = NULL;
for (X509 *ca; (ca = PEM_read_bio_X509(in,NULL,NULL,NULL)); X509_free(ca)) {
if (NULL == chain_store) /*(allocate only if it will not be empty)*/
chain_store = X509_STORE_new();
if (!chain_store || !X509_STORE_add_cert(chain_store, ca)) {
log_error(errh, __FILE__, __LINE__,
"SSL: couldn't read X509 certificates from '%s'", file);
if (chain_store) X509_STORE_free(chain_store);
X509_free(ca);
return 0;
}
}
*chain = chain_store;
return 1;
}
static plugin_cacerts *
mod_openssl_load_cacerts (const buffer *ssl_ca_file, log_error_st *errh)
{
const char *file = ssl_ca_file->ptr;
BIO *in = BIO_new(BIO_s_file());
if (NULL == in) {
log_error(errh, __FILE__, __LINE__,
"SSL: BIO_new(BIO_s_file()) failed");
return NULL;
}
if (BIO_read_filename(in, file) <= 0) {
log_error(errh, __FILE__, __LINE__,
"SSL: BIO_read_filename('%s') failed", file);
BIO_free(in);
return NULL;
}
X509_STORE *chain_store = NULL;
if (!mod_openssl_load_X509_STORE(file, errh, &chain_store, in)) {
BIO_free(in);
return NULL;
}
BIO_free(in);
if (NULL == chain_store) {
log_error(errh, __FILE__, __LINE__,
"SSL: ssl.ca-file is empty %s", file);
return NULL;
}
plugin_cacerts *cacerts = malloc(sizeof(plugin_cacerts));
force_assert(cacerts);
/* (would be more efficient to walk the X509_STORE and build the list,
* but this works for now and matches how ssl.ca-dn-file is handled) */
cacerts->names = SSL_load_client_CA_file(file);
if (NULL == cacerts->names) {
X509_STORE_free(chain_store);
free(cacerts);
return NULL;
}
cacerts->certs = chain_store;
return cacerts;
}
static int
mod_openssl_load_cacrls (X509_STORE *store, const buffer *ssl_ca_crl_file, server *srv)
{
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
if (1 != X509_STORE_load_file(store, ssl_ca_crl_file->ptr))
#else
if (1 != X509_STORE_load_locations(store, ssl_ca_crl_file->ptr, NULL))
#endif
{
log_error(srv->errh, __FILE__, __LINE__,
"SSL: %s %s", ERR_error_string(ERR_get_error(), NULL),
ssl_ca_crl_file->ptr);
return 0;
}
X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
return 1;
}
2020-06-05 07:28:19 +00:00
#if OPENSSL_VERSION_NUMBER < 0x10002000 \
|| defined(LIBRESSL_VERSION_NUMBER)
static int
mod_openssl_load_verify_locn (SSL_CTX *ssl_ctx, const buffer *b, server *srv)
{
const char *fn = b->ptr;
if (1 == SSL_CTX_load_verify_locations(ssl_ctx, fn, NULL))
return 1;
log_error(srv->errh, __FILE__, __LINE__,
"SSL: %s %s", ERR_error_string(ERR_get_error(), NULL), fn);
return 0;
}
static int
mod_openssl_load_ca_files (SSL_CTX *ssl_ctx, plugin_data *p, server *srv)
{
/* load all ssl