source: mod_gnutls/src/gnutls_hooks.c @ e7cf823

asynciodebian/masterdebian/stretch-backportsmainproxy-ticketupstream
Last change on this file since e7cf823 was e7cf823, checked in by Fiona Klute <fiona.klute@…>, 5 years ago

Add process_connection hook, adjust hook order for mod_http2 compatibility

The TLS handshake must have happened before the mod_http2
process_connection hook runs, which means we have to trigger it
explicitly before any reads happen. Some other hooks must have a
certain order relative to mod_http2 as well.

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