source: mod_gnutls/src/gnutls_hooks.c @ b077bdd

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

added more error checks.

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