source: mod_gnutls/src/gnutls_hooks.c @ 235e109

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

Unify initialization of mod_gnutls connection context

  • Property mode set to 100644
File size: 77.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-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
1078int mgs_hook_fixups(request_rec * r) {
1079    unsigned char sbuf[GNUTLS_MAX_SESSION_ID];
1080    const char *tmp;
1081    size_t len;
1082    mgs_handle_t *ctxt;
1083    int rv = OK;
1084
1085    if (r == NULL)
1086        return DECLINED;
1087
1088    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
1089    apr_table_t *env = r->subprocess_env;
1090
1091    ctxt = ap_get_module_config(r->connection->conn_config,
1092                                &gnutls_module);
1093
1094    if (!ctxt || ctxt->enabled != GNUTLS_ENABLED_TRUE || ctxt->session == NULL)
1095    {
1096        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "request declined in %s", __func__);
1097        return DECLINED;
1098    }
1099
1100    apr_table_setn(env, "HTTPS", "on");
1101
1102    apr_table_setn(env, "SSL_VERSION_LIBRARY",
1103            "GnuTLS/" LIBGNUTLS_VERSION);
1104    apr_table_setn(env, "SSL_VERSION_INTERFACE",
1105            "mod_gnutls/" MOD_GNUTLS_VERSION);
1106
1107    apr_table_setn(env, "SSL_PROTOCOL",
1108            gnutls_protocol_get_name(gnutls_protocol_get_version(ctxt->session)));
1109
1110    /* should have been called SSL_CIPHERSUITE instead */
1111    apr_table_setn(env, "SSL_CIPHER",
1112            gnutls_cipher_suite_get_name(gnutls_kx_get(ctxt->session),
1113                                         gnutls_cipher_get(ctxt->session),
1114                                         gnutls_mac_get(ctxt->session)));
1115
1116    apr_table_setn(env, "SSL_COMPRESS_METHOD",
1117            gnutls_compression_get_name(gnutls_compression_get(ctxt->session)));
1118
1119#ifdef ENABLE_SRP
1120    if (ctxt->sc->srp_tpasswd_conf_file != NULL && ctxt->sc->srp_tpasswd_file != NULL) {
1121        tmp = gnutls_srp_server_get_username(ctxt->session);
1122        apr_table_setn(env, "SSL_SRP_USER", (tmp != NULL) ? tmp : "");
1123    } else {
1124        apr_table_unset(env, "SSL_SRP_USER");
1125    }
1126#endif
1127
1128    if (apr_table_get(env, "SSL_CLIENT_VERIFY") == NULL)
1129        apr_table_setn(env, "SSL_CLIENT_VERIFY", "NONE");
1130
1131    unsigned int key_size = 8 * gnutls_cipher_get_key_size(gnutls_cipher_get(ctxt->session));
1132    tmp = apr_psprintf(r->pool, "%u", key_size);
1133
1134    apr_table_setn(env, "SSL_CIPHER_USEKEYSIZE", tmp);
1135
1136    apr_table_setn(env, "SSL_CIPHER_ALGKEYSIZE", tmp);
1137
1138    apr_table_setn(env, "SSL_CIPHER_EXPORT",
1139            (key_size <= 40) ? "true" : "false");
1140
1141    int dhsize = gnutls_dh_get_prime_bits(ctxt->session);
1142    if (dhsize > 0) {
1143        tmp = apr_psprintf(r->pool, "%d", dhsize);
1144        apr_table_setn(env, "SSL_DH_PRIME_BITS", tmp);
1145    }
1146
1147    len = sizeof (sbuf);
1148    gnutls_session_get_id(ctxt->session, sbuf, &len);
1149    apr_table_setn(env, "SSL_SESSION_ID",
1150                   apr_pescape_hex(r->pool, sbuf, len, 0));
1151
1152    if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_X509) {
1153        mgs_add_common_cert_vars(r, ctxt->sc->certs_x509_crt_chain[0], 0, ctxt->sc->export_certificates_size);
1154    } else if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_OPENPGP) {
1155        mgs_add_common_pgpcert_vars(r, ctxt->sc->cert_crt_pgp[0], 0, ctxt->sc->export_certificates_size);
1156    }
1157
1158    return rv;
1159}
1160
1161int mgs_hook_authz(request_rec * r) {
1162    int rv;
1163    mgs_handle_t *ctxt;
1164    mgs_dirconf_rec *dc;
1165
1166    if (r == NULL)
1167        return DECLINED;
1168
1169    dc = ap_get_module_config(r->per_dir_config, &gnutls_module);
1170
1171    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
1172    ctxt =
1173            ap_get_module_config(r->connection->conn_config,
1174            &gnutls_module);
1175
1176    if (!ctxt || ctxt->session == NULL) {
1177        return DECLINED;
1178    }
1179
1180    if (dc->client_verify_mode == GNUTLS_CERT_IGNORE) {
1181        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1182                "GnuTLS: Directory set to Ignore Client Certificate!");
1183    } else {
1184        if (ctxt->sc->client_verify_mode < dc->client_verify_mode) {
1185            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1186                    "GnuTLS: Attempting to rehandshake with peer. %d %d",
1187                    ctxt->sc->client_verify_mode,
1188                    dc->client_verify_mode);
1189
1190            /* If we already have a client certificate, there's no point in
1191             * re-handshaking... */
1192            rv = mgs_cert_verify(r, ctxt);
1193            if (rv != DECLINED && rv != HTTP_FORBIDDEN)
1194                return rv;
1195
1196            gnutls_certificate_server_set_request
1197                    (ctxt->session, dc->client_verify_mode);
1198
1199            if (mgs_rehandshake(ctxt) != 0) {
1200                return HTTP_FORBIDDEN;
1201            }
1202        } else if (ctxt->sc->client_verify_mode ==
1203                GNUTLS_CERT_IGNORE) {
1204#if MOD_GNUTLS_DEBUG
1205            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1206                    "GnuTLS: Peer is set to IGNORE");
1207#endif
1208            return DECLINED;
1209        }
1210        rv = mgs_cert_verify(r, ctxt);
1211        if (rv != DECLINED
1212            && (rv != HTTP_FORBIDDEN
1213                || dc->client_verify_mode == GNUTLS_CERT_REQUIRE
1214                || (dc->client_verify_mode == -1
1215                    && ctxt->sc->client_verify_mode == GNUTLS_CERT_REQUIRE)))
1216        {
1217            return rv;
1218        }
1219    }
1220
1221    return DECLINED;
1222}
1223
1224/* variables that are not sent by default:
1225 *
1226 * SSL_CLIENT_CERT      string  PEM-encoded client certificate
1227 * SSL_SERVER_CERT      string  PEM-encoded client certificate
1228 */
1229
1230/* @param side is either 0 for SERVER or 1 for CLIENT
1231 *
1232 * @param export_cert_size (int) maximum size for environment variable
1233 * to use for the PEM-encoded certificate (0 means do not export)
1234 */
1235#define MGS_SIDE(suffix) ((side==0) ? "SSL_SERVER" suffix : "SSL_CLIENT" suffix)
1236
1237static void mgs_add_common_cert_vars(request_rec * r, gnutls_x509_crt_t cert, int side, size_t export_cert_size) {
1238    unsigned char sbuf[64]; /* buffer to hold serials */
1239    char buf[AP_IOBUFSIZE];
1240    const char *tmp;
1241    char *tmp2;
1242    size_t len;
1243    int ret;
1244
1245    if (r == NULL)
1246        return;
1247
1248    apr_table_t *env = r->subprocess_env;
1249
1250    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
1251    if (export_cert_size > 0) {
1252        len = 0;
1253        ret = gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_PEM, NULL, &len);
1254        if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
1255            if (len >= export_cert_size) {
1256                apr_table_setn(env, MGS_SIDE("_CERT"), "GNUTLS_CERTIFICATE_SIZE_LIMIT_EXCEEDED");
1257                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1258                              "GnuTLS: Failed to export too-large X.509 certificate to environment");
1259            } else {
1260                char* cert_buf = apr_palloc(r->pool, len + 1);
1261                if (cert_buf != NULL && gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_PEM, cert_buf, &len) >= 0) {
1262                    cert_buf[len] = 0;
1263                    apr_table_setn(env, MGS_SIDE("_CERT"), cert_buf);
1264                } else {
1265                    ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1266                                  "GnuTLS: failed to export X.509 certificate");
1267                }
1268            }
1269        } else {
1270            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1271                          "GnuTLS: dazed and confused about X.509 certificate size");
1272        }
1273    }
1274
1275    len = sizeof (buf);
1276    gnutls_x509_crt_get_dn(cert, buf, &len);
1277    apr_table_setn(env, MGS_SIDE("_S_DN"), apr_pstrmemdup(r->pool, buf, len));
1278
1279    len = sizeof (buf);
1280    gnutls_x509_crt_get_issuer_dn(cert, buf, &len);
1281    apr_table_setn(env, MGS_SIDE("_I_DN"), apr_pstrmemdup(r->pool, buf, len));
1282
1283    len = sizeof (sbuf);
1284    gnutls_x509_crt_get_serial(cert, sbuf, &len);
1285    apr_table_setn(env, MGS_SIDE("_M_SERIAL"),
1286                   apr_pescape_hex(r->pool, sbuf, len, 0));
1287
1288    ret = gnutls_x509_crt_get_version(cert);
1289    if (ret > 0)
1290        apr_table_setn(env, MGS_SIDE("_M_VERSION"),
1291                       apr_psprintf(r->pool, "%u", ret));
1292
1293    apr_table_setn(env, MGS_SIDE("_CERT_TYPE"), "X.509");
1294
1295    tmp =
1296            mgs_time2sz(gnutls_x509_crt_get_expiration_time
1297            (cert), buf, sizeof (buf));
1298    apr_table_setn(env, MGS_SIDE("_V_END"), apr_pstrdup(r->pool, tmp));
1299
1300    tmp =
1301            mgs_time2sz(gnutls_x509_crt_get_activation_time
1302            (cert), buf, sizeof (buf));
1303    apr_table_setn(env, MGS_SIDE("_V_START"), apr_pstrdup(r->pool, tmp));
1304
1305    ret = gnutls_x509_crt_get_signature_algorithm(cert);
1306    if (ret >= 0) {
1307        apr_table_setn(env, MGS_SIDE("_A_SIG"),
1308                gnutls_sign_algorithm_get_name(ret));
1309    }
1310
1311    ret = gnutls_x509_crt_get_pk_algorithm(cert, NULL);
1312    if (ret >= 0) {
1313        apr_table_setn(env, MGS_SIDE("_A_KEY"),
1314                gnutls_pk_algorithm_get_name(ret));
1315    }
1316
1317    /* export all the alternative names (DNS, RFC822 and URI) */
1318    for (int i = 0; !(ret < 0); i++)
1319    {
1320        const char *san, *sanlabel;
1321        len = 0;
1322        ret = gnutls_x509_crt_get_subject_alt_name(cert, i,
1323                NULL, &len,
1324                NULL);
1325
1326        if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER && len > 1) {
1327            tmp2 = apr_palloc(r->pool, len + 1);
1328
1329            ret =
1330                    gnutls_x509_crt_get_subject_alt_name(cert, i,
1331                    tmp2,
1332                    &len,
1333                    NULL);
1334            tmp2[len] = 0;
1335
1336            sanlabel = apr_psprintf(r->pool, "%s%u", MGS_SIDE("_S_AN"), i);
1337            if (ret == GNUTLS_SAN_DNSNAME) {
1338                san = apr_psprintf(r->pool, "DNSNAME:%s", tmp2);
1339            } else if (ret == GNUTLS_SAN_RFC822NAME) {
1340                san = apr_psprintf(r->pool, "RFC822NAME:%s", tmp2);
1341            } else if (ret == GNUTLS_SAN_URI) {
1342                san = apr_psprintf(r->pool, "URI:%s", tmp2);
1343            } else {
1344                san = "UNSUPPORTED";
1345            }
1346            apr_table_setn(env, sanlabel, san);
1347        }
1348    }
1349}
1350
1351
1352/* @param side 0: server, 1: client
1353 *
1354 * @param export_cert_size (int) maximum size for environment variable
1355 * to use for the PEM-encoded certificate (0 means do not export)
1356 */
1357static void mgs_add_common_pgpcert_vars(request_rec * r, gnutls_openpgp_crt_t cert, int side, size_t export_cert_size) {
1358
1359        unsigned char sbuf[64]; /* buffer to hold serials */
1360    char buf[AP_IOBUFSIZE];
1361    const char *tmp;
1362    size_t len;
1363    int ret;
1364
1365    if (r == NULL)
1366        return;
1367
1368    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
1369    apr_table_t *env = r->subprocess_env;
1370
1371    if (export_cert_size > 0) {
1372        len = 0;
1373        ret = gnutls_openpgp_crt_export(cert, GNUTLS_OPENPGP_FMT_BASE64, NULL, &len);
1374        if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
1375            if (len >= export_cert_size) {
1376                apr_table_setn(env, MGS_SIDE("_CERT"),
1377                               "GNUTLS_CERTIFICATE_SIZE_LIMIT_EXCEEDED");
1378                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1379                              "GnuTLS: Failed to export too-large OpenPGP certificate to environment");
1380            } else {
1381                char* cert_buf = apr_palloc(r->pool, len + 1);
1382                if (cert_buf != NULL && gnutls_openpgp_crt_export(cert, GNUTLS_OPENPGP_FMT_BASE64, cert_buf, &len) >= 0) {
1383                    cert_buf[len] = 0;
1384                    apr_table_setn(env, MGS_SIDE("_CERT"), cert_buf);
1385                } else {
1386                    ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1387                                  "GnuTLS: failed to export OpenPGP certificate");
1388                }
1389            }
1390        } else {
1391            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1392                          "GnuTLS: dazed and confused about OpenPGP certificate size");
1393        }
1394    }
1395
1396    len = sizeof (buf);
1397    gnutls_openpgp_crt_get_name(cert, 0, buf, &len);
1398    apr_table_setn(env, MGS_SIDE("_NAME"), apr_pstrmemdup(r->pool, buf, len));
1399
1400    len = sizeof (sbuf);
1401    gnutls_openpgp_crt_get_fingerprint(cert, sbuf, &len);
1402    apr_table_setn(env, MGS_SIDE("_FINGERPRINT"),
1403                   apr_pescape_hex(r->pool, sbuf, len, 0));
1404
1405    ret = gnutls_openpgp_crt_get_version(cert);
1406    if (ret > 0)
1407        apr_table_setn(env, MGS_SIDE("_M_VERSION"),
1408                       apr_psprintf(r->pool, "%u", ret));
1409
1410    apr_table_setn(env, MGS_SIDE("_CERT_TYPE"), "OPENPGP");
1411
1412    tmp =
1413            mgs_time2sz(gnutls_openpgp_crt_get_expiration_time
1414            (cert), buf, sizeof (buf));
1415    apr_table_setn(env, MGS_SIDE("_V_END"), apr_pstrdup(r->pool, tmp));
1416
1417    tmp =
1418            mgs_time2sz(gnutls_openpgp_crt_get_creation_time
1419            (cert), buf, sizeof (buf));
1420    apr_table_setn(env, MGS_SIDE("_V_START"), apr_pstrdup(r->pool, tmp));
1421
1422    ret = gnutls_openpgp_crt_get_pk_algorithm(cert, NULL);
1423    if (ret >= 0) {
1424        apr_table_setn(env, MGS_SIDE("_A_KEY"), gnutls_pk_algorithm_get_name(ret));
1425    }
1426
1427}
1428
1429/* TODO: Allow client sending a X.509 certificate chain */
1430static int mgs_cert_verify(request_rec * r, mgs_handle_t * ctxt) {
1431    const gnutls_datum_t *cert_list;
1432    unsigned int cert_list_size;
1433    /* assume the certificate is invalid unless explicitly set
1434     * otherwise */
1435    unsigned int status = GNUTLS_CERT_INVALID;
1436    int rv = GNUTLS_E_NO_CERTIFICATE_FOUND, ret;
1437    unsigned int ch_size = 0;
1438
1439    union {
1440        gnutls_x509_crt_t x509[MAX_CHAIN_SIZE];
1441        gnutls_openpgp_crt_t pgp;
1442    } cert;
1443    apr_time_t expiration_time, cur_time;
1444
1445    if (r == NULL || ctxt == NULL || ctxt->session == NULL)
1446        return HTTP_FORBIDDEN;
1447
1448    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
1449    cert_list =
1450            gnutls_certificate_get_peers(ctxt->session, &cert_list_size);
1451
1452    if (cert_list == NULL || cert_list_size == 0) {
1453        /* It is perfectly OK for a client not to send a certificate if on REQUEST mode
1454         */
1455        if (ctxt->sc->client_verify_mode == GNUTLS_CERT_REQUEST)
1456            return OK;
1457
1458        /* no certificate provided by the client, but one was required. */
1459        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1460                "GnuTLS: Failed to Verify Peer: "
1461                "Client did not submit a certificate");
1462        return HTTP_FORBIDDEN;
1463    }
1464
1465    if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_X509) {
1466        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1467                "GnuTLS: A Chain of %d certificate(s) was provided for validation",
1468                cert_list_size);
1469
1470        for (ch_size = 0; ch_size < cert_list_size; ch_size++) {
1471            gnutls_x509_crt_init(&cert.x509[ch_size]);
1472            rv = gnutls_x509_crt_import(cert.x509[ch_size],
1473                    &cert_list[ch_size],
1474                    GNUTLS_X509_FMT_DER);
1475            // When failure to import, leave the loop
1476            if (rv != GNUTLS_E_SUCCESS) {
1477                if (ch_size < 1) {
1478                    ap_log_rerror(APLOG_MARK,
1479                            APLOG_INFO, 0, r,
1480                            "GnuTLS: Failed to Verify Peer: "
1481                            "Failed to import peer certificates.");
1482                    ret = HTTP_FORBIDDEN;
1483                    goto exit;
1484                }
1485                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1486                        "GnuTLS: Failed to import some peer certificates. Using %d certificates",
1487                        ch_size);
1488                rv = GNUTLS_E_SUCCESS;
1489                break;
1490            }
1491        }
1492    } else if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_OPENPGP) {
1493        if (cert_list_size > 1) {
1494            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1495                    "GnuTLS: Failed to Verify Peer: "
1496                    "Chained Client Certificates are not supported.");
1497            return HTTP_FORBIDDEN;
1498        }
1499
1500        gnutls_openpgp_crt_init(&cert.pgp);
1501        rv = gnutls_openpgp_crt_import(cert.pgp, &cert_list[0],
1502                GNUTLS_OPENPGP_FMT_RAW);
1503
1504    } else
1505        return HTTP_FORBIDDEN;
1506
1507    if (rv < 0) {
1508        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1509                "GnuTLS: Failed to Verify Peer: "
1510                "Failed to import peer certificates.");
1511        ret = HTTP_FORBIDDEN;
1512        goto exit;
1513    }
1514
1515    if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_X509) {
1516        apr_time_ansi_put(&expiration_time,
1517                gnutls_x509_crt_get_expiration_time
1518                (cert.x509[0]));
1519
1520        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1521                      "GnuTLS: Verifying list of %d certificate(s) via method '%s'",
1522                      ch_size, mgs_readable_cvm(ctxt->sc->client_verify_method));
1523        switch(ctxt->sc->client_verify_method) {
1524        case mgs_cvm_cartel:
1525            rv = gnutls_x509_crt_list_verify(cert.x509, ch_size,
1526                                             ctxt->sc->ca_list,
1527                                             ctxt->sc->ca_list_size,
1528                                             NULL, 0, 0, &status);
1529            break;
1530#ifdef ENABLE_MSVA
1531        case mgs_cvm_msva:
1532        {
1533            struct msv_response* resp = NULL;
1534            struct msv_query q = { .context="https", .peertype="client", .pkctype="x509pem" };
1535            msv_ctxt_t ctx = msv_ctxt_init(NULL);
1536            char cert_pem_buf[10 * 1024];
1537            size_t len = sizeof (cert_pem_buf);
1538
1539            rv = 0;
1540            if (gnutls_x509_crt_export(cert.x509[0], GNUTLS_X509_FMT_PEM, cert_pem_buf, &len) >= 0) {
1541                /* FIXME : put together a name from the cert we received, instead of hard-coding this value: */
1542                q.peername = mgs_x509_construct_uid(r, cert.x509[0]);
1543                q.pkcdata = cert_pem_buf;
1544                rv = msv_query_agent(ctx, q, &resp);
1545                if (rv == LIBMSV_ERROR_SUCCESS) {
1546                    status = 0;
1547                } else if (rv == LIBMSV_ERROR_INVALID) {
1548                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1549                                  "GnuTLS: Monkeysphere validation failed: (message: %s)", resp->message);
1550                    status = GNUTLS_CERT_INVALID;
1551                } else {
1552                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1553                                  "GnuTLS: Error communicating with the Monkeysphere Validation Agent: (%d) %s", rv, msv_strerror(ctx, rv));
1554                    status = GNUTLS_CERT_INVALID;
1555                    rv = -1;
1556                }
1557            } else {
1558                ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1559                              "GnuTLS: Could not convert the client certificate to PEM format");
1560                status = GNUTLS_CERT_INVALID;
1561                rv = GNUTLS_E_ASN1_ELEMENT_NOT_FOUND;
1562            }
1563            msv_response_destroy(resp);
1564            msv_ctxt_destroy(ctx);
1565        }
1566            break;
1567#endif
1568        default:
1569            /* If this block is reached, that indicates a
1570             * configuration error or bug in mod_gnutls (invalid value
1571             * of ctxt->sc->client_verify_method). */
1572            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1573                          "GnuTLS: Failed to Verify X.509 Peer: method '%s' is not supported",
1574                          mgs_readable_cvm(ctxt->sc->client_verify_method));
1575            rv = GNUTLS_E_UNIMPLEMENTED_FEATURE;
1576        }
1577
1578    } else {
1579        apr_time_ansi_put(&expiration_time,
1580                gnutls_openpgp_crt_get_expiration_time
1581                (cert.pgp));
1582
1583        switch(ctxt->sc->client_verify_method) {
1584        case mgs_cvm_cartel:
1585            rv = gnutls_openpgp_crt_verify_ring(cert.pgp,
1586                                                ctxt->sc->pgp_list, 0,
1587                                                &status);
1588            break;
1589#ifdef ENABLE_MSVA
1590        case mgs_cvm_msva:
1591            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1592                          "GnuTLS:  OpenPGP verification via MSVA is not yet implemented");
1593            rv = GNUTLS_E_UNIMPLEMENTED_FEATURE;
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 OpenPGP Peer: method '%s' is not supported",
1602                          mgs_readable_cvm(ctxt->sc->client_verify_method));
1603            rv = GNUTLS_E_UNIMPLEMENTED_FEATURE;
1604        }
1605    }
1606
1607    /* "goto exit" at the end of this block skips evaluation of the
1608     * "status" variable */
1609    if (rv < 0) {
1610        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1611                "GnuTLS: Failed to Verify Peer certificate: (%d) %s",
1612                rv, gnutls_strerror(rv));
1613        if (rv == GNUTLS_E_NO_CERTIFICATE_FOUND)
1614            ap_log_rerror(APLOG_MARK, APLOG_EMERG, 0, r,
1615                "GnuTLS: No certificate was found for verification. Did you set the GnuTLSX509CAFile or GnuTLSPGPKeyringFile directives?");
1616        ret = HTTP_FORBIDDEN;
1617        goto exit;
1618    }
1619
1620    /* TODO: X509 CRL Verification. */
1621    /* May add later if anyone needs it.
1622     */
1623    /* ret = gnutls_x509_crt_check_revocation(crt, crl_list, crl_list_size); */
1624
1625    cur_time = apr_time_now();
1626
1627    if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) {
1628        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1629                "GnuTLS: Could not find Signer for Peer Certificate");
1630    }
1631
1632    if (status & GNUTLS_CERT_SIGNER_NOT_CA) {
1633        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1634                "GnuTLS: Peer's Certificate signer is not a CA");
1635    }
1636
1637    if (status & GNUTLS_CERT_INSECURE_ALGORITHM) {
1638        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1639                "GnuTLS: Peer's Certificate is using insecure algorithms");
1640    }
1641
1642    if (status & GNUTLS_CERT_EXPIRED
1643            || status & GNUTLS_CERT_NOT_ACTIVATED) {
1644        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1645                "GnuTLS: Peer's Certificate signer is expired or not yet activated");
1646    }
1647
1648    if (status & GNUTLS_CERT_INVALID) {
1649        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1650                "GnuTLS: Peer Certificate is invalid.");
1651    } else if (status & GNUTLS_CERT_REVOKED) {
1652        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1653                "GnuTLS: Peer Certificate is revoked.");
1654    }
1655
1656    if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_X509)
1657        mgs_add_common_cert_vars(r, cert.x509[0], 1, ctxt->sc->export_certificates_size);
1658    else if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_OPENPGP)
1659        mgs_add_common_pgpcert_vars(r, cert.pgp, 1, ctxt->sc->export_certificates_size);
1660
1661    {
1662        /* days remaining */
1663        unsigned long remain =
1664                (apr_time_sec(expiration_time) -
1665                apr_time_sec(cur_time)) / 86400;
1666        apr_table_setn(r->subprocess_env, "SSL_CLIENT_V_REMAIN",
1667                apr_psprintf(r->pool, "%lu", remain));
1668    }
1669
1670    if (status == 0) {
1671        apr_table_setn(r->subprocess_env, "SSL_CLIENT_VERIFY",
1672                "SUCCESS");
1673        ret = OK;
1674    } else {
1675        apr_table_setn(r->subprocess_env, "SSL_CLIENT_VERIFY",
1676                "FAILED");
1677        if (ctxt->sc->client_verify_mode == GNUTLS_CERT_REQUEST)
1678            ret = OK;
1679        else
1680            ret = HTTP_FORBIDDEN;
1681    }
1682
1683exit:
1684    if (gnutls_certificate_type_get(ctxt->session) == GNUTLS_CRT_X509)
1685        for (unsigned int i = 0; i < ch_size; i++)
1686            gnutls_x509_crt_deinit(cert.x509[i]);
1687    else if (gnutls_certificate_type_get(ctxt->session) ==
1688             GNUTLS_CRT_OPENPGP)
1689        gnutls_openpgp_crt_deinit(cert.pgp);
1690    return ret;
1691}
1692
1693
1694
1695#ifdef ENABLE_MSVA
1696/* this section of code is used only when trying to talk to the MSVA */
1697static const char* mgs_x509_leaf_oid_from_dn(apr_pool_t *pool, const char* oid, gnutls_x509_crt_t cert) {
1698    int rv=GNUTLS_E_SUCCESS, i;
1699    size_t sz=0, lastsz=0;
1700    char* data=NULL;
1701
1702    i = -1;
1703    while(rv != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
1704        i++;
1705        lastsz=sz;
1706        sz=0;
1707        rv = gnutls_x509_crt_get_dn_by_oid (cert, oid, i, 0, NULL, &sz);
1708    }
1709    if (i > 0) {
1710        data = apr_palloc(pool, lastsz);
1711        sz=lastsz;
1712        rv = gnutls_x509_crt_get_dn_by_oid (cert, oid, i-1, 0, data, &sz);
1713        if (rv == GNUTLS_E_SUCCESS)
1714            return data;
1715    }
1716    return NULL;
1717}
1718
1719static const char* mgs_x509_first_type_from_san(apr_pool_t *pool, gnutls_x509_subject_alt_name_t target, gnutls_x509_crt_t cert) {
1720    int rv=GNUTLS_E_SUCCESS;
1721    size_t sz;
1722    char* data=NULL;
1723    unsigned int i;
1724    gnutls_x509_subject_alt_name_t thistype;
1725
1726    i = 0;
1727    while(rv != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
1728        sz = 0;
1729        rv = gnutls_x509_crt_get_subject_alt_name2(cert, i, NULL, &sz, &thistype, NULL);
1730        if (rv == GNUTLS_E_SHORT_MEMORY_BUFFER && thistype == target) {
1731            data = apr_palloc(pool, sz);
1732            rv = gnutls_x509_crt_get_subject_alt_name2(cert, i, data, &sz, &thistype, NULL);
1733            if (rv >=0 && (thistype == target))
1734                return data;
1735        }
1736        i++;
1737    }
1738    return NULL;
1739}
1740
1741
1742/* Create a string representing a candidate User ID from an X.509
1743 * certificate
1744
1745 * We need this for client certification because a client gives us a
1746 * certificate, but doesn't tell us (in any other way) who they are
1747 * trying to authenticate as.
1748
1749 * TODO: we might need another parallel for OpenPGP, but for that it's
1750 * much simpler: we can just assume that the first User ID marked as
1751 * "primary" (or the first User ID, period) is the identity the user
1752 * is trying to present as.
1753
1754 * one complaint might be "but the user wanted to be another identity,
1755 * which is also in the certificate (e.g. in a SubjectAltName)"
1756 * However, given that any user can regenerate their own X.509
1757 * certificate with their own public key content, they should just do
1758 * so, and not expect us to guess at their identity :)
1759
1760 * This function allocates it's response from the pool given it.  When
1761 * that pool is reclaimed, the response will also be deallocated.
1762
1763 * FIXME: what about extracting a server-style cert
1764 *        (e.g. https://imposter.example) from the DN or any sAN?
1765
1766 * FIXME: what if we want to call this outside the context of a
1767 *        request?  That complicates the logging.
1768 */
1769static const char* mgs_x509_construct_uid(request_rec *r, gnutls_x509_crt_t cert) {
1770    /* basic strategy, assuming humans are the users: we are going to
1771     * try to reconstruct a "conventional" User ID by pulling in a
1772     * name, comment, and e-mail address.
1773     */
1774    apr_pool_t *pool = r->pool;
1775    const char *name=NULL, *comment=NULL, *email=NULL;
1776    const char *ret=NULL;
1777    /* subpool for temporary allocation: */
1778    apr_pool_t *sp=NULL;
1779
1780    if (APR_SUCCESS != apr_pool_create(&sp, pool))
1781        return NULL; /* i'm assuming that libapr would log this kind
1782                      * of error on its own */
1783
1784     /* Name
1785
1786     the name comes from the leaf commonName of the cert's Subject.
1787
1788     (MAYBE: should we look at trying to assemble a candidate from
1789             givenName, surName, suffix, etc?  the "name" field
1790             appears to be case-insensitive, which seems problematic
1791             from what we expect; see:
1792             http://www.itu.int/rec/T-REC-X.520-200102-s/e )
1793
1794     (MAYBE: should we try pulling a commonName or otherName or
1795             something from subjectAltName? see:
1796             https://tools.ietf.org/html/rfc5280#section-4.2.1.6
1797             GnuTLS does not support looking for Common Names in the
1798             SAN yet)
1799     */
1800    name = mgs_x509_leaf_oid_from_dn(sp, GNUTLS_OID_X520_COMMON_NAME, cert);
1801
1802    /* Comment
1803
1804       I am inclined to punt on this for now, as Comment has been so
1805       atrociously misused in OpenPGP.  Perhaps if there is a
1806       pseudonym (OID 2.5.4.65, aka GNUTLS_OID_X520_PSEUDONYM) field
1807       in the subject or sAN?
1808    */
1809    comment = mgs_x509_leaf_oid_from_dn(sp, GNUTLS_OID_X520_PSEUDONYM, cert);
1810
1811    /* E-mail
1812
1813       This should be the the first rfc822Name from the sAN.
1814
1815       failing that, we'll take the leaf email in the certificate's
1816       subject; this is a deprecated use though.
1817     */
1818    email = mgs_x509_first_type_from_san(sp, GNUTLS_SAN_RFC822NAME, cert);
1819    if (email == NULL)
1820        email = mgs_x509_leaf_oid_from_dn(sp, GNUTLS_OID_PKCS9_EMAIL, cert);
1821
1822    /* assemble all the parts: */
1823
1824    /* must have at least a name or an e-mail. */
1825    if (name == NULL && email == NULL) {
1826        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1827                "GnuTLS: Need either a name or an e-mail address to get a User ID from an X.509 certificate.");
1828        goto end;
1829    }
1830    if (name) {
1831        if (comment) {
1832            if (email) {
1833                ret = apr_psprintf(pool, "%s (%s) <%s>", name, comment, email);
1834            } else {
1835                ret = apr_psprintf(pool, "%s (%s)", name, comment);
1836            }
1837        } else {
1838            if (email) {
1839                ret = apr_psprintf(pool, "%s <%s>", name, email);
1840            } else {
1841                ret = apr_pstrdup(pool, name);
1842            }
1843        }
1844    } else {
1845        if (comment) {
1846            ret = apr_psprintf(pool, "(%s) <%s>", comment, email);
1847        } else {
1848            ret = apr_psprintf(pool, "<%s>", email);
1849        }
1850    }
1851
1852end:
1853    apr_pool_destroy(sp);
1854    return ret;
1855}
1856#endif /* ENABLE_MSVA */
1857
1858
1859
1860/*
1861 * This hook writes the mod_gnutls status message for a mod_status
1862 * report. According to the comments in mod_status.h, the "flags"
1863 * parameter is a bitwise OR of the AP_STATUS_ flags.
1864 *
1865 * Note that this implementation gives flags explicitly requesting a
1866 * simple response priority, e.g. if AP_STATUS_SHORT is set, flags
1867 * requesting an HTML report will be ignored. As of Apache 2.4.10, the
1868 * following flags were defined in mod_status.h:
1869 *
1870 * AP_STATUS_SHORT (short, non-HTML report requested)
1871 * AP_STATUS_NOTABLE (HTML report without tables)
1872 * AP_STATUS_EXTENDED (detailed report)
1873 */
1874static int mgs_status_hook(request_rec *r, int flags)
1875{
1876    if (r == NULL)
1877        return OK;
1878
1879    mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
1880        ap_get_module_config(r->server->module_config, &gnutls_module);
1881
1882    _gnutls_log(debug_log_fp, "%s: %d\n", __func__, __LINE__);
1883
1884    if (flags & AP_STATUS_SHORT)
1885    {
1886        ap_rprintf(r, "Using GnuTLS version: %s\n", gnutls_check_version(NULL));
1887        ap_rputs("Built against GnuTLS version: " GNUTLS_VERSION "\n", r);
1888    }
1889    else
1890    {
1891        ap_rputs("<hr>\n", r);
1892        ap_rputs("<h2>GnuTLS Information:</h2>\n<dl>\n", r);
1893
1894        ap_rprintf(r, "<dt>Using GnuTLS version:</dt><dd>%s</dd>\n",
1895                   gnutls_check_version(NULL));
1896        ap_rputs("<dt>Built against GnuTLS version:</dt><dd>"
1897                 GNUTLS_VERSION "</dd>\n", r);
1898        ap_rprintf(r, "<dt>Using TLS:</dt><dd>%s</dd>\n",
1899                   (sc->enabled == GNUTLS_ENABLED_FALSE ? "no" : "yes"));
1900    }
1901
1902    if (sc->enabled != GNUTLS_ENABLED_FALSE)
1903    {
1904        mgs_handle_t* ctxt =
1905            ap_get_module_config(r->connection->conn_config, &gnutls_module);
1906        if (ctxt && ctxt->session != NULL)
1907        {
1908            char* s_info = gnutls_session_get_desc(ctxt->session);
1909            if (s_info)
1910            {
1911                if (flags & AP_STATUS_SHORT)
1912                    ap_rprintf(r, "Current TLS session: %s\n", s_info);
1913                else
1914                    ap_rprintf(r, "<dt>Current TLS session:</dt><dd>%s</dd>\n",
1915                               s_info);
1916                gnutls_free(s_info);
1917            }
1918        }
1919    }
1920
1921    if (!(flags & AP_STATUS_SHORT))
1922        ap_rputs("</dl>\n", r);
1923
1924    return OK;
1925}
1926
1927
1928
1929/*
1930 * Callback to check the server certificate for proxy HTTPS
1931 * connections, to be used with
1932 * gnutls_certificate_set_verify_function.
1933
1934 * Returns: 0 if certificate check was successful (certificate
1935 * trusted), non-zero otherwise (error during check or untrusted
1936 * certificate).
1937 */
1938static int gtls_check_server_cert(gnutls_session_t session)
1939{
1940    mgs_handle_t *ctxt = (mgs_handle_t *) gnutls_session_get_ptr(session);
1941    unsigned int status;
1942
1943    /* Get peer hostname from a note left by mod_proxy */
1944    const char *peer_hostname =
1945        apr_table_get(ctxt->c->notes, PROXY_SNI_NOTE);
1946    if (peer_hostname == NULL)
1947        ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, ctxt->c,
1948                      "%s: " PROXY_SNI_NOTE " NULL, cannot check "
1949                      "peer's hostname", __func__);
1950
1951    /* Verify certificate, including hostname match. Should
1952     * peer_hostname be NULL for some reason, the name is not
1953     * checked. */
1954    int err = gnutls_certificate_verify_peers3(session, peer_hostname,
1955                                               &status);
1956    if (err != GNUTLS_E_SUCCESS)
1957    {
1958        ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, ctxt->c,
1959                      "%s: server certificate check failed: %s (%d)",
1960                      __func__, gnutls_strerror(err), err);
1961        return err;
1962    }
1963
1964    if (status == 0)
1965        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, ctxt->c,
1966                      "%s: server certificate is trusted.",
1967                      __func__);
1968    else
1969    {
1970        gnutls_datum_t out;
1971        /* GNUTLS_CRT_X509: ATM, only X509 is supported for proxy
1972         * certs 0: according to function API, the last argument
1973         * should be 0 */
1974        err = gnutls_certificate_verification_status_print(status,
1975                                                           GNUTLS_CRT_X509,
1976                                                           &out, 0);
1977        if (err != GNUTLS_E_SUCCESS)
1978            ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, ctxt->c,
1979                          "%s: server verify print failed: %s (%d)",
1980                          __func__, gnutls_strerror(err), err);
1981        else
1982            ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, ctxt->c,
1983                          "%s: %s",
1984                          __func__, out.data);
1985        gnutls_free(out.data);
1986    }
1987
1988    return status;
1989}
1990
1991
1992
1993static apr_status_t cleanup_proxy_x509_credentials(void *arg)
1994{
1995    mgs_srvconf_rec *sc = (mgs_srvconf_rec *) arg;
1996
1997    if (sc->proxy_x509_creds)
1998    {
1999        /* This implicitly releases the associated trust list
2000         * sc->proxy_x509_tl, too. */
2001        gnutls_certificate_free_credentials(sc->proxy_x509_creds);
2002        sc->proxy_x509_creds = NULL;
2003        sc->proxy_x509_tl = NULL;
2004    }
2005
2006    if (sc->anon_client_creds)
2007    {
2008        gnutls_anon_free_client_credentials(sc->anon_client_creds);
2009        sc->anon_client_creds = NULL;
2010    }
2011
2012    if (sc->proxy_priorities)
2013    {
2014        gnutls_priority_deinit(sc->proxy_priorities);
2015        sc->proxy_priorities = NULL;
2016    }
2017
2018    return APR_SUCCESS;
2019}
2020
2021
2022
2023static apr_status_t load_proxy_x509_credentials(apr_pool_t *pconf,
2024                                                apr_pool_t *ptemp,
2025                                                server_rec *s)
2026{
2027    mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
2028        ap_get_module_config(s->module_config, &gnutls_module);
2029
2030    if (sc == NULL)
2031        return APR_EGENERAL;
2032
2033    apr_status_t ret = APR_EINIT;
2034    int err = GNUTLS_E_SUCCESS;
2035
2036    /* Cleanup function for the GnuTLS structures allocated below */
2037    apr_pool_cleanup_register(pconf, sc, cleanup_proxy_x509_credentials,
2038                              apr_pool_cleanup_null);
2039
2040    /* Function pool, gets destroyed before exit. */
2041    apr_pool_t *pool;
2042    ret = apr_pool_create(&pool, ptemp);
2043    if (ret != APR_SUCCESS)
2044    {
2045        ap_log_error(APLOG_MARK, APLOG_ERR, ret, s,
2046                     "%s: failed to allocate function memory pool.", __func__);
2047        return ret;
2048    }
2049
2050    /* allocate credentials structures */
2051    err = gnutls_certificate_allocate_credentials(&sc->proxy_x509_creds);
2052    if (err != GNUTLS_E_SUCCESS)
2053    {
2054        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2055                     "%s: Failed to initialize proxy credentials: (%d) %s",
2056                     __func__, err, gnutls_strerror(err));
2057        return APR_EGENERAL;
2058    }
2059    err = gnutls_anon_allocate_client_credentials(&sc->anon_client_creds);
2060    if (err != GNUTLS_E_SUCCESS)
2061    {
2062        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2063                     "%s: Failed to initialize anon credentials for proxy: "
2064                     "(%d) %s", __func__, err, gnutls_strerror(err));
2065        return APR_EGENERAL;
2066    }
2067
2068    /* Check if the proxy priorities have been set, fail immediately
2069     * if not */
2070    if (sc->proxy_priorities_str == NULL)
2071    {
2072        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
2073                     "Host '%s:%d' is missing the GnuTLSProxyPriorities "
2074                     "directive!",
2075                     s->server_hostname, s->port);
2076        return APR_EGENERAL;
2077    }
2078    /* parse proxy priorities */
2079    const char *err_pos = NULL;
2080    err = gnutls_priority_init(&sc->proxy_priorities,
2081                               sc->proxy_priorities_str, &err_pos);
2082    if (err != GNUTLS_E_SUCCESS)
2083    {
2084        if (ret == GNUTLS_E_INVALID_REQUEST)
2085            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2086                         "%s: Syntax error parsing proxy priorities "
2087                         "string at: %s",
2088                         __func__, err_pos);
2089        else
2090            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2091                         "Error setting proxy priorities: %s (%d)",
2092                         gnutls_strerror(err), err);
2093        ret = APR_EGENERAL;
2094    }
2095
2096    /* load certificate and key for client auth, if configured */
2097    if (sc->proxy_x509_key_file && sc->proxy_x509_cert_file)
2098    {
2099        char* cert_file = ap_server_root_relative(pool,
2100                                                  sc->proxy_x509_cert_file);
2101        char* key_file = ap_server_root_relative(pool,
2102                                                 sc->proxy_x509_key_file);
2103        err = gnutls_certificate_set_x509_key_file(sc->proxy_x509_creds,
2104                                                   cert_file,
2105                                                   key_file,
2106                                                   GNUTLS_X509_FMT_PEM);
2107        if (err != GNUTLS_E_SUCCESS)
2108        {
2109            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2110                         "%s: loading proxy client credentials failed: %s (%d)",
2111                         __func__, gnutls_strerror(err), err);
2112            ret = APR_EGENERAL;
2113        }
2114    }
2115    else if (!sc->proxy_x509_key_file && sc->proxy_x509_cert_file)
2116    {
2117        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
2118                     "%s: proxy key file not set!", __func__);
2119        ret = APR_EGENERAL;
2120    }
2121    else if (!sc->proxy_x509_cert_file && sc->proxy_x509_key_file)
2122    {
2123        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
2124                     "%s: proxy certificate file not set!", __func__);
2125        ret = APR_EGENERAL;
2126    }
2127    else
2128        /* if both key and cert are NULL, client auth is not used */
2129        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
2130                     "%s: no client credentials for proxy", __func__);
2131
2132    /* must be set if the server certificate is to be checked */
2133    if (sc->proxy_x509_ca_file)
2134    {
2135        /* initialize the trust list */
2136        err = gnutls_x509_trust_list_init(&sc->proxy_x509_tl, 0);
2137        if (err != GNUTLS_E_SUCCESS)
2138        {
2139            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2140                         "%s: gnutls_x509_trust_list_init failed: %s (%d)",
2141                         __func__, gnutls_strerror(err), err);
2142            ret = APR_EGENERAL;
2143        }
2144
2145        char* ca_file = ap_server_root_relative(pool,
2146                                                sc->proxy_x509_ca_file);
2147        /* if no CRL is used, sc->proxy_x509_crl_file is NULL */
2148        char* crl_file = NULL;
2149        if (sc->proxy_x509_crl_file)
2150            crl_file = ap_server_root_relative(pool,
2151                                               sc->proxy_x509_crl_file);
2152
2153        /* returns number of loaded elements */
2154        err = gnutls_x509_trust_list_add_trust_file(sc->proxy_x509_tl,
2155                                                    ca_file,
2156                                                    crl_file,
2157                                                    GNUTLS_X509_FMT_PEM,
2158                                                    0 /* tl_flags */,
2159                                                    0 /* tl_vflags */);
2160        if (err > 0)
2161            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2162                         "%s: proxy CA trust list: %d structures loaded",
2163                         __func__, err);
2164        else if (err == 0)
2165            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
2166                         "%s: proxy CA trust list is empty (%d)",
2167                         __func__, err);
2168        else /* err < 0 */
2169        {
2170            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2171                         "%s: error loading proxy CA trust list: %s (%d)",
2172                         __func__, gnutls_strerror(err), err);
2173            ret = APR_EGENERAL;
2174        }
2175
2176        /* attach trust list to credentials */
2177        gnutls_certificate_set_trust_list(sc->proxy_x509_creds,
2178                                          sc->proxy_x509_tl, 0);
2179    }
2180    else
2181        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
2182                     "%s: no CA trust list for proxy connections, "
2183                     "TLS connections will fail!", __func__);
2184
2185    gnutls_certificate_set_verify_function(sc->proxy_x509_creds,
2186                                           gtls_check_server_cert);
2187    apr_pool_destroy(pool);
2188    return ret;
2189}
Note: See TracBrowser for help on using the repository browser.