source: mod_gnutls/src/gnutls_hooks.c @ ee65fcb

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

added SSL_SERVER_M_SERIAL environment variable

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