source: mod_gnutls/src/gnutls_hooks.c @ 68b5156

debian/masterproxy-ticket
Last change on this file since 68b5156 was 68b5156, checked in by Fiona Klute <fiona.klute@…>, 22 months ago

Move proxy-only functions from gnutls_hooks.c to a dedicated file

  • Property mode set to 100644
File size: 72.2 KB
RevLine 
[104e881]1/*
[c301152]2 *  Copyright 2004-2005 Paul Querna
[e021722]3 *  Copyright 2008, 2014 Nikos Mavrogiannopoulos
[e183628]4 *  Copyright 2011 Dash Shendy
[765cac2]5 *  Copyright 2013-2014 Daniel Kahn Gillmor
[3c123cd]6 *  Copyright 2015-2018 Fiona Klute
[c301152]7 *
8 *  Licensed under the Apache License, Version 2.0 (the "License");
9 *  you may not use this file except in compliance with the License.
10 *  You may obtain a copy of the License at
11 *
12 *      http://www.apache.org/licenses/LICENSE-2.0
13 *
14 *  Unless required by applicable law or agreed to in writing, software
15 *  distributed under the License is distributed on an "AS IS" BASIS,
16 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 *  See the License for the specific language governing permissions and
18 *  limitations under the License.
19 */
20
21#include "mod_gnutls.h"
[04e6e65]22#include "gnutls_cache.h"
[f52f1b4]23#include "gnutls_config.h"
[94cb972]24#include "gnutls_ocsp.h"
[68b5156]25#include "gnutls_proxy.h"
[7ff6c6c]26#include "gnutls_sni.h"
[235e109]27#include "gnutls_util.h"
[0e3f8c6]28#include "gnutls_watchdog.h"
29
[c301152]30#include "http_vhost.h"
[84cb5b2]31#include "ap_mpm.h"
[3aff94d]32#include <mod_status.h>
[c005645]33#include <util_mutex.h>
[f450ac9]34#include <apr_escape.h>
[4e388b0]35/* This provides strcmp and related functions */
36#define APR_WANT_STRFUNC
37#include <apr_want.h>
[c301152]38
[07889ab]39#ifdef ENABLE_MSVA
40#include <msv/msv.h>
41#endif
[0499540]42
[55dc3f0]43#ifdef APLOG_USE_MODULE
44APLOG_USE_MODULE(gnutls);
45#endif
46
[c301152]47#if MOD_GNUTLS_DEBUG
[7bebb42]48static apr_file_t *debug_log_fp;
[c301152]49#endif
50
[b429e4c]51#define IS_PROXY_STR(c) \
52    ((c->is_proxy == GNUTLS_ENABLED_TRUE) ? "proxy " : "")
53
[104e881]54/** Key to encrypt session tickets. Must be kept secret. This key is
55 * generated in the `pre_config` hook and thus constant across
56 * forks. The problem with this approach is that it does not support
57 * regular key rotation. */
[b8df283]58static gnutls_datum_t session_ticket_key = {NULL, 0};
[84cb5b2]59
[60868d2]60
61
[7bebb42]62static int mgs_cert_verify(request_rec * r, mgs_handle_t * ctxt);
[c0fc11e]63/** use side==0 for server and side==1 for client */
[fd82e59]64static void mgs_add_common_cert_vars(request_rec * r, gnutls_x509_crt_t cert, int side, size_t export_cert_size);
[c0fc11e]65mgs_srvconf_rec* mgs_find_sni_server(mgs_handle_t *ctxt);
[b4739cd]66static int mgs_status_hook(request_rec *r, int flags);
[fd82e59]67#ifdef ENABLE_MSVA
68static const char* mgs_x509_construct_uid(request_rec * pool, gnutls_x509_crt_t cert);
69#endif
[e183628]70
[3b4c0d0]71/* Pool Cleanup Function */
[87d507b]72apr_status_t mgs_cleanup_pre_config(void *data __attribute__((unused)))
73{
74    /* Free session ticket master key */
[ac3f500]75#if GNUTLS_VERSION_NUMBER >= 0x030400
[87d507b]76    gnutls_memset(session_ticket_key.data, 0, session_ticket_key.size);
[ac3f500]77#endif
[e183628]78    gnutls_free(session_ticket_key.data);
79    session_ticket_key.data = NULL;
80    session_ticket_key.size = 0;
[60868d2]81
82    /* Deinit default priority setting */
[0fcba60]83    mgs_default_priority_deinit();
[e183628]84    return APR_SUCCESS;
[c301152]85}
86
[3b4c0d0]87/* Logging Function for Maintainers */
[c301152]88#if MOD_GNUTLS_DEBUG
[e183628]89static void gnutls_debug_log_all(int level, const char *str) {
[9ecd212]90    apr_file_printf(debug_log_fp, "<%d> %s", level, str);
[c301152]91}
[a208cd3]92#define _gnutls_log apr_file_printf
93#else
[e183628]94#define _gnutls_log(...)
[c301152]95#endif
96
[07889ab]97static const char* mgs_readable_cvm(mgs_client_verification_method_e m) {
98    switch(m) {
99    case mgs_cvm_unset:
100        return "unset";
101    case mgs_cvm_cartel:
102        return "cartel";
103    case mgs_cvm_msva:
104        return "msva";
105    }
106    return "unknown";
107}
108
[3b4c0d0]109/* Pre-Configuration HOOK: Runs First */
[fd82e59]110int mgs_hook_pre_config(apr_pool_t * pconf, apr_pool_t * plog, apr_pool_t * ptemp __attribute__((unused))) {
[26b08fd]111
[3b4c0d0]112/* Maintainer Logging */
113#if MOD_GNUTLS_DEBUG
114    apr_file_open(&debug_log_fp, "/tmp/gnutls_debug", APR_APPEND | APR_WRITE | APR_CREATE, APR_OS_DEFAULT, pconf);
[e183628]115    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
116    gnutls_global_set_log_level(9);
117    gnutls_global_set_log_function(gnutls_debug_log_all);
[37f8282]118    _gnutls_log(debug_log_fp, "gnutls: %s\n", gnutls_check_version(NULL));
[671b64f]119#endif
[3b4c0d0]120
[33826c5]121    int ret;
[26b08fd]122
[3b4c0d0]123        /* Check for required GnuTLS Library Version */
[932b68e]124    if (gnutls_check_version(LIBGNUTLS_VERSION) == NULL) {
[cb5188f]125                ap_log_perror(APLOG_MARK, APLOG_EMERG, 0, plog, "gnutls_check_version() failed. Required: "
[9ecd212]126                                        "gnutls-%s Found: gnutls-%s", LIBGNUTLS_VERSION, gnutls_check_version(NULL));
[421ef1c]127        return DONE;
[e183628]128    }
[e02dd8c]129
[3b4c0d0]130        /* Generate a Session Key */
[e183628]131    ret = gnutls_session_ticket_key_generate(&session_ticket_key);
132    if (ret < 0) {
[9ecd212]133                ap_log_perror(APLOG_MARK, APLOG_EMERG, 0, plog, "gnutls_session_ticket_key_generate: %s", gnutls_strerror(ret));
[421ef1c]134                return DONE;
[e183628]135    }
[e5bbda4]136
[60868d2]137    /* Initialize default priority setting */
[0fcba60]138    ret = mgs_default_priority_init();
[60868d2]139    if (ret < 0)
140    {
141        ap_log_perror(APLOG_MARK, APLOG_EMERG, 0, plog,
142                      "gnutls_priority_init failed for default '%s': %s (%d)",
143                      MGS_DEFAULT_PRIORITY, gnutls_strerror(ret), ret);
144        return DONE;
145    }
146
[b4739cd]147    AP_OPTIONAL_HOOK(status_hook, mgs_status_hook, NULL, NULL, APR_HOOK_MIDDLE);
148
[c005645]149    ap_mutex_register(pconf, MGS_CACHE_MUTEX_NAME, NULL, APR_LOCK_DEFAULT, 0);
[d6834e0]150    ap_mutex_register(pconf, MGS_OCSP_MUTEX_NAME, NULL, APR_LOCK_DEFAULT, 0);
[babdb29]151    ap_mutex_register(pconf, MGS_OCSP_CACHE_MUTEX_NAME, NULL,
152                      APR_LOCK_DEFAULT, 0);
[c005645]153
154    /* Register a pool clean-up function */
[421ef1c]155    apr_pool_cleanup_register(pconf, NULL, mgs_cleanup_pre_config, apr_pool_cleanup_null);
[c301152]156
[e183628]157    return OK;
[c301152]158}
159
[9cee2e9]160
161
162/**
163 * Get the list of available protocols for this connection and add it
164 * to the GnuTLS session. Must run before the client hello function.
165 */
166static void prepare_alpn_proposals(mgs_handle_t *ctxt)
167{
168    /* Check if any protocol upgrades are available
169     *
170     * The "report_all" parameter to ap_get_protocol_upgrades() is 0
171     * (report only more preferable protocols) because setting it to 1
172     * doesn't actually report ALL protocols, but only all except the
173     * current one. This way we can at least list the current one as
174     * available by appending it without potentially negotiating a
175     * less preferred protocol. */
176    const apr_array_header_t *pupgrades = NULL;
177    apr_status_t ret =
[4963516]178        ap_get_protocol_upgrades(ctxt->c, NULL, ctxt->sc->s,
[9cee2e9]179                                 /*report_all*/ 0, &pupgrades);
180    if (ret != APR_SUCCESS)
181    {
182        ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, ctxt->c,
183                      "%s: ap_get_protocol_upgrades() failed, "
184                      "cannot configure ALPN!", __func__);
185        return;
186    }
187
188    if (pupgrades == NULL || pupgrades->nelts == 0)
189    {
190        ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, ctxt->c,
191                      "%s: No protocol upgrades available.", __func__);
192        return;
193    }
194
195    ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, ctxt->c,
196                  "%s: Found %d protocol upgrade(s) for ALPN: %s",
197                  __func__, pupgrades->nelts,
198                  apr_array_pstrcat(ctxt->c->pool, pupgrades, ','));
199    gnutls_datum_t *alpn_protos =
200        apr_palloc(ctxt->c->pool,
201                   (pupgrades->nelts + 1) * sizeof(gnutls_datum_t));
202    for (int i = 0; i < pupgrades->nelts; i++)
203    {
204        alpn_protos[i].data = (void *) APR_ARRAY_IDX(pupgrades, i, char *);
205        alpn_protos[i].size =
206            strnlen(APR_ARRAY_IDX(pupgrades, i, char *),
207                    pupgrades->elt_size);
208    }
209
210    /* Add the current (default) protocol at the end of the list */
211    alpn_protos[pupgrades->nelts].data =
212        (void*) apr_pstrdup(ctxt->c->pool, ap_get_protocol(ctxt->c));
213    alpn_protos[pupgrades->nelts].size =
214        strlen((char*) alpn_protos[pupgrades->nelts].data);
215    ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, ctxt->c,
216                  "%s: Adding current protocol %s to ALPN set.",
217                  __func__, alpn_protos[pupgrades->nelts].data);
218
219    gnutls_alpn_set_protocols(ctxt->session,
220                              alpn_protos,
221                              pupgrades->nelts,
222                              GNUTLS_ALPN_SERVER_PRECEDENCE);
223}
224
225
226
227/**
228 * Check if ALPN selected any protocol upgrade, try to switch if so.
229 */
230static int process_alpn_result(mgs_handle_t *ctxt)
231{
232    int ret = 0;
233    gnutls_datum_t alpn_proto;
234    ret = gnutls_alpn_get_selected_protocol(ctxt->session, &alpn_proto);
235    if (ret != GNUTLS_E_SUCCESS)
236    {
237        ap_log_cerror(APLOG_MARK, APLOG_TRACE1, APR_SUCCESS, ctxt->c,
238                      "%s: No ALPN result: %s (%d)",
239                      __func__, gnutls_strerror(ret), ret);
240        return GNUTLS_E_SUCCESS;
241    }
242
243    apr_array_header_t *client_protos =
244        apr_array_make(ctxt->c->pool, 1, sizeof(char *));
245    /* apr_pstrndup to ensure that the protocol is null terminated */
246    APR_ARRAY_PUSH(client_protos, char *) =
247        apr_pstrndup(ctxt->c->pool, (char*) alpn_proto.data, alpn_proto.size);
248    const char *selected =
[4963516]249        ap_select_protocol(ctxt->c, NULL, ctxt->sc->s, client_protos);
[9cee2e9]250
251    /* ap_select_protocol() will return NULL if none of the ALPN
252     * proposals matched. GnuTLS negotiated alpn_proto based on the
253     * list provided by the server, but the vhost might have changed
254     * based on SNI. Apache seems to adjust the proposal list to avoid
255     * such issues though.
256     *
257     * GnuTLS will return a fatal "no_application_protocol" alert as
258     * required by RFC 7301 if the post client hello function returns
259     * GNUTLS_E_NO_APPLICATION_PROTOCOL. */
260    if (!selected)
261    {
262        ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, ctxt->c,
263                      "%s: ap_select_protocol() returned NULL! Please "
264                      "make sure any overlapping vhosts have the same "
265                      "protocols available.",
266                      __func__);
267        return GNUTLS_E_NO_APPLICATION_PROTOCOL;
268    }
269
270    if (strcmp(selected, ap_get_protocol(ctxt->c)) == 0)
271    {
272        ap_log_cerror(APLOG_MARK, APLOG_TRACE1, APR_SUCCESS, ctxt->c,
273                      "%s: Already using protocol '%s', nothing to do.",
274                      __func__, selected);
275        return GNUTLS_E_SUCCESS;
276    }
277
278    ap_log_cerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, ctxt->c,
279                  "%s: Switching protocol to '%s' based on ALPN.",
280                  __func__, selected);
281    apr_status_t status = ap_switch_protocol(ctxt->c, NULL,
[4963516]282                                             ctxt->sc->s,
[9cee2e9]283                                             selected);
284    if (status != APR_SUCCESS)
285    {
286        ap_log_cerror(APLOG_MARK, APLOG_ERR, status, ctxt->c,
287                      "%s: Protocol switch to '%s' failed!",
288                      __func__, selected);
289        return GNUTLS_E_NO_APPLICATION_PROTOCOL;
290    }
291    /* ALPN done! */
292    return GNUTLS_E_SUCCESS;
293}
294
295
296
[017ef2d]297/**
[c0fc11e]298 * (Re-)Load credentials and priorities for the connection. This is
299 * meant to be called after virtual host selection in the pre or post
300 * client hello hook.
[017ef2d]301 */
[c0fc11e]302static int reload_session_credentials(mgs_handle_t *ctxt)
[017ef2d]303{
[9180a60]304    int ret = 0;
[7bebb42]305
[c0fc11e]306    gnutls_certificate_server_set_request(ctxt->session,
307                                          ctxt->sc->client_verify_mode);
[7bebb42]308
[beb14d9]309    /* Set x509 credentials */
[c0fc11e]310    gnutls_credentials_set(ctxt->session,
311                           GNUTLS_CRD_CERTIFICATE, ctxt->sc->certs);
[beb14d9]312    /* Set Anon credentials */
[c0fc11e]313    gnutls_credentials_set(ctxt->session, GNUTLS_CRD_ANON,
314                           ctxt->sc->anon_creds);
[7bebb42]315
[787dab7]316#ifdef ENABLE_SRP
[3b4c0d0]317        /* Set SRP credentials */
318    if (ctxt->sc->srp_tpasswd_conf_file != NULL && ctxt->sc->srp_tpasswd_file != NULL) {
[c0fc11e]319        gnutls_credentials_set(ctxt->session, GNUTLS_CRD_SRP,
320                               ctxt->sc->srp_creds);
[e183628]321    }
[787dab7]322#endif
[7bebb42]323
[469861a]324    /* Enable session tickets */
325    if (session_ticket_key.data != NULL &&
326        ctxt->sc->tickets == GNUTLS_ENABLED_TRUE)
327    {
328        ret = gnutls_session_ticket_enable_server(ctxt->session, &session_ticket_key);
329        if (ret != GNUTLS_E_SUCCESS)
330            ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EGENERAL, ctxt->c,
331                          "gnutls_session_ticket_enable_server failed: %s (%d)",
332                          gnutls_strerror(ret), ret);
333    }
334
[9cee2e9]335    /* Update the priorities - to avoid negotiating a ciphersuite that is not
[e183628]336     * enabled on this virtual server. Note that here we ignore the version
[9cee2e9]337     * negotiation. */
[c0fc11e]338    ret = gnutls_priority_set(ctxt->session, ctxt->sc->priorities);
339
340    return ret;
341}
342
343
344
345/**
[0da10eb]346 * Post client hello hook function for GnuTLS. This function has two
347 * purposes: Firstly, it acts as a fallback for early_sni_hook(), by
348 * parsing SNI and selecting a virtual host based on it if
349 * necessary. Secondly, it calls ALPN processing.
[c0fc11e]350 *
351 * @param session the TLS session
352 *
353 * @return zero or a GnuTLS error code, as required by GnuTLS hook
354 * definition
355 */
[0da10eb]356static int post_client_hello_hook(gnutls_session_t session)
[c0fc11e]357{
358    int ret = 0;
359    mgs_handle_t *ctxt = gnutls_session_get_ptr(session);
360
[64470ce]361    /* If ctxt->sni_name is set at this point the early_sni_hook()
362     * function ran, found an SNI server name, selected a virtual
363     * host, and set up credentials, so we don't need to do that
364     * again. Otherwise try again, to cover GnuTLS versions < 3.6.3
365     * and pick up future extensions to gnutls_server_name_get(). */
366    if (ctxt->sni_name == NULL)
[c0fc11e]367    {
[64470ce]368        /* try to find a virtual host */
369        mgs_srvconf_rec *tsc = mgs_find_sni_server(ctxt);
370        if (tsc != NULL)
371        {
372            /* Found a TLS vhost based on the SNI, configure the
373             * connection context. */
374            ctxt->sc = tsc;
375        }
[c0fc11e]376
[64470ce]377        ap_log_cerror(APLOG_MARK, APLOG_TRACE1, APR_SUCCESS, ctxt->c,
378                      "%s: Loading credentials in post client hello hook",
379                      __func__);
380        reload_session_credentials(ctxt);
381    }
[c0fc11e]382
383    ret = process_alpn_result(ctxt);
384    if (ret != GNUTLS_E_SUCCESS)
385        return ret;
[017ef2d]386
[e183628]387    /* actually it shouldn't fail since we have checked at startup */
[9180a60]388    return ret;
[7bebb42]389}
390
[671b64f]391static int cert_retrieve_fn(gnutls_session_t session,
[259e835]392                            const gnutls_datum_t * req_ca_rdn __attribute__((unused)),
393                            int nreqs __attribute__((unused)),
394                            const gnutls_pk_algorithm_t * pk_algos __attribute__((unused)),
395                            int pk_algos_length __attribute__((unused)),
396                            gnutls_pcert_st **pcerts,
397                            unsigned int *pcert_length,
[031acac]398                            gnutls_privkey_t *privkey)
399{
400    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
[3b4c0d0]401
[031acac]402    mgs_handle_t *ctxt;
[3b4c0d0]403
404    if (session == NULL) {
405                // ERROR INVALID SESSION
406        return -1;
[031acac]407    }
408
[c0dd3ab]409    ctxt = gnutls_transport_get_ptr(session);
410
411    if (gnutls_certificate_type_get(session) == GNUTLS_CRT_X509) {
[3b4c0d0]412                // X509 CERTIFICATE
[031acac]413        *pcerts = ctxt->sc->certs_x509_chain;
414        *pcert_length = ctxt->sc->certs_x509_chain_num;
415        *privkey = ctxt->sc->privkey_x509;
[e183628]416        return 0;
[3b4c0d0]417    } else {
418                // UNKNOWN CERTIFICATE
419            return -1;
420        }
[7bebb42]421}
422
[a2b4ab6]423
424
425#if GNUTLS_VERSION_NUMBER >= 0x030506
426#define HAVE_KNOWN_DH_GROUPS 1
427#endif
428#ifdef HAVE_KNOWN_DH_GROUPS
429/**
430 * Try to estimate a GnuTLS security parameter based on the given
431 * private key. Any errors are logged.
432 *
433 * @param s The `server_rec` to use for logging
434 *
435 * @param key The private key to use
436 *
437 * @return `gnutls_sec_param_t` as returned by
438 * `gnutls_pk_bits_to_sec_param` for the key properties, or
439 * GNUTLS_SEC_PARAM_UNKNOWN in case of error
440 */
441static gnutls_sec_param_t sec_param_from_privkey(server_rec *server,
442                                                 gnutls_privkey_t key)
443{
444    unsigned int bits = 0;
445    int pk_algo = gnutls_privkey_get_pk_algorithm(key, &bits);
446    if (pk_algo < 0)
447    {
448        ap_log_error(APLOG_MARK, APLOG_ERR, APR_EGENERAL, server,
449                     "%s: Could not get private key parameters: %s (%d)",
450                     __func__, gnutls_strerror(pk_algo), pk_algo);
451        return GNUTLS_SEC_PARAM_UNKNOWN;
452    }
453    return gnutls_pk_bits_to_sec_param(pk_algo, bits);
454}
455#else
456/** ffdhe2048 DH group as defined in RFC 7919, Appendix A.1. This is
457 * the default DH group if mod_gnutls is compiled agains a GnuTLS
458 * version that does not provide known DH groups based on security
459 * parameters (before 3.5.6). */
460static const char FFDHE2048_PKCS3[] =
461    "-----BEGIN DH PARAMETERS-----\n"
462    "MIIBDAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n"
463    "+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n"
464    "87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n"
465    "YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n"
466    "7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n"
467    "ssbzSibBsu/6iGtCOGEoXJf//////////wIBAgICAQA=\n"
468    "-----END DH PARAMETERS-----\n";
469const gnutls_datum_t default_dh_params = {
470    (void *) FFDHE2048_PKCS3,
471    sizeof(FFDHE2048_PKCS3)
472};
473#endif
474
475
476
477/**
478 * Configure the default DH groups to use for the given server. When
479 * compiled against GnuTLS version 3.5.6 or newer the known DH group
480 * matching the GnuTLS security parameter estimated from the private
481 * key is used. Otherwise the ffdhe2048 DH group as defined in RFC
482 * 7919, Appendix A.1 is the default.
483 *
484 * @param server the host to configure
485 *
486 * @return `OK` on success, `HTTP_UNAUTHORIZED` otherwise
487 */
488static int set_default_dh_param(server_rec *server)
489{
490    mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
491        ap_get_module_config(server->module_config, &gnutls_module);
492
493#ifdef HAVE_KNOWN_DH_GROUPS
494    gnutls_sec_param_t seclevel = GNUTLS_SEC_PARAM_UNKNOWN;
495    if (sc->privkey_x509)
496    {
497        seclevel = sec_param_from_privkey(server, sc->privkey_x509);
498        ap_log_error(APLOG_MARK, APLOG_TRACE1, APR_SUCCESS, server,
499                     "%s: GnuTLS security param estimated based on "
500                     "private key '%s': %s",
501                     __func__, sc->x509_key_file,
502                     gnutls_sec_param_get_name(seclevel));
503    }
504
505    if (seclevel == GNUTLS_SEC_PARAM_UNKNOWN)
506        seclevel = GNUTLS_SEC_PARAM_MEDIUM;
507    ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, server,
508                 "%s: Setting DH params for security level '%s'.",
509                 __func__, gnutls_sec_param_get_name(seclevel));
510
511    int ret = gnutls_certificate_set_known_dh_params(sc->certs, seclevel);
512    if (ret < 0)
513    {
514        ap_log_error(APLOG_MARK, APLOG_EMERG, APR_EGENERAL, server,
515                     "%s: setting known DH params failed: %s (%d)",
516                     __func__, gnutls_strerror(ret), ret);
517        return HTTP_UNAUTHORIZED;
518    }
519    ret = gnutls_anon_set_server_known_dh_params(sc->anon_creds, seclevel);
520    if (ret < 0)
521    {
522        ap_log_error(APLOG_MARK, APLOG_EMERG, APR_EGENERAL, server,
523                     "%s: setting known DH params failed: %s (%d)",
524                     __func__, gnutls_strerror(ret), ret);
525        return HTTP_UNAUTHORIZED;
526    }
527#else
528    int ret = gnutls_dh_params_init(&sc->dh_params);
529    if (ret < 0)
530    {
531        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, server,
532                     "%s: Failed to initialize DH params structure: "
533                     "%s (%d)", __func__, gnutls_strerror(ret), ret);
534        return HTTP_UNAUTHORIZED;
535    }
536    ret = gnutls_dh_params_import_pkcs3(sc->dh_params, &default_dh_params,
537                                        GNUTLS_X509_FMT_PEM);
538    if (ret < 0)
539    {
540        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, server,
541                     "%s: Failed to import default DH params: %s (%d)",
542                     __func__, gnutls_strerror(ret), ret);
543        return HTTP_UNAUTHORIZED;
544    }
545
546    gnutls_certificate_set_dh_params(sc->certs, sc->dh_params);
547    gnutls_anon_set_server_dh_params(sc->anon_creds, sc->dh_params);
548#endif
549
550    return OK;
551}
552
553
554
[104e881]555/**
556 * Post config hook.
557 *
[64856fd]558 * Must return OK or DECLINED on success, something else on
559 * error. These codes are defined in Apache httpd.h along with the
560 * HTTP status codes, so I'm going to use HTTP error codes both for
561 * fun (and to avoid conflicts).
562 */
563int mgs_hook_post_config(apr_pool_t *pconf,
564                         apr_pool_t *plog __attribute__((unused)),
[eee1432]565                         apr_pool_t *ptemp,
[64856fd]566                         server_rec *base_server)
567{
[e183628]568    int rv;
569    server_rec *s;
570    mgs_srvconf_rec *sc;
571    mgs_srvconf_rec *sc_base;
572    void *data = NULL;
573    const char *userdata_key = "mgs_init";
574
575    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
[3b4c0d0]576
577    apr_pool_userdata_get(&data, userdata_key, base_server->process->pool);
[e183628]578    if (data == NULL) {
[3b4c0d0]579        apr_pool_userdata_set((const void *) 1, userdata_key, apr_pool_cleanup_null, base_server->process->pool);
[e183628]580    }
581
582    s = base_server;
[3b4c0d0]583    sc_base = (mgs_srvconf_rec *) ap_get_module_config(s->module_config, &gnutls_module);
[e183628]584
585
[de1ceab]586    rv = mgs_cache_post_config(pconf, ptemp, s, sc_base);
[c005645]587    if (rv != APR_SUCCESS)
588    {
[e183628]589        ap_log_error(APLOG_MARK, APLOG_STARTUP, rv, s,
[c005645]590                     "Post config for cache failed.");
[64856fd]591        return HTTP_INSUFFICIENT_STORAGE;
[e183628]592    }
593
[d6834e0]594    if (sc_base->ocsp_mutex == NULL)
595    {
596        rv = ap_global_mutex_create(&sc_base->ocsp_mutex, NULL,
597                                    MGS_OCSP_MUTEX_NAME, NULL,
598                                    base_server, pconf, 0);
599        if (rv != APR_SUCCESS)
[4f7edd5]600            return rv;
[d6834e0]601    }
602
[9ca1f21]603    /* If GnuTLSP11Module is set, load the listed PKCS #11
604     * modules. Otherwise system defaults will be used. */
605    if (sc_base->p11_modules != NULL)
[87f1ed2]606    {
[746e993]607        rv = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
608        if (rv < 0)
609        {
[87f1ed2]610            ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
[f21d2a6]611                         "GnuTLS: Initializing PKCS #11 "
[87f1ed2]612                         "failed: %s (%d).",
[f21d2a6]613                         gnutls_strerror(rv), rv);
[746e993]614        }
615        else
616        {
[dff03fa]617            for (int i = 0; i < sc_base->p11_modules->nelts; i++)
[9ca1f21]618            {
619                char *p11_module =
620                    APR_ARRAY_IDX(sc_base->p11_modules, i, char *);
621                rv = gnutls_pkcs11_add_provider(p11_module, NULL);
622                if (rv != GNUTLS_E_SUCCESS)
[15368a4]623                    ap_log_error(APLOG_MARK, APLOG_STARTUP, APR_EGENERAL, s,
[9ca1f21]624                                 "GnuTLS: Loading PKCS #11 provider module %s "
625                                 "failed: %s (%d).",
626                                 p11_module, gnutls_strerror(rv), rv);
[15368a4]627                else
628                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
629                                 "%s: PKCS #11 provider module %s loaded.",
630                                 __func__, p11_module);
[9ca1f21]631            }
[746e993]632        }
[87f1ed2]633    }
634
[0e3f8c6]635    sc_base->singleton_wd =
636        mgs_new_singleton_watchdog(base_server, MGS_SINGLETON_WATCHDOG, pconf);
637
[d6834e0]638    for (s = base_server; s; s = s->next)
639    {
[3b4c0d0]640        sc = (mgs_srvconf_rec *) ap_get_module_config(s->module_config, &gnutls_module);
[d4c1a4e]641        sc->s = s;
[b94aee2]642        sc->cache_enable = sc_base->cache_enable;
[e809fb3]643        sc->cache = sc_base->cache;
[f52f1b4]644        if (sc->cache_timeout == MGS_TIMEOUT_UNSET)
645            sc->cache_timeout = sc_base->cache_timeout;
[babdb29]646        sc->ocsp_cache = sc_base->ocsp_cache;
[040387c]647
[0e3f8c6]648        sc->singleton_wd = sc_base->singleton_wd;
649
[040387c]650        /* defaults for unset values: */
651        if (sc->enabled == GNUTLS_ENABLED_UNSET)
652            sc->enabled = GNUTLS_ENABLED_FALSE;
[7d1ab49]653        if (sc->tickets == GNUTLS_ENABLED_UNSET)
[fdd3bf0]654        {
655            /* GnuTLS 3.6.4 introduced automatic master key rotation */
656            if (gnutls_check_version_numeric(3, 6, 4))
657                sc->tickets = GNUTLS_ENABLED_TRUE;
658            else
659                sc->tickets = GNUTLS_ENABLED_FALSE;
660        }
[2aaf4f5]661        if (sc->export_certificates_size < 0)
662            sc->export_certificates_size = 0;
[efd3cfe]663        if (sc->client_verify_mode == -1)
[040387c]664            sc->client_verify_mode = GNUTLS_CERT_IGNORE;
[efd3cfe]665        if (sc->client_verify_method == mgs_cvm_unset)
[cf2b905]666            sc->client_verify_method = mgs_cvm_cartel;
[cb6476c]667
[bac1a32]668        // TODO: None of the stuff below needs to be done if
669        // sc->enabled == GNUTLS_ENABLED_FALSE, we could just continue
670        // to the next host.
671
672        /* Load certificates and stuff (includes parsing priority) */
673        rv = mgs_load_files(pconf, ptemp, s);
674        if (rv != 0) {
675            ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
676                         "%s: Loading credentials failed!", __func__);
677            return HTTP_NOT_FOUND;
678        }
[fa6d0bb]679
680        sc->ocsp_mutex = sc_base->ocsp_mutex;
[cb6476c]681        /* init OCSP configuration unless explicitly disabled */
682        if (sc->enabled && sc->ocsp_staple != GNUTLS_ENABLED_FALSE)
[fa6d0bb]683        {
[efc43b4]684            const char *err = mgs_ocsp_configure_stapling(pconf, ptemp, s);
685            if (err != NULL)
686            {
[cb6476c]687                /* If OCSP stapling is enabled only by default ignore
688                 * error and disable stapling */
689                if (sc->ocsp_staple == GNUTLS_ENABLED_UNSET)
690                {
691                    ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, s,
692                                 "Cannnot enable OCSP stapling for "
693                                 "host '%s:%d': %s",
694                                 s->server_hostname, s->addrs->host_port, err);
695                    sc->ocsp_staple = GNUTLS_ENABLED_FALSE;
696                }
697                /* If OCSP stapling is explicitly enabled this is a
698                 * critical error. */
699                else
700                {
701                    ap_log_error(APLOG_MARK, APLOG_STARTUP, APR_EINVAL, s,
702                                 "OCSP stapling configuration failed for "
703                                 "host '%s:%d': %s",
704                                 s->server_hostname, s->addrs->host_port, err);
705                    return HTTP_INTERNAL_SERVER_ERROR;
706                }
707            }
708            else
709            {
710                /* Might already be set */
711                sc->ocsp_staple = GNUTLS_ENABLED_TRUE;
712                /* Set up stapling */
713                rv = mgs_ocsp_enable_stapling(pconf, ptemp, s);
714                if (rv != OK && rv != DECLINED)
715                    return rv;
[efc43b4]716            }
[fa6d0bb]717        }
[040387c]718
[e183628]719        /* Check if the priorities have been set */
[33826c5]720        if (sc->priorities == NULL && sc->enabled == GNUTLS_ENABLED_TRUE) {
[60868d2]721            ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
722                         "No GnuTLSPriorities directive for host '%s:%d', "
723                         "using default '%s'.",
724                         s->server_hostname, s->addrs->host_port,
725                         MGS_DEFAULT_PRIORITY);
[0fcba60]726            sc->priorities = mgs_get_default_prio();
[e183628]727        }
728
[a2b4ab6]729        /* Set host DH params from user configuration or defaults */
[410d216]730        if (sc->dh_params != NULL) {
731            gnutls_certificate_set_dh_params(sc->certs, sc->dh_params);
[671b64f]732            gnutls_anon_set_server_dh_params(sc->anon_creds, sc->dh_params);
[a2b4ab6]733        } else {
734            rv = set_default_dh_param(s);
735            if (rv != OK)
736                return rv;
[e183628]737        }
738
[2cde8111]739        /* The call after this comment is a workaround for bug in
740         * gnutls_certificate_set_retrieve_function2 that ignores
741         * supported certificate types. Should be fixed in GnuTLS
742         * 3.3.12.
743         *
744         * Details:
745         * https://lists.gnupg.org/pipermail/gnutls-devel/2015-January/007377.html
746         * Workaround from:
[d04f7da]747         * https://github.com/vanrein/tlspool/commit/4938102d3d1b086491d147e6c8e4e2a02825fc12 */
[2cde8111]748#if GNUTLS_VERSION_NUMBER < 0x030312
749        gnutls_certificate_set_retrieve_function(sc->certs, (void *) exit);
[787dab7]750#endif
[7bebb42]751
[031acac]752        gnutls_certificate_set_retrieve_function2(sc->certs, cert_retrieve_fn);
[7bebb42]753
[2b76a9c]754        if ((sc->certs_x509_chain == NULL || sc->certs_x509_chain_num < 1) &&
[7921dc7]755            sc->enabled == GNUTLS_ENABLED_TRUE) {
[671b64f]756                        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
[031acac]757                                                "GnuTLS: Host '%s:%d' is missing a Certificate File!",
[8273683]758                                                s->server_hostname, s->addrs->host_port);
[64856fd]759            return HTTP_UNAUTHORIZED;
[e183628]760        }
[2b76a9c]761        if (sc->enabled == GNUTLS_ENABLED_TRUE &&
[7921dc7]762            (sc->certs_x509_chain_num > 0 && sc->privkey_x509 == NULL))
[44e8944]763        {
[671b64f]764                        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
[031acac]765                                                "GnuTLS: Host '%s:%d' is missing a Private Key File!",
[8273683]766                                                s->server_hostname, s->addrs->host_port);
[64856fd]767            return HTTP_UNAUTHORIZED;
[e183628]768        }
769
[0de1839]770        if (sc->enabled == GNUTLS_ENABLED_TRUE
[4133f2d]771            && sc->proxy_enabled == GNUTLS_ENABLED_TRUE
[f265001]772            && load_proxy_x509_credentials(pconf, ptemp, s) != APR_SUCCESS)
[0de1839]773        {
[4133f2d]774            ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
775                         "%s: loading proxy credentials for host "
776                         "'%s:%d' failed, exiting!",
[8273683]777                         __func__, s->server_hostname, s->addrs->host_port);
[64856fd]778            return HTTP_PROXY_AUTHENTICATION_REQUIRED;
[0de1839]779        }
[e183628]780    }
781
782
[64856fd]783    ap_add_version_component(pconf, "mod_gnutls/" MOD_GNUTLS_VERSION);
[e183628]784
[4ec9183]785    {
[83eafed]786        const char* libvers = gnutls_check_version(NULL);
787        char* gnutls_version = NULL;
[64856fd]788        if(libvers && (gnutls_version = apr_psprintf(pconf, "GnuTLS/%s", libvers))) {
789            ap_add_version_component(pconf, gnutls_version);
[83eafed]790        } else {
[4ec9183]791            // In case we could not create the above string go for the static version instead
[64856fd]792            ap_add_version_component(pconf, "GnuTLS/" GNUTLS_VERSION "-static");
[4ec9183]793        }
794    }
795
[e183628]796    return OK;
[c301152]797}
798
[c005645]799void mgs_hook_child_init(apr_pool_t *p, server_rec *s)
800{
[e183628]801    apr_status_t rv = APR_SUCCESS;
[c005645]802    mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
803        ap_get_module_config(s->module_config, &gnutls_module);
[e183628]804
805    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
[031acac]806
[c005645]807    /* if we use PKCS #11 reinitialize it */
[031acac]808    if (mgs_pkcs11_reinit(s) < 0) {
809            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s,
810                    "GnuTLS: Failed to reinitialize PKCS #11");
811            exit(-1);
812    }
813
[babdb29]814    if (sc->cache_enable == GNUTLS_ENABLED_TRUE)
815    {
816        rv = mgs_cache_child_init(p, s, sc->cache, MGS_CACHE_MUTEX_NAME);
817        if (rv != APR_SUCCESS)
[e183628]818            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
[babdb29]819                    "Child init for session cache failed!");
820    }
821
[eced11a]822    if (sc->ocsp_cache != NULL)
[babdb29]823    {
824        rv = mgs_cache_child_init(p, s, sc->ocsp_cache,
825                                  MGS_OCSP_CACHE_MUTEX_NAME);
826        if (rv != APR_SUCCESS)
827            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
828                    "Child init for OCSP cache failed!");
[e183628]829    }
[c005645]830
[babdb29]831    /* reinit OCSP request mutex */
[d6834e0]832    const char *lockfile = apr_global_mutex_lockfile(sc->ocsp_mutex);
833    rv = apr_global_mutex_child_init(&sc->ocsp_mutex, lockfile, p);
834    if (rv != APR_SUCCESS)
835        ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
836                     "Failed to reinit mutex '" MGS_OCSP_MUTEX_NAME "'.");
837
[33826c5]838    /* Block SIGPIPE Signals */
[671b64f]839    rv = apr_signal_block(SIGPIPE);
[37f8282]840    if(rv != APR_SUCCESS) {
[33826c5]841        /* error sending output */
[37f8282]842        ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
[671b64f]843                "GnuTLS: Error Blocking SIGPIPE Signal!");
844    }
[c301152]845}
846
[e183628]847const char *mgs_hook_http_scheme(const request_rec * r) {
848    mgs_srvconf_rec *sc;
[c301152]849
[e183628]850    if (r == NULL)
851        return NULL;
[e02dd8c]852
[e183628]853    sc = (mgs_srvconf_rec *) ap_get_module_config(r->
854            server->module_config,
855            &gnutls_module);
[e02dd8c]856
[e183628]857    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
858    if (sc->enabled == GNUTLS_ENABLED_FALSE) {
859        return NULL;
860    }
[e02dd8c]861
[e183628]862    return "https";
[c301152]863}
864
[e183628]865apr_port_t mgs_hook_default_port(const request_rec * r) {
866    mgs_srvconf_rec *sc;
[e02dd8c]867
[e183628]868    if (r == NULL)
869        return 0;
[e02dd8c]870
[e183628]871    sc = (mgs_srvconf_rec *) ap_get_module_config(r->
872            server->module_config,
873            &gnutls_module);
[e02dd8c]874
[e183628]875    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
876    if (sc->enabled == GNUTLS_ENABLED_FALSE) {
877        return 0;
878    }
[c301152]879
[e183628]880    return 443;
[c301152]881}
882
[c0fc11e]883
[c301152]884
[7bebb42]885typedef struct {
[e183628]886    mgs_handle_t *ctxt;
887    mgs_srvconf_rec *sc;
888    const char *sni_name;
[c301152]889} vhost_cb_rec;
890
[14d718f]891/**
892 * Matches the current vhost's ServerAlias directives
893 *
894 * @param x vhost callback record
895 * @param s server record
[104e881]896 * @param tsc mod_gnutls server data for `s`
897 *
[14d718f]898 * @return true if a match, false otherwise
899 *
900 */
[104e881]901int check_server_aliases(vhost_cb_rec *x, server_rec * s, mgs_srvconf_rec *tsc)
902{
[3c6645b]903    apr_array_header_t *names;
904    int rv = 0;
905    char ** name;
906
907    /* Check ServerName First! */
[4e388b0]908    if (strcasecmp(x->sni_name, s->server_hostname) == 0) {
[3c6645b]909        // We have a match, save this server configuration
910        x->sc = tsc;
911        rv = 1;
912        /* Check any ServerAlias directives */
913    } else if(s->names->nelts) {
914        names = s->names;
[4e388b0]915        name = (char **) names->elts;
[3c6645b]916        for (int i = 0; i < names->nelts; ++i)
[dff03fa]917        {
[4e388b0]918            if (!name[i])
919                continue;
920            if (strcasecmp(x->sni_name, name[i]) == 0)
921            {
[3c6645b]922                // We have a match, save this server configuration
923                x->sc = tsc;
924                rv = 1;
925            }
926        }
[f06c148]927        /* ServerAlias directives may contain wildcards, check those last. */
[3c6645b]928    } else if(s->wild_names->nelts) {
929        names = s->wild_names;
[f06c148]930        name = (char **) names->elts;
[3c6645b]931        for (int i = 0; i < names->nelts; ++i)
[dff03fa]932        {
[f06c148]933            if (!name[i])
934                continue;
935            if (ap_strcasecmp_match(x->sni_name, name[i]) == 0)
936            {
[3c6645b]937                x->sc = tsc;
938                rv = 1;
939            }
940        }
941    }
942    return rv;
[14d718f]943}
944
[7511bfa]945static int vhost_cb(void *baton, conn_rec *conn, server_rec * s)
946{
[e183628]947    mgs_srvconf_rec *tsc;
948    vhost_cb_rec *x = baton;
[b1c2b01]949    int ret;
[671b64f]950
[e183628]951    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
952    tsc = (mgs_srvconf_rec *) ap_get_module_config(s->module_config,
953            &gnutls_module);
[7bebb42]954
[adceac0]955    if (tsc->enabled != GNUTLS_ENABLED_TRUE) {
[e183628]956        return 0;
957    }
[671b64f]958
[b1c2b01]959    if (tsc->certs_x509_chain_num > 0) {
[031acac]960        /* this check is there to warn administrator of any missing hostname
961         * in the certificate. */
962        ret = gnutls_x509_crt_check_hostname(tsc->certs_x509_crt_chain[0], s->server_hostname);
[b1c2b01]963        if (0 == ret)
[7511bfa]964            ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, conn,
965                          "GnuTLS: the certificate doesn't match requested "
966                          "hostname '%s'", s->server_hostname);
[b1c2b01]967    } else {
[7511bfa]968        ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, conn,
969                      "GnuTLS: SNI request for '%s' but no X.509 certs "
970                      "available at all",
971                      s->server_hostname);
[b1c2b01]972    }
[3b4c0d0]973        return check_server_aliases(x, s, tsc);
[c301152]974}
975
[98cf33f]976/**
977 * Get SNI data from GnuTLS (if any) and search for a matching virtual
978 * host configuration. This method is called from the post client
979 * hello function.
980 *
[c0fc11e]981 * @param ctxt the mod_gnutls connection handle
[98cf33f]982 *
983 * @return either the matching mod_gnutls server config, or `NULL`
984 */
[c0fc11e]985mgs_srvconf_rec *mgs_find_sni_server(mgs_handle_t *ctxt)
[5342265]986{
[c0fc11e]987    if (ctxt->sni_name == NULL)
[98cf33f]988    {
[c0fc11e]989        const char *sni_name = mgs_server_name_get(ctxt);
990        if (sni_name != NULL)
991            ctxt->sni_name = sni_name;
[79fc46b]992        else
993            return NULL;
[e183628]994    }
[7bebb42]995
[98cf33f]996    ap_log_cerror(APLOG_MARK, APLOG_TRACE1, APR_SUCCESS, ctxt->c,
[017ef2d]997                  "%s: client requested server '%s'.",
[c0fc11e]998                  __func__, ctxt->sni_name);
[017ef2d]999
1000    /* Search for vhosts matching connection parameters and the
1001     * SNI. If a match is found, cbx.sc will contain the mod_gnutls
1002     * server config for the vhost. */
1003    vhost_cb_rec cbx = {
1004        .ctxt = ctxt,
1005        .sc = NULL,
[c0fc11e]1006        .sni_name = ctxt->sni_name
[017ef2d]1007    };
[c0fc11e]1008    int rv = ap_vhost_iterate_given_conn(ctxt->c, vhost_cb, &cbx);
[e183628]1009    if (rv == 1) {
1010        return cbx.sc;
1011    }
1012    return NULL;
[836417f]1013}
1014
[7ff6c6c]1015
1016
1017#ifdef ENABLE_EARLY_SNI
[0da10eb]1018/**
1019 * Pre client hello hook function for GnuTLS that implements early SNI
1020 * processing using `gnutls_ext_raw_parse()` (available since GnuTLS
1021 * 3.6.3). Reading the SNI (if any) before GnuTLS processes the client
1022 * hello allows loading virtual host settings that cannot be changed
1023 * in the post client hello hook, including ALPN proposals (required
1024 * for HTTP/2 support using the `Protocols` directive). In addition to
1025 * ALPN this function configures the server credentials.
1026 *
1027 * The function signature is required by the GnuTLS API.
1028 *
1029 * @param session the current session
1030 * @param htype handshake message type
1031 * @param when hook position relative to GnuTLS processing
1032 * @param incoming true if the message is incoming, for client hello
1033 * that means the hook is running on the server
1034 * @param msg raw message data
1035 *
1036 * @return `GNUTLS_E_SUCCESS` or a GnuTLS error code
1037 */
[7ff6c6c]1038static int early_sni_hook(gnutls_session_t session,
[0da10eb]1039                          unsigned int htype,
1040                          unsigned when,
[7ff6c6c]1041                          unsigned int incoming,
1042                          const gnutls_datum_t *msg)
1043{
1044    if (!incoming)
1045        return 0;
1046
1047    mgs_handle_t *ctxt = (mgs_handle_t *) gnutls_session_get_ptr(session);
[a26d3f6]1048
1049    /* This is a hook for pre client hello ONLY! */
1050    if (htype != GNUTLS_HANDSHAKE_CLIENT_HELLO || when != GNUTLS_HOOK_PRE)
1051    {
1052        ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_EINVAL, ctxt->c,
1053                      "%s called outside pre client hello hook, this "
1054                      "indicates a programming error!",
1055                      __func__);
1056        return GNUTLS_E_SELF_TEST_ERROR;
1057    }
1058
[7ff6c6c]1059    int ret = gnutls_ext_raw_parse(session, mgs_sni_ext_hook, msg,
1060                                   GNUTLS_EXT_RAW_FLAG_TLS_CLIENT_HELLO);
1061    if (ret == 0 && ctxt->sni_name != NULL)
1062        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, ctxt->c,
[64470ce]1063                      "%s found SNI name: '%s'",
[7ff6c6c]1064                      __func__, ctxt->sni_name);
[64470ce]1065
1066    /* try to find a virtual host for that name */
1067    mgs_srvconf_rec *tsc = mgs_find_sni_server(ctxt);
1068    if (tsc != NULL)
1069    {
1070        /* Found a TLS vhost based on the SNI, configure the
1071         * connection context. */
1072        ctxt->sc = tsc;
1073        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, ctxt->c,
1074                      "%s: Selected virtual host %s from early SNI, "
1075                      "connection server is still %s.",
1076                      __func__, ctxt->sc->s->server_hostname,
1077                      ctxt->c->base_server->server_hostname);
1078    }
1079
1080    reload_session_credentials(ctxt);
1081
1082    prepare_alpn_proposals(ctxt);
1083
[7ff6c6c]1084    return ret;
1085}
1086#endif
1087
1088
1089
[2ceb836]1090/**
[b429e4c]1091 * This function is intended as a cleanup handler for connections
[2ceb836]1092 * using GnuTLS. If attached to the connection pool, it ensures that
1093 * session resources are released with the connection pool even if the
1094 * session wasn't terminated properly.
[b429e4c]1095 *
1096 * @param data must point to the mgs_handle_t associated with the
1097 * connection
1098 */
1099static apr_status_t cleanup_gnutls_session(void *data)
1100{
1101    /* nothing to do */
1102    if (data == NULL)
1103        return APR_SUCCESS;
1104
1105    /* check if session needs closing */
1106    mgs_handle_t *ctxt = (mgs_handle_t *) data;
1107    if (ctxt->session != NULL)
1108    {
[2ceb836]1109        ap_log_cerror(APLOG_MARK, APLOG_WARNING, APR_ECONNABORTED, ctxt->c,
1110                      "%s: connection pool cleanup in progress but %sTLS "
1111                      "session hasn't been terminated, trying to close",
1112                      __func__, IS_PROXY_STR(ctxt));
[b429e4c]1113        int ret;
1114        /* Try A Clean Shutdown */
1115        do
1116            ret = gnutls_bye(ctxt->session, GNUTLS_SHUT_WR);
1117        while (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN);
1118        if (ret != GNUTLS_E_SUCCESS)
[2ceb836]1119            ap_log_cerror(APLOG_MARK, APLOG_INFO, APR_EGENERAL, ctxt->c,
[b429e4c]1120                          "%s: error while closing TLS %sconnection: %s (%d)",
1121                          __func__, IS_PROXY_STR(ctxt),
1122                          gnutls_strerror(ret), ret);
1123        else
[2ceb836]1124            ap_log_cerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, ctxt->c,
[b429e4c]1125                          "%s: TLS %sconnection closed.",
1126                          __func__, IS_PROXY_STR(ctxt));
1127        /* De-Initialize Session */
1128        gnutls_deinit(ctxt->session);
1129        ctxt->session = NULL;
1130    }
1131    return APR_SUCCESS;
1132}
1133
[e8acf05]1134static void create_gnutls_handle(conn_rec * c)
1135{
[e183628]1136    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
[e8acf05]1137
1138    /* Get connection specific configuration */
[235e109]1139    mgs_handle_t *ctxt = init_gnutls_ctxt(c);
[e8acf05]1140    ctxt->enabled = GNUTLS_ENABLED_TRUE;
[e183628]1141    ctxt->status = 0;
1142    ctxt->input_rc = APR_SUCCESS;
1143    ctxt->input_bb = apr_brigade_create(c->pool, c->bucket_alloc);
1144    ctxt->input_cbuf.length = 0;
1145    ctxt->output_rc = APR_SUCCESS;
1146    ctxt->output_bb = apr_brigade_create(c->pool, c->bucket_alloc);
1147    ctxt->output_blen = 0;
1148    ctxt->output_length = 0;
[e8acf05]1149
[d0be765]1150    /* Initialize GnuTLS Library */
[beb14d9]1151    int err = 0;
1152    if (ctxt->is_proxy == GNUTLS_ENABLED_TRUE)
1153    {
1154        /* this is an outgoing proxy connection, client mode */
1155        err = gnutls_init(&ctxt->session, GNUTLS_CLIENT);
1156        if (err != GNUTLS_E_SUCCESS)
1157            ap_log_cerror(APLOG_MARK, APLOG_ERR, err, c,
1158                          "gnutls_init for proxy connection failed: %s (%d)",
1159                          gnutls_strerror(err), err);
1160    }
1161    else
1162    {
1163        /* incoming connection, server mode */
1164        err = gnutls_init(&ctxt->session, GNUTLS_SERVER);
[e4b58b6]1165        if (err != GNUTLS_E_SUCCESS)
[beb14d9]1166            ap_log_cerror(APLOG_MARK, APLOG_ERR, err, c,
1167                          "gnutls_init for server side failed: %s (%d)",
1168                          gnutls_strerror(err), err);
[d0be765]1169    }
[e183628]1170
[a2368a4]1171    /* Ensure TLS session resources are released when the connection
1172     * pool is cleared, if the filters haven't done that already. */
1173    apr_pool_pre_cleanup_register(c->pool, ctxt, cleanup_gnutls_session);
1174
[d0be765]1175    /* Set Default Priority */
[0fcba60]1176        err = gnutls_priority_set(ctxt->session, mgs_get_default_prio());
[e4b58b6]1177    if (err != GNUTLS_E_SUCCESS)
[60868d2]1178        ap_log_cerror(APLOG_MARK, APLOG_ERR, err, c,
1179                      "gnutls_priority_set failed!");
[64470ce]1180
[7ff6c6c]1181#ifdef ENABLE_EARLY_SNI
1182    /* Pre-handshake hook, EXPERIMENTAL */
1183    gnutls_handshake_set_hook_function(ctxt->session,
1184                                       GNUTLS_HANDSHAKE_CLIENT_HELLO,
1185                                       GNUTLS_HOOK_PRE, early_sni_hook);
[64470ce]1186#else
1187    prepare_alpn_proposals(ctxt);
[7ff6c6c]1188#endif
[64470ce]1189
1190    /* Post client hello hook (called after GnuTLS has parsed it) */
[e183628]1191    gnutls_handshake_set_post_client_hello_function(ctxt->session,
[0da10eb]1192            post_client_hello_hook);
[beb14d9]1193
[0de1839]1194    /* Set GnuTLS user pointer, so we can access the module session
1195     * context in GnuTLS callbacks */
1196    gnutls_session_set_ptr(ctxt->session, ctxt);
1197
[0da10eb]1198    /* If mod_gnutls is the TLS server, early_sni_hook (or
1199     * post_client_hello_hook, if early SNI is not available) will
1200     * load appropriate credentials during the handshake. However,
[beb14d9]1201     * when handling a proxy backend connection, mod_gnutls acts as
1202     * TLS client and credentials must be loaded here. */
1203    if (ctxt->is_proxy == GNUTLS_ENABLED_TRUE)
1204    {
1205        /* Set anonymous client credentials for proxy connections */
1206        gnutls_credentials_set(ctxt->session, GNUTLS_CRD_ANON,
1207                               ctxt->sc->anon_client_creds);
1208        /* Set x509 credentials */
1209        gnutls_credentials_set(ctxt->session, GNUTLS_CRD_CERTIFICATE,
[0de1839]1210                               ctxt->sc->proxy_x509_creds);
[beb14d9]1211        /* Load priorities from the server configuration */
[f030883]1212        err = gnutls_priority_set(ctxt->session, ctxt->sc->proxy_priorities);
[beb14d9]1213        if (err != GNUTLS_E_SUCCESS)
1214            ap_log_cerror(APLOG_MARK, APLOG_ERR, err, c,
[f030883]1215                          "%s: setting priorities for proxy connection "
1216                          "failed: %s (%d)",
[beb14d9]1217                          __func__, gnutls_strerror(err), err);
1218    }
1219
[d0be765]1220    /* Initialize Session Cache */
[e183628]1221    mgs_cache_session_init(ctxt);
[671b64f]1222
[33826c5]1223    /* Set pull, push & ptr functions */
1224    gnutls_transport_set_pull_function(ctxt->session,
1225            mgs_transport_read);
1226    gnutls_transport_set_push_function(ctxt->session,
1227            mgs_transport_write);
[9ee0464]1228    gnutls_transport_set_ptr(ctxt->session, ctxt);
[33826c5]1229    /* Add IO filters */
[671b64f]1230    ctxt->input_filter = ap_add_input_filter(GNUTLS_INPUT_FILTER_NAME,
1231            ctxt, NULL, c);
1232    ctxt->output_filter = ap_add_output_filter(GNUTLS_OUTPUT_FILTER_NAME,
[33826c5]1233            ctxt, NULL, c);
[e183628]1234}
[e02dd8c]1235
[e8acf05]1236int mgs_hook_pre_connection(conn_rec * c, void *csd __attribute__((unused)))
1237{
[e183628]1238    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
[e02dd8c]1239
[2f10643]1240    if (c->master)
1241    {
1242        ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c,
1243                      "%s declined secondary connection", __func__);
1244        return DECLINED;
1245    }
1246
[e8acf05]1247    mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
1248        ap_get_module_config(c->base_server->module_config, &gnutls_module);
1249    mgs_handle_t *ctxt = (mgs_handle_t *)
1250        ap_get_module_config(c->conn_config, &gnutls_module);
[c301152]1251
[2f10643]1252    if ((sc && (!sc->enabled))
1253        || (ctxt && ctxt->enabled == GNUTLS_ENABLED_FALSE))
[e8acf05]1254    {
1255        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, "%s declined connection",
1256                      __func__);
[e183628]1257        return DECLINED;
1258    }
[ae4a2b0]1259
[33826c5]1260    create_gnutls_handle(c);
[e183628]1261    return OK;
1262}
[e02dd8c]1263
[e7cf823]1264
1265
1266/**
1267 * process_connection hook: Do a zero byte read to trigger the
1268 * handshake. Doesn't change anything for traditional protocols that
1269 * just do reads, but HTTP/2 needs the TLS handshake and ALPN to
1270 * happen before its process_connection hook runs.
1271 */
1272int mgs_hook_process_connection(conn_rec* c)
1273{
1274    mgs_handle_t *ctxt = (mgs_handle_t *)
1275        ap_get_module_config(c->conn_config, &gnutls_module);
1276
1277    if ((ctxt != NULL) && (ctxt->enabled == GNUTLS_ENABLED_TRUE))
1278    {
1279        /* This connection is supposed to use TLS. Give the filters a
1280         * kick with a zero byte read to trigger the handshake. */
1281        apr_bucket_brigade* temp =
1282            apr_brigade_create(c->pool, c->bucket_alloc);
1283        ap_get_brigade(c->input_filters, temp,
1284                       AP_MODE_INIT, APR_BLOCK_READ, 0);
1285        apr_brigade_destroy(temp);
1286    }
1287    return DECLINED;
1288}
1289
1290
1291
[de3fad3]1292/* Post request hook, checks if TLS connection and vhost match */
1293int mgs_req_vhost_check(request_rec *r)
1294{
1295    /* mod_gnutls server record for the request vhost */
1296    mgs_srvconf_rec *r_sc = (mgs_srvconf_rec *)
1297        ap_get_module_config(r->server->module_config, &gnutls_module);
1298    mgs_handle_t *ctxt = get_effective_gnutls_ctxt(r->connection);
1299
1300    /* Nothing to check for non-TLS and outgoing proxy connections */
1301    if (ctxt == NULL || !ctxt->enabled || ctxt->is_proxy)
1302        return DECLINED;
1303
1304    if (ctxt->sc != r_sc)
1305    {
1306        ap_log_cerror(APLOG_MARK, APLOG_ERR, APR_SUCCESS, ctxt->c,
1307                      "%s: Mismatch between handshake and request servers!",
1308                      __func__);
1309        return HTTP_MISDIRECTED_REQUEST;
1310    }
1311
[04753db8]1312    if (!ctxt->sni_name)
1313        return DECLINED;
1314
1315    /* Got an SNI name, so verify it matches. */
1316    ap_log_cerror(APLOG_MARK, APLOG_TRACE1, APR_SUCCESS, ctxt->c,
1317                  "%s: Checking request hostname against SNI name '%s'.",
1318                  __func__, ctxt->sni_name);
1319
1320    if (!r->hostname)
1321    {
1322        ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, r->connection,
1323                      "Client requested '%s' via SNI, but provided "
1324                      "no hostname in HTTP request!", ctxt->sni_name);
1325        return HTTP_MISDIRECTED_REQUEST;
1326    }
1327
1328    if (strcasecmp(r->hostname, ctxt->sni_name) != 0)
1329    {
1330        ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, r->connection,
1331                      "Client requested '%s' via SNI, but '%s' in "
1332                      "the HTTP request!", ctxt->sni_name, r->hostname);
1333        return HTTP_MISDIRECTED_REQUEST;
1334    }
1335
[de3fad3]1336    return DECLINED;
1337}
1338
1339
1340
[e183628]1341int mgs_hook_fixups(request_rec * r) {
1342    unsigned char sbuf[GNUTLS_MAX_SESSION_ID];
1343    const char *tmp;
1344    size_t len;
1345    mgs_handle_t *ctxt;
1346    int rv = OK;
[c301152]1347
[e183628]1348    if (r == NULL)
1349        return DECLINED;
[c301152]1350
[e183628]1351    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
1352    apr_table_t *env = r->subprocess_env;
[7bebb42]1353
[2f10643]1354    ctxt = get_effective_gnutls_ctxt(r->connection);
[c301152]1355
[e8acf05]1356    if (!ctxt || ctxt->enabled != GNUTLS_ENABLED_TRUE || ctxt->session == NULL)
1357    {
1358        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "request declined in %s", __func__);
[e183628]1359        return DECLINED;
1360    }
[c301152]1361
[e183628]1362    apr_table_setn(env, "HTTPS", "on");
1363
1364    apr_table_setn(env, "SSL_VERSION_LIBRARY",
1365            "GnuTLS/" LIBGNUTLS_VERSION);
1366    apr_table_setn(env, "SSL_VERSION_INTERFACE",
1367            "mod_gnutls/" MOD_GNUTLS_VERSION);
1368
1369    apr_table_setn(env, "SSL_PROTOCOL",
[9720026]1370            gnutls_protocol_get_name(gnutls_protocol_get_version(ctxt->session)));
[e183628]1371
1372    /* should have been called SSL_CIPHERSUITE instead */
1373    apr_table_setn(env, "SSL_CIPHER",
[9720026]1374            gnutls_cipher_suite_get_name(gnutls_kx_get(ctxt->session),
1375                                         gnutls_cipher_get(ctxt->session),
1376                                         gnutls_mac_get(ctxt->session)));
[e183628]1377
[72377cf]1378#if GNUTLS_VERSION_NUMBER >= 0x030600
1379    /* Compression support has been removed since GnuTLS 3.6.0 */
1380    apr_table_setn(env, "SSL_COMPRESS_METHOD", "NULL");
1381#else
[e183628]1382    apr_table_setn(env, "SSL_COMPRESS_METHOD",
[9720026]1383            gnutls_compression_get_name(gnutls_compression_get(ctxt->session)));
[72377cf]1384#endif
[7bebb42]1385
[787dab7]1386#ifdef ENABLE_SRP
[369f47a]1387    if (ctxt->sc->srp_tpasswd_conf_file != NULL && ctxt->sc->srp_tpasswd_file != NULL) {
1388        tmp = gnutls_srp_server_get_username(ctxt->session);
1389        apr_table_setn(env, "SSL_SRP_USER", (tmp != NULL) ? tmp : "");
1390    } else {
1391        apr_table_unset(env, "SSL_SRP_USER");
1392    }
[787dab7]1393#endif
[c301152]1394
[e183628]1395    if (apr_table_get(env, "SSL_CLIENT_VERIFY") == NULL)
1396        apr_table_setn(env, "SSL_CLIENT_VERIFY", "NONE");
[c301152]1397
[9720026]1398    unsigned int key_size = 8 * gnutls_cipher_get_key_size(gnutls_cipher_get(ctxt->session));
[e183628]1399    tmp = apr_psprintf(r->pool, "%u", key_size);
[c301152]1400
[e183628]1401    apr_table_setn(env, "SSL_CIPHER_USEKEYSIZE", tmp);
[c301152]1402
[e183628]1403    apr_table_setn(env, "SSL_CIPHER_ALGKEYSIZE", tmp);
[c301152]1404
[e183628]1405    apr_table_setn(env, "SSL_CIPHER_EXPORT",
1406            (key_size <= 40) ? "true" : "false");
[7bebb42]1407
[5674676]1408    int dhsize = gnutls_dh_get_prime_bits(ctxt->session);
1409    if (dhsize > 0) {
1410        tmp = apr_psprintf(r->pool, "%d", dhsize);
1411        apr_table_setn(env, "SSL_DH_PRIME_BITS", tmp);
1412    }
1413
[e183628]1414    len = sizeof (sbuf);
1415    gnutls_session_get_id(ctxt->session, sbuf, &len);
[f450ac9]1416    apr_table_setn(env, "SSL_SESSION_ID",
1417                   apr_pescape_hex(r->pool, sbuf, len, 0));
[7ba803b]1418
[3b4c0d0]1419    if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_X509) {
[7921dc7]1420        mgs_add_common_cert_vars(r, ctxt->sc->certs_x509_crt_chain[0], 0,
1421                                 ctxt->sc->export_certificates_size);
[031acac]1422    }
[7bebb42]1423
[e183628]1424    return rv;
[c301152]1425}
1426
[e183628]1427int mgs_hook_authz(request_rec * r) {
1428    int rv;
1429    mgs_handle_t *ctxt;
1430    mgs_dirconf_rec *dc;
1431
1432    if (r == NULL)
1433        return DECLINED;
1434
1435    dc = ap_get_module_config(r->per_dir_config, &gnutls_module);
1436
1437    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
[2f10643]1438    ctxt = get_effective_gnutls_ctxt(r->connection);
[e183628]1439
1440    if (!ctxt || ctxt->session == NULL) {
1441        return DECLINED;
1442    }
1443
1444    if (dc->client_verify_mode == GNUTLS_CERT_IGNORE) {
1445        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1446                "GnuTLS: Directory set to Ignore Client Certificate!");
1447    } else {
1448        if (ctxt->sc->client_verify_mode < dc->client_verify_mode) {
1449            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1450                    "GnuTLS: Attempting to rehandshake with peer. %d %d",
1451                    ctxt->sc->client_verify_mode,
1452                    dc->client_verify_mode);
1453
1454            /* If we already have a client certificate, there's no point in
1455             * re-handshaking... */
1456            rv = mgs_cert_verify(r, ctxt);
1457            if (rv != DECLINED && rv != HTTP_FORBIDDEN)
1458                return rv;
1459
1460            gnutls_certificate_server_set_request
1461                    (ctxt->session, dc->client_verify_mode);
1462
1463            if (mgs_rehandshake(ctxt) != 0) {
1464                return HTTP_FORBIDDEN;
1465            }
1466        } else if (ctxt->sc->client_verify_mode ==
1467                GNUTLS_CERT_IGNORE) {
[c301152]1468#if MOD_GNUTLS_DEBUG
[e183628]1469            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1470                    "GnuTLS: Peer is set to IGNORE");
[c301152]1471#endif
[e183628]1472            return DECLINED;
1473        }
1474        rv = mgs_cert_verify(r, ctxt);
[5a8a32b]1475        if (rv != DECLINED
1476            && (rv != HTTP_FORBIDDEN
1477                || dc->client_verify_mode == GNUTLS_CERT_REQUIRE
1478                || (dc->client_verify_mode == -1
1479                    && ctxt->sc->client_verify_mode == GNUTLS_CERT_REQUIRE)))
1480        {
[e183628]1481            return rv;
1482        }
1483    }
1484
1485    return DECLINED;
[7bebb42]1486}
1487
1488/* variables that are not sent by default:
1489 *
1490 * SSL_CLIENT_CERT      string  PEM-encoded client certificate
1491 * SSL_SERVER_CERT      string  PEM-encoded client certificate
1492 */
[836c2f9]1493
[7d1ab49]1494/* @param side is either 0 for SERVER or 1 for CLIENT
[671b64f]1495 *
[2aaf4f5]1496 * @param export_cert_size (int) maximum size for environment variable
1497 * to use for the PEM-encoded certificate (0 means do not export)
[7bebb42]1498 */
[765cac2]1499#define MGS_SIDE(suffix) ((side==0) ? "SSL_SERVER" suffix : "SSL_CLIENT" suffix)
[e183628]1500
[fd82e59]1501static void mgs_add_common_cert_vars(request_rec * r, gnutls_x509_crt_t cert, int side, size_t export_cert_size) {
[e183628]1502    unsigned char sbuf[64]; /* buffer to hold serials */
1503    char buf[AP_IOBUFSIZE];
1504    const char *tmp;
1505    char *tmp2;
1506    size_t len;
[dff03fa]1507    int ret;
[e183628]1508
1509    if (r == NULL)
1510        return;
1511
1512    apr_table_t *env = r->subprocess_env;
1513
1514    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
[2aaf4f5]1515    if (export_cert_size > 0) {
1516        len = 0;
1517        ret = gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_PEM, NULL, &len);
1518        if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
1519            if (len >= export_cert_size) {
[765cac2]1520                apr_table_setn(env, MGS_SIDE("_CERT"), "GNUTLS_CERTIFICATE_SIZE_LIMIT_EXCEEDED");
[2aaf4f5]1521                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1522                              "GnuTLS: Failed to export too-large X.509 certificate to environment");
1523            } else {
1524                char* cert_buf = apr_palloc(r->pool, len + 1);
1525                if (cert_buf != NULL && gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_PEM, cert_buf, &len) >= 0) {
1526                    cert_buf[len] = 0;
[765cac2]1527                    apr_table_setn(env, MGS_SIDE("_CERT"), cert_buf);
[2aaf4f5]1528                } else {
1529                    ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1530                                  "GnuTLS: failed to export X.509 certificate");
1531                }
1532            }
1533        } else {
1534            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1535                          "GnuTLS: dazed and confused about X.509 certificate size");
1536        }
[7d1ab49]1537    }
[671b64f]1538
[e183628]1539    len = sizeof (buf);
1540    gnutls_x509_crt_get_dn(cert, buf, &len);
[765cac2]1541    apr_table_setn(env, MGS_SIDE("_S_DN"), apr_pstrmemdup(r->pool, buf, len));
[e183628]1542
1543    len = sizeof (buf);
1544    gnutls_x509_crt_get_issuer_dn(cert, buf, &len);
[765cac2]1545    apr_table_setn(env, MGS_SIDE("_I_DN"), apr_pstrmemdup(r->pool, buf, len));
[e183628]1546
1547    len = sizeof (sbuf);
1548    gnutls_x509_crt_get_serial(cert, sbuf, &len);
[f450ac9]1549    apr_table_setn(env, MGS_SIDE("_M_SERIAL"),
1550                   apr_pescape_hex(r->pool, sbuf, len, 0));
[e183628]1551
1552    ret = gnutls_x509_crt_get_version(cert);
1553    if (ret > 0)
[765cac2]1554        apr_table_setn(env, MGS_SIDE("_M_VERSION"),
1555                       apr_psprintf(r->pool, "%u", ret));
[e183628]1556
[765cac2]1557    apr_table_setn(env, MGS_SIDE("_CERT_TYPE"), "X.509");
[e183628]1558
1559    tmp =
1560            mgs_time2sz(gnutls_x509_crt_get_expiration_time
1561            (cert), buf, sizeof (buf));
[765cac2]1562    apr_table_setn(env, MGS_SIDE("_V_END"), apr_pstrdup(r->pool, tmp));
[e183628]1563
1564    tmp =
1565            mgs_time2sz(gnutls_x509_crt_get_activation_time
1566            (cert), buf, sizeof (buf));
[765cac2]1567    apr_table_setn(env, MGS_SIDE("_V_START"), apr_pstrdup(r->pool, tmp));
[e183628]1568
1569    ret = gnutls_x509_crt_get_signature_algorithm(cert);
1570    if (ret >= 0) {
[765cac2]1571        apr_table_setn(env, MGS_SIDE("_A_SIG"),
[e183628]1572                gnutls_sign_algorithm_get_name(ret));
1573    }
1574
1575    ret = gnutls_x509_crt_get_pk_algorithm(cert, NULL);
1576    if (ret >= 0) {
[765cac2]1577        apr_table_setn(env, MGS_SIDE("_A_KEY"),
[e183628]1578                gnutls_pk_algorithm_get_name(ret));
1579    }
1580
1581    /* export all the alternative names (DNS, RFC822 and URI) */
[dff03fa]1582    for (int i = 0; !(ret < 0); i++)
1583    {
[765cac2]1584        const char *san, *sanlabel;
[e183628]1585        len = 0;
1586        ret = gnutls_x509_crt_get_subject_alt_name(cert, i,
1587                NULL, &len,
1588                NULL);
1589
1590        if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER && len > 1) {
1591            tmp2 = apr_palloc(r->pool, len + 1);
1592
1593            ret =
1594                    gnutls_x509_crt_get_subject_alt_name(cert, i,
1595                    tmp2,
1596                    &len,
1597                    NULL);
1598            tmp2[len] = 0;
1599
[765cac2]1600            sanlabel = apr_psprintf(r->pool, "%s%u", MGS_SIDE("_S_AN"), i);
[e183628]1601            if (ret == GNUTLS_SAN_DNSNAME) {
[765cac2]1602                san = apr_psprintf(r->pool, "DNSNAME:%s", tmp2);
[e183628]1603            } else if (ret == GNUTLS_SAN_RFC822NAME) {
[765cac2]1604                san = apr_psprintf(r->pool, "RFC822NAME:%s", tmp2);
[e183628]1605            } else if (ret == GNUTLS_SAN_URI) {
[765cac2]1606                san = apr_psprintf(r->pool, "URI:%s", tmp2);
[e183628]1607            } else {
[765cac2]1608                san = "UNSUPPORTED";
[e183628]1609            }
[765cac2]1610            apr_table_setn(env, sanlabel, san);
[e183628]1611        }
1612    }
[e5bbda4]1613}
[7bebb42]1614
[7d1ab49]1615
[e5bbda4]1616
[2b3a248b]1617/* TODO: Allow client sending a X.509 certificate chain */
[e183628]1618static int mgs_cert_verify(request_rec * r, mgs_handle_t * ctxt) {
1619    const gnutls_datum_t *cert_list;
[99f8375]1620    unsigned int cert_list_size;
1621    /* assume the certificate is invalid unless explicitly set
1622     * otherwise */
1623    unsigned int status = GNUTLS_CERT_INVALID;
[e183628]1624    int rv = GNUTLS_E_NO_CERTIFICATE_FOUND, ret;
1625    unsigned int ch_size = 0;
1626
[7921dc7]1627    // TODO: union no longer needed here after removing its "pgp" component.
[e183628]1628    union {
1629        gnutls_x509_crt_t x509[MAX_CHAIN_SIZE];
1630    } cert;
1631    apr_time_t expiration_time, cur_time;
1632
1633    if (r == NULL || ctxt == NULL || ctxt->session == NULL)
1634        return HTTP_FORBIDDEN;
1635
1636    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
1637    cert_list =
1638            gnutls_certificate_get_peers(ctxt->session, &cert_list_size);
1639
1640    if (cert_list == NULL || cert_list_size == 0) {
1641        /* It is perfectly OK for a client not to send a certificate if on REQUEST mode
1642         */
1643        if (ctxt->sc->client_verify_mode == GNUTLS_CERT_REQUEST)
1644            return OK;
1645
1646        /* no certificate provided by the client, but one was required. */
1647        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1648                "GnuTLS: Failed to Verify Peer: "
1649                "Client did not submit a certificate");
1650        return HTTP_FORBIDDEN;
1651    }
1652
1653    if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_X509) {
1654        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1655                "GnuTLS: A Chain of %d certificate(s) was provided for validation",
1656                cert_list_size);
1657
1658        for (ch_size = 0; ch_size < cert_list_size; ch_size++) {
1659            gnutls_x509_crt_init(&cert.x509[ch_size]);
1660            rv = gnutls_x509_crt_import(cert.x509[ch_size],
1661                    &cert_list[ch_size],
1662                    GNUTLS_X509_FMT_DER);
1663            // When failure to import, leave the loop
1664            if (rv != GNUTLS_E_SUCCESS) {
1665                if (ch_size < 1) {
1666                    ap_log_rerror(APLOG_MARK,
1667                            APLOG_INFO, 0, r,
1668                            "GnuTLS: Failed to Verify Peer: "
1669                            "Failed to import peer certificates.");
1670                    ret = HTTP_FORBIDDEN;
1671                    goto exit;
1672                }
1673                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1674                        "GnuTLS: Failed to import some peer certificates. Using %d certificates",
1675                        ch_size);
1676                rv = GNUTLS_E_SUCCESS;
1677                break;
1678            }
1679        }
1680    } else
1681        return HTTP_FORBIDDEN;
1682
1683    if (rv < 0) {
1684        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1685                "GnuTLS: Failed to Verify Peer: "
1686                "Failed to import peer certificates.");
1687        ret = HTTP_FORBIDDEN;
1688        goto exit;
1689    }
1690
1691    if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_X509) {
1692        apr_time_ansi_put(&expiration_time,
1693                gnutls_x509_crt_get_expiration_time
1694                (cert.x509[0]));
1695
1696        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
[5c0d491]1697                      "GnuTLS: Verifying list of %d certificate(s) via method '%s'",
1698                      ch_size, mgs_readable_cvm(ctxt->sc->client_verify_method));
1699        switch(ctxt->sc->client_verify_method) {
1700        case mgs_cvm_cartel:
1701            rv = gnutls_x509_crt_list_verify(cert.x509, ch_size,
1702                                             ctxt->sc->ca_list,
1703                                             ctxt->sc->ca_list_size,
1704                                             NULL, 0, 0, &status);
1705            break;
1706#ifdef ENABLE_MSVA
1707        case mgs_cvm_msva:
1708        {
[a01f8ab]1709            struct msv_response* resp = NULL;
1710            struct msv_query q = { .context="https", .peertype="client", .pkctype="x509pem" };
1711            msv_ctxt_t ctx = msv_ctxt_init(NULL);
[5c0d491]1712            char cert_pem_buf[10 * 1024];
1713            size_t len = sizeof (cert_pem_buf);
1714
1715            rv = 0;
1716            if (gnutls_x509_crt_export(cert.x509[0], GNUTLS_X509_FMT_PEM, cert_pem_buf, &len) >= 0) {
1717                /* FIXME : put together a name from the cert we received, instead of hard-coding this value: */
[a01f8ab]1718                q.peername = mgs_x509_construct_uid(r, cert.x509[0]);
1719                q.pkcdata = cert_pem_buf;
1720                rv = msv_query_agent(ctx, q, &resp);
[5c0d491]1721                if (rv == LIBMSV_ERROR_SUCCESS) {
1722                    status = 0;
1723                } else if (rv == LIBMSV_ERROR_INVALID) {
1724                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
[a01f8ab]1725                                  "GnuTLS: Monkeysphere validation failed: (message: %s)", resp->message);
[5c0d491]1726                    status = GNUTLS_CERT_INVALID;
1727                } else {
1728                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
[a01f8ab]1729                                  "GnuTLS: Error communicating with the Monkeysphere Validation Agent: (%d) %s", rv, msv_strerror(ctx, rv));
[5c0d491]1730                    status = GNUTLS_CERT_INVALID;
1731                    rv = -1;
[671b64f]1732                }
[5c0d491]1733            } else {
1734                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1735                              "GnuTLS: Could not convert the client certificate to PEM format");
1736                status = GNUTLS_CERT_INVALID;
1737                rv = GNUTLS_E_ASN1_ELEMENT_NOT_FOUND;
1738            }
[a01f8ab]1739            msv_response_destroy(resp);
1740            msv_ctxt_destroy(ctx);
[5c0d491]1741        }
1742            break;
1743#endif
1744        default:
[99f8375]1745            /* If this block is reached, that indicates a
1746             * configuration error or bug in mod_gnutls (invalid value
1747             * of ctxt->sc->client_verify_method). */
[5c0d491]1748            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1749                          "GnuTLS: Failed to Verify X.509 Peer: method '%s' is not supported",
1750                          mgs_readable_cvm(ctxt->sc->client_verify_method));
[99f8375]1751            rv = GNUTLS_E_UNIMPLEMENTED_FEATURE;
[5c0d491]1752        }
[671b64f]1753
[e183628]1754    } else {
[7921dc7]1755        /* Unknown certificate type */
1756        rv = GNUTLS_E_UNIMPLEMENTED_FEATURE;
[e183628]1757    }
1758
[99f8375]1759    /* "goto exit" at the end of this block skips evaluation of the
1760     * "status" variable */
[e183628]1761    if (rv < 0) {
1762        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1763                "GnuTLS: Failed to Verify Peer certificate: (%d) %s",
1764                rv, gnutls_strerror(rv));
1765        if (rv == GNUTLS_E_NO_CERTIFICATE_FOUND)
1766            ap_log_rerror(APLOG_MARK, APLOG_EMERG, 0, r,
[7921dc7]1767                "GnuTLS: No certificate was found for verification. Did you set the GnuTLSClientCAFile directive?");
[e183628]1768        ret = HTTP_FORBIDDEN;
1769        goto exit;
1770    }
1771
1772    /* TODO: X509 CRL Verification. */
1773    /* May add later if anyone needs it.
1774     */
1775    /* ret = gnutls_x509_crt_check_revocation(crt, crl_list, crl_list_size); */
1776
1777    cur_time = apr_time_now();
1778
1779    if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) {
1780        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1781                "GnuTLS: Could not find Signer for Peer Certificate");
1782    }
1783
1784    if (status & GNUTLS_CERT_SIGNER_NOT_CA) {
1785        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1786                "GnuTLS: Peer's Certificate signer is not a CA");
1787    }
1788
1789    if (status & GNUTLS_CERT_INSECURE_ALGORITHM) {
1790        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1791                "GnuTLS: Peer's Certificate is using insecure algorithms");
1792    }
1793
1794    if (status & GNUTLS_CERT_EXPIRED
1795            || status & GNUTLS_CERT_NOT_ACTIVATED) {
1796        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1797                "GnuTLS: Peer's Certificate signer is expired or not yet activated");
1798    }
1799
1800    if (status & GNUTLS_CERT_INVALID) {
1801        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1802                "GnuTLS: Peer Certificate is invalid.");
1803    } else if (status & GNUTLS_CERT_REVOKED) {
1804        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1805                "GnuTLS: Peer Certificate is revoked.");
1806    }
1807
[7921dc7]1808    mgs_add_common_cert_vars(r, cert.x509[0], 1, ctxt->sc->export_certificates_size);
[e183628]1809
1810    {
1811        /* days remaining */
1812        unsigned long remain =
1813                (apr_time_sec(expiration_time) -
1814                apr_time_sec(cur_time)) / 86400;
1815        apr_table_setn(r->subprocess_env, "SSL_CLIENT_V_REMAIN",
1816                apr_psprintf(r->pool, "%lu", remain));
1817    }
1818
1819    if (status == 0) {
1820        apr_table_setn(r->subprocess_env, "SSL_CLIENT_VERIFY",
1821                "SUCCESS");
1822        ret = OK;
1823    } else {
1824        apr_table_setn(r->subprocess_env, "SSL_CLIENT_VERIFY",
1825                "FAILED");
1826        if (ctxt->sc->client_verify_mode == GNUTLS_CERT_REQUEST)
1827            ret = OK;
1828        else
1829            ret = HTTP_FORBIDDEN;
1830    }
1831
1832exit:
[dff03fa]1833    if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_X509)
1834        for (unsigned int i = 0; i < ch_size; i++)
[e183628]1835            gnutls_x509_crt_deinit(cert.x509[i]);
[7921dc7]1836
[e183628]1837    return ret;
[dff03fa]1838}
[7bebb42]1839
1840
[832182b]1841
[fd82e59]1842#ifdef ENABLE_MSVA
1843/* this section of code is used only when trying to talk to the MSVA */
[832182b]1844static const char* mgs_x509_leaf_oid_from_dn(apr_pool_t *pool, const char* oid, gnutls_x509_crt_t cert) {
1845    int rv=GNUTLS_E_SUCCESS, i;
1846    size_t sz=0, lastsz=0;
1847    char* data=NULL;
1848
1849    i = -1;
1850    while(rv != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
1851        i++;
1852        lastsz=sz;
1853        sz=0;
1854        rv = gnutls_x509_crt_get_dn_by_oid (cert, oid, i, 0, NULL, &sz);
1855    }
1856    if (i > 0) {
1857        data = apr_palloc(pool, lastsz);
1858        sz=lastsz;
1859        rv = gnutls_x509_crt_get_dn_by_oid (cert, oid, i-1, 0, data, &sz);
1860        if (rv == GNUTLS_E_SUCCESS)
1861            return data;
1862    }
1863    return NULL;
1864}
1865
1866static const char* mgs_x509_first_type_from_san(apr_pool_t *pool, gnutls_x509_subject_alt_name_t target, gnutls_x509_crt_t cert) {
1867    int rv=GNUTLS_E_SUCCESS;
1868    size_t sz;
1869    char* data=NULL;
1870    unsigned int i;
1871    gnutls_x509_subject_alt_name_t thistype;
1872
1873    i = 0;
1874    while(rv != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
1875        sz = 0;
1876        rv = gnutls_x509_crt_get_subject_alt_name2(cert, i, NULL, &sz, &thistype, NULL);
1877        if (rv == GNUTLS_E_SHORT_MEMORY_BUFFER && thistype == target) {
1878            data = apr_palloc(pool, sz);
1879            rv = gnutls_x509_crt_get_subject_alt_name2(cert, i, data, &sz, &thistype, NULL);
[fd82e59]1880            if (rv >=0 && (thistype == target))
[832182b]1881                return data;
1882        }
1883        i++;
1884    }
1885    return NULL;
1886}
1887
[fd82e59]1888
[832182b]1889/* Create a string representing a candidate User ID from an X.509
1890 * certificate
1891
1892 * We need this for client certification because a client gives us a
1893 * certificate, but doesn't tell us (in any other way) who they are
1894 * trying to authenticate as.
1895
1896 * one complaint might be "but the user wanted to be another identity,
1897 * which is also in the certificate (e.g. in a SubjectAltName)"
1898 * However, given that any user can regenerate their own X.509
1899 * certificate with their own public key content, they should just do
1900 * so, and not expect us to guess at their identity :)
1901
1902 * This function allocates it's response from the pool given it.  When
1903 * that pool is reclaimed, the response will also be deallocated.
1904
1905 * FIXME: what about extracting a server-style cert
1906 *        (e.g. https://imposter.example) from the DN or any sAN?
1907
1908 * FIXME: what if we want to call this outside the context of a
1909 *        request?  That complicates the logging.
1910 */
1911static const char* mgs_x509_construct_uid(request_rec *r, gnutls_x509_crt_t cert) {
1912    /* basic strategy, assuming humans are the users: we are going to
1913     * try to reconstruct a "conventional" User ID by pulling in a
1914     * name, comment, and e-mail address.
1915     */
1916    apr_pool_t *pool = r->pool;
1917    const char *name=NULL, *comment=NULL, *email=NULL;
1918    const char *ret=NULL;
1919    /* subpool for temporary allocation: */
1920    apr_pool_t *sp=NULL;
1921
[671b64f]1922    if (APR_SUCCESS != apr_pool_create(&sp, pool))
[832182b]1923        return NULL; /* i'm assuming that libapr would log this kind
1924                      * of error on its own */
1925
1926     /* Name
[671b64f]1927
[832182b]1928     the name comes from the leaf commonName of the cert's Subject.
[671b64f]1929
[832182b]1930     (MAYBE: should we look at trying to assemble a candidate from
1931             givenName, surName, suffix, etc?  the "name" field
1932             appears to be case-insensitive, which seems problematic
1933             from what we expect; see:
1934             http://www.itu.int/rec/T-REC-X.520-200102-s/e )
1935
1936     (MAYBE: should we try pulling a commonName or otherName or
1937             something from subjectAltName? see:
1938             https://tools.ietf.org/html/rfc5280#section-4.2.1.6
1939             GnuTLS does not support looking for Common Names in the
1940             SAN yet)
1941     */
1942    name = mgs_x509_leaf_oid_from_dn(sp, GNUTLS_OID_X520_COMMON_NAME, cert);
1943
1944    /* Comment
1945
1946       I am inclined to punt on this for now, as Comment has been so
1947       atrociously misused in OpenPGP.  Perhaps if there is a
1948       pseudonym (OID 2.5.4.65, aka GNUTLS_OID_X520_PSEUDONYM) field
1949       in the subject or sAN?
1950    */
1951    comment = mgs_x509_leaf_oid_from_dn(sp, GNUTLS_OID_X520_PSEUDONYM, cert);
1952
1953    /* E-mail
1954
1955       This should be the the first rfc822Name from the sAN.
1956
[b55bf71]1957       failing that, we'll take the leaf email in the certificate's
1958       subject; this is a deprecated use though.
[832182b]1959     */
1960    email = mgs_x509_first_type_from_san(sp, GNUTLS_SAN_RFC822NAME, cert);
[b55bf71]1961    if (email == NULL)
1962        email = mgs_x509_leaf_oid_from_dn(sp, GNUTLS_OID_PKCS9_EMAIL, cert);
[832182b]1963
1964    /* assemble all the parts: */
1965
1966    /* must have at least a name or an e-mail. */
1967    if (name == NULL && email == NULL) {
1968        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1969                "GnuTLS: Need either a name or an e-mail address to get a User ID from an X.509 certificate.");
1970        goto end;
1971    }
1972    if (name) {
1973        if (comment) {
1974            if (email) {
1975                ret = apr_psprintf(pool, "%s (%s) <%s>", name, comment, email);
1976            } else {
1977                ret = apr_psprintf(pool, "%s (%s)", name, comment);
1978            }
1979        } else {
1980            if (email) {
1981                ret = apr_psprintf(pool, "%s <%s>", name, email);
1982            } else {
1983                ret = apr_pstrdup(pool, name);
1984            }
1985        }
1986    } else {
1987        if (comment) {
1988            ret = apr_psprintf(pool, "(%s) <%s>", comment, email);
1989        } else {
1990            ret = apr_psprintf(pool, "<%s>", email);
1991        }
1992    }
1993
1994end:
1995    apr_pool_destroy(sp);
1996    return ret;
1997}
[fd82e59]1998#endif /* ENABLE_MSVA */
[b4739cd]1999
2000
[bc539d5]2001
2002/*
2003 * This hook writes the mod_gnutls status message for a mod_status
2004 * report. According to the comments in mod_status.h, the "flags"
2005 * parameter is a bitwise OR of the AP_STATUS_ flags.
2006 *
2007 * Note that this implementation gives flags explicitly requesting a
2008 * simple response priority, e.g. if AP_STATUS_SHORT is set, flags
2009 * requesting an HTML report will be ignored. As of Apache 2.4.10, the
2010 * following flags were defined in mod_status.h:
2011 *
2012 * AP_STATUS_SHORT (short, non-HTML report requested)
2013 * AP_STATUS_NOTABLE (HTML report without tables)
2014 * AP_STATUS_EXTENDED (detailed report)
2015 */
2016static int mgs_status_hook(request_rec *r, int flags)
2017{
[b4739cd]2018    if (r == NULL)
2019        return OK;
2020
[bc539d5]2021    mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
2022        ap_get_module_config(r->server->module_config, &gnutls_module);
[b4739cd]2023
2024    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
2025
[bc539d5]2026    if (flags & AP_STATUS_SHORT)
2027    {
2028        ap_rprintf(r, "Using GnuTLS version: %s\n", gnutls_check_version(NULL));
2029        ap_rputs("Built against GnuTLS version: " GNUTLS_VERSION "\n", r);
2030    }
2031    else
2032    {
2033        ap_rputs("<hr>\n", r);
2034        ap_rputs("<h2>GnuTLS Information:</h2>\n<dl>\n", r);
2035
2036        ap_rprintf(r, "<dt>Using GnuTLS version:</dt><dd>%s</dd>\n",
2037                   gnutls_check_version(NULL));
2038        ap_rputs("<dt>Built against GnuTLS version:</dt><dd>"
2039                 GNUTLS_VERSION "</dd>\n", r);
2040        ap_rprintf(r, "<dt>Using TLS:</dt><dd>%s</dd>\n",
2041                   (sc->enabled == GNUTLS_ENABLED_FALSE ? "no" : "yes"));
2042    }
[b4739cd]2043
[bc539d5]2044    if (sc->enabled != GNUTLS_ENABLED_FALSE)
2045    {
[2f10643]2046        mgs_handle_t* ctxt = get_effective_gnutls_ctxt(r->connection);
[600cf16]2047        if (ctxt && ctxt->session != NULL)
2048        {
[bc539d5]2049            char* s_info = gnutls_session_get_desc(ctxt->session);
2050            if (s_info)
2051            {
2052                if (flags & AP_STATUS_SHORT)
2053                    ap_rprintf(r, "Current TLS session: %s\n", s_info);
2054                else
2055                    ap_rprintf(r, "<dt>Current TLS session:</dt><dd>%s</dd>\n",
2056                               s_info);
2057                gnutls_free(s_info);
[b4739cd]2058            }
2059        }
2060    }
2061
[bc539d5]2062    if (!(flags & AP_STATUS_SHORT))
2063        ap_rputs("</dl>\n", r);
2064
[3aff94d]2065    if (sc->ocsp_cache)
2066        mgs_cache_status(sc->ocsp_cache, "GnuTLS OCSP Cache", r, flags);
2067    if (sc->cache_enable)
2068        mgs_cache_status(sc->cache, "GnuTLS Session Cache", r, flags);
2069
[b4739cd]2070    return OK;
2071}
Note: See TracBrowser for help on using the repository browser.