source: mod_gnutls/src/gnutls_hooks.c @ 619953c

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