source: mod_gnutls/src/gnutls_hooks.c @ fd73a08

asynciodebian/masterdebian/stretch-backportsjessie-backportsmainmsvaproxy-ticketupstream
Last change on this file since fd73a08 was fd73a08, checked in by Nokis Mavrogiannopoulos <nmav@…>, 15 years ago

Added support for subject alternative names. (untested)

  • Property mode set to 100644
File size: 25.9 KB
Line 
1/**
2 *  Copyright 2004-2005 Paul Querna
3 *  Copyright 2007 Nikos Mavrogiannopoulos
4 *
5 *  Licensed under the Apache License, Version 2.0 (the "License");
6 *  you may not use this file except in compliance with the License.
7 *  You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 *
17 */
18
19#include "mod_gnutls.h"
20#include "http_vhost.h"
21#include "ap_mpm.h"
22
23#if !USING_2_1_RECENT
24extern server_rec *ap_server_conf;
25#endif
26
27#if APR_HAS_THREADS
28GCRY_THREAD_OPTION_PTHREAD_IMPL;
29#endif
30
31#if MOD_GNUTLS_DEBUG
32static apr_file_t *debug_log_fp;
33#endif
34
35static int mpm_is_threaded;
36
37static int mgs_cert_verify(request_rec * r, mgs_handle_t * ctxt);
38/* use side==0 for server and side==1 for client */
39static void mgs_add_common_cert_vars(request_rec * r, gnutls_x509_crt cert,
40                                     int side,
41                                     int export_certificates_enabled);
42
43static apr_status_t mgs_cleanup_pre_config(void *data)
44{
45    gnutls_global_deinit();
46    return APR_SUCCESS;
47}
48
49#if MOD_GNUTLS_DEBUG
50static void gnutls_debug_log_all(int level, const char *str)
51{
52    apr_file_printf(debug_log_fp, "<%d> %s\n", level, str);
53}
54#endif
55
56int
57mgs_hook_pre_config(apr_pool_t * pconf,
58                    apr_pool_t * plog, apr_pool_t * ptemp)
59{
60
61#if APR_HAS_THREADS
62    ap_mpm_query(AP_MPMQ_IS_THREADED, &mpm_is_threaded);
63    if (mpm_is_threaded) {
64        gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
65    }
66#else
67    mpm_is_threaded = 0;
68#endif
69
70    gnutls_global_init();
71
72    apr_pool_cleanup_register(pconf, NULL, mgs_cleanup_pre_config,
73                              apr_pool_cleanup_null);
74
75#if MOD_GNUTLS_DEBUG
76    apr_file_open(&debug_log_fp, "/tmp/gnutls_debug",
77                  APR_APPEND | APR_WRITE | APR_CREATE, APR_OS_DEFAULT,
78                  pconf);
79
80    gnutls_global_set_log_level(9);
81    gnutls_global_set_log_function(gnutls_debug_log_all);
82#endif
83
84    return OK;
85}
86
87
88static gnutls_datum
89load_params(const char *file, server_rec * s, apr_pool_t * pool)
90{
91    gnutls_datum ret = { NULL, 0 };
92    apr_file_t *fp;
93    apr_finfo_t finfo;
94    apr_status_t rv;
95    apr_size_t br = 0;
96
97    rv = apr_file_open(&fp, file, APR_READ | APR_BINARY, APR_OS_DEFAULT,
98                       pool);
99    if (rv != APR_SUCCESS) {
100        ap_log_error(APLOG_MARK, APLOG_STARTUP, rv, s,
101                     "GnuTLS failed to load params file at: %s. Will use internal params.",
102                     file);
103        return ret;
104    }
105
106    rv = apr_file_info_get(&finfo, APR_FINFO_SIZE, fp);
107
108    if (rv != APR_SUCCESS) {
109        ap_log_error(APLOG_MARK, APLOG_STARTUP, rv, s,
110                     "GnuTLS failed to stat params file at: %s", file);
111        return ret;
112    }
113
114    ret.data = apr_palloc(pool, finfo.size + 1);
115    rv = apr_file_read_full(fp, ret.data, finfo.size, &br);
116
117    if (rv != APR_SUCCESS) {
118        ap_log_error(APLOG_MARK, APLOG_STARTUP, rv, s,
119                     "GnuTLS failed to read params file at: %s", file);
120        return ret;
121    }
122    apr_file_close(fp);
123    ret.data[br] = '\0';
124    ret.size = br;
125
126    return ret;
127}
128
129/* We don't support openpgp certificates, yet */
130const static int cert_type_prio[2] = { GNUTLS_CRT_X509, 0 };
131
132static int mgs_select_virtual_server_cb(gnutls_session_t session)
133{
134    mgs_handle_t *ctxt;
135    mgs_srvconf_rec *tsc;
136    int ret;
137
138    ctxt = gnutls_transport_get_ptr(session);
139
140    /* find the virtual server */
141    tsc = mgs_find_sni_server(session);
142
143    if (tsc != NULL)
144        ctxt->sc = tsc;
145
146    gnutls_certificate_server_set_request(session,
147                                          ctxt->sc->client_verify_mode);
148
149    /* set the new server credentials
150     */
151
152    gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
153                           ctxt->sc->certs);
154
155    gnutls_credentials_set(session, GNUTLS_CRD_ANON, ctxt->sc->anon_creds);
156
157    if (ctxt->sc->srp_tpasswd_conf_file != NULL
158        && ctxt->sc->srp_tpasswd_file != NULL) {
159        gnutls_credentials_set(session, GNUTLS_CRD_SRP,
160                               ctxt->sc->srp_creds);
161    }
162
163    /* update the priorities - to avoid negotiating a ciphersuite that is not
164     * enabled on this virtual server. Note that here we ignore the version
165     * negotiation.
166     */
167    ret = gnutls_priority_set(session, ctxt->sc->priorities);
168    gnutls_certificate_type_set_priority(session, cert_type_prio);
169
170
171    /* actually it shouldn't fail since we have checked at startup */
172    if (ret < 0)
173        return ret;
174
175    /* allow separate caches per virtual host. Actually allowing the same is a
176     * bad idea, since they might have different security requirements.
177     */
178    mgs_cache_session_init(ctxt);
179
180    return 0;
181}
182
183static int cert_retrieve_fn(gnutls_session_t session, gnutls_retr_st * ret)
184{
185    mgs_handle_t *ctxt;
186
187    ctxt = gnutls_transport_get_ptr(session);
188
189    ret->type = GNUTLS_CRT_X509;
190    ret->ncerts = 1;
191    ret->deinit_all = 0;
192
193    ret->cert.x509 = &ctxt->sc->cert_x509;
194    ret->key.x509 = ctxt->sc->privkey_x509;
195    return 0;
196}
197
198const char static_dh_params[] = "-----BEGIN DH PARAMETERS-----\n"
199    "MIIBBwKCAQCsa9tBMkqam/Fm3l4TiVgvr3K2ZRmH7gf8MZKUPbVgUKNzKcu0oJnt\n"
200    "gZPgdXdnoT3VIxKrSwMxDc1/SKnaBP1Q6Ag5ae23Z7DPYJUXmhY6s2YaBfvV+qro\n"
201    "KRipli8Lk7hV+XmT7Jde6qgNdArb9P90c1nQQdXDPqcdKB5EaxR3O8qXtDoj+4AW\n"
202    "dr0gekNsZIHx0rkHhxdGGludMuaI+HdIVEUjtSSw1X1ep3onddLs+gMs+9v1L7N4\n"
203    "YWAnkATleuavh05zA85TKZzMBBx7wwjYKlaY86jQw4JxrjX46dv7tpS1yAPYn3rk\n"
204    "Nd4jbVJfVHWbZeNy/NaO8g+nER+eSv9zAgEC\n"
205    "-----END DH PARAMETERS-----\n";
206
207/* Read the common name or the alternative name of the certificate.
208 * We only support a single name per certificate.
209 *
210 * Returns negative on error.
211 */
212static int read_crt_cn(apr_pool_t * p, gnutls_x509_crt cert,
213                       char **cert_cn)
214{
215    int rv = 0, i;
216    size_t data_len;
217
218
219    *cert_cn = NULL;
220
221    rv = gnutls_x509_crt_get_dn_by_oid(cert,
222                                       GNUTLS_OID_X520_COMMON_NAME,
223                                       0, 0, NULL, &data_len);
224
225    if (rv >= 0 && data_len > 1) {
226        *cert_cn = apr_palloc(p, data_len);
227        rv = gnutls_x509_crt_get_dn_by_oid(cert,
228                                           GNUTLS_OID_X520_COMMON_NAME, 0,
229                                           0, *cert_cn, &data_len);
230    } else {                    /* No CN return subject alternative name */
231
232        /* read subject alternative name */
233        for (i = 0; !(rv < 0); i++) {
234            rv = gnutls_x509_crt_get_subject_alt_name(cert, i,
235                    NULL, &data_len, NULL);
236                   
237            if (rv == GNUTLS_SAN_DNSNAME) {
238                *cert_cn = apr_palloc(p, data_len);
239                rv = gnutls_x509_crt_get_subject_alt_name(cert, i,
240                    *cert_cn, &data_len, NULL);
241                break;
242
243            }
244        }
245    }
246   
247    return rv;
248
249}
250
251int
252mgs_hook_post_config(apr_pool_t * p, apr_pool_t * plog,
253                     apr_pool_t * ptemp, server_rec * base_server)
254{
255    int rv;
256    server_rec *s;
257    gnutls_dh_params_t dh_params;
258    gnutls_rsa_params_t rsa_params;
259    mgs_srvconf_rec *sc;
260    mgs_srvconf_rec *sc_base;
261    void *data = NULL;
262    int first_run = 0;
263    const char *userdata_key = "mgs_init";
264
265    apr_pool_userdata_get(&data, userdata_key, base_server->process->pool);
266    if (data == NULL) {
267        first_run = 1;
268        apr_pool_userdata_set((const void *) 1, userdata_key,
269                              apr_pool_cleanup_null,
270                              base_server->process->pool);
271    }
272
273
274    {
275        gnutls_datum pdata;
276        apr_pool_t *tpool;
277        s = base_server;
278        sc_base =
279            (mgs_srvconf_rec *) ap_get_module_config(s->module_config,
280                                                     &gnutls_module);
281
282        apr_pool_create(&tpool, p);
283
284        gnutls_dh_params_init(&dh_params);
285
286        pdata = load_params(sc_base->dh_params_file, s, tpool);
287
288        if (pdata.size != 0) {
289            rv = gnutls_dh_params_import_pkcs3(dh_params, &pdata,
290                                               GNUTLS_X509_FMT_PEM);
291            if (rv != 0) {
292                ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
293                             "GnuTLS: Unable to load DH Params: (%d) %s",
294                             rv, gnutls_strerror(rv));
295                exit(rv);
296            }
297        } else {
298            /* If the file does not exist use internal parameters
299             */
300            pdata.data = (void *) static_dh_params;
301            pdata.size = sizeof(static_dh_params);
302            rv = gnutls_dh_params_import_pkcs3(dh_params, &pdata,
303                                               GNUTLS_X509_FMT_PEM);
304
305            if (rv < 0) {
306                ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
307                             "GnuTLS: Unable to load internal DH Params."
308                             " Shutting down.");
309                exit(-1);
310            }
311        }
312        apr_pool_clear(tpool);
313
314        rsa_params = NULL;
315
316        pdata = load_params(sc_base->rsa_params_file, s, tpool);
317
318        if (pdata.size != 0) {
319            gnutls_rsa_params_init(&rsa_params);
320            rv = gnutls_rsa_params_import_pkcs1(rsa_params, &pdata,
321                                                GNUTLS_X509_FMT_PEM);
322            if (rv != 0) {
323                ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
324                             "GnuTLS: Unable to load RSA Params: (%d) %s",
325                             rv, gnutls_strerror(rv));
326                exit(rv);
327            }
328        }
329        /* not an error but RSA-EXPORT ciphersuites are not available
330         */
331
332        apr_pool_destroy(tpool);
333        rv = mgs_cache_post_config(p, s, sc_base);
334        if (rv != 0) {
335            ap_log_error(APLOG_MARK, APLOG_STARTUP, rv, s,
336                         "GnuTLS: Post Config for GnuTLSCache Failed."
337                         " Shutting Down.");
338            exit(-1);
339        }
340
341        for (s = base_server; s; s = s->next) {
342            sc = (mgs_srvconf_rec *) ap_get_module_config(s->module_config,
343                                                          &gnutls_module);
344            sc->cache_type = sc_base->cache_type;
345            sc->cache_config = sc_base->cache_config;
346
347            if (rsa_params != NULL)
348                gnutls_certificate_set_rsa_export_params(sc->certs,
349                                                         rsa_params);
350            gnutls_certificate_set_dh_params(sc->certs, dh_params);
351
352            gnutls_anon_set_server_dh_params(sc->anon_creds, dh_params);
353
354            gnutls_certificate_server_set_retrieve_function(sc->certs,
355                                                            cert_retrieve_fn);
356
357            if (sc->srp_tpasswd_conf_file != NULL
358                && sc->srp_tpasswd_file != NULL) {
359                gnutls_srp_set_server_credentials_file(sc->srp_creds,
360                                                       sc->
361                                                       srp_tpasswd_file,
362                                                       sc->
363                                                       srp_tpasswd_conf_file);
364            }
365
366            if (sc->cert_x509 == NULL
367                && sc->enabled == GNUTLS_ENABLED_TRUE) {
368                ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s,
369                             "[GnuTLS] - Host '%s:%d' is missing a "
370                             "Certificate File!", s->server_hostname,
371                             s->port);
372                exit(-1);
373            }
374
375            if (sc->privkey_x509 == NULL
376                && sc->enabled == GNUTLS_ENABLED_TRUE) {
377                ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s,
378                             "[GnuTLS] - Host '%s:%d' is missing a "
379                             "Private Key File!",
380                             s->server_hostname, s->port);
381                exit(-1);
382            }
383
384            if (sc->enabled == GNUTLS_ENABLED_TRUE) {
385                rv = read_crt_cn(p, sc->cert_x509, &sc->cert_cn);
386                if (rv < 0) {
387                    sc->enabled = GNUTLS_ENABLED_FALSE;
388                    sc->cert_cn = NULL;
389                    continue;
390                }
391            }
392        }
393    }
394
395    ap_add_version_component(p, "mod_gnutls/" MOD_GNUTLS_VERSION);
396
397    return OK;
398}
399
400void mgs_hook_child_init(apr_pool_t * p, server_rec * s)
401{
402    apr_status_t rv = APR_SUCCESS;
403    mgs_srvconf_rec *sc = ap_get_module_config(s->module_config,
404                                               &gnutls_module);
405
406    if (sc->cache_type != mgs_cache_none) {
407        rv = mgs_cache_child_init(p, s, sc);
408        if (rv != APR_SUCCESS) {
409            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
410                         "[GnuTLS] - Failed to run Cache Init");
411        }
412    } else {
413        ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
414                     "[GnuTLS] - No Cache Configured. Hint: GnuTLSCache");
415    }
416}
417
418const char *mgs_hook_http_scheme(const request_rec * r)
419{
420    mgs_srvconf_rec *sc =
421        (mgs_srvconf_rec *) ap_get_module_config(r->server->module_config,
422                                                 &gnutls_module);
423
424    if (sc->enabled == GNUTLS_ENABLED_FALSE) {
425        return NULL;
426    }
427
428    return "https";
429}
430
431apr_port_t mgs_hook_default_port(const request_rec * r)
432{
433    mgs_srvconf_rec *sc =
434        (mgs_srvconf_rec *) ap_get_module_config(r->server->module_config,
435                                                 &gnutls_module);
436
437    if (sc->enabled == GNUTLS_ENABLED_FALSE) {
438        return 0;
439    }
440
441    return 443;
442}
443
444#define MAX_HOST_LEN 255
445
446#if USING_2_1_RECENT
447typedef struct {
448    mgs_handle_t *ctxt;
449    mgs_srvconf_rec *sc;
450    const char *sni_name;
451} vhost_cb_rec;
452
453static int vhost_cb(void *baton, conn_rec * conn, server_rec * s)
454{
455    mgs_srvconf_rec *tsc;
456    vhost_cb_rec *x = baton;
457
458    tsc = (mgs_srvconf_rec *) ap_get_module_config(s->module_config,
459                                                   &gnutls_module);
460
461    if (tsc->enabled != GNUTLS_ENABLED_TRUE || tsc->cert_cn == NULL) {
462        return 0;
463    }
464
465    /* The CN can contain a * -- this will match those too. */
466    if (ap_strcasecmp_match(x->sni_name, tsc->cert_cn) == 0) {
467        /* found a match */
468#if MOD_GNUTLS_DEBUG
469        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
470                     x->ctxt->c->base_server,
471                     "GnuTLS: Virtual Host CB: "
472                     "'%s' == '%s'", tsc->cert_cn, x->sni_name);
473#endif
474        /* Because we actually change the server used here, we need to reset
475         * things like ClientVerify.
476         */
477        x->sc = tsc;
478        /* Shit. Crap. Dammit. We *really* should rehandshake here, as our
479         * certificate structure *should* change when the server changes.
480         * acccckkkkkk.
481         */
482        return 1;
483    }
484    return 0;
485}
486#endif
487
488mgs_srvconf_rec *mgs_find_sni_server(gnutls_session_t session)
489{
490    int rv;
491    unsigned int sni_type;
492    size_t data_len = MAX_HOST_LEN;
493    char sni_name[MAX_HOST_LEN];
494    mgs_handle_t *ctxt;
495#if USING_2_1_RECENT
496    vhost_cb_rec cbx;
497#else
498    server_rec *s;
499    mgs_srvconf_rec *tsc;
500#endif
501
502    ctxt = gnutls_transport_get_ptr(session);
503
504    sni_type = gnutls_certificate_type_get(session);
505    if (sni_type != GNUTLS_CRT_X509) {
506        /* In theory, we could support OpenPGP Certificates. Theory != code. */
507        ap_log_error(APLOG_MARK, APLOG_CRIT, 0,
508                     ctxt->c->base_server,
509                     "GnuTLS: Only x509 Certificates are currently supported.");
510        return NULL;
511    }
512
513    rv = gnutls_server_name_get(ctxt->session, sni_name,
514                                &data_len, &sni_type, 0);
515
516    if (rv != 0) {
517        return NULL;
518    }
519
520    if (sni_type != GNUTLS_NAME_DNS) {
521        ap_log_error(APLOG_MARK, APLOG_CRIT, 0,
522                     ctxt->c->base_server,
523                     "GnuTLS: Unknown type '%d' for SNI: "
524                     "'%s'", sni_type, sni_name);
525        return NULL;
526    }
527
528    /**
529     * Code in the Core already sets up the c->base_server as the base
530     * for this IP/Port combo.  Trust that the core did the 'right' thing.
531     */
532#if USING_2_1_RECENT
533    cbx.ctxt = ctxt;
534    cbx.sc = NULL;
535    cbx.sni_name = sni_name;
536
537    rv = ap_vhost_iterate_given_conn(ctxt->c, vhost_cb, &cbx);
538    if (rv == 1) {
539        return cbx.sc;
540    }
541#else
542    for (s = ap_server_conf; s; s = s->next) {
543
544        tsc = (mgs_srvconf_rec *) ap_get_module_config(s->module_config,
545                                                       &gnutls_module);
546        if (tsc->enabled != GNUTLS_ENABLED_TRUE) {
547            continue;
548        }
549#if MOD_GNUTLS_DEBUG
550        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
551                     ctxt->c->base_server,
552                     "GnuTLS: sni-x509 cn: %s/%d pk: %s s: 0x%08X s->n: 0x%08X  sc: 0x%08X",
553                     tsc->cert_cn, rv,
554                     gnutls_pk_algorithm_get_name
555                     (gnutls_x509_privkey_get_pk_algorithm
556                      (ctxt->sc->privkey_x509)), (unsigned int) s,
557                     (unsigned int) s->next, (unsigned int) tsc);
558#endif
559        /* The CN can contain a * -- this will match those too. */
560        if (ap_strcasecmp_match(sni_name, tsc->cert_cn) == 0) {
561#if MOD_GNUTLS_DEBUG
562            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
563                         ctxt->c->base_server,
564                         "GnuTLS: Virtual Host: "
565                         "'%s' == '%s'", tsc->cert_cn, sni_name);
566#endif
567            return tsc;
568        }
569    }
570#endif
571    return NULL;
572}
573
574
575static const int protocol_priority[] = {
576    GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0
577};
578
579
580static mgs_handle_t *create_gnutls_handle(apr_pool_t * pool, conn_rec * c)
581{
582    mgs_handle_t *ctxt;
583    mgs_srvconf_rec *sc =
584        (mgs_srvconf_rec *) ap_get_module_config(c->base_server->
585                                                 module_config,
586                                                 &gnutls_module);
587
588    ctxt = apr_pcalloc(pool, sizeof(*ctxt));
589    ctxt->c = c;
590    ctxt->sc = sc;
591    ctxt->status = 0;
592
593    ctxt->input_rc = APR_SUCCESS;
594    ctxt->input_bb = apr_brigade_create(c->pool, c->bucket_alloc);
595    ctxt->input_cbuf.length = 0;
596
597    ctxt->output_rc = APR_SUCCESS;
598    ctxt->output_bb = apr_brigade_create(c->pool, c->bucket_alloc);
599    ctxt->output_blen = 0;
600    ctxt->output_length = 0;
601
602    gnutls_init(&ctxt->session, GNUTLS_SERVER);
603
604    /* This is not very good as it trades security for compatibility,
605     * but it is the only way to be ultra-portable.
606     */
607    gnutls_session_enable_compatibility_mode(ctxt->session);
608
609    /* because we don't set any default priorities here (we set later at
610     * the user hello callback) we need to at least set this in order for
611     * gnutls to be able to read packets.
612     */
613    gnutls_protocol_set_priority(ctxt->session, protocol_priority);
614
615    gnutls_handshake_set_post_client_hello_function(ctxt->session,
616                                                    mgs_select_virtual_server_cb);
617
618    return ctxt;
619}
620
621int mgs_hook_pre_connection(conn_rec * c, void *csd)
622{
623    mgs_handle_t *ctxt;
624    mgs_srvconf_rec *sc =
625        (mgs_srvconf_rec *) ap_get_module_config(c->base_server->
626                                                 module_config,
627                                                 &gnutls_module);
628
629    if (!(sc && (sc->enabled == GNUTLS_ENABLED_TRUE))) {
630        return DECLINED;
631    }
632
633    ctxt = create_gnutls_handle(c->pool, c);
634
635    ap_set_module_config(c->conn_config, &gnutls_module, ctxt);
636
637    gnutls_transport_set_pull_function(ctxt->session, mgs_transport_read);
638    gnutls_transport_set_push_function(ctxt->session, mgs_transport_write);
639    gnutls_transport_set_ptr(ctxt->session, ctxt);
640
641    ctxt->input_filter =
642        ap_add_input_filter(GNUTLS_INPUT_FILTER_NAME, ctxt, NULL, c);
643    ctxt->output_filter =
644        ap_add_output_filter(GNUTLS_OUTPUT_FILTER_NAME, ctxt, NULL, c);
645
646    return OK;
647}
648
649int mgs_hook_fixups(request_rec * r)
650{
651    unsigned char sbuf[GNUTLS_MAX_SESSION_ID];
652    char buf[AP_IOBUFSIZE];
653    const char *tmp;
654    size_t len;
655    mgs_handle_t *ctxt;
656    int rv = OK;
657
658    apr_table_t *env = r->subprocess_env;
659
660    ctxt =
661        ap_get_module_config(r->connection->conn_config, &gnutls_module);
662
663    if (!ctxt) {
664        return DECLINED;
665    }
666
667    apr_table_setn(env, "HTTPS", "on");
668
669    apr_table_setn(env, "SSL_VERSION_LIBRARY",
670                   "GnuTLS/" LIBGNUTLS_VERSION);
671    apr_table_setn(env, "SSL_VERSION_INTERFACE",
672                   "mod_gnutls/" MOD_GNUTLS_VERSION);
673
674    apr_table_setn(env, "SSL_PROTOCOL",
675                   gnutls_protocol_get_name(gnutls_protocol_get_version
676                                            (ctxt->session)));
677
678    /* should have been called SSL_CIPHERSUITE instead */
679    apr_table_setn(env, "SSL_CIPHER",
680                   gnutls_cipher_suite_get_name(gnutls_kx_get
681                                                (ctxt->session),
682                                                gnutls_cipher_get(ctxt->
683                                                                  session),
684                                                gnutls_mac_get(ctxt->
685                                                               session)));
686
687    apr_table_setn(env, "SSL_COMPRESS_METHOD",
688                   gnutls_compression_get_name(gnutls_compression_get
689                                               (ctxt->session)));
690
691    apr_table_setn(env, "SSL_SRP_USER",
692                   gnutls_srp_server_get_username(ctxt->session));
693
694    if (apr_table_get(env, "SSL_CLIENT_VERIFY") == NULL)
695        apr_table_setn(env, "SSL_CLIENT_VERIFY", "NONE");
696
697    unsigned int key_size =
698        8 * gnutls_cipher_get_key_size(gnutls_cipher_get(ctxt->session));
699    tmp = apr_psprintf(r->pool, "%u", key_size);
700
701    apr_table_setn(env, "SSL_CIPHER_USEKEYSIZE", tmp);
702
703    apr_table_setn(env, "SSL_CIPHER_ALGKEYSIZE", tmp);
704
705    apr_table_setn(env, "SSL_CIPHER_EXPORT",
706                   (key_size <= 40) ? "true" : "false");
707
708    len = sizeof(sbuf);
709    gnutls_session_get_id(ctxt->session, sbuf, &len);
710    tmp = mgs_session_id2sz(sbuf, len, buf, sizeof(buf));
711    apr_table_setn(env, "SSL_SESSION_ID", apr_pstrdup(r->pool, tmp));
712
713    mgs_add_common_cert_vars(r, ctxt->sc->cert_x509, 0,
714                             ctxt->sc->export_certificates_enabled);
715
716    return rv;
717}
718
719int mgs_hook_authz(request_rec * r)
720{
721    int rv;
722    mgs_handle_t *ctxt;
723    mgs_dirconf_rec *dc = ap_get_module_config(r->per_dir_config,
724                                               &gnutls_module);
725
726    ctxt =
727        ap_get_module_config(r->connection->conn_config, &gnutls_module);
728
729    if (!ctxt) {
730        return DECLINED;
731    }
732
733    if (dc->client_verify_mode == GNUTLS_CERT_IGNORE) {
734        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
735                      "GnuTLS: Directory set to Ignore Client Certificate!");
736    } else {
737        if (ctxt->sc->client_verify_mode < dc->client_verify_mode) {
738            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
739                          "GnuTLS: Attempting to rehandshake with peer. %d %d",
740                          ctxt->sc->client_verify_mode,
741                          dc->client_verify_mode);
742
743            gnutls_certificate_server_set_request(ctxt->session,
744                                                  dc->client_verify_mode);
745
746            if (mgs_rehandshake(ctxt) != 0) {
747                return HTTP_FORBIDDEN;
748            }
749        } else if (ctxt->sc->client_verify_mode == GNUTLS_CERT_IGNORE) {
750#if MOD_GNUTLS_DEBUG
751            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
752                          "GnuTLS: Peer is set to IGNORE");
753#endif
754        } else {
755            rv = mgs_cert_verify(r, ctxt);
756            if (rv != DECLINED) {
757                return rv;
758            }
759        }
760    }
761
762    return DECLINED;
763}
764
765/* variables that are not sent by default:
766 *
767 * SSL_CLIENT_CERT      string  PEM-encoded client certificate
768 * SSL_SERVER_CERT      string  PEM-encoded client certificate
769 */
770
771/* side is either 0 for SERVER or 1 for CLIENT
772 */
773#define MGS_SIDE ((side==0)?"SSL_SERVER":"SSL_CLIENT")
774static void
775mgs_add_common_cert_vars(request_rec * r, gnutls_x509_crt cert, int side,
776                         int export_certificates_enabled)
777{
778    unsigned char sbuf[64];     /* buffer to hold serials */
779    char buf[AP_IOBUFSIZE];
780    const char *tmp;
781    size_t len;
782    int alg;
783
784    apr_table_t *env = r->subprocess_env;
785
786    if (export_certificates_enabled != 0) {
787        char cert_buf[10 * 1024];
788        len = sizeof(cert_buf);
789
790        if (gnutls_x509_crt_export
791            (cert, GNUTLS_X509_FMT_PEM, cert_buf, &len) >= 0)
792            apr_table_setn(env,
793                           apr_pstrcat(r->pool, MGS_SIDE, "_CERT", NULL),
794                           apr_pstrmemdup(r->pool, cert_buf, len));
795
796    }
797
798    len = sizeof(buf);
799    gnutls_x509_crt_get_dn(cert, buf, &len);
800    apr_table_setn(env, apr_pstrcat(r->pool, MGS_SIDE, "_S_DN", NULL),
801                   apr_pstrmemdup(r->pool, buf, len));
802
803    len = sizeof(buf);
804    gnutls_x509_crt_get_issuer_dn(cert, buf, &len);
805    apr_table_setn(env, apr_pstrcat(r->pool, MGS_SIDE, "_I_DN", NULL),
806                   apr_pstrmemdup(r->pool, buf, len));
807
808    len = sizeof(sbuf);
809    gnutls_x509_crt_get_serial(cert, sbuf, &len);
810    tmp = mgs_session_id2sz(sbuf, len, buf, sizeof(buf));
811    apr_table_setn(env, apr_pstrcat(r->pool, MGS_SIDE, "_M_SERIAL", NULL),
812                   apr_pstrdup(r->pool, tmp));
813
814    tmp =
815        mgs_time2sz(gnutls_x509_crt_get_expiration_time
816                    (cert), buf, sizeof(buf));
817    apr_table_setn(env, apr_pstrcat(r->pool, MGS_SIDE, "_V_END", NULL),
818                   apr_pstrdup(r->pool, tmp));
819
820    tmp =
821        mgs_time2sz(gnutls_x509_crt_get_activation_time
822                    (cert), buf, sizeof(buf));
823    apr_table_setn(env, apr_pstrcat(r->pool, MGS_SIDE, "_V_START", NULL),
824                   apr_pstrdup(r->pool, tmp));
825
826    alg = gnutls_x509_crt_get_signature_algorithm(cert);
827    if (alg >= 0) {
828        apr_table_setn(env, apr_pstrcat(r->pool, MGS_SIDE, "_A_SIG", NULL),
829                       gnutls_sign_algorithm_get_name(alg));
830    }
831
832    alg = gnutls_x509_crt_get_pk_algorithm(cert, NULL);
833    if (alg >= 0) {
834        apr_table_setn(env, apr_pstrcat(r->pool, MGS_SIDE, "_A_KEY", NULL),
835                       gnutls_pk_algorithm_get_name(alg));
836    }
837
838
839}
840
841
842static int mgs_cert_verify(request_rec * r, mgs_handle_t * ctxt)
843{
844    const gnutls_datum_t *cert_list;
845    unsigned int cert_list_size, status, expired;
846    int rv, ret;
847    gnutls_x509_crt_t cert;
848    apr_time_t activation_time, expiration_time, cur_time;
849
850    cert_list =
851        gnutls_certificate_get_peers(ctxt->session, &cert_list_size);
852
853    if (cert_list == NULL || cert_list_size == 0) {
854        /* It is perfectly OK for a client not to send a certificate if on REQUEST mode
855         */
856        if (ctxt->sc->client_verify_mode == GNUTLS_CERT_REQUEST)
857            return OK;
858
859        /* no certificate provided by the client, but one was required. */
860        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
861                      "GnuTLS: Failed to Verify Peer: "
862                      "Client did not submit a certificate");
863        return HTTP_FORBIDDEN;
864    }
865
866    if (cert_list_size > 1) {
867        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
868                      "GnuTLS: Failed to Verify Peer: "
869                      "Chained Client Certificates are not supported.");
870        return HTTP_FORBIDDEN;
871    }
872
873    gnutls_x509_crt_init(&cert);
874    rv = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
875    if (rv < 0) {
876        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
877                      "GnuTLS: Failed to Verify Peer: "
878                      "Failed to import peer certificates.");
879        ret = HTTP_FORBIDDEN;
880        goto exit;
881    }
882
883    apr_time_ansi_put(&expiration_time,
884                      gnutls_x509_crt_get_expiration_time(cert));
885    apr_time_ansi_put(&activation_time,
886                      gnutls_x509_crt_get_activation_time(cert));
887
888    rv = gnutls_x509_crt_verify(cert, ctxt->sc->ca_list,
889                                ctxt->sc->ca_list_size, 0, &status);
890
891    if (rv < 0) {
892        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
893                      "GnuTLS: Failed to Verify Peer certificate: (%d) %s",
894                      rv, gnutls_strerror(rv));
895        ret = HTTP_FORBIDDEN;
896        goto exit;
897    }
898
899    expired = 0;
900    cur_time = apr_time_now();
901    if (activation_time > cur_time) {
902        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
903                      "GnuTLS: Failed to Verify Peer: "
904                      "Peer Certificate is not yet activated.");
905        expired = 1;
906    }
907
908    if (expiration_time < cur_time) {
909        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
910                      "GnuTLS: Failed to Verify Peer: "
911                      "Peer Certificate is expired.");
912        expired = 1;
913    }
914
915    if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) {
916        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
917                      "GnuTLS: Could not find Signer for Peer Certificate");
918    }
919
920    if (status & GNUTLS_CERT_SIGNER_NOT_CA) {
921        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
922                      "GnuTLS: Peer's Certificate signer is not a CA");
923    }
924
925    if (status & GNUTLS_CERT_INVALID) {
926        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
927                      "GnuTLS: Peer Certificate is invalid.");
928    } else if (status & GNUTLS_CERT_REVOKED) {
929        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
930                      "GnuTLS: Peer Certificate is revoked.");
931    }
932
933    /* TODO: Further Verification. */
934    /* Revocation is X.509 non workable paradigm, I really doubt implementation
935     * is worth doing --nmav
936     */
937/// ret = gnutls_x509_crt_check_revocation(crt, crl_list, crl_list_size);
938
939//    mgs_hook_fixups(r);
940//    rv = mgs_authz_lua(r);
941
942    mgs_add_common_cert_vars(r, cert, 1,
943                             ctxt->sc->export_certificates_enabled);
944
945    {
946        /* days remaining */
947        unsigned long remain =
948            (apr_time_sec(expiration_time) -
949             apr_time_sec(cur_time)) / 86400;
950        apr_table_setn(r->subprocess_env, "SSL_CLIENT_V_REMAIN",
951                       apr_psprintf(r->pool, "%lu", remain));
952    }
953
954    if (status == 0 && expired == 0) {
955        apr_table_setn(r->subprocess_env, "SSL_CLIENT_VERIFY", "SUCCESS");
956        ret = OK;
957    } else {
958        apr_table_setn(r->subprocess_env, "SSL_CLIENT_VERIFY", "FAILED");
959        if (ctxt->sc->client_verify_mode == GNUTLS_CERT_REQUEST)
960            ret = OK;
961        else
962            ret = HTTP_FORBIDDEN;
963    }
964
965  exit:
966    gnutls_x509_crt_deinit(cert);
967    return ret;
968
969
970}
Note: See TracBrowser for help on using the repository browser.