source: mod_gnutls/src/gnutls_hooks.c @ 0e3f8c6

asynciodebian/mastermainproxy-ticket
Last change on this file since 0e3f8c6 was 0e3f8c6, checked in by Fiona Klute <fiona.klute@…>, 5 years ago

Create module-wide singleton watchdog during post_config

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