source: mod_gnutls/src/gnutls_hooks.c @ 36736d4

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

added SSL_SERVER/CLIENT_S_TYPE

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