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#include "mpm_common.h"
31
32/*  _________________________________________________________________
33**
34**  Module Initialization
35**  _________________________________________________________________
36*/
37
38#ifdef HAVE_ECC
39#define KEYTYPES "RSA, DSA or ECC"
40#else
41#define KEYTYPES "RSA or DSA"
42#endif
43
44static void ssl_add_version_components(apr_pool_t *p,
45                                       server_rec *s)
46{
47    char *modver = ssl_var_lookup(p, s, NULL, NULL, "SSL_VERSION_INTERFACE");
48    char *libver = ssl_var_lookup(p, s, NULL, NULL, "SSL_VERSION_LIBRARY");
49    char *incver = ssl_var_lookup(p, s, NULL, NULL,
50                                  "SSL_VERSION_LIBRARY_INTERFACE");
51
52    ap_add_version_component(p, libver);
53
54    ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01876)
55                 "%s compiled against Server: %s, Library: %s",
56                 modver, AP_SERVER_BASEVERSION, incver);
57}
58
59/*
60 *  Per-module initialization
61 */
62apr_status_t ssl_init_Module(apr_pool_t *p, apr_pool_t *plog,
63                             apr_pool_t *ptemp,
64                             server_rec *base_server)
65{
66    SSLModConfigRec *mc = myModConfig(base_server);
67    SSLSrvConfigRec *sc;
68    server_rec *s;
69    apr_status_t rv;
70    apr_array_header_t *pphrases;
71
72    if (SSLeay() < SSL_LIBRARY_VERSION) {
73        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, base_server, APLOGNO(01882)
74                     "Init: this version of mod_ssl was compiled against "
75                     "a newer library (%s, version currently loaded is %s)"
76                     " - may result in undefined or erroneous behavior",
77                     SSL_LIBRARY_TEXT, SSLeay_version(SSLEAY_VERSION));
78    }
79
80    /* We initialize mc->pid per-process in the child init,
81     * but it should be initialized for startup before we
82     * call ssl_rand_seed() below.
83     */
84    mc->pid = getpid();
85
86    /*
87     * Let us cleanup on restarts and exits
88     */
89    apr_pool_cleanup_register(p, base_server,
90                              ssl_init_ModuleKill,
91                              apr_pool_cleanup_null);
92
93    /*
94     * Any init round fixes the global config
95     */
96    ssl_config_global_create(base_server); /* just to avoid problems */
97    ssl_config_global_fix(mc);
98
99    /*
100     *  try to fix the configuration and open the dedicated SSL
101     *  logfile as early as possible
102     */
103    for (s = base_server; s; s = s->next) {
104        sc = mySrvConfig(s);
105
106        if (sc->server) {
107            sc->server->sc = sc;
108        }
109
110        if (sc->proxy) {
111            sc->proxy->sc = sc;
112        }
113
114        /*
115         * Create the server host:port string because we need it a lot
116         */
117        sc->vhost_id = ssl_util_vhostid(p, s);
118        sc->vhost_id_len = strlen(sc->vhost_id);
119
120        if (ap_get_server_protocol(s) &&
121            strcmp("https", ap_get_server_protocol(s)) == 0) {
122            sc->enabled = SSL_ENABLED_TRUE;
123        }
124
125        /* If sc->enabled is UNSET, then SSL is optional on this vhost  */
126        /* Fix up stuff that may not have been set */
127        if (sc->enabled == SSL_ENABLED_UNSET) {
128            sc->enabled = SSL_ENABLED_FALSE;
129        }
130        if (sc->proxy_enabled == UNSET) {
131            sc->proxy_enabled = FALSE;
132        }
133
134        if (sc->session_cache_timeout == UNSET) {
135            sc->session_cache_timeout = SSL_SESSION_CACHE_TIMEOUT;
136        }
137
138        if (sc->server && sc->server->pphrase_dialog_type == SSL_PPTYPE_UNSET) {
139            sc->server->pphrase_dialog_type = SSL_PPTYPE_BUILTIN;
140        }
141
142#ifdef HAVE_FIPS
143        if (sc->fips == UNSET) {
144            sc->fips = FALSE;
145        }
146#endif
147        if (sc->allow_empty_fragments == UNSET)
148            sc->allow_empty_fragments = TRUE;
149
150    }
151
152#if APR_HAS_THREADS
153    ssl_util_thread_setup(p);
154#endif
155
156    /*
157     * SSL external crypto device ("engine") support
158     */
159#if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
160    if ((rv = ssl_init_Engine(base_server, p)) != APR_SUCCESS) {
161        return rv;
162    }
163#endif
164
165    ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01883)
166                 "Init: Initialized %s library", SSL_LIBRARY_NAME);
167
168    /*
169     * Seed the Pseudo Random Number Generator (PRNG)
170     * only need ptemp here; nothing inside allocated from the pool
171     * needs to live once we return from ssl_rand_seed().
172     */
173    ssl_rand_seed(base_server, ptemp, SSL_RSCTX_STARTUP, "Init: ");
174
175#ifdef HAVE_FIPS
176    if(sc->fips) {
177        if (!FIPS_mode()) {
178            if (FIPS_mode_set(1)) {
179                ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, APLOGNO(01884)
180                             "Operating in SSL FIPS mode");
181            }
182            else {
183                ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01885) "FIPS mode failed");
184                ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
185                return ssl_die(s);
186            }
187        }
188    }
189    else {
190        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01886)
191                     "SSL FIPS mode disabled");
192    }
193#endif
194
195    /*
196     * initialize the mutex handling
197     */
198    if (!ssl_mutex_init(base_server, p)) {
199        return HTTP_INTERNAL_SERVER_ERROR;
200    }
201#ifdef HAVE_OCSP_STAPLING
202    ssl_stapling_ex_init();
203#endif
204
205    /*
206     * initialize session caching
207     */
208    if ((rv = ssl_scache_init(base_server, p)) != APR_SUCCESS) {
209        return rv;
210    }
211
212    pphrases = apr_array_make(ptemp, 2, sizeof(char *));
213
214    /*
215     *  initialize servers
216     */
217    ap_log_error(APLOG_MARK, APLOG_INFO, 0, base_server, APLOGNO(01887)
218                 "Init: Initializing (virtual) servers for SSL");
219
220    for (s = base_server; s; s = s->next) {
221        sc = mySrvConfig(s);
222        /*
223         * Either now skip this server when SSL is disabled for
224         * it or give out some information about what we're
225         * configuring.
226         */
227
228        /*
229         * Read the server certificate and key
230         */
231        if ((rv = ssl_init_ConfigureServer(s, p, ptemp, sc, pphrases))
232            != APR_SUCCESS) {
233            return rv;
234        }
235    }
236
237    if (pphrases->nelts > 0) {
238        memset(pphrases->elts, 0, pphrases->elt_size * pphrases->nelts);
239        pphrases->nelts = 0;
240        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02560)
241                     "Init: Wiped out the queried pass phrases from memory");
242    }
243
244    /*
245     * Configuration consistency checks
246     */
247    if ((rv = ssl_init_CheckServers(base_server, ptemp)) != APR_SUCCESS) {
248        return rv;
249    }
250
251    /*
252     *  Announce mod_ssl and SSL library in HTTP Server field
253     *  as ``mod_ssl/X.X.X OpenSSL/X.X.X''
254     */
255    ssl_add_version_components(p, base_server);
256
257    SSL_init_app_data2_idx(); /* for SSL_get_app_data2() at request time */
258
259    return OK;
260}
261
262/*
263 * Support for external a Crypto Device ("engine"), usually
264 * a hardware accellerator card for crypto operations.
265 */
266#if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
267apr_status_t ssl_init_Engine(server_rec *s, apr_pool_t *p)
268{
269    SSLModConfigRec *mc = myModConfig(s);
270    ENGINE *e;
271
272    if (mc->szCryptoDevice) {
273        if (!(e = ENGINE_by_id(mc->szCryptoDevice))) {
274            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01888)
275                         "Init: Failed to load Crypto Device API `%s'",
276                         mc->szCryptoDevice);
277            ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
278            return ssl_die(s);
279        }
280
281        if (strEQ(mc->szCryptoDevice, "chil")) {
282            ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
283        }
284
285        if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
286            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01889)
287                         "Init: Failed to enable Crypto Device API `%s'",
288                         mc->szCryptoDevice);
289            ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
290            return ssl_die(s);
291        }
292        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01890)
293                     "Init: loaded Crypto Device API `%s'",
294                     mc->szCryptoDevice);
295
296        ENGINE_free(e);
297    }
298
299    return APR_SUCCESS;
300}
301#endif
302
303#ifdef HAVE_TLSEXT
304static apr_status_t ssl_init_ctx_tls_extensions(server_rec *s,
305                                                apr_pool_t *p,
306                                                apr_pool_t *ptemp,
307                                                modssl_ctx_t *mctx)
308{
309    apr_status_t rv;
310
311    /*
312     * Configure TLS extensions support
313     */
314    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01893)
315                 "Configuring TLS extension handling");
316
317    /*
318     * Server name indication (SNI)
319     */
320    if (!SSL_CTX_set_tlsext_servername_callback(mctx->ssl_ctx,
321                          ssl_callback_ServerNameIndication) ||
322        !SSL_CTX_set_tlsext_servername_arg(mctx->ssl_ctx, mctx)) {
323        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01894)
324                     "Unable to initialize TLS servername extension "
325                     "callback (incompatible OpenSSL version?)");
326        ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
327        return ssl_die(s);
328    }
329
330#ifdef HAVE_OCSP_STAPLING
331    /*
332     * OCSP Stapling support, status_request extension
333     */
334    if ((mctx->pkp == FALSE) && (mctx->stapling_enabled == TRUE)) {
335        if ((rv = modssl_init_stapling(s, p, ptemp, mctx)) != APR_SUCCESS) {
336            return rv;
337        }
338    }
339#endif
340
341#ifdef HAVE_SRP
342    /*
343     * TLS-SRP support
344     */
345    if (mctx->srp_vfile != NULL) {
346        int err;
347        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02308)
348                     "Using SRP verifier file [%s]", mctx->srp_vfile);
349
350        if (!(mctx->srp_vbase = SRP_VBASE_new(mctx->srp_unknown_user_seed))) {
351            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02309)
352                         "Unable to initialize SRP verifier structure "
353                         "[%s seed]",
354                         mctx->srp_unknown_user_seed ? "with" : "without");
355            ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
356            return ssl_die(s);
357        }
358
359        err = SRP_VBASE_init(mctx->srp_vbase, mctx->srp_vfile);
360        if (err != SRP_NO_ERROR) {
361            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02310)
362                         "Unable to load SRP verifier file [error %d]", err);
363            ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
364            return ssl_die(s);
365        }
366
367        SSL_CTX_set_srp_username_callback(mctx->ssl_ctx,
368                                          ssl_callback_SRPServerParams);
369        SSL_CTX_set_srp_cb_arg(mctx->ssl_ctx, mctx);
370    }
371#endif
372    return APR_SUCCESS;
373}
374#endif
375
376static apr_status_t ssl_init_ctx_protocol(server_rec *s,
377                                          apr_pool_t *p,
378                                          apr_pool_t *ptemp,
379                                          modssl_ctx_t *mctx)
380{
381    SSL_CTX *ctx = NULL;
382    MODSSL_SSL_METHOD_CONST SSL_METHOD *method = NULL;
383    char *cp;
384    int protocol = mctx->protocol;
385    SSLSrvConfigRec *sc = mySrvConfig(s);
386
387    /*
388     *  Create the new per-server SSL context
389     */
390    if (protocol == SSL_PROTOCOL_NONE) {
391        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02231)
392                "No SSL protocols available [hint: SSLProtocol]");
393        return ssl_die(s);
394    }
395
396    cp = apr_pstrcat(p,
397                     (protocol & SSL_PROTOCOL_SSLV3 ? "SSLv3, " : ""),
398                     (protocol & SSL_PROTOCOL_TLSV1 ? "TLSv1, " : ""),
399#ifdef HAVE_TLSV1_X
400                     (protocol & SSL_PROTOCOL_TLSV1_1 ? "TLSv1.1, " : ""),
401                     (protocol & SSL_PROTOCOL_TLSV1_2 ? "TLSv1.2, " : ""),
402#endif
403                     NULL);
404    cp[strlen(cp)-2] = NUL;
405
406    ap_log_error(APLOG_MARK, APLOG_TRACE3, 0, s,
407                 "Creating new SSL context (protocols: %s)", cp);
408
409    if (protocol == SSL_PROTOCOL_SSLV3) {
410        method = mctx->pkp ?
411            SSLv3_client_method() : /* proxy */
412            SSLv3_server_method();  /* server */
413    }
414    else if (protocol == SSL_PROTOCOL_TLSV1) {
415        method = mctx->pkp ?
416            TLSv1_client_method() : /* proxy */
417            TLSv1_server_method();  /* server */
418    }
419#ifdef HAVE_TLSV1_X
420    else if (protocol == SSL_PROTOCOL_TLSV1_1) {
421        method = mctx->pkp ?
422            TLSv1_1_client_method() : /* proxy */
423            TLSv1_1_server_method();  /* server */
424    }
425    else if (protocol == SSL_PROTOCOL_TLSV1_2) {
426        method = mctx->pkp ?
427            TLSv1_2_client_method() : /* proxy */
428            TLSv1_2_server_method();  /* server */
429    }
430#endif
431    else { /* For multiple protocols, we need a flexible method */
432        method = mctx->pkp ?
433            SSLv23_client_method() : /* proxy */
434            SSLv23_server_method();  /* server */
435    }
436    ctx = SSL_CTX_new(method);
437
438    mctx->ssl_ctx = ctx;
439
440    SSL_CTX_set_options(ctx, SSL_OP_ALL);
441
442    if (sc->allow_empty_fragments) {
443        SSL_CTX_clear_options(ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
444    }
445
446    /* always disable SSLv2, as per RFC 6176 */
447    SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
448
449    if (!(protocol & SSL_PROTOCOL_SSLV3)) {
450        SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);
451    }
452
453    if (!(protocol & SSL_PROTOCOL_TLSV1)) {
454        SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1);
455    }
456
457#ifdef HAVE_TLSV1_X
458    if (!(protocol & SSL_PROTOCOL_TLSV1_1)) {
459        SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_1);
460    }
461
462    if (!(protocol & SSL_PROTOCOL_TLSV1_2)) {
463        SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_2);
464    }
465#endif
466
467#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
468    if (sc->cipher_server_pref == TRUE) {
469        SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
470    }
471#endif
472
473
474#ifndef OPENSSL_NO_COMP
475    if (sc->compression != TRUE) {
476#ifdef SSL_OP_NO_COMPRESSION
477        /* OpenSSL >= 1.0 only */
478        SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION);
479#else
480        sk_SSL_COMP_zero(SSL_COMP_get_compression_methods());
481#endif
482    }
483#endif
484
485#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
486    if (sc->insecure_reneg == TRUE) {
487        SSL_CTX_set_options(ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
488    }
489#endif
490
491    SSL_CTX_set_app_data(ctx, s);
492
493    /*
494     * Configure additional context ingredients
495     */
496    SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
497#ifdef HAVE_ECC
498    SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
499#endif
500
501#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
502    /*
503     * Disallow a session from being resumed during a renegotiation,
504     * so that an acceptable cipher suite can be negotiated.
505     */
506    SSL_CTX_set_options(ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
507#endif
508
509#ifdef SSL_MODE_RELEASE_BUFFERS
510    /* If httpd is configured to reduce mem usage, ask openssl to do so, too */
511    if (ap_max_mem_free != APR_ALLOCATOR_MAX_FREE_UNLIMITED)
512        SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
513#endif
514
515    return APR_SUCCESS;
516}
517
518static void ssl_init_ctx_session_cache(server_rec *s,
519                                       apr_pool_t *p,
520                                       apr_pool_t *ptemp,
521                                       modssl_ctx_t *mctx)
522{
523    SSL_CTX *ctx = mctx->ssl_ctx;
524    SSLModConfigRec *mc = myModConfig(s);
525
526    SSL_CTX_set_session_cache_mode(ctx, mc->sesscache_mode);
527
528    if (mc->sesscache) {
529        SSL_CTX_sess_set_new_cb(ctx,    ssl_callback_NewSessionCacheEntry);
530        SSL_CTX_sess_set_get_cb(ctx,    ssl_callback_GetSessionCacheEntry);
531        SSL_CTX_sess_set_remove_cb(ctx, ssl_callback_DelSessionCacheEntry);
532    }
533}
534
535static void ssl_init_ctx_callbacks(server_rec *s,
536                                   apr_pool_t *p,
537                                   apr_pool_t *ptemp,
538                                   modssl_ctx_t *mctx)
539{
540    SSL_CTX *ctx = mctx->ssl_ctx;
541
542    SSL_CTX_set_tmp_dh_callback(ctx,  ssl_callback_TmpDH);
543
544    SSL_CTX_set_info_callback(ctx, ssl_callback_Info);
545}
546
547static apr_status_t ssl_init_ctx_verify(server_rec *s,
548                                        apr_pool_t *p,
549                                        apr_pool_t *ptemp,
550                                        modssl_ctx_t *mctx)
551{
552    SSL_CTX *ctx = mctx->ssl_ctx;
553
554    int verify = SSL_VERIFY_NONE;
555    STACK_OF(X509_NAME) *ca_list;
556
557    if (mctx->auth.verify_mode == SSL_CVERIFY_UNSET) {
558        mctx->auth.verify_mode = SSL_CVERIFY_NONE;
559    }
560
561    if (mctx->auth.verify_depth == UNSET) {
562        mctx->auth.verify_depth = 1;
563    }
564
565    /*
566     *  Configure callbacks for SSL context
567     */
568    if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
569        verify |= SSL_VERIFY_PEER_STRICT;
570    }
571
572    if ((mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL) ||
573        (mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL_NO_CA))
574    {
575        verify |= SSL_VERIFY_PEER;
576    }
577
578    SSL_CTX_set_verify(ctx, verify, ssl_callback_SSLVerify);
579
580    /*
581     * Configure Client Authentication details
582     */
583    if (mctx->auth.ca_cert_file || mctx->auth.ca_cert_path) {
584        ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, s,
585                     "Configuring client authentication");
586
587        if (!SSL_CTX_load_verify_locations(ctx,
588                                           mctx->auth.ca_cert_file,
589                                           mctx->auth.ca_cert_path))
590        {
591            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01895)
592                    "Unable to configure verify locations "
593                    "for client authentication");
594            ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
595            return ssl_die(s);
596        }
597
598        if (mctx->pks && (mctx->pks->ca_name_file || mctx->pks->ca_name_path)) {
599            ca_list = ssl_init_FindCAList(s, ptemp,
600                                          mctx->pks->ca_name_file,
601                                          mctx->pks->ca_name_path);
602        } else
603            ca_list = ssl_init_FindCAList(s, ptemp,
604                                          mctx->auth.ca_cert_file,
605                                          mctx->auth.ca_cert_path);
606        if (sk_X509_NAME_num(ca_list) <= 0) {
607            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01896)
608                    "Unable to determine list of acceptable "
609                    "CA certificates for client authentication");
610            return ssl_die(s);
611        }
612
613        SSL_CTX_set_client_CA_list(ctx, ca_list);
614    }
615
616    /*
617     * Give a warning when no CAs were configured but client authentication
618     * should take place. This cannot work.
619     */
620    if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
621        ca_list = SSL_CTX_get_client_CA_list(ctx);
622
623        if (sk_X509_NAME_num(ca_list) == 0) {
624            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01897)
625                         "Init: Oops, you want to request client "
626                         "authentication, but no CAs are known for "
627                         "verification!?  [Hint: SSLCACertificate*]");
628        }
629    }
630
631    return APR_SUCCESS;
632}
633
634static apr_status_t ssl_init_ctx_cipher_suite(server_rec *s,
635                                              apr_pool_t *p,
636                                              apr_pool_t *ptemp,
637                                              modssl_ctx_t *mctx)
638{
639    SSL_CTX *ctx = mctx->ssl_ctx;
640    const char *suite;
641
642    /*
643     *  Configure SSL Cipher Suite. Always disable NULL and export ciphers,
644     *  see also ssl_engine_config.c:ssl_cmd_SSLCipherSuite().
645     *  OpenSSL's SSL_DEFAULT_CIPHER_LIST already includes !aNULL:!eNULL,
646     *  so only prepend !EXP in this case.
647     */
648    suite = mctx->auth.cipher_suite ? mctx->auth.cipher_suite :
649            apr_pstrcat(ptemp, "!EXP:", SSL_DEFAULT_CIPHER_LIST, NULL);
650
651    ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, s,
652                 "Configuring permitted SSL ciphers [%s]",
653                 suite);
654
655    if (!SSL_CTX_set_cipher_list(ctx, suite)) {
656        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01898)
657                "Unable to configure permitted SSL ciphers");
658        ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
659        return ssl_die(s);
660    }
661
662    return APR_SUCCESS;
663}
664
665static apr_status_t ssl_init_ctx_crl(server_rec *s,
666                                     apr_pool_t *p,
667                                     apr_pool_t *ptemp,
668                                     modssl_ctx_t *mctx)
669{
670    X509_STORE *store = SSL_CTX_get_cert_store(mctx->ssl_ctx);
671    unsigned long crlflags = 0;
672    char *cfgp = mctx->pkp ? "SSLProxy" : "SSL";
673
674    /*
675     * Configure Certificate Revocation List (CRL) Details
676     */
677
678    if (!(mctx->crl_file || mctx->crl_path)) {
679        if (mctx->crl_check_mode == SSL_CRLCHECK_LEAF ||
680            mctx->crl_check_mode == SSL_CRLCHECK_CHAIN) {
681            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01899)
682                         "Host %s: CRL checking has been enabled, but "
683                         "neither %sCARevocationFile nor %sCARevocationPath "
684                         "is configured", mctx->sc->vhost_id, cfgp, cfgp);
685            return ssl_die(s);
686        }
687        return APR_SUCCESS;
688    }
689
690    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01900)
691                 "Configuring certificate revocation facility");
692
693    if (!store || !X509_STORE_load_locations(store, mctx->crl_file,
694                                             mctx->crl_path)) {
695        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01901)
696                     "Host %s: unable to configure X.509 CRL storage "
697                     "for certificate revocation", mctx->sc->vhost_id);
698        ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
699        return ssl_die(s);
700    }
701
702    switch (mctx->crl_check_mode) {
703       case SSL_CRLCHECK_LEAF:
704           crlflags = X509_V_FLAG_CRL_CHECK;
705           break;
706       case SSL_CRLCHECK_CHAIN:
707           crlflags = X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
708           break;
709       default:
710           crlflags = 0;
711    }
712
713    if (crlflags) {
714        X509_STORE_set_flags(store, crlflags);
715    } else {
716        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01902)
717                     "Host %s: X.509 CRL storage locations configured, "
718                     "but CRL checking (%sCARevocationCheck) is not "
719                     "enabled", mctx->sc->vhost_id, cfgp);
720    }
721
722    return APR_SUCCESS;
723}
724
725static apr_status_t ssl_init_ctx_cert_chain(server_rec *s,
726                                            apr_pool_t *p,
727                                            apr_pool_t *ptemp,
728                                            modssl_ctx_t *mctx)
729{
730    BOOL skip_first = FALSE;
731    int i, n;
732    const char *chain = mctx->cert_chain;
733
734    /*
735     * Optionally configure extra server certificate chain certificates.
736     * This is usually done by OpenSSL automatically when one of the
737     * server cert issuers are found under SSLCACertificatePath or in
738     * SSLCACertificateFile. But because these are intended for client
739     * authentication it can conflict. For instance when you use a
740     * Global ID server certificate you've to send out the intermediate
741     * CA certificate, too. When you would just configure this with
742     * SSLCACertificateFile and also use client authentication mod_ssl
743     * would accept all clients also issued by this CA. Obviously this
744     * isn't what we want in this situation. So this feature here exists
745     * to allow one to explicity configure CA certificates which are
746     * used only for the server certificate chain.
747     */
748    if (!chain) {
749        return APR_SUCCESS;
750    }
751
752    for (i = 0; (i < mctx->pks->cert_files->nelts) &&
753         APR_ARRAY_IDX(mctx->pks->cert_files, i, const char *); i++) {
754        if (strEQ(APR_ARRAY_IDX(mctx->pks->cert_files, i, const char *), chain)) {
755            skip_first = TRUE;
756            break;
757        }
758    }
759
760    n = SSL_CTX_use_certificate_chain(mctx->ssl_ctx,
761                                      (char *)chain,
762                                      skip_first, NULL);
763    if (n < 0) {
764        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01903)
765                "Failed to configure CA certificate chain!");
766        return ssl_die(s);
767    }
768
769    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01904)
770                 "Configuring server certificate chain "
771                 "(%d CA certificate%s)",
772                 n, n == 1 ? "" : "s");
773
774    return APR_SUCCESS;
775}
776
777static apr_status_t ssl_init_ctx(server_rec *s,
778                                 apr_pool_t *p,
779                                 apr_pool_t *ptemp,
780                                 modssl_ctx_t *mctx)
781{
782    apr_status_t rv;
783
784    if ((rv = ssl_init_ctx_protocol(s, p, ptemp, mctx)) != APR_SUCCESS) {
785        return rv;
786    }
787
788    ssl_init_ctx_session_cache(s, p, ptemp, mctx);
789
790    ssl_init_ctx_callbacks(s, p, ptemp, mctx);
791
792    if ((rv = ssl_init_ctx_verify(s, p, ptemp, mctx)) != APR_SUCCESS) {
793        return rv;
794    }
795
796    if ((rv = ssl_init_ctx_cipher_suite(s, p, ptemp, mctx)) != APR_SUCCESS) {
797        return rv;
798    }
799
800    if ((rv = ssl_init_ctx_crl(s, p, ptemp, mctx)) != APR_SUCCESS) {
801        return rv;
802    }
803
804    if (mctx->pks) {
805        /* XXX: proxy support? */
806        if ((rv = ssl_init_ctx_cert_chain(s, p, ptemp, mctx)) != APR_SUCCESS) {
807            return rv;
808        }
809#ifdef HAVE_TLSEXT
810        if ((rv = ssl_init_ctx_tls_extensions(s, p, ptemp, mctx)) !=
811            APR_SUCCESS) {
812            return rv;
813        }
814#endif
815    }
816
817    return APR_SUCCESS;
818}
819
820static void ssl_check_public_cert(server_rec *s,
821                                  apr_pool_t *ptemp,
822                                  X509 *cert,
823                                  const char *key_id)
824{
825    int is_ca, pathlen;
826
827    if (!cert) {
828        return;
829    }
830
831    /*
832     * Some information about the certificate(s)
833     */
834
835    if (SSL_X509_getBC(cert, &is_ca, &pathlen)) {
836        if (is_ca) {
837            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01906)
838                         "%s server certificate is a CA certificate "
839                         "(BasicConstraints: CA == TRUE !?)", key_id);
840        }
841
842        if (pathlen > 0) {
843            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01907)
844                         "%s server certificate is not a leaf certificate "
845                         "(BasicConstraints: pathlen == %d > 0 !?)",
846                         key_id, pathlen);
847        }
848    }
849
850    if (SSL_X509_match_name(ptemp, cert, (const char *)s->server_hostname,
851                            TRUE, s) == FALSE) {
852        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01909)
853                     "%s server certificate does NOT include an ID "
854                     "which matches the server name", key_id);
855    }
856}
857
858/* prevent OpenSSL from showing its "Enter PEM pass phrase:" prompt */
859static int ssl_no_passwd_prompt_cb(char *buf, int size, int rwflag,
860                                   void *userdata) {
861   return 0;
862}
863
864static apr_status_t ssl_init_server_certs(server_rec *s,
865                                          apr_pool_t *p,
866                                          apr_pool_t *ptemp,
867                                          modssl_ctx_t *mctx,
868                                          apr_array_header_t *pphrases)
869{
870    SSLModConfigRec *mc = myModConfig(s);
871    const char *vhost_id = mctx->sc->vhost_id, *key_id, *certfile, *keyfile;
872    int i;
873    X509 *cert;
874    DH *dhparams;
875#ifdef HAVE_ECC
876    EC_GROUP *ecparams;
877    int nid;
878    EC_KEY *eckey;
879#endif
880#ifndef HAVE_SSL_CONF_CMD
881    SSL *ssl;
882#endif
883
884    /* no OpenSSL default prompts for any of the SSL_CTX_use_* calls, please */
885    SSL_CTX_set_default_passwd_cb(mctx->ssl_ctx, ssl_no_passwd_prompt_cb);
886
887    /* Iterate over the SSLCertificateFile array */
888    for (i = 0; (i < mctx->pks->cert_files->nelts) &&
889                (certfile = APR_ARRAY_IDX(mctx->pks->cert_files, i,
890                                          const char *));
891         i++) {
892        key_id = apr_psprintf(ptemp, "%s:%d", vhost_id, i);
893
894        /* first the certificate (public key) */
895        if (mctx->cert_chain) {
896            if ((SSL_CTX_use_certificate_file(mctx->ssl_ctx, certfile,
897                                              SSL_FILETYPE_PEM) < 1)) {
898                ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02561)
899                             "Failed to configure certificate %s, check %s",
900                             key_id, certfile);
901                ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
902                return APR_EGENERAL;
903            }
904        } else {
905            if ((SSL_CTX_use_certificate_chain_file(mctx->ssl_ctx,
906                                                    certfile) < 1)) {
907                ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02562)
908                             "Failed to configure certificate %s (with chain),"
909                             " check %s", key_id, certfile);
910                ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
911                return APR_EGENERAL;
912            }
913        }
914
915        /* and second, the private key */
916        keyfile = APR_ARRAY_IDX(mctx->pks->key_files, i, const char *);
917        if (keyfile == NULL)
918            keyfile = certfile;
919
920        ERR_clear_error();
921
922        if ((SSL_CTX_use_PrivateKey_file(mctx->ssl_ctx, keyfile,
923                                         SSL_FILETYPE_PEM) < 1) &&
924            (ERR_GET_FUNC(ERR_peek_last_error())
925                != X509_F_X509_CHECK_PRIVATE_KEY)) {
926            ssl_asn1_t *asn1;
927            EVP_PKEY *pkey;
928            const unsigned char *ptr;
929
930            ERR_clear_error();
931
932            /* perhaps it's an encrypted private key, so try again */
933            ssl_load_encrypted_pkey(s, ptemp, i, keyfile, &pphrases);
934
935            if (!(asn1 = ssl_asn1_table_get(mc->tPrivateKey, key_id)) ||
936                !(ptr = asn1->cpData) ||
937                !(pkey = d2i_AutoPrivateKey(NULL, &ptr, asn1->nData)) ||
938                (SSL_CTX_use_PrivateKey(mctx->ssl_ctx, pkey) < 1)) {
939                ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02564)
940                             "Failed to configure encrypted (?) private key %s,"
941                             " check %s", key_id, keyfile);
942                ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
943                return APR_EGENERAL;
944            }
945        }
946
947        if (SSL_CTX_check_private_key(mctx->ssl_ctx) < 1) {
948            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02565)
949                         "Certificate and private key %s from %s and %s "
950                         "do not match", key_id, certfile, keyfile);
951            return APR_EGENERAL;
952        }
953
954#ifdef HAVE_SSL_CONF_CMD
955        /*
956         * workaround for those OpenSSL versions where SSL_CTX_get0_certificate
957         * is not yet available: create an SSL struct which we dispose of
958         * as soon as we no longer need access to the cert. (Strictly speaking,
959         * SSL_CTX_get0_certificate does not depend on the SSL_CONF stuff,
960         * but there's no reliable way to check for its existence, so we
961         * assume that if SSL_CONF is available, it's OpenSSL 1.0.2 or later,
962         * and SSL_CTX_get0_certificate is implemented.)
963         */
964        if (!(cert = SSL_CTX_get0_certificate(mctx->ssl_ctx))) {
965#else
966        ssl = SSL_new(mctx->ssl_ctx);
967	if (ssl) {
968            /* Workaround bug in SSL_get_certificate in OpenSSL 0.9.8y */
969            SSL_set_connect_state(ssl);
970            cert = SSL_get_certificate(ssl);
971        }
972        if (!ssl || !cert) {
973#endif
974            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02566)
975                         "Unable to retrieve certificate %s", key_id);
976#ifndef HAVE_SSL_CONF_CMD
977            if (ssl)
978                SSL_free(ssl);
979#endif
980            return APR_EGENERAL;
981        }
982
983        /* warn about potential cert issues */
984        ssl_check_public_cert(s, ptemp, cert, key_id);
985
986#if defined(HAVE_OCSP_STAPLING) && !defined(SSL_CTRL_SET_CURRENT_CERT)
987        /*
988         * OpenSSL up to 1.0.1: configure stapling as we go. In 1.0.2
989         * and later, there's SSL_CTX_set_current_cert, which allows
990         * iterating over all certs in an SSL_CTX (including those possibly
991         * loaded via SSLOpenSSLConfCmd Certificate), so for 1.0.2 and
992         * later, we defer to the code in ssl_init_server_ctx.
993         */
994        if ((mctx->stapling_enabled == TRUE) &&
995            !ssl_stapling_init_cert(s, mctx, cert)) {
996            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02567)
997                         "Unable to configure certificate %s for stapling",
998                         key_id);
999        }
1000#endif
1001
1002#ifndef HAVE_SSL_CONF_CMD
1003        SSL_free(ssl);
1004#endif
1005
1006        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02568)
1007                     "Certificate and private key %s configured from %s and %s",
1008                     key_id, certfile, keyfile);
1009    }
1010
1011    /*
1012     * Try to read DH parameters from the (first) SSLCertificateFile
1013     */
1014    if ((certfile = APR_ARRAY_IDX(mctx->pks->cert_files, 0, const char *)) &&
1015        (dhparams = ssl_dh_GetParamFromFile(certfile))) {
1016        SSL_CTX_set_tmp_dh(mctx->ssl_ctx, dhparams);
1017        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02540)
1018                     "Custom DH parameters (%d bits) for %s loaded from %s",
1019                     BN_num_bits(dhparams->p), vhost_id, certfile);
1020    }
1021
1022#ifdef HAVE_ECC
1023    /*
1024     * Similarly, try to read the ECDH curve name from SSLCertificateFile...
1025     */
1026    if ((certfile != NULL) &&
1027        (ecparams = ssl_ec_GetParamFromFile(certfile)) &&
1028        (nid = EC_GROUP_get_curve_name(ecparams)) &&
1029        (eckey = EC_KEY_new_by_curve_name(nid))) {
1030        SSL_CTX_set_tmp_ecdh(mctx->ssl_ctx, eckey);
1031        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02541)
1032                     "ECDH curve %s for %s specified in %s",
1033                     OBJ_nid2sn(nid), vhost_id, certfile);
1034    }
1035    /*
1036     * ...otherwise, enable auto curve selection (OpenSSL 1.0.2 and later)
1037     * or configure NIST P-256 (required to enable ECDHE for earlier versions)
1038     */
1039    else {
1040#if defined(SSL_CTX_set_ecdh_auto)
1041        SSL_CTX_set_ecdh_auto(mctx->ssl_ctx, 1);
1042#else
1043        SSL_CTX_set_tmp_ecdh(mctx->ssl_ctx,
1044                             EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
1045#endif
1046    }
1047#endif
1048
1049    return APR_SUCCESS;
1050}
1051
1052#ifdef HAVE_TLS_SESSION_TICKETS
1053static apr_status_t ssl_init_ticket_key(server_rec *s,
1054                                        apr_pool_t *p,
1055                                        apr_pool_t *ptemp,
1056                                        modssl_ctx_t *mctx)
1057{
1058    apr_status_t rv;
1059    apr_file_t *fp;
1060    apr_size_t len;
1061    char buf[TLSEXT_TICKET_KEY_LEN];
1062    char *path;
1063    modssl_ticket_key_t *ticket_key = mctx->ticket_key;
1064
1065    if (!ticket_key->file_path) {
1066        return APR_SUCCESS;
1067    }
1068
1069    path = ap_server_root_relative(p, ticket_key->file_path);
1070
1071    rv = apr_file_open(&fp, path, APR_READ|APR_BINARY,
1072                       APR_OS_DEFAULT, ptemp);
1073
1074    if (rv != APR_SUCCESS) {
1075        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02286)
1076                     "Failed to open ticket key file %s: (%d) %pm",
1077                     path, rv, &rv);
1078        return ssl_die(s);
1079    }
1080
1081    rv = apr_file_read_full(fp, &buf[0], TLSEXT_TICKET_KEY_LEN, &len);
1082
1083    if (rv != APR_SUCCESS) {
1084        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02287)
1085                     "Failed to read %d bytes from %s: (%d) %pm",
1086                     TLSEXT_TICKET_KEY_LEN, path, rv, &rv);
1087        return ssl_die(s);
1088    }
1089
1090    memcpy(ticket_key->key_name, buf, 16);
1091    memcpy(ticket_key->hmac_secret, buf + 16, 16);
1092    memcpy(ticket_key->aes_key, buf + 32, 16);
1093
1094    if (!SSL_CTX_set_tlsext_ticket_key_cb(mctx->ssl_ctx,
1095                                          ssl_callback_SessionTicket)) {
1096        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01913)
1097                     "Unable to initialize TLS session ticket key callback "
1098                     "(incompatible OpenSSL version?)");
1099        ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1100        return ssl_die(s);
1101    }
1102
1103    ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02288)
1104                 "TLS session ticket key for %s successfully loaded from %s",
1105                 (mySrvConfig(s))->vhost_id, path);
1106
1107    return APR_SUCCESS;
1108}
1109#endif
1110
1111static apr_status_t 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    modssl_pk_proxy_t *pkp = mctx->pkp;
1119    STACK_OF(X509) *chain;
1120    X509_STORE_CTX *sctx;
1121    X509_STORE *store = SSL_CTX_get_cert_store(mctx->ssl_ctx);
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 APR_SUCCESS;
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, APLOGNO(02206)
1143                     "no client certs found for SSL proxy");
1144        return APR_SUCCESS;
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, APLOGNO(02252)
1156                         "incomplete client cert configured for SSL proxy "
1157                         "(missing or encrypted private key?)");
1158            return ssl_die(s);
1159        }
1160
1161        if (X509_check_private_key(inf->x509, inf->x_pkey->dec_pkey) != 1) {
1162            ssl_log_xerror(SSLLOG_MARK, APLOG_STARTUP, 0, ptemp, s, inf->x509,
1163                           APLOGNO(02326) "proxy client certificate and "
1164                           "private key do not match");
1165            ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
1166            return ssl_die(s);
1167        }
1168    }
1169
1170    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02207)
1171                 "loaded %d client certs for SSL proxy",
1172                 ncerts);
1173    pkp->certs = sk;
1174
1175
1176    if (!pkp->ca_cert_file || !store) {
1177        return APR_SUCCESS;
1178    }
1179
1180    /* If SSLProxyMachineCertificateChainFile is configured, load all
1181     * the CA certs and have OpenSSL attempt to construct a full chain
1182     * from each configured end-entity cert up to a root.  This will
1183     * allow selection of the correct cert given a list of root CA
1184     * names in the certificate request from the server.  */
1185    pkp->ca_certs = (STACK_OF(X509) **) apr_pcalloc(p, ncerts * sizeof(sk));
1186    sctx = X509_STORE_CTX_new();
1187
1188    if (!sctx) {
1189        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02208)
1190                     "SSL proxy client cert initialization failed");
1191        ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1192        return ssl_die(s);
1193    }
1194
1195    X509_STORE_load_locations(store, pkp->ca_cert_file, NULL);
1196
1197    for (n = 0; n < ncerts; n++) {
1198        int i;
1199
1200        X509_INFO *inf = sk_X509_INFO_value(pkp->certs, n);
1201        X509_STORE_CTX_init(sctx, store, inf->x509, NULL);
1202
1203        /* Attempt to verify the client cert */
1204        if (X509_verify_cert(sctx) != 1) {
1205            int err = X509_STORE_CTX_get_error(sctx);
1206            ssl_log_xerror(SSLLOG_MARK, APLOG_WARNING, 0, ptemp, s, inf->x509,
1207                           APLOGNO(02270) "SSL proxy client cert chain "
1208                           "verification failed: %s :",
1209                           X509_verify_cert_error_string(err));
1210        }
1211
1212        /* Clear X509_verify_cert errors */
1213        ERR_clear_error();
1214
1215        /* Obtain a copy of the verified chain */
1216        chain = X509_STORE_CTX_get1_chain(sctx);
1217
1218        if (chain != NULL) {
1219            /* Discard end entity cert from the chain */
1220            X509_free(sk_X509_shift(chain));
1221
1222            if ((i = sk_X509_num(chain)) > 0) {
1223                /* Store the chain for later use */
1224                pkp->ca_certs[n] = chain;
1225            }
1226            else {
1227                /* Discard empty chain */
1228                sk_X509_pop_free(chain, X509_free);
1229                pkp->ca_certs[n] = NULL;
1230            }
1231
1232            ssl_log_xerror(SSLLOG_MARK, APLOG_DEBUG, 0, ptemp, s, inf->x509,
1233                           APLOGNO(02271)
1234                           "loaded %i intermediate CA%s for cert %i: ",
1235                           i, i == 1 ? "" : "s", n);
1236            if (i > 0) {
1237                int j;
1238                for (j = 0; j < i; j++) {
1239                    ssl_log_xerror(SSLLOG_MARK, APLOG_DEBUG, 0, ptemp, s,
1240                                   sk_X509_value(chain, j), "%i:", j);
1241                }
1242            }
1243        }
1244
1245        /* get ready for next X509_STORE_CTX_init */
1246        X509_STORE_CTX_cleanup(sctx);
1247    }
1248
1249    X509_STORE_CTX_free(sctx);
1250
1251    return APR_SUCCESS;
1252}
1253
1254static apr_status_t ssl_init_proxy_ctx(server_rec *s,
1255                                       apr_pool_t *p,
1256                                       apr_pool_t *ptemp,
1257                                       SSLSrvConfigRec *sc)
1258{
1259    apr_status_t rv;
1260
1261    if ((rv = ssl_init_ctx(s, p, ptemp, sc->proxy)) != APR_SUCCESS) {
1262        return rv;
1263    }
1264
1265    if ((rv = ssl_init_proxy_certs(s, p, ptemp, sc->proxy)) != APR_SUCCESS) {
1266        return rv;
1267    }
1268
1269    return APR_SUCCESS;
1270}
1271
1272static apr_status_t ssl_init_server_ctx(server_rec *s,
1273                                        apr_pool_t *p,
1274                                        apr_pool_t *ptemp,
1275                                        SSLSrvConfigRec *sc,
1276                                        apr_array_header_t *pphrases)
1277{
1278    apr_status_t rv;
1279#ifdef HAVE_SSL_CONF_CMD
1280    ssl_ctx_param_t *param = (ssl_ctx_param_t *)sc->server->ssl_ctx_param->elts;
1281    SSL_CONF_CTX *cctx = sc->server->ssl_ctx_config;
1282    int i;
1283#endif
1284
1285    /*
1286     *  Check for problematic re-initializations
1287     */
1288    if (sc->server->ssl_ctx) {
1289        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02569)
1290                     "Illegal attempt to re-initialise SSL for server "
1291                     "(SSLEngine On should go in the VirtualHost, not in global scope.)");
1292        return APR_EGENERAL;
1293    }
1294
1295    if ((rv = ssl_init_ctx(s, p, ptemp, sc->server)) != APR_SUCCESS) {
1296        return rv;
1297    }
1298
1299    if ((rv = ssl_init_server_certs(s, p, ptemp, sc->server, pphrases))
1300        != APR_SUCCESS) {
1301        return rv;
1302    }
1303
1304#ifdef HAVE_SSL_CONF_CMD
1305    SSL_CONF_CTX_set_ssl_ctx(cctx, sc->server->ssl_ctx);
1306    for (i = 0; i < sc->server->ssl_ctx_param->nelts; i++, param++) {
1307        ERR_clear_error();
1308        if (SSL_CONF_cmd(cctx, param->name, param->value) <= 0) {
1309            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02407)
1310                         "\"SSLOpenSSLConfCmd %s %s\" failed for %s",
1311                         param->name, param->value, sc->vhost_id);
1312            ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1313            return ssl_die(s);
1314        } else {
1315            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02556)
1316                         "\"SSLOpenSSLConfCmd %s %s\" applied to %s",
1317                         param->name, param->value, sc->vhost_id);
1318        }
1319    }
1320
1321    if (SSL_CONF_CTX_finish(cctx) == 0) {
1322            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02547)
1323                         "SSL_CONF_CTX_finish() failed");
1324            SSL_CONF_CTX_free(cctx);
1325            ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1326            return ssl_die(s);
1327    }
1328    SSL_CONF_CTX_free(cctx);
1329#endif
1330
1331    if (SSL_CTX_check_private_key(sc->server->ssl_ctx) != 1) {
1332        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02572)
1333                     "Failed to configure at least one certificate and key "
1334                     "for %s", sc->vhost_id);
1335        ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1336        return ssl_die(s);
1337    }
1338
1339#if defined(HAVE_OCSP_STAPLING) && defined(SSL_CTRL_SET_CURRENT_CERT)
1340    /*
1341     * OpenSSL 1.0.2 and later allows iterating over all SSL_CTX certs
1342     * by means of SSL_CTX_set_current_cert. Enabling stapling at this
1343     * (late) point makes sure that we catch both certificates loaded
1344     * via SSLCertificateFile and SSLOpenSSLConfCmd Certificate.
1345     */
1346    if (sc->server->stapling_enabled == TRUE) {
1347        X509 *cert;
1348        int i = 0;
1349        int ret = SSL_CTX_set_current_cert(sc->server->ssl_ctx,
1350                                           SSL_CERT_SET_FIRST);
1351        while (ret) {
1352            cert = SSL_CTX_get0_certificate(sc->server->ssl_ctx);
1353            if (!cert || !ssl_stapling_init_cert(s, sc->server, cert)) {
1354                ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02604)
1355                             "Unable to configure certificate %s:%d "
1356                             "for stapling", sc->vhost_id, i);
1357            }
1358            ret = SSL_CTX_set_current_cert(sc->server->ssl_ctx,
1359                                           SSL_CERT_SET_NEXT);
1360            i++;
1361        }
1362    }
1363#endif
1364
1365#ifdef HAVE_TLS_SESSION_TICKETS
1366    if ((rv = ssl_init_ticket_key(s, p, ptemp, sc->server)) != APR_SUCCESS) {
1367        return rv;
1368    }
1369#endif
1370
1371    return APR_SUCCESS;
1372}
1373
1374/*
1375 * Configure a particular server
1376 */
1377apr_status_t ssl_init_ConfigureServer(server_rec *s,
1378                                      apr_pool_t *p,
1379                                      apr_pool_t *ptemp,
1380                                      SSLSrvConfigRec *sc,
1381                                      apr_array_header_t *pphrases)
1382{
1383    apr_status_t rv;
1384
1385    /* Initialize the server if SSL is enabled or optional.
1386     */
1387    if ((sc->enabled == SSL_ENABLED_TRUE) || (sc->enabled == SSL_ENABLED_OPTIONAL)) {
1388        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01914)
1389                     "Configuring server %s for SSL protocol", sc->vhost_id);
1390        if ((rv = ssl_init_server_ctx(s, p, ptemp, sc, pphrases))
1391            != APR_SUCCESS) {
1392            return rv;
1393        }
1394    }
1395
1396    if (sc->proxy_enabled) {
1397        if ((rv = ssl_init_proxy_ctx(s, p, ptemp, sc)) != APR_SUCCESS) {
1398            return rv;
1399        }
1400    }
1401
1402    return APR_SUCCESS;
1403}
1404
1405apr_status_t ssl_init_CheckServers(server_rec *base_server, apr_pool_t *p)
1406{
1407    server_rec *s, *ps;
1408    SSLSrvConfigRec *sc;
1409    apr_hash_t *table;
1410    const char *key;
1411    apr_ssize_t klen;
1412
1413    BOOL conflict = FALSE;
1414
1415    /*
1416     * Give out warnings when a server has HTTPS configured
1417     * for the HTTP port or vice versa
1418     */
1419    for (s = base_server; s; s = s->next) {
1420        sc = mySrvConfig(s);
1421
1422        if ((sc->enabled == SSL_ENABLED_TRUE) && (s->port == DEFAULT_HTTP_PORT)) {
1423            ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1424                         base_server, APLOGNO(01915)
1425                         "Init: (%s) You configured HTTPS(%d) "
1426                         "on the standard HTTP(%d) port!",
1427                         ssl_util_vhostid(p, s),
1428                         DEFAULT_HTTPS_PORT, DEFAULT_HTTP_PORT);
1429        }
1430
1431        if ((sc->enabled == SSL_ENABLED_FALSE) && (s->port == DEFAULT_HTTPS_PORT)) {
1432            ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1433                         base_server, APLOGNO(01916)
1434                         "Init: (%s) You configured HTTP(%d) "
1435                         "on the standard HTTPS(%d) port!",
1436                         ssl_util_vhostid(p, s),
1437                         DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT);
1438        }
1439    }
1440
1441    /*
1442     * Give out warnings when more than one SSL-aware virtual server uses the
1443     * same IP:port. This doesn't work because mod_ssl then will always use
1444     * just the certificate/keys of one virtual host (which one cannot be said
1445     * easily - but that doesn't matter here).
1446     */
1447    table = apr_hash_make(p);
1448
1449    for (s = base_server; s; s = s->next) {
1450        char *addr;
1451
1452        sc = mySrvConfig(s);
1453
1454        if (!((sc->enabled == SSL_ENABLED_TRUE) && s->addrs)) {
1455            continue;
1456        }
1457
1458        apr_sockaddr_ip_get(&addr, s->addrs->host_addr);
1459        key = apr_psprintf(p, "%s:%u", addr, s->addrs->host_port);
1460        klen = strlen(key);
1461
1462        if ((ps = (server_rec *)apr_hash_get(table, key, klen))) {
1463#ifndef HAVE_TLSEXT
1464            int level = APLOG_WARNING;
1465            const char *problem = "conflict";
1466#else
1467            int level = APLOG_DEBUG;
1468            const char *problem = "overlap";
1469#endif
1470            ap_log_error(APLOG_MARK, level, 0, base_server,
1471                         "Init: SSL server IP/port %s: "
1472                         "%s (%s:%d) vs. %s (%s:%d)",
1473                         problem, ssl_util_vhostid(p, s),
1474                         (s->defn_name ? s->defn_name : "unknown"),
1475                         s->defn_line_number,
1476                         ssl_util_vhostid(p, ps),
1477                         (ps->defn_name ? ps->defn_name : "unknown"),
1478                         ps->defn_line_number);
1479            conflict = TRUE;
1480            continue;
1481        }
1482
1483        apr_hash_set(table, key, klen, s);
1484    }
1485
1486    if (conflict) {
1487#ifndef HAVE_TLSEXT
1488        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, base_server, APLOGNO(01917)
1489                     "Init: You should not use name-based "
1490                     "virtual hosts in conjunction with SSL!!");
1491#else
1492        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, base_server, APLOGNO(02292)
1493                     "Init: Name-based SSL virtual hosts only "
1494                     "work for clients with TLS server name indication "
1495                     "support (RFC 4366)");
1496#endif
1497    }
1498
1499    return APR_SUCCESS;
1500}
1501
1502static int ssl_init_FindCAList_X509NameCmp(const X509_NAME * const *a,
1503                                           const X509_NAME * const *b)
1504{
1505    return(X509_NAME_cmp(*a, *b));
1506}
1507
1508static void ssl_init_PushCAList(STACK_OF(X509_NAME) *ca_list,
1509                                server_rec *s, apr_pool_t *ptemp,
1510                                const char *file)
1511{
1512    int n;
1513    STACK_OF(X509_NAME) *sk;
1514
1515    sk = (STACK_OF(X509_NAME) *)
1516             SSL_load_client_CA_file(file);
1517
1518    if (!sk) {
1519        return;
1520    }
1521
1522    for (n = 0; n < sk_X509_NAME_num(sk); n++) {
1523        X509_NAME *name = sk_X509_NAME_value(sk, n);
1524
1525        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02209)
1526                     "CA certificate: %s",
1527                     SSL_X509_NAME_to_string(ptemp, name, 0));
1528
1529        /*
1530         * note that SSL_load_client_CA_file() checks for duplicates,
1531         * but since we call it multiple times when reading a directory
1532         * we must also check for duplicates ourselves.
1533         */
1534
1535        if (sk_X509_NAME_find(ca_list, name) < 0) {
1536            /* this will be freed when ca_list is */
1537            sk_X509_NAME_push(ca_list, name);
1538        }
1539        else {
1540            /* need to free this ourselves, else it will leak */
1541            X509_NAME_free(name);
1542        }
1543    }
1544
1545    sk_X509_NAME_free(sk);
1546}
1547
1548STACK_OF(X509_NAME) *ssl_init_FindCAList(server_rec *s,
1549                                         apr_pool_t *ptemp,
1550                                         const char *ca_file,
1551                                         const char *ca_path)
1552{
1553    STACK_OF(X509_NAME) *ca_list;
1554
1555    /*
1556     * Start with a empty stack/list where new
1557     * entries get added in sorted order.
1558     */
1559    ca_list = sk_X509_NAME_new(ssl_init_FindCAList_X509NameCmp);
1560
1561    /*
1562     * Process CA certificate bundle file
1563     */
1564    if (ca_file) {
1565        ssl_init_PushCAList(ca_list, s, ptemp, ca_file);
1566        /*
1567         * If ca_list is still empty after trying to load ca_file
1568         * then the file failed to load, and users should hear about that.
1569         */
1570        if (sk_X509_NAME_num(ca_list) == 0) {
1571            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02210)
1572                    "Failed to load SSLCACertificateFile: %s", ca_file);
1573            ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
1574        }
1575    }
1576
1577    /*
1578     * Process CA certificate path files
1579     */
1580    if (ca_path) {
1581        apr_dir_t *dir;
1582        apr_finfo_t direntry;
1583        apr_int32_t finfo_flags = APR_FINFO_TYPE|APR_FINFO_NAME;
1584        apr_status_t rv;
1585
1586        if ((rv = apr_dir_open(&dir, ca_path, ptemp)) != APR_SUCCESS) {
1587            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, APLOGNO(02211)
1588                    "Failed to open Certificate Path `%s'",
1589                    ca_path);
1590            sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
1591            return NULL;
1592        }
1593
1594        while ((apr_dir_read(&direntry, finfo_flags, dir)) == APR_SUCCESS) {
1595            const char *file;
1596            if (direntry.filetype == APR_DIR) {
1597                continue; /* don't try to load directories */
1598            }
1599            file = apr_pstrcat(ptemp, ca_path, "/", direntry.name, NULL);
1600            ssl_init_PushCAList(ca_list, s, ptemp, file);
1601        }
1602
1603        apr_dir_close(dir);
1604    }
1605
1606    /*
1607     * Cleanup
1608     */
1609    (void) sk_X509_NAME_set_cmp_func(ca_list, NULL);
1610
1611    return ca_list;
1612}
1613
1614void ssl_init_Child(apr_pool_t *p, server_rec *s)
1615{
1616    SSLModConfigRec *mc = myModConfig(s);
1617    mc->pid = getpid(); /* only call getpid() once per-process */
1618
1619    /* XXX: there should be an ap_srand() function */
1620    srand((unsigned int)time(NULL));
1621
1622    /* open the mutex lockfile */
1623    ssl_mutex_reinit(s, p);
1624#ifdef HAVE_OCSP_STAPLING
1625    ssl_stapling_mutex_reinit(s, p);
1626#endif
1627}
1628
1629#define MODSSL_CFG_ITEM_FREE(func, item) \
1630    if (item) { \
1631        func(item); \
1632        item = NULL; \
1633    }
1634
1635static void ssl_init_ctx_cleanup(modssl_ctx_t *mctx)
1636{
1637    MODSSL_CFG_ITEM_FREE(SSL_CTX_free, mctx->ssl_ctx);
1638
1639#ifdef HAVE_SRP
1640    if (mctx->srp_vbase != NULL) {
1641        SRP_VBASE_free(mctx->srp_vbase);
1642        mctx->srp_vbase = NULL;
1643    }
1644#endif
1645}
1646
1647static void ssl_init_ctx_cleanup_proxy(modssl_ctx_t *mctx)
1648{
1649    ssl_init_ctx_cleanup(mctx);
1650
1651    if (mctx->pkp->certs) {
1652        int i = 0;
1653        int ncerts = sk_X509_INFO_num(mctx->pkp->certs);
1654
1655        if (mctx->pkp->ca_certs) {
1656            for (i = 0; i < ncerts; i++) {
1657                if (mctx->pkp->ca_certs[i] != NULL) {
1658                    sk_X509_pop_free(mctx->pkp->ca_certs[i], X509_free);
1659                }
1660            }
1661        }
1662
1663        sk_X509_INFO_pop_free(mctx->pkp->certs, X509_INFO_free);
1664        mctx->pkp->certs = NULL;
1665    }
1666}
1667
1668apr_status_t ssl_init_ModuleKill(void *data)
1669{
1670    SSLSrvConfigRec *sc;
1671    server_rec *base_server = (server_rec *)data;
1672    server_rec *s;
1673
1674    /*
1675     * Drop the session cache and mutex
1676     */
1677    ssl_scache_kill(base_server);
1678
1679    /*
1680     * Free the non-pool allocated structures
1681     * in the per-server configurations
1682     */
1683    for (s = base_server; s; s = s->next) {
1684        sc = mySrvConfig(s);
1685
1686        ssl_init_ctx_cleanup_proxy(sc->proxy);
1687
1688        ssl_init_ctx_cleanup(sc->server);
1689    }
1690
1691    return APR_SUCCESS;
1692}
1693