1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements.  See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License.  You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*                      _             _
18 *  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
19 * | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
20 * | | | | | | (_) | (_| |   \__ \__ \ |
21 * |_| |_| |_|\___/ \__,_|___|___/___/_|
22 *                      |_____|
23 *  ssl_engine_init.c
24 *  Initialization of Servers
25 */
26                             /* ``Recursive, adj.;
27                                  see Recursive.''
28                                        -- Unknown   */
29#include "ssl_private.h"
30
31/*  _________________________________________________________________
32**
33**  Module Initialization
34**  _________________________________________________________________
35*/
36
37
38static void ssl_add_version_components(apr_pool_t *p,
39                                       server_rec *s)
40{
41    char *modver = ssl_var_lookup(p, s, NULL, NULL, "SSL_VERSION_INTERFACE");
42    char *libver = ssl_var_lookup(p, s, NULL, NULL, "SSL_VERSION_LIBRARY");
43    char *incver = ssl_var_lookup(p, s, NULL, NULL,
44                                  "SSL_VERSION_LIBRARY_INTERFACE");
45
46    ap_add_version_component(p, modver);
47    ap_add_version_component(p, libver);
48
49    ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
50                 "%s compiled against Server: %s, Library: %s",
51                 modver, AP_SERVER_BASEVERSION, incver);
52}
53
54
55/*
56 * Handle the Temporary RSA Keys and DH Params
57 */
58
59#define MODSSL_TMP_KEY_FREE(mc, type, idx) \
60    if (mc->pTmpKeys[idx]) { \
61        type##_free((type *)mc->pTmpKeys[idx]); \
62        mc->pTmpKeys[idx] = NULL; \
63    }
64
65#define MODSSL_TMP_KEYS_FREE(mc, type) \
66    MODSSL_TMP_KEY_FREE(mc, type, SSL_TMP_KEY_##type##_512); \
67    MODSSL_TMP_KEY_FREE(mc, type, SSL_TMP_KEY_##type##_1024)
68
69static void ssl_tmp_keys_free(server_rec *s)
70{
71    SSLModConfigRec *mc = myModConfig(s);
72
73    MODSSL_TMP_KEYS_FREE(mc, RSA);
74    MODSSL_TMP_KEYS_FREE(mc, DH);
75#ifndef OPENSSL_NO_EC
76    MODSSL_TMP_KEY_FREE(mc, EC_KEY, SSL_TMP_KEY_EC_256);
77#endif
78}
79
80static int ssl_tmp_key_init_rsa(server_rec *s,
81                                int bits, int idx)
82{
83    SSLModConfigRec *mc = myModConfig(s);
84
85#ifdef HAVE_FIPS
86
87    if (FIPS_mode() && bits < 1024) {
88        mc->pTmpKeys[idx] = NULL;
89        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
90                     "Init: Skipping generating temporary "
91                     "%d bit RSA private key in FIPS mode", bits);
92        return OK;
93    }
94
95#endif
96
97    if (!(mc->pTmpKeys[idx] =
98          RSA_generate_key(bits, RSA_F4, NULL, NULL)))
99    {
100        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
101                     "Init: Failed to generate temporary "
102                     "%d bit RSA private key", bits);
103        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
104        return !OK;
105    }
106
107    return OK;
108}
109
110static int ssl_tmp_key_init_dh(server_rec *s,
111                               int bits, int idx)
112{
113    SSLModConfigRec *mc = myModConfig(s);
114
115#ifdef HAVE_FIPS
116
117    if (FIPS_mode() && bits < 1024) {
118        mc->pTmpKeys[idx] = NULL;
119        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
120                     "Init: Skipping generating temporary "
121                     "%d bit DH parameters in FIPS mode", bits);
122        return OK;
123    }
124
125#endif
126
127    if (!(mc->pTmpKeys[idx] =
128          ssl_dh_GetTmpParam(bits)))
129    {
130        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
131                     "Init: Failed to generate temporary "
132                     "%d bit DH parameters", bits);
133        return !OK;
134    }
135
136    return OK;
137}
138
139#ifndef OPENSSL_NO_EC
140static int ssl_tmp_key_init_ec(server_rec *s,
141                               int bits, int idx)
142{
143    SSLModConfigRec *mc = myModConfig(s);
144    EC_KEY *ecdh = NULL;
145
146    /* XXX: Are there any FIPS constraints we should enforce? */
147
148    if (bits != 256) {
149        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
150                     "Init: Failed to generate temporary "
151                     "%d bit EC parameters, only 256 bits supported", bits);
152        return !OK;
153    }
154
155    if ((ecdh = EC_KEY_new()) == NULL ||
156        EC_KEY_set_group(ecdh, EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)) != 1)
157    {
158        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
159                     "Init: Failed to generate temporary "
160                     "%d bit EC parameters", bits);
161        return !OK;
162    }
163
164    mc->pTmpKeys[idx] = ecdh;
165    return OK;
166}
167
168#define MODSSL_TMP_KEY_INIT_EC(s, bits) \
169    ssl_tmp_key_init_ec(s, bits, SSL_TMP_KEY_EC_##bits)
170
171#endif
172
173#define MODSSL_TMP_KEY_INIT_RSA(s, bits) \
174    ssl_tmp_key_init_rsa(s, bits, SSL_TMP_KEY_RSA_##bits)
175
176#define MODSSL_TMP_KEY_INIT_DH(s, bits) \
177    ssl_tmp_key_init_dh(s, bits, SSL_TMP_KEY_DH_##bits)
178
179static int ssl_tmp_keys_init(server_rec *s)
180{
181    ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
182                 "Init: Generating temporary RSA private keys (512/1024 bits)");
183
184    if (MODSSL_TMP_KEY_INIT_RSA(s, 512) ||
185        MODSSL_TMP_KEY_INIT_RSA(s, 1024)) {
186        return !OK;
187    }
188
189    ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
190                 "Init: Generating temporary DH parameters (512/1024 bits)");
191
192    if (MODSSL_TMP_KEY_INIT_DH(s, 512) ||
193        MODSSL_TMP_KEY_INIT_DH(s, 1024)) {
194        return !OK;
195    }
196
197#ifndef OPENSSL_NO_EC
198    ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
199                 "Init: Generating temporary EC parameters (256 bits)");
200
201    if (MODSSL_TMP_KEY_INIT_EC(s, 256)) {
202        return !OK;
203    }
204#endif
205
206    return OK;
207}
208
209/*
210 *  Per-module initialization
211 */
212int ssl_init_Module(apr_pool_t *p, apr_pool_t *plog,
213                    apr_pool_t *ptemp,
214                    server_rec *base_server)
215{
216    SSLModConfigRec *mc = myModConfig(base_server);
217    SSLSrvConfigRec *sc;
218    server_rec *s;
219
220    /* We initialize mc->pid per-process in the child init,
221     * but it should be initialized for startup before we
222     * call ssl_rand_seed() below.
223     */
224    mc->pid = getpid();
225
226    /*
227     * Let us cleanup on restarts and exists
228     */
229    apr_pool_cleanup_register(p, base_server,
230                              ssl_init_ModuleKill,
231                              apr_pool_cleanup_null);
232
233    /*
234     * Any init round fixes the global config
235     */
236    ssl_config_global_create(base_server); /* just to avoid problems */
237    ssl_config_global_fix(mc);
238
239    /*
240     *  try to fix the configuration and open the dedicated SSL
241     *  logfile as early as possible
242     */
243    for (s = base_server; s; s = s->next) {
244        sc = mySrvConfig(s);
245
246        if (sc->server) {
247            sc->server->sc = sc;
248        }
249
250        if (sc->proxy) {
251            sc->proxy->sc = sc;
252        }
253
254        /*
255         * Create the server host:port string because we need it a lot
256         */
257        sc->vhost_id = ssl_util_vhostid(p, s);
258        sc->vhost_id_len = strlen(sc->vhost_id);
259
260        if (ap_get_server_protocol(s) &&
261            strcmp("https", ap_get_server_protocol(s)) == 0) {
262            sc->enabled = SSL_ENABLED_TRUE;
263        }
264
265       /* If sc->enabled is UNSET, then SSL is optional on this vhost  */
266        /* Fix up stuff that may not have been set */
267        if (sc->enabled == SSL_ENABLED_UNSET) {
268            sc->enabled = SSL_ENABLED_FALSE;
269        }
270        if (sc->proxy_enabled == UNSET) {
271            sc->proxy_enabled = FALSE;
272        }
273
274        if (sc->session_cache_timeout == UNSET) {
275            sc->session_cache_timeout = SSL_SESSION_CACHE_TIMEOUT;
276        }
277
278        if (sc->server->pphrase_dialog_type == SSL_PPTYPE_UNSET) {
279            sc->server->pphrase_dialog_type = SSL_PPTYPE_BUILTIN;
280        }
281
282#ifdef HAVE_FIPS
283        if (sc->fips == UNSET) {
284            sc->fips = FALSE;
285        }
286#endif
287    }
288
289#if APR_HAS_THREADS
290    ssl_util_thread_setup(p);
291#endif
292
293    /*
294     * SSL external crypto device ("engine") support
295     */
296#if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
297    ssl_init_Engine(base_server, p);
298#endif
299
300    ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
301                 "Init: Initialized %s library", SSL_LIBRARY_NAME);
302
303    /*
304     * Seed the Pseudo Random Number Generator (PRNG)
305     * only need ptemp here; nothing inside allocated from the pool
306     * needs to live once we return from ssl_rand_seed().
307     */
308    ssl_rand_seed(base_server, ptemp, SSL_RSCTX_STARTUP, "Init: ");
309
310#ifdef HAVE_FIPS
311    if(sc->fips) {
312        if (!FIPS_mode()) {
313            if (FIPS_mode_set(1)) {
314                ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
315                             "Operating in SSL FIPS mode");
316            }
317            else {
318                ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, "FIPS mode failed");
319                ssl_log_ssl_error(APLOG_MARK, APLOG_EMERG, s);
320                ssl_die();
321            }
322        }
323    }
324    else {
325        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
326                     "SSL FIPS mode disabled");
327    }
328#endif
329
330    /*
331     * read server private keys/public certs into memory.
332     * decrypting any encrypted keys via configured SSLPassPhraseDialogs
333     * anything that needs to live longer than ptemp needs to also survive
334     * restarts, in which case they'll live inside s->process->pool.
335     */
336    ssl_pphrase_Handle(base_server, ptemp);
337
338    if (ssl_tmp_keys_init(base_server)) {
339        return !OK;
340    }
341
342    /*
343     * initialize the mutex handling
344     */
345    if (!ssl_mutex_init(base_server, p)) {
346        return HTTP_INTERNAL_SERVER_ERROR;
347    }
348
349    /*
350     * initialize session caching
351     */
352    ssl_scache_init(base_server, p);
353
354    /*
355     *  initialize servers
356     */
357    ap_log_error(APLOG_MARK, APLOG_INFO, 0, base_server,
358                 "Init: Initializing (virtual) servers for SSL");
359
360    for (s = base_server; s; s = s->next) {
361        sc = mySrvConfig(s);
362        /*
363         * Either now skip this server when SSL is disabled for
364         * it or give out some information about what we're
365         * configuring.
366         */
367
368        /*
369         * Read the server certificate and key
370         */
371        ssl_init_ConfigureServer(s, p, ptemp, sc);
372    }
373
374    /*
375     * Configuration consistency checks
376     */
377    ssl_init_CheckServers(base_server, ptemp);
378
379    /*
380     *  Announce mod_ssl and SSL library in HTTP Server field
381     *  as ``mod_ssl/X.X.X OpenSSL/X.X.X''
382     */
383    ssl_add_version_components(p, base_server);
384
385    SSL_init_app_data2_idx(); /* for SSL_get_app_data2() at request time */
386
387    return OK;
388}
389
390/*
391 * Support for external a Crypto Device ("engine"), usually
392 * a hardware accellerator card for crypto operations.
393 */
394#if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
395void ssl_init_Engine(server_rec *s, apr_pool_t *p)
396{
397    SSLModConfigRec *mc = myModConfig(s);
398    ENGINE *e;
399
400    if (mc->szCryptoDevice) {
401        if (!(e = ENGINE_by_id(mc->szCryptoDevice))) {
402            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
403                         "Init: Failed to load Crypto Device API `%s'",
404                         mc->szCryptoDevice);
405            ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
406            ssl_die();
407        }
408
409        if (strEQ(mc->szCryptoDevice, "chil")) {
410            ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
411        }
412
413        if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
414            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
415                         "Init: Failed to enable Crypto Device API `%s'",
416                         mc->szCryptoDevice);
417            ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
418            ssl_die();
419        }
420        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
421                     "Init: loaded Crypto Device API `%s'",
422                     mc->szCryptoDevice);
423
424        ENGINE_free(e);
425    }
426}
427#endif
428
429static void ssl_init_server_check(server_rec *s,
430                                  apr_pool_t *p,
431                                  apr_pool_t *ptemp,
432                                  modssl_ctx_t *mctx)
433{
434    /*
435     * check for important parameters and the
436     * possibility that the user forgot to set them.
437     */
438    if (!mctx->pks->cert_files[0]) {
439        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
440                "No SSL Certificate set [hint: SSLCertificateFile]");
441        ssl_die();
442    }
443
444    /*
445     *  Check for problematic re-initializations
446     */
447    if (mctx->pks->certs[SSL_AIDX_RSA] ||
448        mctx->pks->certs[SSL_AIDX_DSA]
449#ifndef OPENSSL_NO_EC
450      || mctx->pks->certs[SSL_AIDX_ECC]
451#endif
452        )
453    {
454        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
455                "Illegal attempt to re-initialise SSL for server "
456                "(SSLEngine On should go in the VirtualHost, not in global scope.)");
457        ssl_die();
458    }
459}
460
461#ifndef OPENSSL_NO_TLSEXT
462static void ssl_init_ctx_tls_extensions(server_rec *s,
463                                        apr_pool_t *p,
464                                        apr_pool_t *ptemp,
465                                        modssl_ctx_t *mctx)
466{
467    /*
468     * Configure TLS extensions support
469     */
470    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
471                 "Configuring TLS extension handling");
472
473    /*
474     * Server name indication (SNI)
475     */
476    if (!SSL_CTX_set_tlsext_servername_callback(mctx->ssl_ctx,
477                          ssl_callback_ServerNameIndication) ||
478        !SSL_CTX_set_tlsext_servername_arg(mctx->ssl_ctx, mctx)) {
479        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
480                     "Unable to initialize TLS servername extension "
481                     "callback (incompatible OpenSSL version?)");
482        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
483        ssl_die();
484    }
485}
486#endif
487
488static void ssl_init_ctx_protocol(server_rec *s,
489                                  apr_pool_t *p,
490                                  apr_pool_t *ptemp,
491                                  modssl_ctx_t *mctx)
492{
493    SSL_CTX *ctx = NULL;
494    MODSSL_SSL_METHOD_CONST SSL_METHOD *method = NULL;
495    char *cp;
496    int protocol = mctx->protocol;
497    SSLSrvConfigRec *sc = mySrvConfig(s);
498
499    /*
500     *  Create the new per-server SSL context
501     */
502    if (protocol == SSL_PROTOCOL_NONE) {
503        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
504                "No SSL protocols available [hint: SSLProtocol]");
505        ssl_die();
506    }
507
508    cp = apr_pstrcat(p,
509#ifndef OPENSSL_NO_SSL2
510                     (protocol & SSL_PROTOCOL_SSLV2 ? "SSLv2, " : ""),
511#endif
512                     (protocol & SSL_PROTOCOL_SSLV3 ? "SSLv3, " : ""),
513                     (protocol & SSL_PROTOCOL_TLSV1 ? "TLSv1, " : ""),
514#ifdef HAVE_TLSV1_X
515                     (protocol & SSL_PROTOCOL_TLSV1_1 ? "TLSv1.1, " : ""),
516                     (protocol & SSL_PROTOCOL_TLSV1_2 ? "TLSv1.2, " : ""),
517#endif
518                     NULL);
519    cp[strlen(cp)-2] = NUL;
520
521    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
522                 "Creating new SSL context (protocols: %s)", cp);
523
524#ifndef OPENSSL_NO_SSL2
525    if (protocol == SSL_PROTOCOL_SSLV2) {
526        method = mctx->pkp ?
527            SSLv2_client_method() : /* proxy */
528            SSLv2_server_method();  /* server */
529    }
530    else
531#endif
532#ifdef HAVE_TLSV1_X
533    if (protocol == SSL_PROTOCOL_TLSV1_1) {
534        method = mctx->pkp ?
535            TLSv1_1_client_method() : /* proxy */
536            TLSv1_1_server_method();  /* server */
537    }
538    else if (protocol == SSL_PROTOCOL_TLSV1_2) {
539        method = mctx->pkp ?
540            TLSv1_2_client_method() : /* proxy */
541            TLSv1_2_server_method();  /* server */
542    }
543    else
544#endif
545    {
546        method = mctx->pkp ?
547            SSLv23_client_method() : /* proxy */
548            SSLv23_server_method();  /* server */
549    }
550    ctx = SSL_CTX_new(method);
551
552    mctx->ssl_ctx = ctx;
553
554    SSL_CTX_set_options(ctx, SSL_OP_ALL);
555
556#ifndef OPENSSL_NO_SSL2
557    if (!(protocol & SSL_PROTOCOL_SSLV2)) {
558        SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
559    }
560#endif
561
562    if (!(protocol & SSL_PROTOCOL_SSLV3)) {
563        SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);
564    }
565
566    if (!(protocol & SSL_PROTOCOL_TLSV1)) {
567        SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1);
568    }
569
570#ifdef HAVE_TLSV1_X
571    if (!(protocol & SSL_PROTOCOL_TLSV1_1)) {
572        SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_1);
573    }
574
575    if (!(protocol & SSL_PROTOCOL_TLSV1_2)) {
576        SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_2);
577    }
578#endif
579
580#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
581    if (sc->cipher_server_pref == TRUE) {
582        SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
583    }
584#endif
585
586
587#ifndef OPENSSL_NO_COMP
588    if (sc->compression != TRUE) {
589#ifdef SSL_OP_NO_COMPRESSION
590        /* OpenSSL >= 1.0 only */
591        SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION);
592#elif OPENSSL_VERSION_NUMBER >= 0x00908000L
593        sk_SSL_COMP_zero(SSL_COMP_get_compression_methods());
594#endif
595    }
596#endif
597
598#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
599    if (sc->insecure_reneg == TRUE) {
600        SSL_CTX_set_options(ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
601    }
602#endif
603
604    SSL_CTX_set_app_data(ctx, s);
605
606    /*
607     * Configure additional context ingredients
608     */
609    SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
610
611#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
612    /*
613     * Disallow a session from being resumed during a renegotiation,
614     * so that an acceptable cipher suite can be negotiated.
615     */
616    SSL_CTX_set_options(ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
617#endif
618}
619
620static void ssl_init_ctx_session_cache(server_rec *s,
621                                       apr_pool_t *p,
622                                       apr_pool_t *ptemp,
623                                       modssl_ctx_t *mctx)
624{
625    SSL_CTX *ctx = mctx->ssl_ctx;
626    SSLModConfigRec *mc = myModConfig(s);
627    long cache_mode = SSL_SESS_CACHE_OFF;
628    if (mc->nSessionCacheMode != SSL_SCMODE_NONE) {
629        /* SSL_SESS_CACHE_NO_INTERNAL will force OpenSSL
630         * to ignore process local-caching and
631         * to always get/set/delete sessions using mod_ssl's callbacks.
632         */
633        cache_mode = SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL;
634    }
635
636    SSL_CTX_set_session_cache_mode(ctx, cache_mode);
637
638    SSL_CTX_sess_set_new_cb(ctx,    ssl_callback_NewSessionCacheEntry);
639    SSL_CTX_sess_set_get_cb(ctx,    ssl_callback_GetSessionCacheEntry);
640    SSL_CTX_sess_set_remove_cb(ctx, ssl_callback_DelSessionCacheEntry);
641}
642
643static void ssl_init_ctx_callbacks(server_rec *s,
644                                   apr_pool_t *p,
645                                   apr_pool_t *ptemp,
646                                   modssl_ctx_t *mctx)
647{
648    SSL_CTX *ctx = mctx->ssl_ctx;
649
650    SSL_CTX_set_tmp_rsa_callback(ctx, ssl_callback_TmpRSA);
651    SSL_CTX_set_tmp_dh_callback(ctx,  ssl_callback_TmpDH);
652#ifndef OPENSSL_NO_EC
653    SSL_CTX_set_tmp_ecdh_callback(ctx,ssl_callback_TmpECDH);
654#endif
655
656    SSL_CTX_set_info_callback(ctx, ssl_callback_Info);
657}
658
659static void ssl_init_ctx_verify(server_rec *s,
660                                apr_pool_t *p,
661                                apr_pool_t *ptemp,
662                                modssl_ctx_t *mctx)
663{
664    SSL_CTX *ctx = mctx->ssl_ctx;
665
666    int verify = SSL_VERIFY_NONE;
667    STACK_OF(X509_NAME) *ca_list;
668
669    if (mctx->auth.verify_mode == SSL_CVERIFY_UNSET) {
670        mctx->auth.verify_mode = SSL_CVERIFY_NONE;
671    }
672
673    if (mctx->auth.verify_depth == UNSET) {
674        mctx->auth.verify_depth = 1;
675    }
676
677    /*
678     *  Configure callbacks for SSL context
679     */
680    if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
681        verify |= SSL_VERIFY_PEER_STRICT;
682    }
683
684    if ((mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL) ||
685        (mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL_NO_CA))
686    {
687        verify |= SSL_VERIFY_PEER;
688    }
689
690    SSL_CTX_set_verify(ctx, verify, ssl_callback_SSLVerify);
691
692    /*
693     * Configure Client Authentication details
694     */
695    if (mctx->auth.ca_cert_file || mctx->auth.ca_cert_path) {
696        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
697                     "Configuring client authentication");
698
699        if (!SSL_CTX_load_verify_locations(ctx,
700                         MODSSL_PCHAR_CAST mctx->auth.ca_cert_file,
701                         MODSSL_PCHAR_CAST mctx->auth.ca_cert_path))
702        {
703            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
704                    "Unable to configure verify locations "
705                    "for client authentication");
706            ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
707            ssl_die();
708        }
709
710        if (mctx->pks && (mctx->pks->ca_name_file || mctx->pks->ca_name_path)) {
711            ca_list = ssl_init_FindCAList(s, ptemp,
712                                          mctx->pks->ca_name_file,
713                                          mctx->pks->ca_name_path);
714        } else
715            ca_list = ssl_init_FindCAList(s, ptemp,
716                                          mctx->auth.ca_cert_file,
717                                          mctx->auth.ca_cert_path);
718        if (!ca_list) {
719            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
720                    "Unable to determine list of acceptable "
721                    "CA certificates for client authentication");
722            ssl_die();
723        }
724
725        SSL_CTX_set_client_CA_list(ctx, ca_list);
726    }
727
728    /*
729     * Give a warning when no CAs were configured but client authentication
730     * should take place. This cannot work.
731     */
732    if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
733        ca_list = SSL_CTX_get_client_CA_list(ctx);
734
735        if (sk_X509_NAME_num(ca_list) == 0) {
736            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
737                         "Init: Oops, you want to request client "
738                         "authentication, but no CAs are known for "
739                         "verification!?  [Hint: SSLCACertificate*]");
740        }
741    }
742}
743
744static void ssl_init_ctx_cipher_suite(server_rec *s,
745                                      apr_pool_t *p,
746                                      apr_pool_t *ptemp,
747                                      modssl_ctx_t *mctx)
748{
749    SSL_CTX *ctx = mctx->ssl_ctx;
750    const char *suite = mctx->auth.cipher_suite;
751
752    /*
753     *  Configure SSL Cipher Suite
754     */
755    if (!suite) {
756        return;
757    }
758
759    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
760                 "Configuring permitted SSL ciphers [%s]",
761                 suite);
762
763    if (!SSL_CTX_set_cipher_list(ctx, MODSSL_PCHAR_CAST suite)) {
764        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
765                "Unable to configure permitted SSL ciphers");
766        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
767        ssl_die();
768    }
769}
770
771static void ssl_init_ctx_crl(server_rec *s,
772                             apr_pool_t *p,
773                             apr_pool_t *ptemp,
774                             modssl_ctx_t *mctx)
775{
776    /*
777     * Configure Certificate Revocation List (CRL) Details
778     */
779
780    if (!(mctx->crl_file || mctx->crl_path)) {
781        return;
782    }
783
784    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
785                 "Configuring certificate revocation facility");
786
787    mctx->crl =
788        SSL_X509_STORE_create((char *)mctx->crl_file,
789                              (char *)mctx->crl_path);
790
791    if (!mctx->crl) {
792        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
793                "Unable to configure X.509 CRL storage "
794                "for certificate revocation");
795        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
796        ssl_die();
797    }
798}
799
800static void ssl_init_ctx_cert_chain(server_rec *s,
801                                    apr_pool_t *p,
802                                    apr_pool_t *ptemp,
803                                    modssl_ctx_t *mctx)
804{
805    BOOL skip_first = FALSE;
806    int i, n;
807    const char *chain = mctx->cert_chain;
808
809    /*
810     * Optionally configure extra server certificate chain certificates.
811     * This is usually done by OpenSSL automatically when one of the
812     * server cert issuers are found under SSLCACertificatePath or in
813     * SSLCACertificateFile. But because these are intended for client
814     * authentication it can conflict. For instance when you use a
815     * Global ID server certificate you've to send out the intermediate
816     * CA certificate, too. When you would just configure this with
817     * SSLCACertificateFile and also use client authentication mod_ssl
818     * would accept all clients also issued by this CA. Obviously this
819     * isn't what we want in this situation. So this feature here exists
820     * to allow one to explicity configure CA certificates which are
821     * used only for the server certificate chain.
822     */
823    if (!chain) {
824        return;
825    }
826
827    for (i = 0; (i < SSL_AIDX_MAX) && mctx->pks->cert_files[i]; i++) {
828        if (strEQ(mctx->pks->cert_files[i], chain)) {
829            skip_first = TRUE;
830            break;
831        }
832    }
833
834    n = SSL_CTX_use_certificate_chain(mctx->ssl_ctx,
835                                      (char *)chain,
836                                      skip_first, NULL);
837    if (n < 0) {
838        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
839                "Failed to configure CA certificate chain!");
840        ssl_die();
841    }
842
843    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
844                 "Configuring server certificate chain "
845                 "(%d CA certificate%s)",
846                 n, n == 1 ? "" : "s");
847}
848
849static void ssl_init_ctx(server_rec *s,
850                         apr_pool_t *p,
851                         apr_pool_t *ptemp,
852                         modssl_ctx_t *mctx)
853{
854    ssl_init_ctx_protocol(s, p, ptemp, mctx);
855
856    ssl_init_ctx_session_cache(s, p, ptemp, mctx);
857
858    ssl_init_ctx_callbacks(s, p, ptemp, mctx);
859
860    ssl_init_ctx_verify(s, p, ptemp, mctx);
861
862    ssl_init_ctx_cipher_suite(s, p, ptemp, mctx);
863
864    ssl_init_ctx_crl(s, p, ptemp, mctx);
865
866    if (mctx->pks) {
867        /* XXX: proxy support? */
868        ssl_init_ctx_cert_chain(s, p, ptemp, mctx);
869#ifndef OPENSSL_NO_TLSEXT
870        ssl_init_ctx_tls_extensions(s, p, ptemp, mctx);
871#endif
872    }
873}
874
875static int ssl_server_import_cert(server_rec *s,
876                                  modssl_ctx_t *mctx,
877                                  const char *id,
878                                  int idx)
879{
880    SSLModConfigRec *mc = myModConfig(s);
881    ssl_asn1_t *asn1;
882    MODSSL_D2I_X509_CONST unsigned char *ptr;
883    const char *type = ssl_asn1_keystr(idx);
884    X509 *cert;
885
886    if (!(asn1 = ssl_asn1_table_get(mc->tPublicCert, id))) {
887        return FALSE;
888    }
889
890    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
891                 "Configuring %s server certificate", type);
892
893    ptr = asn1->cpData;
894    if (!(cert = d2i_X509(NULL, &ptr, asn1->nData))) {
895        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
896                "Unable to import %s server certificate", type);
897        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
898        ssl_die();
899    }
900
901    if (SSL_CTX_use_certificate(mctx->ssl_ctx, cert) <= 0) {
902        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
903                "Unable to configure %s server certificate", type);
904        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
905        ssl_die();
906    }
907
908    mctx->pks->certs[idx] = cert;
909
910    return TRUE;
911}
912
913static int ssl_server_import_key(server_rec *s,
914                                 modssl_ctx_t *mctx,
915                                 const char *id,
916                                 int idx)
917{
918    SSLModConfigRec *mc = myModConfig(s);
919    ssl_asn1_t *asn1;
920    MODSSL_D2I_PrivateKey_CONST unsigned char *ptr;
921    const char *type = ssl_asn1_keystr(idx);
922    int pkey_type;
923    EVP_PKEY *pkey;
924
925#ifndef OPENSSL_NO_EC
926    if (idx == SSL_AIDX_ECC)
927      pkey_type = EVP_PKEY_EC;
928    else
929#endif
930    pkey_type = (idx == SSL_AIDX_RSA) ? EVP_PKEY_RSA : EVP_PKEY_DSA;
931
932    if (!(asn1 = ssl_asn1_table_get(mc->tPrivateKey, id))) {
933        return FALSE;
934    }
935
936    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
937                 "Configuring %s server private key", type);
938
939    ptr = asn1->cpData;
940    if (!(pkey = d2i_PrivateKey(pkey_type, NULL, &ptr, asn1->nData)))
941    {
942        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
943                "Unable to import %s server private key", type);
944        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
945        ssl_die();
946    }
947
948    if (SSL_CTX_use_PrivateKey(mctx->ssl_ctx, pkey) <= 0) {
949        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
950                "Unable to configure %s server private key", type);
951        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
952        ssl_die();
953    }
954
955    /*
956     * XXX: wonder if this is still needed, this is old todo doc.
957     * (see http://www.psy.uq.edu.au/~ftp/Crypto/ssleay/TODO.html)
958     */
959    if ((pkey_type == EVP_PKEY_DSA) && mctx->pks->certs[idx]) {
960        EVP_PKEY *pubkey = X509_get_pubkey(mctx->pks->certs[idx]);
961
962        if (pubkey && EVP_PKEY_missing_parameters(pubkey)) {
963            EVP_PKEY_copy_parameters(pubkey, pkey);
964            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
965                    "Copying DSA parameters from private key to certificate");
966            ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
967            EVP_PKEY_free(pubkey);
968        }
969    }
970
971    mctx->pks->keys[idx] = pkey;
972
973    return TRUE;
974}
975
976static void ssl_check_public_cert(server_rec *s,
977                                  apr_pool_t *ptemp,
978                                  X509 *cert,
979                                  int type)
980{
981    int is_ca, pathlen;
982    char *cn;
983
984    if (!cert) {
985        return;
986    }
987
988    /*
989     * Some information about the certificate(s)
990     */
991
992    if (SSL_X509_isSGC(cert)) {
993        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
994                     "%s server certificate enables "
995                     "Server Gated Cryptography (SGC)",
996                     ssl_asn1_keystr(type));
997    }
998
999    if (SSL_X509_getBC(cert, &is_ca, &pathlen)) {
1000        if (is_ca) {
1001            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1002                         "%s server certificate is a CA certificate "
1003                         "(BasicConstraints: CA == TRUE !?)",
1004                         ssl_asn1_keystr(type));
1005        }
1006
1007        if (pathlen > 0) {
1008            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1009                         "%s server certificate is not a leaf certificate "
1010                         "(BasicConstraints: pathlen == %d > 0 !?)",
1011                         ssl_asn1_keystr(type), pathlen);
1012        }
1013    }
1014
1015    if (SSL_X509_getCN(ptemp, cert, &cn)) {
1016        int fnm_flags = APR_FNM_PERIOD|APR_FNM_CASE_BLIND;
1017
1018        if (apr_fnmatch_test(cn)) {
1019            if (apr_fnmatch(cn, s->server_hostname,
1020                            fnm_flags) == APR_FNM_NOMATCH) {
1021                ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1022                             "%s server certificate wildcard CommonName "
1023                             "(CN) `%s' does NOT match server name!?",
1024                             ssl_asn1_keystr(type), cn);
1025            }
1026        }
1027        else if (strNE(s->server_hostname, cn)) {
1028            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1029                         "%s server certificate CommonName (CN) `%s' "
1030                         "does NOT match server name!?",
1031                         ssl_asn1_keystr(type), cn);
1032        }
1033    }
1034}
1035
1036static void ssl_init_server_certs(server_rec *s,
1037                                  apr_pool_t *p,
1038                                  apr_pool_t *ptemp,
1039                                  modssl_ctx_t *mctx)
1040{
1041    const char *rsa_id, *dsa_id;
1042#ifndef OPENSSL_NO_EC
1043    const char *ecc_id;
1044#endif
1045    const char *vhost_id = mctx->sc->vhost_id;
1046    int i;
1047    int have_rsa, have_dsa;
1048#ifndef OPENSSL_NO_EC
1049    int have_ecc;
1050#endif
1051
1052    rsa_id = ssl_asn1_table_keyfmt(ptemp, vhost_id, SSL_AIDX_RSA);
1053    dsa_id = ssl_asn1_table_keyfmt(ptemp, vhost_id, SSL_AIDX_DSA);
1054#ifndef OPENSSL_NO_EC
1055    ecc_id = ssl_asn1_table_keyfmt(ptemp, vhost_id, SSL_AIDX_ECC);
1056#endif
1057
1058    have_rsa = ssl_server_import_cert(s, mctx, rsa_id, SSL_AIDX_RSA);
1059    have_dsa = ssl_server_import_cert(s, mctx, dsa_id, SSL_AIDX_DSA);
1060#ifndef OPENSSL_NO_EC
1061    have_ecc = ssl_server_import_cert(s, mctx, ecc_id, SSL_AIDX_ECC);
1062#endif
1063
1064    if (!(have_rsa || have_dsa
1065#ifndef OPENSSL_NO_EC
1066        || have_ecc
1067#endif
1068)) {
1069        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1070#ifndef OPENSSL_NO_EC
1071                "Oops, no RSA, DSA or ECC server certificate found "
1072#else
1073                "Oops, no RSA or DSA server certificate found "
1074#endif
1075                "for '%s:%d'?!", s->server_hostname, s->port);
1076        ssl_die();
1077    }
1078
1079    for (i = 0; i < SSL_AIDX_MAX; i++) {
1080        ssl_check_public_cert(s, ptemp, mctx->pks->certs[i], i);
1081    }
1082
1083    have_rsa = ssl_server_import_key(s, mctx, rsa_id, SSL_AIDX_RSA);
1084    have_dsa = ssl_server_import_key(s, mctx, dsa_id, SSL_AIDX_DSA);
1085#ifndef OPENSSL_NO_EC
1086    have_ecc = ssl_server_import_key(s, mctx, ecc_id, SSL_AIDX_ECC);
1087#endif
1088
1089    if (!(have_rsa || have_dsa
1090#ifndef OPENSSL_NO_EC
1091        || have_ecc
1092#endif
1093          )) {
1094        ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1095#ifndef OPENSSL_NO_EC
1096                "Oops, no RSA, DSA or ECC server private key found?!");
1097#else
1098                "Oops, no RSA or DSA server private key found?!");
1099#endif
1100        ssl_die();
1101    }
1102}
1103
1104static void ssl_init_proxy_certs(server_rec *s,
1105                                 apr_pool_t *p,
1106                                 apr_pool_t *ptemp,
1107                                 modssl_ctx_t *mctx)
1108{
1109    int n, ncerts = 0;
1110    STACK_OF(X509_INFO) *sk;
1111    STACK_OF(X509) *chain;
1112    X509_STORE_CTX *sctx;
1113    X509_STORE *store = SSL_CTX_get_cert_store(mctx->ssl_ctx);
1114    modssl_pk_proxy_t *pkp = mctx->pkp;
1115
1116    SSL_CTX_set_client_cert_cb(mctx->ssl_ctx,
1117                               ssl_callback_proxy_cert);
1118
1119    if (!(pkp->cert_file || pkp->cert_path)) {
1120        return;
1121    }
1122
1123    sk = sk_X509_INFO_new_null();
1124
1125    if (pkp->cert_file) {
1126        SSL_X509_INFO_load_file(ptemp, sk, pkp->cert_file);
1127    }
1128
1129    if (pkp->cert_path) {
1130        SSL_X509_INFO_load_path(ptemp, sk, pkp->cert_path);
1131    }
1132
1133    if ((ncerts = sk_X509_INFO_num(sk)) <= 0) {
1134        sk_X509_INFO_free(sk);
1135        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1136                     "no client certs found for SSL proxy");
1137        return;
1138    }
1139
1140    /* Check that all client certs have got certificates and private
1141     * keys. */
1142    for (n = 0; n < ncerts; n++) {
1143        X509_INFO *inf = sk_X509_INFO_value(sk, n);
1144
1145        if (!inf->x509 || !inf->x_pkey || !inf->x_pkey->dec_pkey ||
1146            inf->enc_data) {
1147            sk_X509_INFO_free(sk);
1148            ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
1149                         "incomplete client cert configured for SSL proxy "
1150                         "(missing or encrypted private key?)");
1151            ssl_die();
1152            return;
1153        }
1154
1155        if (X509_check_private_key(inf->x509, inf->x_pkey->dec_pkey) != 1) {
1156            ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s,
1157                           "proxy client certificate and "
1158                           "private key do not match");
1159            ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
1160            ssl_die();
1161            return;
1162        }
1163    }
1164
1165    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1166                 "loaded %d client certs for SSL proxy",
1167                 ncerts);
1168    pkp->certs = sk;
1169
1170    if (!pkp->ca_cert_file || !store) {
1171        return;
1172    }
1173
1174    /* If SSLProxyMachineCertificateChainFile is configured, load all
1175     * the CA certs and have OpenSSL attempt to construct a full chain
1176     * from each configured end-entity cert up to a root.  This will
1177     * allow selection of the correct cert given a list of root CA
1178     * names in the certificate request from the server.  */
1179    pkp->ca_certs = (STACK_OF(X509) **) apr_pcalloc(p, ncerts * sizeof(sk));
1180    sctx = X509_STORE_CTX_new();
1181
1182    if (!sctx) {
1183        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s,
1184                     "SSL proxy client cert initialization failed");
1185        ssl_log_ssl_error(APLOG_MARK, APLOG_EMERG, s);
1186        ssl_die();
1187    }
1188
1189    X509_STORE_load_locations(store, pkp->ca_cert_file, NULL);
1190
1191    for (n = 0; n < ncerts; n++) {
1192        int i;
1193
1194        X509_INFO *inf = sk_X509_INFO_value(pkp->certs, n);
1195        X509_NAME *name = X509_get_subject_name(inf->x509);
1196        char *cert_dn = SSL_X509_NAME_to_string(ptemp, name, 0);
1197        X509_STORE_CTX_init(sctx, store, inf->x509, NULL);
1198
1199        /* Attempt to verify the client cert */
1200        if (X509_verify_cert(sctx) != 1) {
1201            int err = X509_STORE_CTX_get_error(sctx);
1202            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1203                         "SSL proxy client cert chain verification failed for %s: %s",
1204                         cert_dn, X509_verify_cert_error_string(err));
1205        }
1206
1207        /* Clear X509_verify_cert errors */
1208        ERR_clear_error();
1209
1210        /* Obtain a copy of the verified chain */
1211        chain = X509_STORE_CTX_get1_chain(sctx);
1212
1213        if (chain != NULL) {
1214            /* Discard end entity cert from the chain */
1215            X509_free(sk_X509_shift(chain));
1216
1217            if ((i = sk_X509_num(chain)) > 0) {
1218                /* Store the chain for later use */
1219                pkp->ca_certs[n] = chain;
1220            }
1221            else {
1222                /* Discard empty chain */
1223                sk_X509_pop_free(chain, X509_free);
1224                pkp->ca_certs[n] = NULL;
1225            }
1226
1227            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1228                         "loaded %i intermediate CA%s for cert %i (%s)",
1229                         i, i == 1 ? "" : "s", n, cert_dn);
1230            if (i > 0) {
1231                int j;
1232                for (j = 0; j < i; j++) {
1233                    X509_NAME *ca_name = X509_get_subject_name(sk_X509_value(chain, j));
1234                    char *ca_dn = SSL_X509_NAME_to_string(ptemp, ca_name, 0);
1235                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "%i: %s", j, ca_dn);
1236                }
1237            }
1238        }
1239
1240        /* get ready for next X509_STORE_CTX_init */
1241        X509_STORE_CTX_cleanup(sctx);
1242    }
1243
1244    X509_STORE_CTX_free(sctx);
1245}
1246
1247static void ssl_init_proxy_ctx(server_rec *s,
1248                               apr_pool_t *p,
1249                               apr_pool_t *ptemp,
1250                               SSLSrvConfigRec *sc)
1251{
1252    ssl_init_ctx(s, p, ptemp, sc->proxy);
1253
1254    ssl_init_proxy_certs(s, p, ptemp, sc->proxy);
1255}
1256
1257static void ssl_init_server_ctx(server_rec *s,
1258                                apr_pool_t *p,
1259                                apr_pool_t *ptemp,
1260                                SSLSrvConfigRec *sc)
1261{
1262    ssl_init_server_check(s, p, ptemp, sc->server);
1263
1264    ssl_init_ctx(s, p, ptemp, sc->server);
1265
1266    ssl_init_server_certs(s, p, ptemp, sc->server);
1267}
1268
1269/*
1270 * Configure a particular server
1271 */
1272void ssl_init_ConfigureServer(server_rec *s,
1273                              apr_pool_t *p,
1274                              apr_pool_t *ptemp,
1275                              SSLSrvConfigRec *sc)
1276{
1277    /* Initialize the server if SSL is enabled or optional.
1278     */
1279    if ((sc->enabled == SSL_ENABLED_TRUE) || (sc->enabled == SSL_ENABLED_OPTIONAL)) {
1280        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
1281                     "Configuring server for SSL protocol");
1282        ssl_init_server_ctx(s, p, ptemp, sc);
1283    }
1284
1285    if (sc->proxy_enabled) {
1286        ssl_init_proxy_ctx(s, p, ptemp, sc);
1287    }
1288}
1289
1290void ssl_init_CheckServers(server_rec *base_server, apr_pool_t *p)
1291{
1292    server_rec *s, *ps;
1293    SSLSrvConfigRec *sc;
1294    apr_hash_t *table;
1295    const char *key;
1296    apr_ssize_t klen;
1297
1298    BOOL conflict = FALSE;
1299
1300    /*
1301     * Give out warnings when a server has HTTPS configured
1302     * for the HTTP port or vice versa
1303     */
1304    for (s = base_server; s; s = s->next) {
1305        sc = mySrvConfig(s);
1306
1307        if ((sc->enabled == SSL_ENABLED_TRUE) && (s->port == DEFAULT_HTTP_PORT)) {
1308            ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1309                         base_server,
1310                         "Init: (%s) You configured HTTPS(%d) "
1311                         "on the standard HTTP(%d) port!",
1312                         ssl_util_vhostid(p, s),
1313                         DEFAULT_HTTPS_PORT, DEFAULT_HTTP_PORT);
1314        }
1315
1316        if ((sc->enabled == SSL_ENABLED_FALSE) && (s->port == DEFAULT_HTTPS_PORT)) {
1317            ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1318                         base_server,
1319                         "Init: (%s) You configured HTTP(%d) "
1320                         "on the standard HTTPS(%d) port!",
1321                         ssl_util_vhostid(p, s),
1322                         DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT);
1323        }
1324    }
1325
1326    /*
1327     * Give out warnings when more than one SSL-aware virtual server uses the
1328     * same IP:port. This doesn't work because mod_ssl then will always use
1329     * just the certificate/keys of one virtual host (which one cannot be said
1330     * easily - but that doesn't matter here).
1331     */
1332    table = apr_hash_make(p);
1333
1334    for (s = base_server; s; s = s->next) {
1335        char *addr;
1336
1337        sc = mySrvConfig(s);
1338
1339        if (!((sc->enabled == SSL_ENABLED_TRUE) && s->addrs)) {
1340            continue;
1341        }
1342
1343        apr_sockaddr_ip_get(&addr, s->addrs->host_addr);
1344        key = apr_psprintf(p, "%s:%u", addr, s->addrs->host_port);
1345        klen = strlen(key);
1346
1347        if ((ps = (server_rec *)apr_hash_get(table, key, klen))) {
1348#ifdef OPENSSL_NO_TLSEXT
1349            int level = APLOG_WARNING;
1350            const char *problem = "conflict";
1351#else
1352            int level = APLOG_DEBUG;
1353            const char *problem = "overlap";
1354#endif
1355            ap_log_error(APLOG_MARK, level, 0, base_server,
1356                         "Init: SSL server IP/port %s: "
1357                         "%s (%s:%d) vs. %s (%s:%d)",
1358                         problem, ssl_util_vhostid(p, s),
1359                         (s->defn_name ? s->defn_name : "unknown"),
1360                         s->defn_line_number,
1361                         ssl_util_vhostid(p, ps),
1362                         (ps->defn_name ? ps->defn_name : "unknown"),
1363                         ps->defn_line_number);
1364            conflict = TRUE;
1365            continue;
1366        }
1367
1368        apr_hash_set(table, key, klen, s);
1369    }
1370
1371    if (conflict) {
1372        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, base_server,
1373#ifdef OPENSSL_NO_TLSEXT
1374                     "Init: You should not use name-based "
1375                     "virtual hosts in conjunction with SSL!!");
1376#else
1377                     "Init: Name-based SSL virtual hosts only "
1378                     "work for clients with TLS server name indication "
1379                     "support (RFC 4366)");
1380#endif
1381    }
1382}
1383
1384#ifdef SSLC_VERSION_NUMBER
1385static int ssl_init_FindCAList_X509NameCmp(char **a, char **b)
1386{
1387    return(X509_NAME_cmp((void*)*a, (void*)*b));
1388}
1389#else
1390static int ssl_init_FindCAList_X509NameCmp(const X509_NAME * const *a,
1391                                           const X509_NAME * const *b)
1392{
1393    return(X509_NAME_cmp(*a, *b));
1394}
1395#endif
1396
1397static void ssl_init_PushCAList(STACK_OF(X509_NAME) *ca_list,
1398                                server_rec *s, const char *file)
1399{
1400    int n;
1401    STACK_OF(X509_NAME) *sk;
1402
1403    sk = (STACK_OF(X509_NAME) *)
1404             SSL_load_client_CA_file(MODSSL_PCHAR_CAST file);
1405
1406    if (!sk) {
1407        return;
1408    }
1409
1410    for (n = 0; n < sk_X509_NAME_num(sk); n++) {
1411        char name_buf[256];
1412        X509_NAME *name = sk_X509_NAME_value(sk, n);
1413
1414        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1415                     "CA certificate: %s",
1416                     X509_NAME_oneline(name, name_buf, sizeof(name_buf)));
1417
1418        /*
1419         * note that SSL_load_client_CA_file() checks for duplicates,
1420         * but since we call it multiple times when reading a directory
1421         * we must also check for duplicates ourselves.
1422         */
1423
1424        if (sk_X509_NAME_find(ca_list, name) < 0) {
1425            /* this will be freed when ca_list is */
1426            sk_X509_NAME_push(ca_list, name);
1427        }
1428        else {
1429            /* need to free this ourselves, else it will leak */
1430            X509_NAME_free(name);
1431        }
1432    }
1433
1434    sk_X509_NAME_free(sk);
1435}
1436
1437STACK_OF(X509_NAME) *ssl_init_FindCAList(server_rec *s,
1438                                         apr_pool_t *ptemp,
1439                                         const char *ca_file,
1440                                         const char *ca_path)
1441{
1442    STACK_OF(X509_NAME) *ca_list;
1443
1444    /*
1445     * Start with a empty stack/list where new
1446     * entries get added in sorted order.
1447     */
1448    ca_list = sk_X509_NAME_new(ssl_init_FindCAList_X509NameCmp);
1449
1450    /*
1451     * Process CA certificate bundle file
1452     */
1453    if (ca_file) {
1454        ssl_init_PushCAList(ca_list, s, ca_file);
1455    }
1456
1457    /*
1458     * Process CA certificate path files
1459     */
1460    if (ca_path) {
1461        apr_dir_t *dir;
1462        apr_finfo_t direntry;
1463        apr_int32_t finfo_flags = APR_FINFO_TYPE|APR_FINFO_NAME;
1464        apr_status_t rv;
1465
1466        if ((rv = apr_dir_open(&dir, ca_path, ptemp)) != APR_SUCCESS) {
1467            ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1468                    "Failed to open Certificate Path `%s'",
1469                    ca_path);
1470            ssl_die();
1471        }
1472
1473        while ((apr_dir_read(&direntry, finfo_flags, dir)) == APR_SUCCESS) {
1474            const char *file;
1475            if (direntry.filetype == APR_DIR) {
1476                continue; /* don't try to load directories */
1477            }
1478            file = apr_pstrcat(ptemp, ca_path, "/", direntry.name, NULL);
1479            ssl_init_PushCAList(ca_list, s, file);
1480        }
1481
1482        apr_dir_close(dir);
1483    }
1484
1485    /*
1486     * Cleanup
1487     */
1488    (void) sk_X509_NAME_set_cmp_func(ca_list, NULL);
1489
1490    return ca_list;
1491}
1492
1493void ssl_init_Child(apr_pool_t *p, server_rec *s)
1494{
1495    SSLModConfigRec *mc = myModConfig(s);
1496    mc->pid = getpid(); /* only call getpid() once per-process */
1497
1498    /* XXX: there should be an ap_srand() function */
1499    srand((unsigned int)time(NULL));
1500
1501    /* open the mutex lockfile */
1502    ssl_mutex_reinit(s, p);
1503}
1504
1505#define MODSSL_CFG_ITEM_FREE(func, item) \
1506    if (item) { \
1507        func(item); \
1508        item = NULL; \
1509    }
1510
1511static void ssl_init_ctx_cleanup(modssl_ctx_t *mctx)
1512{
1513    MODSSL_CFG_ITEM_FREE(X509_STORE_free, mctx->crl);
1514
1515    MODSSL_CFG_ITEM_FREE(SSL_CTX_free, mctx->ssl_ctx);
1516}
1517
1518static void ssl_init_ctx_cleanup_proxy(modssl_ctx_t *mctx)
1519{
1520    ssl_init_ctx_cleanup(mctx);
1521
1522    if (mctx->pkp->certs) {
1523        int i = 0;
1524        int ncerts = sk_X509_INFO_num(mctx->pkp->certs);
1525
1526        if (mctx->pkp->ca_certs) {
1527            for (i = 0; i < ncerts; i++) {
1528                if (mctx->pkp->ca_certs[i] != NULL) {
1529                    sk_X509_pop_free(mctx->pkp->ca_certs[i], X509_free);
1530                }
1531            }
1532        }
1533
1534        sk_X509_INFO_pop_free(mctx->pkp->certs, X509_INFO_free);
1535        mctx->pkp->certs = NULL;
1536    }
1537}
1538
1539static void ssl_init_ctx_cleanup_server(modssl_ctx_t *mctx)
1540{
1541    int i;
1542
1543    ssl_init_ctx_cleanup(mctx);
1544
1545    for (i=0; i < SSL_AIDX_MAX; i++) {
1546        MODSSL_CFG_ITEM_FREE(X509_free,
1547                             mctx->pks->certs[i]);
1548
1549        MODSSL_CFG_ITEM_FREE(EVP_PKEY_free,
1550                             mctx->pks->keys[i]);
1551    }
1552}
1553
1554apr_status_t ssl_init_ModuleKill(void *data)
1555{
1556    SSLSrvConfigRec *sc;
1557    server_rec *base_server = (server_rec *)data;
1558    server_rec *s;
1559
1560    /*
1561     * Drop the session cache and mutex
1562     */
1563    ssl_scache_kill(base_server);
1564
1565    /*
1566     * Destroy the temporary keys and params
1567     */
1568    ssl_tmp_keys_free(base_server);
1569
1570    /*
1571     * Free the non-pool allocated structures
1572     * in the per-server configurations
1573     */
1574    for (s = base_server; s; s = s->next) {
1575        sc = mySrvConfig(s);
1576
1577        ssl_init_ctx_cleanup_proxy(sc->proxy);
1578
1579        ssl_init_ctx_cleanup_server(sc->server);
1580    }
1581
1582    return APR_SUCCESS;
1583}
1584
1585