lighttpd 1.4.x https://www.lighttpd.net/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lighttpd1.4/src/mod_openssl.c

2447 lines
85 KiB

#include "first.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifndef USE_OPENSSL_KERBEROS
#ifndef OPENSSL_NO_KRB5
#define OPENSSL_NO_KRB5
#endif
#endif
#include "sys-crypto.h"
#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>
#ifndef OPENSSL_NO_DH
#include <openssl/dh.h>
#endif
#if ! defined OPENSSL_NO_TLSEXT && ! defined SSL_CTRL_SET_TLSEXT_HOSTNAME
#define OPENSSL_NO_TLSEXT
#endif
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
#ifndef OPENSSL_NO_ECDH
#include <openssl/ecdh.h>
#endif
#endif
#include "base.h"
#include "http_header.h"
#include "log.h"
#include "plugin.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;
const buffer *ssl_pemfile;
const buffer *ssl_privkey;
} plugin_cert;
typedef struct {
SSL_CTX *ssl_ctx;
EVP_PKEY *ssl_pemfile_pkey;
} plugin_ssl_ctx;
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)*/
EVP_PKEY *ssl_pemfile_pkey;
X509 *ssl_pemfile_x509;
const buffer *ssl_pemfile;
const buffer *ssl_privkey;
STACK_OF(X509_NAME) *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;
} plugin_config_socket; /*(used at startup during configuration)*/
typedef struct {
/* SNI per host: w/ COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
EVP_PKEY *ssl_pemfile_pkey;
X509 *ssl_pemfile_x509;
const buffer *ssl_pemfile;
STACK_OF(X509_NAME) *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;
array *cafiles;
} 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;
connection *con;
short renegotiations; /* count of SSL_CB_HANDSHAKE_START */
short close_notify;
unsigned short request_env_patched;
unsigned short alpn;
plugin_config conf;
server *srv;
} 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);
}
INIT_FUNC(mod_openssl_init)
{
plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
#ifdef DEBUG_WOLFSSL
wolfSSL_Debugging_ON();
#endif
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)
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_write(srv, __FILE__, __LINE__, "ss", "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;
#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);
}
break;
case 2: /* ssl.ca-file */
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;
}
}
}
}
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.ca-files specified in the config
* into each SSL_CTX to be prepared for SNI */
for (uint32_t i = 0, used = p->cafiles->used; i < used; ++i) {
const buffer *b = &((data_string *)p->cafiles->data[i])->value;
if (!mod_openssl_load_verify_locn(ssl_ctx, b, srv))
return 0;
}
return 1;
}
FREE_FUNC(mod_openssl_free)
{
plugin_data *p = p_d;
if (!p) return HANDLER_GO_ON;
UNUSED(srv);
mod_openssl_free_config(srv, p);
mod_openssl_free_openssl();
free(p->cvlist);
free(p);
return HANDLER_GO_ON;
}
static void
mod_openssl_merge_config_cpv (plugin_config * const pconf, const config_plugin_value_t * const cpv)
{
switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
case 0: /* ssl.pemfile */
if (cpv->vtype == T_CONFIG_LOCAL) {
plugin_cert *pc = cpv->v.v;
pconf->ssl_pemfile_pkey = pc->ssl_pemfile_pkey;
pconf->ssl_pemfile_x509 = pc->ssl_pemfile_x509;
pconf->ssl_pemfile = pc->ssl_pemfile;
}
break;
case 1: /* ssl.privkey */
break;
case 2: /* ssl.ca-file */
if (cpv->vtype == T_CONFIG_LOCAL)
pconf->ssl_ca_file = cpv->v.v;
break;
case 3: /* ssl.ca-dn-file */
if (cpv->vtype == T_CONFIG_LOCAL)
pconf->ssl_ca_dn_file = cpv->v.v;
break;
case 4: /* ssl.ca-crl-file */
pconf->ssl_ca_crl_file = cpv->v.b;
break;
case 5: /* ssl.read-ahead */
pconf->ssl_read_ahead = (0 != cpv->v.u);
break;
case 6: /* ssl.disable-client-renegotiation */
pconf->ssl_disable_client_renegotiation = (0 != cpv->v.u);
break;
case 7: /* ssl.verifyclient.activate */
pconf->ssl_verifyclient = (0 != cpv->v.u);
break;
case 8: /* ssl.verifyclient.enforce */
pconf->ssl_verifyclient_enforce = (0 != cpv->v.u);
break;
case 9: /* ssl.verifyclient.depth */
pconf->ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
break;
case 10:/* ssl.verifyclient.username */
pconf->ssl_verifyclient_username = cpv->v.b;
break;
case 11:/* ssl.verifyclient.exportcert */
pconf->ssl_verifyclient_export_cert = (0 != cpv->v.u);
break;
case 12:/* ssl.acme-tls-1 */
pconf->ssl_acme_tls_1 = cpv->v.b;
break;
case 13:/* debug.log-ssl-noise */
pconf->ssl_log_noise = (0 != cpv->v.u);
break;
default:/* should not happen */
return;
}
}
static void
mod_openssl_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
{
do {
mod_openssl_merge_config_cpv(pconf, cpv);
} while ((++cpv)->k_id != -1);
}
static void
mod_openssl_patch_config (connection * const con, plugin_config * const pconf)
{
plugin_data * const p = plugin_data_singleton;
memcpy(pconf, &p->defaults, sizeof(plugin_config));
for (int i = 1, used = p->nconfig; i < used; ++i) {
if (config_check_cond(con, (uint32_t)p->cvlist[i].k_id))
mod_openssl_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]);
}
}
static int
safer_X509_NAME_oneline(X509_NAME *name, char *buf, size_t sz)
{
BIO *bio = BIO_new(BIO_s_mem());
if (bio) {
int len = X509_NAME_print_ex(bio, name, 0, XN_FLAG_ONELINE);
BIO_gets(bio, buf, (int)sz); /*(may be truncated if len >= sz)*/
BIO_free(bio);
return len; /*return value has similar semantics to that of snprintf()*/
}
else {
buf[0] = '\0';
return -1;
}
}
static void
ssl_info_callback (const SSL *ssl, int where, int ret)
{
UNUSED(ret);
if (0 != (where & SSL_CB_HANDSHAKE_START)) {
handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
if (hctx->renegotiations >= 0) ++hctx->renegotiations;
}
#ifdef TLS1_3_VERSION
/* https://github.com/openssl/openssl/issues/5721
* "TLSv1.3 unexpected InfoCallback after handshake completed" */
if (0 != (where & SSL_CB_HANDSHAKE_DONE)) {
/* SSL_version() is valid after initial handshake completed */
if (SSL_version(ssl) >= TLS1_3_VERSION) {
/* https://wiki.openssl.org/index.php/TLS1.3
* "Renegotiation is not possible in a TLSv1.3 connection" */
handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
hctx->renegotiations = -1;
}
}
#endif
}
/* https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_verify(3)#EXAMPLES */
static int
verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
char buf[256];
X509 *err_cert;
int err, depth;
SSL *ssl;
handler_ctx *hctx;
server *srv;
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
/*
* Retrieve the pointer to the SSL of the connection currently treated
* and the application specific data stored into the SSL object.
*/
ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
hctx = (handler_ctx *) SSL_get_app_data(ssl);
srv = hctx->srv;
/*
* Catch a too long certificate chain. The depth limit set using
* SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
* that whenever the "depth>verify_depth" condition is met, we
* have violated the limit and want to log this error condition.
* We must do it here, because the CHAIN_TOO_LONG error would not
* be found explicitly; only errors introduced by cutting off the
* additional certificates would be logged.
*/
if (depth > hctx->conf.ssl_verifyclient_depth) {
preverify_ok = 0;
err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
X509_STORE_CTX_set_error(ctx, err);
}
if (preverify_ok && 0 == depth
&& NULL != hctx->conf.ssl_ca_dn_file
&& NULL != hctx->conf.ssl_ca_file) {
/* verify that client cert is issued by CA in ssl.ca-dn-file
* if both ssl.ca-dn-file and ssl.ca-file were configured */
STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file;
X509_NAME *issuer;
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
err_cert = X509_STORE_CTX_get_current_cert(ctx);
#else
err_cert = ctx->current_cert;
#endif
if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
issuer = X509_get_issuer_name(err_cert);
#if 0 /*(?desirable/undesirable to have cert_names sorted?)*/
if (-1 != sk_X509_NAME_find(cert_names, issuer))
return preverify_ok; /* match */
#else
for (int i = 0, len = sk_X509_NAME_num(cert_names); i < len; ++i) {
if (0 == X509_NAME_cmp(sk_X509_NAME_value(cert_names, i), issuer))
return preverify_ok; /* match */
}
#endif
preverify_ok = 0;
err = X509_V_ERR_CERT_REJECTED;
X509_STORE_CTX_set_error(ctx, err);
}
if (preverify_ok) {
return preverify_ok;
}
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
err_cert = X509_STORE_CTX_get_current_cert(ctx);
#else
err_cert = ctx->current_cert;
#endif
if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
safer_X509_NAME_oneline(X509_get_subject_name(err_cert),buf,sizeof(buf));
log_error_write(srv, __FILE__, __LINE__, "SDSSSDSS",
"SSL: verify error:num=", err, ":",
X509_verify_cert_error_string(err), ":depth=", depth,
":subject=", buf);
/*
* At this point, err contains the last verification error. We can use
* it for something special
*/
if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY ||
err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
safer_X509_NAME_oneline(X509_get_issuer_name(err_cert),buf,sizeof(buf));
log_error_write(srv, __FILE__, __LINE__, "SS", "SSL: issuer=", buf);
}
return !hctx->conf.ssl_verifyclient_enforce;
}
#ifndef OPENSSL_NO_TLSEXT
static int
mod_openssl_SNI (SSL *ssl, server *srv, handler_ctx *hctx, const char *servername, size_t len)
{
if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/
log_error(srv->errh, __FILE__, __LINE__,
"SSL: SNI name too long %.*s", (int)len, servername);
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
/* use SNI to patch mod_openssl config and then reset COMP_HTTP_HOST */
connection * const con = hctx->con;
buffer_copy_string_len(con->uri.authority, servername, len);
buffer_to_lower(con->uri.authority);
#if 0
/*(con->uri.authority used below for configuration before request read;
* revisit for h2)*/
if (0 != http_request_host_policy(con, con->uri.authority, con->uri.scheme))
return SSL_TLSEXT_ERR_ALERT_FATAL;
#endif
const buffer * const ssl_pemfile = hctx->conf.ssl_pemfile;
con->conditional_is_valid |= (1 << COMP_HTTP_SCHEME)
| (1 << COMP_HTTP_HOST);
mod_openssl_patch_config(con, &hctx->conf);
/* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */
/*(done in response.c:config_cond_cache_reset() after request hdrs read)*/
/*config_cond_cache_reset_item(con, COMP_HTTP_HOST);*/
/*buffer_clear(con->uri.authority);*/
if (!buffer_is_equal(hctx->conf.ssl_pemfile, ssl_pemfile)) {
/* reconfigure to use SNI-specific cert if SNI-specific cert provided */
if (NULL == hctx->conf.ssl_pemfile_x509
|| NULL == hctx->conf.ssl_pemfile_pkey) {
/* x509/pkey available <=> pemfile was set <=> pemfile got patched:
* so this should never happen, unless you nest $SERVER["socket"] */
log_error(srv->errh, __FILE__, __LINE__,
"SSL: no certificate/private key for TLS server name %s",
con->uri.authority->ptr);
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
/* first set certificate!
* setting private key checks whether certificate matches it */
if (1 != SSL_use_certificate(ssl, hctx->conf.ssl_pemfile_x509)) {
log_error(srv->errh, __FILE__, __LINE__,
"SSL: failed to set certificate for TLS server name %s: %s",
con->uri.authority->ptr, ERR_error_string(ERR_get_error(), NULL));
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
if (1 != SSL_use_PrivateKey(ssl, hctx->conf.ssl_pemfile_pkey)) {
log_error(srv->errh, __FILE__, __LINE__,
"SSL: failed to set private key for TLS server name %s: %s",
con->uri.authority->ptr, ERR_error_string(ERR_get_error(), NULL));
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
}
if (hctx->conf.ssl_verifyclient) {
int mode;
STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file
? hctx->conf.ssl_ca_dn_file
: hctx->conf.ssl_ca_file;
if (NULL == cert_names) {
log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
"can't verify client without ssl.ca-file "
"or ssl.ca-dn-file for TLS server name",
con->uri.authority,
ERR_error_string(ERR_get_error(), NULL));
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
SSL_set_client_CA_list(ssl, SSL_dup_CA_list(cert_names));
/* forcing verification here is really not that useful
* -- a client could just connect without SNI */
mode = SSL_VERIFY_PEER;
if (hctx->conf.ssl_verifyclient_enforce) {
mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
}
SSL_set_verify(ssl, mode, verify_callback);
SSL_set_verify_depth(ssl, hctx->conf.ssl_verifyclient_depth + 1);
} else {
SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
}
return SSL_TLSEXT_ERR_OK;
}
#ifdef SSL_CLIENT_HELLO_SUCCESS
static int
mod_openssl_client_hello_cb (SSL *ssl, int *al, void *srv)
{
handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
buffer_copy_string(hctx->con->uri.scheme, "https");
const unsigned char *name;
size_t len, slen;
if (!SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &name, &len)) {
return SSL_CLIENT_HELLO_SUCCESS; /* client did not provide SNI */
}
/* expecting single element in the server_name extension; parse first one */
if (len > 5
&& (size_t)((name[0] << 8) + name[1]) == len-2
&& name[2] == TLSEXT_TYPE_server_name
&& (slen = (name[3] << 8) + name[4]) <= len-5) { /*(first)*/
int rc = mod_openssl_SNI(ssl, srv, hctx, (const char *)name+5, slen);
if (rc == SSL_TLSEXT_ERR_OK)
return SSL_CLIENT_HELLO_SUCCESS;
}
*al = TLS1_AD_UNRECOGNIZED_NAME;
return SSL_CLIENT_HELLO_ERROR;
}
#else
static int
network_ssl_servername_callback (SSL *ssl, int *al, server *srv)
{
handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
buffer_copy_string(hctx->con->uri.scheme, "https");
UNUSED(al);
const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
return (NULL != servername)
? mod_openssl_SNI(ssl, srv, hctx, servername, strlen(servername))
: SSL_TLSEXT_ERR_NOACK; /* client did not provide SNI */
}
#endif
#endif
static X509 *
x509_load_pem_file (server *srv, const char *file)
{
BIO *in;
X509 *x = NULL;
in = BIO_new(BIO_s_file());
if (NULL == in) {
log_error_write(srv, __FILE__, __LINE__, "S",
"SSL: BIO_new(BIO_s_file()) failed");
goto error;
}
if (BIO_read_filename(in,file) <= 0) {
log_error_write(srv, __FILE__, __LINE__, "SSS",
"SSL: BIO_read_filename('", file,"') failed");
goto error;
}
x = PEM_read_bio_X509(in, NULL, NULL, NULL);
if (NULL == x) {
log_error_write(srv, __FILE__, __LINE__, "SSS",
"SSL: couldn't read X509 certificate from '", file,"'");
goto error;
}
BIO_free(in);
return x;
error:
if (NULL != in) BIO_free(in);
return NULL;
}
static EVP_PKEY *
evp_pkey_load_pem_file (server *srv, const char *file)
{
BIO *in;
EVP_PKEY *x = NULL;
in = BIO_new(BIO_s_file());
if (NULL == in) {
log_error_write(srv, __FILE__, __LINE__, "s",
"SSL: BIO_new(BIO_s_file()) failed");
goto error;
}
if (BIO_read_filename(in,file) <= 0) {
log_error_write(srv, __FILE__, __LINE__, "SSS",
"SSL: BIO_read_filename('", file,"') failed");
goto error;
}
x = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
if (NULL == x) {
log_error_write(srv, __FILE__, __LINE__, "SSS",
"SSL: couldn't read private key from '", file,"'");
goto error;
}
BIO_free(in);
return x;
error:
if (NULL != in) BIO_free(in);
return NULL;
}
static void *
network_openssl_load_pemfile (server *srv, const buffer *pemfile, const buffer *privkey)
{
if (!mod_openssl_init_once_openssl(srv)) return NULL;
X509 *ssl_pemfile_x509 = x509_load_pem_file(srv, pemfile->ptr);
if (NULL == ssl_pemfile_x509)
return NULL;
EVP_PKEY *ssl_pemfile_pkey = evp_pkey_load_pem_file(srv, privkey->ptr);
if (NULL == ssl_pemfile_pkey) {
X509_free(ssl_pemfile_x509);
return NULL;
}
if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
log_error(srv->errh, __FILE__, __LINE__, "SSL:"
"Private key does not match the certificate public key, "
"reason: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
pemfile->ptr, privkey->ptr);
EVP_PKEY_free(ssl_pemfile_pkey);
X509_free(ssl_pemfile_x509);
return NULL;
}
plugin_cert *pc = malloc(sizeof(plugin_cert));
force_assert(pc);
pc->ssl_pemfile_pkey = ssl_pemfile_pkey;
pc->ssl_pemfile_x509 = ssl_pemfile_x509;
pc->ssl_pemfile = pemfile;
pc->ssl_privkey = privkey;
return pc;
}
#ifndef OPENSSL_NO_TLSEXT
#if OPENSSL_VERSION_NUMBER >= 0x10002000
static int
mod_openssl_acme_tls_1 (SSL *ssl, handler_ctx *hctx)
{
server *srv = hctx->srv;
buffer *b = srv->tmp_buf;
buffer *name = hctx->con->uri.authority;
X509 *ssl_pemfile_x509 = NULL;
EVP_PKEY *ssl_pemfile_pkey = NULL;
size_t len;
int rc = SSL_TLSEXT_ERR_ALERT_FATAL;
/* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/
if (buffer_string_is_empty(hctx->conf.ssl_acme_tls_1))
return SSL_TLSEXT_ERR_NOACK; /*(reuse value here for not-configured)*/
buffer_copy_buffer(b, hctx->conf.ssl_acme_tls_1);
buffer_append_slash(b);
/* check if SNI set server name (required for acme-tls/1 protocol)
* and perform simple path checks for no '/'
* and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */
if (buffer_string_is_empty(name)) return rc;
if (NULL != strchr(name->ptr, '/')) return rc;
if (name->ptr[0] == '.') return rc;
#if 0
if (0 != http_request_host_policy(hctx->con, name, hctx->con->uri.scheme))
return rc;
#endif
buffer_append_string_buffer(b, name);
len = buffer_string_length(b);
do {
buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
ssl_pemfile_x509 = x509_load_pem_file(srv, b->ptr);
if (NULL == ssl_pemfile_x509) {
log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
"Failed to load acme-tls/1 pemfile:", b);
break;
}
buffer_string_set_length(b, len); /*(remove ".crt.pem")*/
buffer_append_string_len(b, CONST_STR_LEN(".key.pem"));
ssl_pemfile_pkey = evp_pkey_load_pem_file(srv, b->ptr);
if (NULL == ssl_pemfile_pkey) {
log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
"Failed to load acme-tls/1 pemfile:", b);
break;
}
#if 0 /* redundant with below? */
if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
log_error_write(srv, __FILE__, __LINE__, "sssb", "SSL:",
"Private key does not match acme-tls/1 certificate public key,"
" reason:" ERR_error_string(ERR_get_error(), NULL), b);
break;
}
#endif
/* first set certificate!
* setting private key checks whether certificate matches it */
if (1 != SSL_use_certificate(ssl, ssl_pemfile_x509)) {
log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
"failed to set acme-tls/1 certificate for TLS server name",
name, ERR_error_string(ERR_get_error(), NULL));
break;
}
if (1 != SSL_use_PrivateKey(ssl, ssl_pemfile_pkey)) {
log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
"failed to set acme-tls/1 private key for TLS server name",
name, ERR_error_string(ERR_get_error(), NULL));
break;
}
rc = SSL_TLSEXT_ERR_OK;
} while (0);
if (ssl_pemfile_pkey) EVP_PKEY_free(ssl_pemfile_pkey);
if (ssl_pemfile_x509) X509_free(ssl_pemfile_x509);
return rc;
}
enum {
MOD_OPENSSL_ALPN_HTTP11 = 1
,MOD_OPENSSL_ALPN_HTTP10 = 2
,MOD_OPENSSL_ALPN_H2 = 3
,MOD_OPENSSL_ALPN_ACME_TLS_1 = 4
};
/* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */
static int
mod_openssl_alpn_select_cb (SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
{
handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
unsigned short proto;
UNUSED(arg);
for (unsigned int i = 0, n; i < inlen; i += n) {
n = in[i++];
if (i+n > inlen || 0 == n) break;
switch (n) {
#if 0
case 2: /* "h2" */
if (in[i] == 'h' && in[i+1] == '2') {
proto = MOD_OPENSSL_ALPN_H2;
break;
}
continue;
#endif
case 8: /* "http/1.1" "http/1.0" */
if (0 == memcmp(in+i, "http/1.", 7)) {
if (in[i+7] == '1') {
proto = MOD_OPENSSL_ALPN_HTTP11;
break;
}
if (in[i+7] == '0') {
proto = MOD_OPENSSL_ALPN_HTTP10;
break;
}
}
continue;
case 10: /* "acme-tls/1" */
if (0 == memcmp(in+i, "acme-tls/1", 10)) {
int rc = mod_openssl_acme_tls_1(ssl, hctx);