source: mod_gnutls/src/gnutls_hooks.c @ 104e881

asynciodebian/masterdebian/stretch-backportsmainproxy-ticketupstream
Last change on this file since 104e881 was 104e881, checked in by Thomas Klute <thomas2.klute@…>, 6 years ago

General comment updates for Doxygen compatibility

Mostly /* */ vs. / */ changes so Doxygen does catch the correct
descriptions instead of e.g. license headers, plus some minor comment
updates.

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