You cannot 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_gnutls.c

3093 lines
108 KiB
C

/*
* mod_gnutls - GnuTLS support for lighttpd
*
* Copyright(c) 2020 Glenn Strauss gstrauss()gluelogic.com All rights reserved
* License: BSD 3-clause (same as lighttpd)
*/
/*
* GnuTLS manual: https://www.gnutls.org/documentation.html
*
* future possible enhancements: OCSP stapling
*
* Note: session tickets are disabled by default. If enabled,
* mod_gnutls rotates server ticket encryption key (STEK) every 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 other than by (some external job) restarting 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, 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 24 hours if session tickets are enabled and
* multiple lighttpd workers are configured.
*/
#include "first.h"
#include <sys/types.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h> /* vsnprintf() */
#include <string.h>
#include <unistd.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/abstract.h>
#ifdef GNUTLS_SKIP_GLOBAL_INIT
GNUTLS_SKIP_GLOBAL_INIT
#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 */
gnutls_certificate_credentials_t ssl_cred;
char trust_inited;
gnutls_datum_t *ssl_pemfile_x509;
gnutls_privkey_t ssl_pemfile_pkey;
} plugin_cert;
typedef struct {
int8_t ssl_session_ticket;
/*(preserved here for deinit at server shutdown)*/
gnutls_priority_t priority_cache;
#if GNUTLS_VERSION_NUMBER < 0x030600
gnutls_dh_params_t dh_params;
#endif
} plugin_ssl_ctx;
typedef struct {
plugin_cert *pc;
/*(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;
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)*/
gnutls_priority_t priority_cache;
unsigned char ssl_session_ticket;
unsigned char ssl_verifyclient;
unsigned char ssl_verifyclient_enforce;
unsigned char ssl_verifyclient_depth;
const char *priority_base;
buffer priority_str;
#if GNUTLS_VERSION_NUMBER < 0x030600
gnutls_dh_params_t dh_params;
#endif
} 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;
gnutls_datum_t *ssl_ca_file; /* .data is (gnutls_x509_crt_t) */
gnutls_datum_t *ssl_ca_dn_file; /* .data is (gnutls_x509_crt_t) */
gnutls_datum_t *ssl_ca_crl_file;/* .data is (gnutls_x509_crl_t) */
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;
#if GNUTLS_VERSION_NUMBER < 0x030600
gnutls_dh_params_t dh_params;
#endif
} plugin_config;
typedef struct {
PLUGIN_DATA;
plugin_ssl_ctx *ssl_ctxs;
plugin_config defaults;
server *srv;
} 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 = r->plugin_ctx[plugin_data_singleton->id]; */
static plugin_data *plugin_data_singleton;
#define LOCAL_SEND_BUFSIZE 16384 /* DEFAULT_MAX_RECORD_SIZE */
static char *local_send_buffer;
typedef struct {
gnutls_session_t ssl; /* gnutls request/connection context */
request_st *r;
connection *con;
int8_t request_env_patched;
int8_t close_notify;
uint8_t alpn;
int8_t ssl_session_ticket;
int handshake;
size_t pending_write;
plugin_config conf;
unsigned int verify_status;
buffer *tmp_buf;
gnutls_certificate_credentials_t acme_tls_1_cred;
} 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)
{
gnutls_deinit(hctx->ssl);
if (hctx->acme_tls_1_cred)
gnutls_certificate_free_credentials(hctx->acme_tls_1_cred);
free(hctx);
}
__attribute_cold__
static void elog(log_error_st * const errh,
const char * const file, const int line,
const int rc, const char * const msg)
{
/* error logging convenience function that decodes gnutls result codes */
log_error(errh, file, line, "GnuTLS: %s: (%s) %s",
msg, gnutls_strerror_name(rc), gnutls_strerror(rc));
}
__attribute_cold__
__attribute_format__((__printf__, 5, 6))
static void elogf(log_error_st * const errh,
const char * const file, const int line,
const int rc, const char * const fmt, ...)
{
char msg[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
elog(errh, file, line, rc, msg);
}
/* gnutls func gnutls_load_file() loads file contents into a gnutls_datum_t.
* The data loaded could be sensitive, e.g. a private key included in a pemfile.
* However, gnutls_load_file() is not careful about zeroizing memory on error,
* might use realloc() (which does not guarantee to zeroize memory released),
* and silently continues on short read, so provide our own. Updates to
* gnutls 3.6.14 may be more careful with private key files, but do not
* extend the same care to pemfiles which might contain private keys.
* Related, see also mod_gnutls_datum_wipe() below.
* https://gitlab.com/gnutls/gnutls/-/issues/1001
* https://gitlab.com/gnutls/gnutls/-/issues/1002
* https://gitlab.com/gnutls/gnutls/-/merge_requests/1270
*/
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include "fdevent.h"
static int
mod_gnutls_load_file (const char * const fn, gnutls_datum_t * const d, log_error_st *errh)
{
#if 0
int rc = gnutls_load_file(fn, d);
if (rc < 0)
elogf(errh, __FILE__, __LINE__, rc, "%s() %s", __func__, fn);
return rc;
#else
int fd = -1;
unsigned int sz = 0;
char *buf = NULL;
do {
fd = fdevent_open_cloexec(fn, 1, O_RDONLY, 0); /*(1: follows symlinks)*/
if (fd < 0) break;
struct stat st;
if (0 != fstat(fd, &st)) break;
if (st.st_size >= UINT_MAX) { /*(file too large for gnutls_datum_t)*/
errno = EOVERFLOW;
break;
}
sz = (unsigned int)st.st_size;
buf = gnutls_malloc(sz+1); /*(+1 trailing '\0' for gnutls_load_file())*/
if (NULL == buf) break;
ssize_t rd = 0;
unsigned int off = 0;
do {
rd = read(fd, buf+off, sz-off);
} while (rd > 0 ? (off += (unsigned int)rd) != sz : errno == EINTR);
if (off != sz) { /*(file truncated?)*/
if (rd >= 0) errno = EIO;
break;
}
buf[sz] = '\0';
d->data = (unsigned char *)buf;
d->size = sz;
close(fd);
return 0;
} while (0);
int errnum = errno;
log_perror(errh, __FILE__, __LINE__, "%s() %s", __func__, fn);
if (fd >= 0) close(fd);
if (buf) {
gnutls_memset(buf, 0, sz);
gnutls_free(buf);
}
errno = errnum;
return GNUTLS_E_FILE_ERROR;
#endif
}
/* GnuTLS does not expose _gnutls_free_key_datum() so provide our own */
static void
mod_gnutls_datum_wipe (gnutls_datum_t * const d)
{
if (NULL == d) return;
if (d->data) {
if (d->size) gnutls_memset(d->data, 0, d->size);
gnutls_free(d->data);
d->data = NULL;
}
d->size = 0;
}
static time_t stek_rotate_ts;
static gnutls_datum_t session_ticket_key;
static void
mod_gnutls_session_ticket_key_free (void)
{
mod_gnutls_datum_wipe(&session_ticket_key);
}
static void
mod_gnutls_session_ticket_key_init (server *srv)
{
int rc = gnutls_session_ticket_key_generate(&session_ticket_key);
if (rc < 0) {
/*(should not happen, but if it does, disable session ticket)*/
session_ticket_key.size = 0;
elog(srv->errh, __FILE__, __LINE__, rc,
"gnutls_session_ticket_key_generate()");
}
}
static void
mod_gnutls_session_ticket_key_rotate (server *srv)
{
mod_gnutls_session_ticket_key_free();
mod_gnutls_session_ticket_key_init(srv);
}
INIT_FUNC(mod_gnutls_init)
{
plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
return plugin_data_singleton;
}
static int mod_gnutls_init_once_gnutls (void)
{
if (ssl_is_init) return 1;
ssl_is_init = 1;
/* Note: on systems with support for weak symbols, GNUTLS_SKIP_GLOBAL_INIT
* is set near top of this file to inhibit GnuTLS implicit initialization
* in a library constructor. On systems without support for weak symbols,
* set GNUTLS_NO_EXPLICIT_INIT=1 in the environment before starting lighttpd
* (GnuTLS 3.3.0 or later) */
if (gnutls_global_init() != GNUTLS_E_SUCCESS)
return 0;
local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
force_assert(NULL != local_send_buffer);
return 1;
}
static void mod_gnutls_free_gnutls (void)
{
if (!ssl_is_init) return;
mod_gnutls_session_ticket_key_free();
gnutls_global_deinit();
free(local_send_buffer);
ssl_is_init = 0;
}
static void
mod_gnutls_free_config_crts (gnutls_datum_t *d)
{
if (NULL == d) return;
gnutls_x509_crt_t *crts = (gnutls_x509_crt_t *)(void *)d->data;
unsigned int u = d->size;
for (unsigned int i = 0; i < u; ++i)
gnutls_x509_crt_deinit(crts[i]);
gnutls_free(crts);
gnutls_free(d);
}
static void
mod_gnutls_free_config_crls (gnutls_datum_t *d)
{
if (NULL == d) return;
gnutls_x509_crl_t *crls = (gnutls_x509_crl_t *)(void *)d->data;
unsigned int u = d->size;
for (unsigned int i = 0; i < u; ++i)
gnutls_x509_crl_deinit(crls[i]);
gnutls_free(crls);
gnutls_free(d);
}
static gnutls_datum_t *
mod_gnutls_load_config_crts (const char *fn, log_error_st *errh)
{
/*(very similar to other mod_gnutls_load_config_*())*/
if (!mod_gnutls_init_once_gnutls()) return NULL;
gnutls_datum_t f = { NULL, 0 };
int rc = mod_gnutls_load_file(fn, &f, errh);
if (rc < 0) return NULL;
gnutls_datum_t *d = gnutls_malloc(sizeof(gnutls_datum_t));
if (d == NULL) {
mod_gnutls_datum_wipe(&f);
return NULL;
}
d->data = NULL;
d->size = 0;
rc = gnutls_x509_crt_list_import2((gnutls_x509_crt_t **)&d->data, &d->size,
&f, GNUTLS_X509_FMT_PEM,
GNUTLS_X509_CRT_LIST_SORT);
mod_gnutls_datum_wipe(&f);
if (rc < 0) {
elogf(errh, __FILE__, __LINE__, rc,
"gnutls_x509_crt_list_import2() %s", fn);
mod_gnutls_free_config_crts(d);
return NULL;
}
return d;
}
static gnutls_datum_t *
mod_gnutls_load_config_crls (const char *fn, log_error_st *errh)
{
/*(very similar to other mod_gnutls_load_config_*())*/
if (!mod_gnutls_init_once_gnutls()) return NULL;
gnutls_datum_t f = { NULL, 0 };
int rc = mod_gnutls_load_file(fn, &f, errh);
if (rc < 0) return NULL;
gnutls_datum_t *d = gnutls_malloc(sizeof(gnutls_datum_t));
if (d == NULL) {
mod_gnutls_datum_wipe(&f);
return NULL;
}
d->data = NULL;
d->size = 0;
rc = gnutls_x509_crl_list_import2((gnutls_x509_crl_t **)&d->data, &d->size,
&f, GNUTLS_X509_FMT_PEM, 0);
mod_gnutls_datum_wipe(&f);
if (rc < 0) {
elogf(errh, __FILE__, __LINE__, rc,
"gnutls_x509_crl_list_import2() %s", fn);
mod_gnutls_free_config_crls(d);
return NULL;
}
return d;
}
static gnutls_privkey_t
mod_gnutls_load_config_pkey (const char *fn, log_error_st *errh)
{
/*(very similar to other mod_gnutls_load_config_*())*/
if (!mod_gnutls_init_once_gnutls()) return NULL;
gnutls_datum_t f = { NULL, 0 };
int rc = mod_gnutls_load_file(fn, &f, errh);
if (rc < 0) return NULL;
gnutls_privkey_t pkey;
rc = gnutls_privkey_init(&pkey);
if (rc < 0) {
mod_gnutls_datum_wipe(&f);
return NULL;
}
rc = gnutls_privkey_import_x509_raw(pkey, &f, GNUTLS_X509_FMT_PEM, NULL, 0);
mod_gnutls_datum_wipe(&f);
if (rc < 0) {
elogf(errh, __FILE__, __LINE__, rc,
"gnutls_privkey_import_x509_raw() %s", fn);
gnutls_privkey_deinit(pkey);
return NULL;
}
return pkey;
}
static void
mod_gnutls_free_config (server *srv, plugin_data * const p)
{
if (NULL != p->ssl_ctxs) {
gnutls_priority_t pcache_global_scope = p->ssl_ctxs->priority_cache;
/* free 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->priority_cache && s->priority_cache != pcache_global_scope) {
if (s->priority_cache)
gnutls_priority_deinit(s->priority_cache);
#if GNUTLS_VERSION_NUMBER < 0x030600
if (s->dh_params)
gnutls_dh_params_deinit(s->dh_params);
#endif
}
}
/* free from global scope */
if (pcache_global_scope) {
if (p->ssl_ctxs[0].priority_cache)
gnutls_priority_deinit(p->ssl_ctxs[0].priority_cache);
#if GNUTLS_VERSION_NUMBER < 0x030600
if (p->ssl_ctxs[0].dh_params)
gnutls_dh_params_deinit(p->ssl_ctxs[0].dh_params);
#endif
}
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;
gnutls_certificate_free_credentials(pc->ssl_cred);
mod_gnutls_free_config_crts(pc->ssl_pemfile_x509);
gnutls_privkey_deinit(pc->ssl_pemfile_pkey);
free(pc);
}
break;
case 2: /* ssl.ca-file */
case 3: /* ssl.ca-dn-file */
if (cpv->vtype == T_CONFIG_LOCAL)
mod_gnutls_free_config_crts(cpv->v.v);
break;
case 4: /* ssl.ca-crl-file */
if (cpv->vtype == T_CONFIG_LOCAL)
mod_gnutls_free_config_crls(cpv->v.v);
break;
default:
break;
}
}
}
}
FREE_FUNC(mod_gnutls_free)
{
plugin_data *p = p_d;
if (NULL == p->srv) return;
mod_gnutls_free_config(p->srv, p);
mod_gnutls_free_gnutls();
}
static void
mod_gnutls_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)
pconf->pc = cpv->v.v;
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 */
if (cpv->vtype == T_CONFIG_LOCAL)
pconf->ssl_ca_crl_file = cpv->v.v;
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 = (unsigned char)cpv->v.shrt;
break;
default:/* should not happen */
return;
}
}
static void
mod_gnutls_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
{
do {
mod_gnutls_merge_config_cpv(pconf, cpv);
} while ((++cpv)->k_id != -1);
}
static void
mod_gnutls_patch_config (request_st * const r, 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(r, (uint32_t)p->cvlist[i].k_id))
mod_gnutls_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]);
}
}
static int
mod_gnutls_verify_set_tlist (handler_ctx *hctx, int req)
{
/* XXX GnuTLS interfaces appear to be better for client-side use than for
* server-side use. If gnutls_x509_trust_list_t were available to attach
* to a gnutls_session_t (without copying), then there would not be race
* conditions swapping trust lists on the credential *shared* between
* connections when ssl.ca-dn-file and ssl.ca-file are both set. If both
* are set, current code attempts to set ssl.ca-dn-file right before sending
* client cert request, and sets ssl.ca-file right before client cert verify
*
* Architecture would be cleaner if the trust list for verifying client cert
* (gnutls_x509_trust_list_t) were available to attach to a gnutls_session_t
* instead of attaching to a gnutls_certificate_credentials_t.
*/
if (hctx->conf.pc->trust_inited) return GNUTLS_E_SUCCESS;
gnutls_datum_t *d;
int rc;
/* set trust list using ssl_ca_dn_file, if set, for client cert request
* (when req is true) (for CAs sent by server to client in cert request)
* (trust is later replaced by ssl_ca_file for client cert verification) */
d = req && hctx->conf.ssl_ca_dn_file
? hctx->conf.ssl_ca_dn_file
: hctx->conf.ssl_ca_file;
if (NULL == d) {
log_error(hctx->r->conf.errh, __FILE__, __LINE__,
"GnuTLS: can't verify client without ssl.ca-file "
"for TLS server name %s",
hctx->r->uri.authority.ptr); /*(might not be set yet if no SNI)*/
return GNUTLS_E_INTERNAL_ERROR;
}
gnutls_x509_trust_list_t tlist = NULL;
rc = gnutls_x509_trust_list_init(&tlist, 0);
if (rc < 0) {
elog(hctx->r->conf.errh, __FILE__, __LINE__, rc,
"gnutls_x509_trust_list_init()");
return rc;
}
gnutls_x509_crt_t *clist = (gnutls_x509_crt_t *)(void *)d->data;
rc = gnutls_x509_trust_list_add_cas(tlist, clist, d->size, 0);
if (rc < 0) {
elog(hctx->r->conf.errh, __FILE__, __LINE__, rc,
"gnutls_x509_trust_list_add_cas()");
gnutls_x509_trust_list_deinit(tlist, 0);
return rc;
}
d = hctx->conf.ssl_ca_crl_file;
if (NULL != d && req && hctx->conf.ssl_ca_dn_file) {
/*(check req and ssl_ca_dn_file to see if tlist will be replaced later,
* and, if so, defer setting crls until later)*/
gnutls_x509_crl_t *crl_list = (gnutls_x509_crl_t *)(void *)d->data;
rc = gnutls_x509_trust_list_add_crls(tlist, crl_list, d->size, 0, 0);
if (rc < 0) {
elog(hctx->r->conf.errh, __FILE__, __LINE__, rc,
"gnutls_x509_trust_list_add_crls()");
gnutls_x509_trust_list_deinit(tlist, 0);
return rc;
}
}
/* gnutls limitation; wasteful to have to copy into each cred */
/* (would be better to share list with session, instead of with cred) */
gnutls_certificate_credentials_t ssl_cred = hctx->conf.pc->ssl_cred;
gnutls_certificate_set_trust_list(ssl_cred, tlist, 0); /* transfer tlist */
/* (must flip trust lists back and forth b/w DN names and verify CAs) */
if (NULL == hctx->conf.ssl_ca_dn_file)
hctx->conf.pc->trust_inited = 1;
return GNUTLS_E_SUCCESS;
}
static int
mod_gnutls_verify_cb (gnutls_session_t ssl)
{
handler_ctx * const hctx = gnutls_session_get_ptr(ssl);
if (!hctx->conf.ssl_verifyclient) return 0;
if (gnutls_auth_client_get_type(ssl) != GNUTLS_CRD_CERTIFICATE)
return GNUTLS_E_SUCCESS;
int rc;
/* gnutls limitation; wasteful to have to copy into each cred */
/* (would be better to share list with session, instead of with cred) */
if (hctx->conf.ssl_ca_dn_file) {
rc = mod_gnutls_verify_set_tlist(hctx, 0); /* for client cert verify */
if (rc < 0) return rc;
}
/* gnutls_certificate_verify_peers2() includes processing OCSP staping,
* as well as certificate depth verification before getting internal
* flags and calling gnutls_x509_trust_list_verify_crt2()
* advanced reference:
* gnutls lib/cert-sessions.c:_gnutls_x509_cert_verify_peers()
* XXX: if GnuTLS provided a more advanced interface which permitted
* providing trust list, verify depth, and flags, we could avoid copying
* ca chain and crls into each credential, using
* gnutls_x509_trust_list_add_cas()
* gnutls_x509_trust_list_add_crls()
* gnutls_x509_trust_list_verify_crt2()
* See also GnuTLS manual Section 7.3.4 Advanced certificate verification
*/
rc = gnutls_certificate_verify_peers2(ssl, &hctx->verify_status);
if (rc < 0) return rc;
if (hctx->verify_status == 0 && hctx->conf.ssl_ca_dn_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 */
gnutls_x509_crt_t *CA_list =
(gnutls_x509_crt_t *)&hctx->conf.ssl_ca_dn_file->data;
unsigned int len = hctx->conf.ssl_ca_dn_file->size;
unsigned int i;
gnutls_x509_dn_t issuer, subject;
unsigned int crt_size = 0;
const gnutls_datum_t *crts;
gnutls_x509_crt_t crt = NULL;
crts = gnutls_certificate_get_peers(ssl, &crt_size);
if (0 == crt_size
|| gnutls_x509_crt_init(&crt) < 0
|| gnutls_x509_crt_import(crt, &crts[0], GNUTLS_X509_FMT_DER) < 0
|| gnutls_x509_crt_get_subject(crt, &issuer) < 0)
len = 0; /*(trigger failure path below)*/
for (i = 0; i < len; ++i) {
if (gnutls_x509_crt_get_subject(CA_list[i], &subject) >= 0
&& 0 == memcmp(&subject, &issuer, sizeof(issuer)))
break;
}
if (i == len)
hctx->verify_status |= GNUTLS_CERT_SIGNER_NOT_CA;
if (crt) gnutls_x509_crt_deinit(crt);
}
if (hctx->verify_status != 0 && hctx->conf.ssl_verifyclient_enforce) {
/* (not looping on GNUTLS_E_INTERRUPTED or GNUTLS_E_AGAIN
* since we do not want to block here (and not expecting to have to))*/
(void)gnutls_alert_send(ssl, GNUTLS_AL_FATAL, GNUTLS_A_ACCESS_DENIED);
return GNUTLS_E_CERTIFICATE_VERIFICATION_ERROR;
}
return GNUTLS_E_SUCCESS;
}
static int
mod_gnutls_construct_crt_chain (plugin_cert *pc, gnutls_datum_t *d, log_error_st *errh)
{
/* Historically, openssl will use the cert chain in (SSL_CTX *) if a cert
* does not have a chain configured in (SSL *). Attempt to provide
* compatible behavior here. This may be called after startup since
* ssl.pemfile might be defined in a config scope without ssl.ca-file,
* and at runtime is when ssl.ca-file (e.g. from matching $SERVER["socket"])
* would be known along with ssl.pemfile (e.g. from $HTTP["host"]) */
gnutls_certificate_credentials_t ssl_cred;
int rc = gnutls_certificate_allocate_credentials(&ssl_cred);
if (rc < 0) return rc;
unsigned int ncrt = (d ? d->size : 0);
unsigned int off = (d == pc->ssl_pemfile_x509) ? 0 : 1;
gnutls_pcert_st * const pcert_list =
gnutls_malloc(sizeof(gnutls_pcert_st) * (off+ncrt));
if (NULL == pcert_list) {
gnutls_certificate_free_credentials(ssl_cred);
return GNUTLS_E_MEMORY_ERROR;
}
memset(pcert_list, 0, sizeof(gnutls_pcert_st) * (off+ncrt));
rc = 0;
if (off) { /*(add crt to chain if different from d)*/
/*assert(pc->ssl_pemfile_x509->size == 1)*/
gnutls_x509_crt_t *crts =
(gnutls_x509_crt_t *)(void *)pc->ssl_pemfile_x509->data;
rc = gnutls_pcert_import_x509(pcert_list, crts[0], 0);
}
if (0 == rc && ncrt) {
gnutls_x509_crt_t *crts = (gnutls_x509_crt_t *)(void *)d->data;
#if GNUTLS_VERSION_NUMBER < 0x030400
/*(GNUTLS_X509_CRT_LIST_SORT not needed; crts sorted when file read)*/
rc = gnutls_pcert_import_x509_list(pcert_list+off, crts, &ncrt, 0);
#else /* manually import list, but note that sorting is not implemented */
rc = 0;
for (unsigned int i = 0; i < ncrt; ++i) {
rc = gnutls_pcert_import_x509(pcert_list+off+i, crts[i], 0);
if (rc < 0) break;
}
#endif
}
ncrt += off;
if (0 == rc)
rc = gnutls_certificate_set_key(ssl_cred, NULL, 0, pcert_list, ncrt,
pc->ssl_pemfile_pkey);
if (rc < 0) {
for (unsigned int i = 0; i < ncrt; ++i)
gnutls_pcert_deinit(pcert_list+i);
gnutls_free(pcert_list);
gnutls_certificate_free_credentials(ssl_cred);
elog(errh, __FILE__, __LINE__, rc, "gnutls_certificate_set_key()");
return rc;
}
/* XXX: gnutls_certificate_set_key() has an inconsistent implementation.
* On success, key ownership is transferred, and so should not be freed,
* but pcert_list is a shallow memcpy(), so gnutls_pcert_deinit() should
* not be run on gnutls_pcert_st in list, though top-level list storage
* should be freed. On failure, ownership is not transferred for either. */
gnutls_free(pcert_list);
pc->ssl_pemfile_pkey = NULL;
pc->ssl_cred = ssl_cred;
/* release lists used to configure pc->ssl_cred */
mod_gnutls_free_config_crts(pc->ssl_pemfile_x509);
pc->ssl_pemfile_x509 = NULL;
return 0;
}
static void *
network_gnutls_load_pemfile (server *srv, const buffer *pemfile, const buffer *privkey)
{
#if 0 /* see comments in mod_gnutls_construct_crt_chain() above */
gnutls_certificate_credentials_t ssl_cred = NULL;
int rc;
rc = gnutls_certificate_allocate_credentials(&ssl_cred);
if (rc < 0) return NULL;
rc = gnutls_certificate_set_x509_key_file2(ssl_cred,
pemfile->ptr, privkey->ptr,
GNUTLS_X509_FMT_PEM, NULL, 0);
if (rc < 0) {
elogf(srv->errh, __FILE__, __LINE__, rc,
"gnutls_certificate_set_x509_key_file2(%s, %s)",
pemfile->ptr, privkey->ptr);
gnutls_certificate_free_credentials(ssl_cred);
return NULL;
}
plugin_cert *pc = malloc(sizeof(plugin_cert));
force_assert(pc);
pc->ssl_cred = ssl_cred;
pc->trust_inited = 0;
return pc;
#else
gnutls_datum_t *d = mod_gnutls_load_config_crts(pemfile->ptr, srv->errh);
if (NULL == d) return NULL;
if (0 == d->size) {
mod_gnutls_free_config_crts(d);
return NULL;
}
gnutls_privkey_t pkey = mod_gnutls_load_config_pkey(privkey->ptr,srv->errh);
if (NULL == pkey) {
mod_gnutls_free_config_crts(d);
return NULL;
}
plugin_cert *pc = malloc(sizeof(plugin_cert));
force_assert(pc);
pc->ssl_cred = NULL;
pc->trust_inited = 0;
pc->ssl_pemfile_x509 = d;
pc->ssl_pemfile_pkey = pkey;
if (d->size > 1) { /*(certificate chain provided)*/
int rc = mod_gnutls_construct_crt_chain(pc, d, srv->errh);
if (rc < 0) {
mod_gnutls_free_config_crts(d);
gnutls_privkey_deinit(pkey);
free(pc);
return NULL;
}
}
return pc;
#endif
}
#if GNUTLS_VERSION_NUMBER >= 0x030200
static int
mod_gnutls_acme_tls_1 (handler_ctx *hctx)
{
buffer * const b = hctx->tmp_buf;
const buffer * const name = &hctx->r->uri.authority;
log_error_st * const errh = hctx->r->conf.errh;
int rc = GNUTLS_E_INVALID_REQUEST;
/* 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 0; /*(should not happen)*/
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(name, hctx->r->conf.http_parseopts, 443))
return rc;
#endif
buffer_append_string_buffer(b, name);
#if 0
buffer *privkey = buffer_init_buffer(b);
buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
buffer_append_string_len(privkey, CONST_STR_LEN(".key.pem"));
/*(similar to network_gnutls_load_pemfile() but propagates rc)*/
gnutls_certificate_credentials_t ssl_cred = NULL;
rc = gnutls_certificate_allocate_credentials(&ssl_cred);
if (rc < 0) { buffer_free(privkey); return rc; }
rc = gnutls_certificate_set_x509_key_file2(ssl_cred,
b->ptr, privkey->ptr,
GNUTLS_X509_FMT_PEM, NULL, 0);
if (rc < 0) {
elogf(errh, __FILE__, __LINE__, rc,
"failed to load acme-tls/1 cert (%s, %s)",
b->ptr, privkey->ptr);
buffer_free(privkey);
gnutls_certificate_free_credentials(ssl_cred);
return rc;
}
buffer_free(privkey);
#else
/* gnutls_certificate_set_x509_key_file2() does not securely wipe
* sensitive data from memory, so take a few extra steps */
/* similar to network_gnutls_load_pemfile() */
uint32_t len = buffer_string_length(b);
buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
gnutls_datum_t *d = mod_gnutls_load_config_crts(b->ptr, errh);
if (NULL == d) return GNUTLS_E_FILE_ERROR;
if (0 == d->size) {
mod_gnutls_free_config_crts(d);
return GNUTLS_E_FILE_ERROR;
}
buffer_string_set_length(b, len);
buffer_append_string_len(b, CONST_STR_LEN(".key.pem"));
gnutls_privkey_t pkey = mod_gnutls_load_config_pkey(b->ptr, errh);
if (NULL == pkey) {
mod_gnutls_free_config_crts(d);
return GNUTLS_E_FILE_ERROR;
}
plugin_cert pc;
pc.ssl_cred = NULL;
pc.trust_inited = 0;
pc.ssl_pemfile_x509 = d;
pc.ssl_pemfile_pkey = pkey;
rc = mod_gnutls_construct_crt_chain(&pc, d, errh);
if (rc < 0) {
mod_gnutls_free_config_crts(d);
gnutls_privkey_deinit(pkey);
return rc;
}
gnutls_certificate_credentials_t ssl_cred = pc.ssl_cred;
#endif
hctx->acme_tls_1_cred = ssl_cred; /*(save ptr and free later)*/
rc = gnutls_credentials_set(hctx->ssl, GNUTLS_CRD_CERTIFICATE, ssl_cred);
if (rc < 0) {
elogf(hctx->r->conf.errh, __FILE__, __LINE__, rc,
"failed to set acme-tls/1 certificate for TLS server name %s",
hctx->r->uri.authority.ptr);
return rc;
}
return GNUTLS_E_SUCCESS; /* 0 */
}
enum {
MOD_GNUTLS_ALPN_HTTP11 = 1
,MOD_GNUTLS_ALPN_HTTP10 = 2
,MOD_GNUTLS_ALPN_H2 = 3
,MOD_GNUTLS_ALPN_ACME_TLS_1 = 4
};
static int
mod_gnutls_alpn_select_cb (gnutls_session_t ssl, handler_ctx *hctx)
{
const int i = 0;
uint8_t proto;
gnutls_datum_t d = { NULL, 0 };
if (gnutls_alpn_get_selected_protocol(ssl, &d) < 0)
return 0; /* ignore GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE */
const char *in = (const char *)d.data;
const int n = (int)d.size;
switch (n) {
#if 0
case 2: /* "h2" */
if (in[i] == 'h' && in[i+1] == '2') {
proto = MOD_GNUTLS_ALPN_H2;
break;
}
return 0;
#endif
case 8: /* "http/1.1" "http/1.0" */
if (0 == memcmp(in+i, "http/1.", 7)) {
if (in[i+7] == '1') {
proto = MOD_GNUTLS_ALPN_HTTP11;
break;
}
if (in[i+7] == '0') {
proto = MOD_GNUTLS_ALPN_HTTP10;
break;
}
}
return 0;
case 10: /* "acme-tls/1" */
if (0 == memcmp(in+i, "acme-tls/1", 10)) {
int rc = mod_gnutls_acme_tls_1(hctx);
if (0 == rc) {
proto = MOD_GNUTLS_ALPN_ACME_TLS_1;
break;
}
return rc;
}
return 0;
default:
return 0;
}
hctx->alpn = proto;
return 0;
}
#endif /* GNUTLS_VERSION_NUMBER >= 0x030200 */
static int
mod_gnutls_SNI(void *ctx, unsigned int tls_id,
const unsigned char *servername, unsigned int len)
{
if (tls_id != 0) return 0;
/* server name */
/* https://www.gnutls.org/manual/gnutls.html#Virtual-hosts-and-credentials
* figure the advertized name - the following hack relies on the fact that
* this extension only supports DNS names, and due to a protocol bug cannot
* be extended to support anything else. */
if (len < 5) return 0;
len -= 5;
servername += 5;
handler_ctx * const hctx = (handler_ctx *) ctx;
request_st * const r = hctx->r;
buffer_copy_string(&r->uri.scheme, "https");
if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/
log_error(r->conf.errh, __FILE__, __LINE__,
"GnuTLS: SNI name too long %.*s", (int)len, servername);
return GNUTLS_E_INVALID_REQUEST;
}
/* use SNI to patch mod_gnutls config and then reset COMP_HTTP_HOST */
buffer_copy_string_len(&r->uri.authority, (const char *)servername, len);
buffer_to_lower(&r->uri.authority);
#if 0
/*(r->uri.authority used below for configuration before request read;
* revisit for h2)*/
if (0 != http_request_host_policy(&r->uri.authority,
r->conf.http_parseopts, 443))
return GNUTLS_E_INVALID_REQUEST;
#endif
r->conditional_is_valid |= (1 << COMP_HTTP_SCHEME)
| (1 << COMP_HTTP_HOST);
mod_gnutls_patch_config(r, &hctx->conf);
/* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */
/*(done in configfile-glue.c:config_cond_cache_reset() after request hdrs read)*/
/*config_cond_cache_reset_item(r, COMP_HTTP_HOST);*/
/*buffer_clear(&r->uri.authority);*/
return 0;
}
static int
mod_gnutls_client_hello_hook_post(gnutls_session_t ssl)
{
#if GNUTLS_VERSION_NUMBER >= 0x030200
handler_ctx * const hctx = gnutls_session_get_ptr(ssl);
int rc = mod_gnutls_alpn_select_cb(ssl, hctx);
if (rc < 0)
return rc;
/* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/
if (hctx->alpn == MOD_GNUTLS_ALPN_ACME_TLS_1) {
/*(acme-tls/1 is separate from certificate auth access to website)*/
gnutls_certificate_server_set_request(ssl, GNUTLS_CERT_IGNORE);
return GNUTLS_E_SUCCESS; /* 0 */ /*(skip further session config below)*/
}
#endif
return GNUTLS_E_SUCCESS; /* 0 */
}
static int
mod_gnutls_client_hello_hook(gnutls_session_t ssl, unsigned int htype,
unsigned when, unsigned int incoming,