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