source: mod_gnutls/src/gnutls_hooks.c @ 4f2c988

asynciomainproxy-ticket
Last change on this file since 4f2c988 was 4f2c988, checked in by Fiona Klute <fiona.klute@…>, 3 years ago

Send 403 if required client post-handshake authentication fails

This is the (presumed) expected behavior if the initial handshake was
allowed and part of the server is accessible to the client.

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