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 "mod_ssl.h"
31 #include "mod_ssl_openssl.h"
32 #include "mpm_common.h"
33 #include "mod_md.h"
34 
35 static apr_status_t ssl_init_ca_cert_path(server_rec *, apr_pool_t *, const char *,
36                                           STACK_OF(X509_NAME) *, STACK_OF(X509_INFO) *);
37 
38 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ssl, SSL, int, init_server,
39                                     (server_rec *s,apr_pool_t *p,int is_proxy,SSL_CTX *ctx),
40                                     (s,p,is_proxy,ctx), OK, DECLINED)
41 
42 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ssl, SSL, int, add_cert_files,
43                                     (server_rec *s, apr_pool_t *p,
44                                     apr_array_header_t *cert_files, apr_array_header_t *key_files),
45                                     (s, p, cert_files, key_files),
46                                     OK, DECLINED)
47 
48 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ssl, SSL, int, add_fallback_cert_files,
49                                     (server_rec *s, apr_pool_t *p,
50                                     apr_array_header_t *cert_files, apr_array_header_t *key_files),
51                                     (s, p, cert_files, key_files),
52                                     OK, DECLINED)
53 
54 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ssl, SSL, int, answer_challenge,
55                                     (conn_rec *c, const char *server_name,
56                                     X509 **pcert, EVP_PKEY **pkey),
57                                     (c, server_name, pcert, pkey),
58                                     DECLINED, DECLINED)
59 
60 
61 /*  _________________________________________________________________
62 **
63 **  Module Initialization
64 **  _________________________________________________________________
65 */
66 
67 #ifdef HAVE_ECC
68 #define KEYTYPES "RSA, DSA or ECC"
69 #else
70 #define KEYTYPES "RSA or DSA"
71 #endif
72 
73 #if MODSSL_USE_OPENSSL_PRE_1_1_API
74 /* OpenSSL Pre-1.1.0 compatibility */
75 /* Taken from OpenSSL 1.1.0 snapshot 20160410 */
DH_set0_pqg(DH * dh,BIGNUM * p,BIGNUM * q,BIGNUM * g)76 static int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
77 {
78     /* q is optional */
79     if (p == NULL || g == NULL)
80         return 0;
81     BN_free(dh->p);
82     BN_free(dh->q);
83     BN_free(dh->g);
84     dh->p = p;
85     dh->q = q;
86     dh->g = g;
87 
88     if (q != NULL) {
89         dh->length = BN_num_bits(q);
90     }
91 
92     return 1;
93 }
94 
95 /*
96  * Grab well-defined DH parameters from OpenSSL, see the BN_get_rfc*
97  * functions in <openssl/bn.h> for all available primes.
98  */
make_dh_params(BIGNUM * (* prime)(BIGNUM *))99 static DH *make_dh_params(BIGNUM *(*prime)(BIGNUM *))
100 {
101     DH *dh = DH_new();
102     BIGNUM *p, *g;
103 
104     if (!dh) {
105         return NULL;
106     }
107     p = prime(NULL);
108     g = BN_new();
109     if (g != NULL) {
110         BN_set_word(g, 2);
111     }
112     if (!p || !g || !DH_set0_pqg(dh, p, NULL, g)) {
113         DH_free(dh);
114         BN_free(p);
115         BN_free(g);
116         return NULL;
117     }
118     return dh;
119 }
120 
121 /* Storage and initialization for DH parameters. */
122 static struct dhparam {
123     BIGNUM *(*const prime)(BIGNUM *); /* function to generate... */
124     DH *dh;                           /* ...this, used for keys.... */
125     const unsigned int min;           /* ...of length >= this. */
126 } dhparams[] = {
127     { BN_get_rfc3526_prime_8192, NULL, 6145 },
128     { BN_get_rfc3526_prime_6144, NULL, 4097 },
129     { BN_get_rfc3526_prime_4096, NULL, 3073 },
130     { BN_get_rfc3526_prime_3072, NULL, 2049 },
131     { BN_get_rfc3526_prime_2048, NULL, 1025 },
132     { BN_get_rfc2409_prime_1024, NULL, 0 }
133 };
134 
init_dh_params(void)135 static void init_dh_params(void)
136 {
137     unsigned n;
138 
139     for (n = 0; n < sizeof(dhparams)/sizeof(dhparams[0]); n++)
140         dhparams[n].dh = make_dh_params(dhparams[n].prime);
141 }
142 
free_dh_params(void)143 static void free_dh_params(void)
144 {
145     unsigned n;
146 
147     /* DH_free() is a noop for a NULL parameter, so these are harmless
148      * in the (unexpected) case where these variables are already
149      * NULL. */
150     for (n = 0; n < sizeof(dhparams)/sizeof(dhparams[0]); n++) {
151         DH_free(dhparams[n].dh);
152         dhparams[n].dh = NULL;
153     }
154 }
155 
156 /* Hand out the same DH structure though once generated as we leak
157  * memory otherwise and freeing the structure up after use would be
158  * hard to track and in fact is not needed at all as it is safe to
159  * use the same parameters over and over again security wise (in
160  * contrast to the keys itself) and code safe as the returned structure
161  * is duplicated by OpenSSL anyway. Hence no modification happens
162  * to our copy. */
modssl_get_dh_params(unsigned keylen)163 DH *modssl_get_dh_params(unsigned keylen)
164 {
165     unsigned n;
166 
167     for (n = 0; n < sizeof(dhparams)/sizeof(dhparams[0]); n++)
168         if (keylen >= dhparams[n].min)
169             return dhparams[n].dh;
170 
171     return NULL; /* impossible to reach. */
172 }
173 #endif
174 
ssl_add_version_components(apr_pool_t * ptemp,apr_pool_t * pconf,server_rec * s)175 static void ssl_add_version_components(apr_pool_t *ptemp, apr_pool_t *pconf,
176                                        server_rec *s)
177 {
178     char *modver = ssl_var_lookup(ptemp, s, NULL, NULL, "SSL_VERSION_INTERFACE");
179     char *libver = ssl_var_lookup(ptemp, s, NULL, NULL, "SSL_VERSION_LIBRARY");
180     char *incver = ssl_var_lookup(ptemp, s, NULL, NULL,
181                                   "SSL_VERSION_LIBRARY_INTERFACE");
182 
183     ap_add_version_component(pconf, libver);
184 
185     ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01876)
186                  "%s compiled against Server: %s, Library: %s",
187                  modver, AP_SERVER_BASEVERSION, incver);
188 }
189 
190 /*  _________________________________________________________________
191 **
192 **  Let other answer special connection attempts.
193 **  Used in ACME challenge handling by mod_md.
194 **  _________________________________________________________________
195 */
196 
ssl_is_challenge(conn_rec * c,const char * servername,X509 ** pcert,EVP_PKEY ** pkey,const char ** pcert_pem,const char ** pkey_pem)197 int ssl_is_challenge(conn_rec *c, const char *servername,
198                      X509 **pcert, EVP_PKEY **pkey,
199                      const char **pcert_pem, const char **pkey_pem)
200 {
201     *pcert = NULL;
202     *pkey = NULL;
203     *pcert_pem = *pkey_pem = NULL;
204     if (ap_ssl_answer_challenge(c, servername, pcert_pem, pkey_pem)) {
205         return 1;
206     }
207     else if (OK == ssl_run_answer_challenge(c, servername, pcert, pkey)) {
208         return 1;
209     }
210     return 0;
211 }
212 
213 #ifdef HAVE_FIPS
modssl_fips_cleanup(void * data)214 static apr_status_t modssl_fips_cleanup(void *data)
215 {
216     FIPS_mode_set(0);
217     return APR_SUCCESS;
218 }
219 #endif
220 
221 /*
222  *  Per-module initialization
223  */
ssl_init_Module(apr_pool_t * p,apr_pool_t * plog,apr_pool_t * ptemp,server_rec * base_server)224 apr_status_t ssl_init_Module(apr_pool_t *p, apr_pool_t *plog,
225                              apr_pool_t *ptemp,
226                              server_rec *base_server)
227 {
228     SSLModConfigRec *mc = myModConfig(base_server);
229     SSLSrvConfigRec *sc;
230     server_rec *s;
231     apr_status_t rv;
232     apr_array_header_t *pphrases;
233 
234     if (SSLeay() < MODSSL_LIBRARY_VERSION) {
235         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, base_server, APLOGNO(01882)
236                      "Init: this version of mod_ssl was compiled against "
237                      "a newer library (%s, version currently loaded is %s)"
238                      " - may result in undefined or erroneous behavior",
239                      MODSSL_LIBRARY_TEXT, MODSSL_LIBRARY_DYNTEXT);
240     }
241 
242     /* We initialize mc->pid per-process in the child init,
243      * but it should be initialized for startup before we
244      * call ssl_rand_seed() below.
245      */
246     mc->pid = getpid();
247 
248     /*
249      * Let us cleanup on restarts and exits
250      */
251     apr_pool_cleanup_register(p, base_server,
252                               ssl_init_ModuleKill,
253                               apr_pool_cleanup_null);
254 
255     /*
256      * Any init round fixes the global config
257      */
258     ssl_config_global_create(base_server); /* just to avoid problems */
259     ssl_config_global_fix(mc);
260 
261     /*
262      *  try to fix the configuration and open the dedicated SSL
263      *  logfile as early as possible
264      */
265     for (s = base_server; s; s = s->next) {
266         sc = mySrvConfig(s);
267 
268         if (sc->server) {
269             sc->server->sc = sc;
270         }
271 
272         /*
273          * Create the server host:port string because we need it a lot
274          */
275         if (sc->vhost_id) {
276             /* already set. This should only happen if this config rec is
277              * shared with another server. Argh! */
278             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10104)
279                          "%s, SSLSrvConfigRec shared from %s",
280                          ssl_util_vhostid(p, s), sc->vhost_id);
281         }
282         sc->vhost_id = ssl_util_vhostid(p, s);
283         sc->vhost_id_len = strlen(sc->vhost_id);
284 
285         /* Default to enabled if SSLEngine is not set explicitly, and
286          * the protocol is https. */
287         if (ap_get_server_protocol(s)
288             && strcmp("https", ap_get_server_protocol(s)) == 0
289             && sc->enabled == SSL_ENABLED_UNSET
290             && (!apr_is_empty_array(sc->server->pks->cert_files))) {
291             sc->enabled = SSL_ENABLED_TRUE;
292         }
293 
294         /* Fix up stuff that may not have been set.  If sc->enabled is
295          * UNSET, then SSL is disabled on this vhost.  */
296         if (sc->enabled == SSL_ENABLED_UNSET) {
297             sc->enabled = SSL_ENABLED_FALSE;
298         }
299 
300         if (sc->session_cache_timeout == UNSET) {
301             sc->session_cache_timeout = SSL_SESSION_CACHE_TIMEOUT;
302         }
303 
304         if (sc->server && sc->server->pphrase_dialog_type == SSL_PPTYPE_UNSET) {
305             sc->server->pphrase_dialog_type = SSL_PPTYPE_BUILTIN;
306         }
307 
308 #ifdef HAVE_FIPS
309         if (sc->fips == UNSET) {
310             sc->fips = FALSE;
311         }
312 #endif
313     }
314 
315 #if APR_HAS_THREADS && MODSSL_USE_OPENSSL_PRE_1_1_API
316     ssl_util_thread_setup(p);
317 #endif
318 
319     /*
320      * SSL external crypto device ("engine") support
321      */
322 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
323     if ((rv = ssl_init_Engine(base_server, p)) != APR_SUCCESS) {
324         return rv;
325     }
326 #endif
327 
328     ap_log_error(APLOG_MARK, APLOG_INFO, 0, base_server, APLOGNO(01883)
329                  "Init: Initialized %s library", MODSSL_LIBRARY_NAME);
330 
331     /*
332      * Seed the Pseudo Random Number Generator (PRNG)
333      * only need ptemp here; nothing inside allocated from the pool
334      * needs to live once we return from ssl_rand_seed().
335      */
336     ssl_rand_seed(base_server, ptemp, SSL_RSCTX_STARTUP, "Init: ");
337 
338 #ifdef HAVE_FIPS
339     if (sc->fips) {
340         if (!FIPS_mode()) {
341             if (FIPS_mode_set(1)) {
342                 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, APLOGNO(01884)
343                              "Operating in SSL FIPS mode");
344                 apr_pool_cleanup_register(p, NULL, modssl_fips_cleanup,
345                                           apr_pool_cleanup_null);
346             }
347             else {
348                 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01885) "FIPS mode failed");
349                 ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
350                 return ssl_die(s);
351             }
352         }
353     }
354     else {
355         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01886)
356                      "SSL FIPS mode disabled");
357     }
358 #endif
359 
360     /*
361      * initialize the mutex handling
362      */
363     if (!ssl_mutex_init(base_server, p)) {
364         return HTTP_INTERNAL_SERVER_ERROR;
365     }
366 #ifdef HAVE_OCSP_STAPLING
367     ssl_stapling_certinfo_hash_init(p);
368 #endif
369 
370     /*
371      * initialize session caching
372      */
373     if ((rv = ssl_scache_init(base_server, p)) != APR_SUCCESS) {
374         return rv;
375     }
376 
377     pphrases = apr_array_make(ptemp, 2, sizeof(char *));
378 
379     /*
380      *  initialize servers
381      */
382     ap_log_error(APLOG_MARK, APLOG_INFO, 0, base_server, APLOGNO(01887)
383                  "Init: Initializing (virtual) servers for SSL");
384 
385     for (s = base_server; s; s = s->next) {
386         sc = mySrvConfig(s);
387         /*
388          * Either now skip this server when SSL is disabled for
389          * it or give out some information about what we're
390          * configuring.
391          */
392 
393         /*
394          * Read the server certificate and key
395          */
396         if ((rv = ssl_init_ConfigureServer(s, p, ptemp, sc, pphrases))
397             != APR_SUCCESS) {
398             return rv;
399         }
400     }
401 
402     if (pphrases->nelts > 0) {
403         memset(pphrases->elts, 0, pphrases->elt_size * pphrases->nelts);
404         pphrases->nelts = 0;
405         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02560)
406                      "Init: Wiped out the queried pass phrases from memory");
407     }
408 
409     /*
410      * Configuration consistency checks
411      */
412     if ((rv = ssl_init_CheckServers(base_server, ptemp)) != APR_SUCCESS) {
413         return rv;
414     }
415 
416     for (s = base_server; s; s = s->next) {
417         SSLDirConfigRec *sdc = ap_get_module_config(s->lookup_defaults,
418                                                     &ssl_module);
419 
420         sc = mySrvConfig(s);
421         if (sc->enabled == SSL_ENABLED_TRUE || sc->enabled == SSL_ENABLED_OPTIONAL) {
422             if ((rv = ssl_run_init_server(s, p, 0, sc->server->ssl_ctx)) != APR_SUCCESS) {
423                 return rv;
424             }
425         }
426 
427         if (sdc->proxy_enabled) {
428             rv = ssl_run_init_server(s, p, 1, sdc->proxy->ssl_ctx);
429             if (rv != APR_SUCCESS) {
430                 return rv;
431             }
432         }
433     }
434 
435     /*
436      *  Announce mod_ssl and SSL library in HTTP Server field
437      *  as ``mod_ssl/X.X.X OpenSSL/X.X.X''
438      */
439     ssl_add_version_components(ptemp, p, base_server);
440 
441     modssl_init_app_data2_idx(); /* for modssl_get_app_data2() at request time */
442 
443 #if MODSSL_USE_OPENSSL_PRE_1_1_API
444     init_dh_params();
445 #else
446     init_bio_methods();
447 #endif
448 
449 #ifdef HAVE_OPENSSL_KEYLOG
450     {
451         const char *logfn = getenv("SSLKEYLOGFILE");
452 
453         if (logfn) {
454             rv = apr_file_open(&mc->keylog_file, logfn,
455                                APR_FOPEN_CREATE|APR_FOPEN_WRITE|APR_FOPEN_APPEND|APR_FOPEN_LARGEFILE,
456                                APR_FPROT_UREAD|APR_FPROT_UWRITE,
457                                mc->pPool);
458             if (rv) {
459                 ap_log_error(APLOG_MARK, APLOG_NOTICE, rv, s, APLOGNO(10226)
460                              "Could not open log file '%s' configured via SSLKEYLOGFILE",
461                              logfn);
462                 return rv;
463             }
464 
465             ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, APLOGNO(10227)
466                          "Init: Logging SSL private key material to %s", logfn);
467         }
468     }
469 #endif
470 
471     return OK;
472 }
473 
474 /*
475  * Support for external a Crypto Device ("engine"), usually
476  * a hardware accellerator card for crypto operations.
477  */
478 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
ssl_init_Engine(server_rec * s,apr_pool_t * p)479 apr_status_t ssl_init_Engine(server_rec *s, apr_pool_t *p)
480 {
481     SSLModConfigRec *mc = myModConfig(s);
482     ENGINE *e;
483 
484     if (mc->szCryptoDevice) {
485         if (!(e = ENGINE_by_id(mc->szCryptoDevice))) {
486             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01888)
487                          "Init: Failed to load Crypto Device API `%s'",
488                          mc->szCryptoDevice);
489             ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
490             return ssl_die(s);
491         }
492 
493 #ifdef ENGINE_CTRL_CHIL_SET_FORKCHECK
494         if (strEQ(mc->szCryptoDevice, "chil")) {
495             ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
496         }
497 #endif
498 
499         if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
500             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01889)
501                          "Init: Failed to enable Crypto Device API `%s'",
502                          mc->szCryptoDevice);
503             ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
504             return ssl_die(s);
505         }
506         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01890)
507                      "Init: loaded Crypto Device API `%s'",
508                      mc->szCryptoDevice);
509 
510         ENGINE_free(e);
511     }
512 
513     return APR_SUCCESS;
514 }
515 #endif
516 
517 #ifdef HAVE_TLSEXT
ssl_init_ctx_tls_extensions(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx)518 static apr_status_t ssl_init_ctx_tls_extensions(server_rec *s,
519                                                 apr_pool_t *p,
520                                                 apr_pool_t *ptemp,
521                                                 modssl_ctx_t *mctx)
522 {
523     apr_status_t rv;
524 
525     /*
526      * Configure TLS extensions support
527      */
528     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01893)
529                  "Configuring TLS extension handling");
530 
531     /*
532      * The Server Name Indication (SNI) provided by the ClientHello can be
533      * used to select the right (name-based-)vhost and its SSL configuration
534      * before the handshake takes place.
535      */
536     if (!SSL_CTX_set_tlsext_servername_callback(mctx->ssl_ctx,
537                           ssl_callback_ServerNameIndication) ||
538         !SSL_CTX_set_tlsext_servername_arg(mctx->ssl_ctx, mctx)) {
539         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01894)
540                      "Unable to initialize TLS servername extension "
541                      "callback (incompatible OpenSSL version?)");
542         ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
543         return ssl_die(s);
544     }
545 
546 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER)
547     /*
548      * The ClientHello callback also allows to retrieve the SNI, but since it
549      * runs at the earliest possible connection stage we can even set the TLS
550      * protocol version(s) according to the selected (name-based-)vhost, which
551      * is not possible at the SNI callback stage (due to OpenSSL internals).
552      */
553     SSL_CTX_set_client_hello_cb(mctx->ssl_ctx, ssl_callback_ClientHello, NULL);
554 #endif
555 
556 #ifdef HAVE_OCSP_STAPLING
557     /*
558      * OCSP Stapling support, status_request extension
559      */
560     if ((mctx->pkp == FALSE) && (mctx->stapling_enabled == TRUE)) {
561         if ((rv = modssl_init_stapling(s, p, ptemp, mctx)) != APR_SUCCESS) {
562             return rv;
563         }
564     }
565 #endif
566 
567 #ifdef HAVE_SRP
568     /*
569      * TLS-SRP support
570      */
571     if (mctx->srp_vfile != NULL) {
572         int err;
573         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02308)
574                      "Using SRP verifier file [%s]", mctx->srp_vfile);
575 
576         if (!(mctx->srp_vbase = SRP_VBASE_new(mctx->srp_unknown_user_seed))) {
577             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02309)
578                          "Unable to initialize SRP verifier structure "
579                          "[%s seed]",
580                          mctx->srp_unknown_user_seed ? "with" : "without");
581             ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
582             return ssl_die(s);
583         }
584 
585         err = SRP_VBASE_init(mctx->srp_vbase, mctx->srp_vfile);
586         if (err != SRP_NO_ERROR) {
587             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02310)
588                          "Unable to load SRP verifier file [error %d]", err);
589             ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
590             return ssl_die(s);
591         }
592 
593         SSL_CTX_set_srp_username_callback(mctx->ssl_ctx,
594                                           ssl_callback_SRPServerParams);
595         SSL_CTX_set_srp_cb_arg(mctx->ssl_ctx, mctx);
596     }
597 #endif
598     return APR_SUCCESS;
599 }
600 #endif
601 
ssl_init_ctx_protocol(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx)602 static apr_status_t ssl_init_ctx_protocol(server_rec *s,
603                                           apr_pool_t *p,
604                                           apr_pool_t *ptemp,
605                                           modssl_ctx_t *mctx)
606 {
607     SSL_CTX *ctx = NULL;
608     MODSSL_SSL_METHOD_CONST SSL_METHOD *method = NULL;
609     char *cp;
610     int protocol = mctx->protocol;
611     SSLSrvConfigRec *sc = mySrvConfig(s);
612 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !(defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L)
613     int prot;
614 #endif
615 
616     /*
617      *  Create the new per-server SSL context
618      */
619     if (protocol == SSL_PROTOCOL_NONE) {
620         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02231)
621                 "No SSL protocols available [hint: SSLProtocol]");
622         return ssl_die(s);
623     }
624 
625     cp = apr_pstrcat(p,
626 #ifndef OPENSSL_NO_SSL3
627                      (protocol & SSL_PROTOCOL_SSLV3 ? "SSLv3, " : ""),
628 #endif
629                      (protocol & SSL_PROTOCOL_TLSV1 ? "TLSv1, " : ""),
630 #ifdef HAVE_TLSV1_X
631                      (protocol & SSL_PROTOCOL_TLSV1_1 ? "TLSv1.1, " : ""),
632                      (protocol & SSL_PROTOCOL_TLSV1_2 ? "TLSv1.2, " : ""),
633 #if SSL_HAVE_PROTOCOL_TLSV1_3
634                      (protocol & SSL_PROTOCOL_TLSV1_3 ? "TLSv1.3, " : ""),
635 #endif
636 #endif
637                      NULL);
638     cp[strlen(cp)-2] = NUL;
639 
640     ap_log_error(APLOG_MARK, APLOG_TRACE3, 0, s,
641                  "Creating new SSL context (protocols: %s)", cp);
642 
643 #if OPENSSL_VERSION_NUMBER < 0x10100000L
644 #ifndef OPENSSL_NO_SSL3
645     if (protocol == SSL_PROTOCOL_SSLV3) {
646         method = mctx->pkp ?
647             SSLv3_client_method() : /* proxy */
648             SSLv3_server_method();  /* server */
649     }
650     else
651 #endif
652     if (protocol == SSL_PROTOCOL_TLSV1) {
653         method = mctx->pkp ?
654             TLSv1_client_method() : /* proxy */
655             TLSv1_server_method();  /* server */
656     }
657 #ifdef HAVE_TLSV1_X
658     else if (protocol == SSL_PROTOCOL_TLSV1_1) {
659         method = mctx->pkp ?
660             TLSv1_1_client_method() : /* proxy */
661             TLSv1_1_server_method();  /* server */
662     }
663     else if (protocol == SSL_PROTOCOL_TLSV1_2) {
664         method = mctx->pkp ?
665             TLSv1_2_client_method() : /* proxy */
666             TLSv1_2_server_method();  /* server */
667     }
668 #if SSL_HAVE_PROTOCOL_TLSV1_3
669     else if (protocol == SSL_PROTOCOL_TLSV1_3) {
670         method = mctx->pkp ?
671             TLSv1_3_client_method() : /* proxy */
672             TLSv1_3_server_method();  /* server */
673     }
674 #endif
675 #endif
676     else { /* For multiple protocols, we need a flexible method */
677         method = mctx->pkp ?
678             SSLv23_client_method() : /* proxy */
679             SSLv23_server_method();  /* server */
680     }
681 #else
682     method = mctx->pkp ?
683         TLS_client_method() : /* proxy */
684         TLS_server_method();  /* server */
685 #endif
686     ctx = SSL_CTX_new(method);
687 
688     mctx->ssl_ctx = ctx;
689 
690     SSL_CTX_set_options(ctx, SSL_OP_ALL);
691 
692 #if OPENSSL_VERSION_NUMBER < 0x10100000L  || \
693 	(defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20800000L)
694     /* always disable SSLv2, as per RFC 6176 */
695     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
696 
697 #ifndef OPENSSL_NO_SSL3
698     if (!(protocol & SSL_PROTOCOL_SSLV3)) {
699         SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);
700     }
701 #endif
702 
703     if (!(protocol & SSL_PROTOCOL_TLSV1)) {
704         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1);
705     }
706 
707 #ifdef HAVE_TLSV1_X
708     if (!(protocol & SSL_PROTOCOL_TLSV1_1)) {
709         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_1);
710     }
711 
712     if (!(protocol & SSL_PROTOCOL_TLSV1_2)) {
713         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_2);
714     }
715 #if SSL_HAVE_PROTOCOL_TLSV1_3
716     ssl_set_ctx_protocol_option(s, ctx, SSL_OP_NO_TLSv1_3,
717                                 protocol & SSL_PROTOCOL_TLSV1_3, "TLSv1.3");
718 #endif
719 #endif
720 
721 #else /* #if OPENSSL_VERSION_NUMBER < 0x10100000L */
722     /* We first determine the maximum protocol version we should provide */
723 #if SSL_HAVE_PROTOCOL_TLSV1_3
724     if (protocol & SSL_PROTOCOL_TLSV1_3) {
725         prot = TLS1_3_VERSION;
726     } else
727 #endif
728     if (protocol & SSL_PROTOCOL_TLSV1_2) {
729         prot = TLS1_2_VERSION;
730     } else if (protocol & SSL_PROTOCOL_TLSV1_1) {
731         prot = TLS1_1_VERSION;
732     } else if (protocol & SSL_PROTOCOL_TLSV1) {
733         prot = TLS1_VERSION;
734 #ifndef OPENSSL_NO_SSL3
735     } else if (protocol & SSL_PROTOCOL_SSLV3) {
736         prot = SSL3_VERSION;
737 #endif
738     } else {
739         SSL_CTX_free(ctx);
740         mctx->ssl_ctx = NULL;
741         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(03378)
742                 "No SSL protocols available [hint: SSLProtocol]");
743         return ssl_die(s);
744     }
745     SSL_CTX_set_max_proto_version(ctx, prot);
746 
747     /* Next we scan for the minimal protocol version we should provide,
748      * but we do not allow holes between max and min */
749 #if SSL_HAVE_PROTOCOL_TLSV1_3
750     if (prot == TLS1_3_VERSION && protocol & SSL_PROTOCOL_TLSV1_2) {
751         prot = TLS1_2_VERSION;
752     }
753 #endif
754     if (prot == TLS1_2_VERSION && protocol & SSL_PROTOCOL_TLSV1_1) {
755         prot = TLS1_1_VERSION;
756     }
757     if (prot == TLS1_1_VERSION && protocol & SSL_PROTOCOL_TLSV1) {
758         prot = TLS1_VERSION;
759     }
760 #ifndef OPENSSL_NO_SSL3
761     if (prot == TLS1_VERSION && protocol & SSL_PROTOCOL_SSLV3) {
762         prot = SSL3_VERSION;
763     }
764 #endif
765     SSL_CTX_set_min_proto_version(ctx, prot);
766 #endif /* if OPENSSL_VERSION_NUMBER < 0x10100000L */
767 
768 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
769     if (sc->cipher_server_pref == TRUE) {
770         SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
771     }
772 #endif
773 
774 
775 #ifndef OPENSSL_NO_COMP
776     if (sc->compression != TRUE) {
777 #ifdef SSL_OP_NO_COMPRESSION
778         /* OpenSSL >= 1.0 only */
779         SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION);
780 #else
781         sk_SSL_COMP_zero(SSL_COMP_get_compression_methods());
782 #endif
783     }
784 #endif
785 
786 #ifdef SSL_OP_NO_TICKET
787     /*
788      * Configure using RFC 5077 TLS session tickets
789      * for session resumption.
790      */
791     if (sc->session_tickets == FALSE) {
792         SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
793     }
794 #endif
795 
796 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
797     if (sc->insecure_reneg == TRUE) {
798         SSL_CTX_set_options(ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
799     }
800 #endif
801 
802     SSL_CTX_set_app_data(ctx, s);
803 
804     /*
805      * Configure additional context ingredients
806      */
807     SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
808 #ifdef HAVE_ECC
809     SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
810 #endif
811 
812 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
813     /*
814      * Disallow a session from being resumed during a renegotiation,
815      * so that an acceptable cipher suite can be negotiated.
816      */
817     SSL_CTX_set_options(ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
818 #endif
819 
820 #ifdef SSL_MODE_RELEASE_BUFFERS
821     /* If httpd is configured to reduce mem usage, ask openssl to do so, too */
822     if (ap_max_mem_free != APR_ALLOCATOR_MAX_FREE_UNLIMITED)
823         SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
824 #endif
825 
826 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL
827     /* For OpenSSL >=1.1.1, disable auto-retry mode so it's possible
828      * to consume handshake records without blocking for app-data.
829      * https://github.com/openssl/openssl/issues/7178 */
830     SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
831 #endif
832 
833 #ifdef HAVE_OPENSSL_KEYLOG
834     if (mctx->sc->mc->keylog_file) {
835         SSL_CTX_set_keylog_callback(ctx, modssl_callback_keylog);
836     }
837 #endif
838 
839     return APR_SUCCESS;
840 }
841 
ssl_init_ctx_session_cache(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx)842 static void ssl_init_ctx_session_cache(server_rec *s,
843                                        apr_pool_t *p,
844                                        apr_pool_t *ptemp,
845                                        modssl_ctx_t *mctx)
846 {
847     SSL_CTX *ctx = mctx->ssl_ctx;
848     SSLModConfigRec *mc = myModConfig(s);
849 
850     SSL_CTX_set_session_cache_mode(ctx, mc->sesscache_mode);
851 
852     if (mc->sesscache) {
853         SSL_CTX_sess_set_new_cb(ctx,    ssl_callback_NewSessionCacheEntry);
854         SSL_CTX_sess_set_get_cb(ctx,    ssl_callback_GetSessionCacheEntry);
855         SSL_CTX_sess_set_remove_cb(ctx, ssl_callback_DelSessionCacheEntry);
856     }
857 }
858 
ssl_init_ctx_callbacks(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx)859 static void ssl_init_ctx_callbacks(server_rec *s,
860                                    apr_pool_t *p,
861                                    apr_pool_t *ptemp,
862                                    modssl_ctx_t *mctx)
863 {
864     SSL_CTX *ctx = mctx->ssl_ctx;
865 
866 #if MODSSL_USE_OPENSSL_PRE_1_1_API
867     /* Note that for OpenSSL>=1.1, auto selection is enabled via
868      * SSL_CTX_set_dh_auto(,1) if no parameter is configured. */
869     SSL_CTX_set_tmp_dh_callback(ctx,  ssl_callback_TmpDH);
870 #endif
871 
872     SSL_CTX_set_info_callback(ctx, ssl_callback_Info);
873 
874 #ifdef HAVE_TLS_ALPN
875     SSL_CTX_set_alpn_select_cb(ctx, ssl_callback_alpn_select, NULL);
876 #endif
877 }
878 
879 static APR_INLINE
modssl_CTX_load_verify_locations(SSL_CTX * ctx,const char * file,const char * path)880 int modssl_CTX_load_verify_locations(SSL_CTX *ctx,
881                                      const char *file,
882                                      const char *path)
883 {
884 #if OPENSSL_VERSION_NUMBER < 0x30000000L
885     if (!SSL_CTX_load_verify_locations(ctx, file, path))
886         return 0;
887 #else
888     if (file && !SSL_CTX_load_verify_file(ctx, file))
889         return 0;
890     if (path && !SSL_CTX_load_verify_dir(ctx, path))
891         return 0;
892 #endif
893     return 1;
894 }
895 
ssl_init_ctx_verify(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx)896 static apr_status_t ssl_init_ctx_verify(server_rec *s,
897                                         apr_pool_t *p,
898                                         apr_pool_t *ptemp,
899                                         modssl_ctx_t *mctx)
900 {
901     SSL_CTX *ctx = mctx->ssl_ctx;
902 
903     int verify = SSL_VERIFY_NONE;
904     STACK_OF(X509_NAME) *ca_list;
905 
906     if (mctx->auth.verify_mode == SSL_CVERIFY_UNSET) {
907         mctx->auth.verify_mode = SSL_CVERIFY_NONE;
908     }
909 
910     if (mctx->auth.verify_depth == UNSET) {
911         mctx->auth.verify_depth = 1;
912     }
913 
914     /*
915      *  Configure callbacks for SSL context
916      */
917     if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
918         verify |= SSL_VERIFY_PEER_STRICT;
919     }
920 
921     if ((mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL) ||
922         (mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL_NO_CA))
923     {
924         verify |= SSL_VERIFY_PEER;
925     }
926 
927     SSL_CTX_set_verify(ctx, verify, ssl_callback_SSLVerify);
928 
929     /*
930      * Configure Client Authentication details
931      */
932     if (mctx->auth.ca_cert_file || mctx->auth.ca_cert_path) {
933         ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, s,
934                      "Configuring client authentication");
935 
936         if (!modssl_CTX_load_verify_locations(ctx, mctx->auth.ca_cert_file,
937                                                    mctx->auth.ca_cert_path)) {
938             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01895)
939                     "Unable to configure verify locations "
940                     "for client authentication");
941             ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
942             return ssl_die(s);
943         }
944 
945         if (mctx->pks && (mctx->pks->ca_name_file || mctx->pks->ca_name_path)) {
946             ca_list = ssl_init_FindCAList(s, ptemp,
947                                           mctx->pks->ca_name_file,
948                                           mctx->pks->ca_name_path);
949         } else
950             ca_list = ssl_init_FindCAList(s, ptemp,
951                                           mctx->auth.ca_cert_file,
952                                           mctx->auth.ca_cert_path);
953         if (sk_X509_NAME_num(ca_list) <= 0) {
954             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01896)
955                     "Unable to determine list of acceptable "
956                     "CA certificates for client authentication");
957             return ssl_die(s);
958         }
959 
960         SSL_CTX_set_client_CA_list(ctx, ca_list);
961     }
962 
963     /*
964      * Give a warning when no CAs were configured but client authentication
965      * should take place. This cannot work.
966      */
967     if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
968         ca_list = SSL_CTX_get_client_CA_list(ctx);
969 
970         if (sk_X509_NAME_num(ca_list) == 0) {
971             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01897)
972                          "Init: Oops, you want to request client "
973                          "authentication, but no CAs are known for "
974                          "verification!?  [Hint: SSLCACertificate*]");
975         }
976     }
977 
978     return APR_SUCCESS;
979 }
980 
ssl_init_ctx_cipher_suite(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx)981 static apr_status_t ssl_init_ctx_cipher_suite(server_rec *s,
982                                               apr_pool_t *p,
983                                               apr_pool_t *ptemp,
984                                               modssl_ctx_t *mctx)
985 {
986     SSL_CTX *ctx = mctx->ssl_ctx;
987     const char *suite;
988 
989     /*
990      *  Configure SSL Cipher Suite. Always disable NULL and export ciphers,
991      *  see also ssl_engine_config.c:ssl_cmd_SSLCipherSuite().
992      *  OpenSSL's SSL_DEFAULT_CIPHER_LIST includes !aNULL:!eNULL from 0.9.8f,
993      *  and !EXP from 0.9.8zf/1.0.1m/1.0.2a, so append them while we support
994      *  earlier versions.
995      */
996     suite = mctx->auth.cipher_suite ? mctx->auth.cipher_suite :
997             apr_pstrcat(ptemp, SSL_DEFAULT_CIPHER_LIST, ":!aNULL:!eNULL:!EXP",
998                         NULL);
999 
1000     ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, s,
1001                  "Configuring permitted SSL ciphers [%s]",
1002                  suite);
1003 
1004     if (!SSL_CTX_set_cipher_list(ctx, suite)) {
1005         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01898)
1006                 "Unable to configure permitted SSL ciphers");
1007         ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1008         return ssl_die(s);
1009     }
1010 #if SSL_HAVE_PROTOCOL_TLSV1_3
1011     if (mctx->auth.tls13_ciphers
1012         && !SSL_CTX_set_ciphersuites(ctx, mctx->auth.tls13_ciphers)) {
1013         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(10127)
1014                 "Unable to configure permitted TLSv1.3 ciphers");
1015         ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1016         return ssl_die(s);
1017     }
1018 #endif
1019     return APR_SUCCESS;
1020 }
1021 
1022 static APR_INLINE
modssl_X509_STORE_load_locations(X509_STORE * store,const char * file,const char * path)1023 int modssl_X509_STORE_load_locations(X509_STORE *store,
1024                                      const char *file,
1025                                      const char *path)
1026 {
1027 #if OPENSSL_VERSION_NUMBER < 0x30000000L
1028     if (!X509_STORE_load_locations(store, file, path))
1029         return 0;
1030 #else
1031     if (file && !X509_STORE_load_file(store, file))
1032         return 0;
1033     if (path && !X509_STORE_load_path(store, path))
1034         return 0;
1035 #endif
1036     return 1;
1037 }
1038 
ssl_init_ctx_crl(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx)1039 static apr_status_t ssl_init_ctx_crl(server_rec *s,
1040                                      apr_pool_t *p,
1041                                      apr_pool_t *ptemp,
1042                                      modssl_ctx_t *mctx)
1043 {
1044     X509_STORE *store = SSL_CTX_get_cert_store(mctx->ssl_ctx);
1045     unsigned long crlflags = 0;
1046     char *cfgp = mctx->pkp ? "SSLProxy" : "SSL";
1047     int crl_check_mode;
1048 
1049     if (mctx->ocsp_mask == UNSET) {
1050         mctx->ocsp_mask = SSL_OCSPCHECK_NONE;
1051     }
1052 
1053     if (mctx->crl_check_mask == UNSET) {
1054         mctx->crl_check_mask = SSL_CRLCHECK_NONE;
1055     }
1056     crl_check_mode = mctx->crl_check_mask & ~SSL_CRLCHECK_FLAGS;
1057 
1058     /*
1059      * Configure Certificate Revocation List (CRL) Details
1060      */
1061 
1062     if (!(mctx->crl_file || mctx->crl_path)) {
1063         if (crl_check_mode == SSL_CRLCHECK_LEAF ||
1064             crl_check_mode == SSL_CRLCHECK_CHAIN) {
1065             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01899)
1066                          "Host %s: CRL checking has been enabled, but "
1067                          "neither %sCARevocationFile nor %sCARevocationPath "
1068                          "is configured", mctx->sc->vhost_id, cfgp, cfgp);
1069             return ssl_die(s);
1070         }
1071         return APR_SUCCESS;
1072     }
1073 
1074     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01900)
1075                  "Configuring certificate revocation facility");
1076 
1077     if (!store || !modssl_X509_STORE_load_locations(store, mctx->crl_file,
1078                                                            mctx->crl_path)) {
1079         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01901)
1080                      "Host %s: unable to configure X.509 CRL storage "
1081                      "for certificate revocation", mctx->sc->vhost_id);
1082         ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1083         return ssl_die(s);
1084     }
1085 
1086     switch (crl_check_mode) {
1087        case SSL_CRLCHECK_LEAF:
1088            crlflags = X509_V_FLAG_CRL_CHECK;
1089            break;
1090        case SSL_CRLCHECK_CHAIN:
1091            crlflags = X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
1092            break;
1093        default:
1094            crlflags = 0;
1095     }
1096 
1097     if (crlflags) {
1098         X509_STORE_set_flags(store, crlflags);
1099     } else {
1100         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01902)
1101                      "Host %s: X.509 CRL storage locations configured, "
1102                      "but CRL checking (%sCARevocationCheck) is not "
1103                      "enabled", mctx->sc->vhost_id, cfgp);
1104     }
1105 
1106     return APR_SUCCESS;
1107 }
1108 
1109 /*
1110  * Read a file that optionally contains the server certificate in PEM
1111  * format, possibly followed by a sequence of CA certificates that
1112  * should be sent to the peer in the SSL Certificate message.
1113  */
use_certificate_chain(SSL_CTX * ctx,char * file,int skipfirst,pem_password_cb * cb)1114 static int use_certificate_chain(
1115     SSL_CTX *ctx, char *file, int skipfirst, pem_password_cb *cb)
1116 {
1117     BIO *bio;
1118     X509 *x509;
1119     unsigned long err;
1120     int n;
1121 
1122     if ((bio = BIO_new(BIO_s_file())) == NULL)
1123         return -1;
1124     if (BIO_read_filename(bio, file) <= 0) {
1125         BIO_free(bio);
1126         return -1;
1127     }
1128     /* optionally skip a leading server certificate */
1129     if (skipfirst) {
1130         if ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) == NULL) {
1131             BIO_free(bio);
1132             return -1;
1133         }
1134         X509_free(x509);
1135     }
1136     /* free a perhaps already configured extra chain */
1137 #ifdef OPENSSL_NO_SSL_INTERN
1138     SSL_CTX_clear_extra_chain_certs(ctx);
1139 #else
1140     if (ctx->extra_certs != NULL) {
1141         sk_X509_pop_free((STACK_OF(X509) *)ctx->extra_certs, X509_free);
1142         ctx->extra_certs = NULL;
1143     }
1144 #endif
1145 
1146     /* create new extra chain by loading the certs */
1147     n = 0;
1148     ERR_clear_error();
1149     while ((x509 = PEM_read_bio_X509(bio, NULL, cb, NULL)) != NULL) {
1150         if (!SSL_CTX_add_extra_chain_cert(ctx, x509)) {
1151             X509_free(x509);
1152             BIO_free(bio);
1153             return -1;
1154         }
1155         n++;
1156     }
1157     /* Make sure that only the error is just an EOF */
1158     if ((err = ERR_peek_error()) > 0) {
1159         if (!(   ERR_GET_LIB(err) == ERR_LIB_PEM
1160               && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
1161             BIO_free(bio);
1162             return -1;
1163         }
1164         while (ERR_get_error() > 0) ;
1165     }
1166     BIO_free(bio);
1167     return n;
1168 }
1169 
ssl_init_ctx_cert_chain(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx)1170 static apr_status_t ssl_init_ctx_cert_chain(server_rec *s,
1171                                             apr_pool_t *p,
1172                                             apr_pool_t *ptemp,
1173                                             modssl_ctx_t *mctx)
1174 {
1175     BOOL skip_first = FALSE;
1176     int i, n;
1177     const char *chain = mctx->cert_chain;
1178 
1179     /*
1180      * Optionally configure extra server certificate chain certificates.
1181      * This is usually done by OpenSSL automatically when one of the
1182      * server cert issuers are found under SSLCACertificatePath or in
1183      * SSLCACertificateFile. But because these are intended for client
1184      * authentication it can conflict. For instance when you use a
1185      * Global ID server certificate you've to send out the intermediate
1186      * CA certificate, too. When you would just configure this with
1187      * SSLCACertificateFile and also use client authentication mod_ssl
1188      * would accept all clients also issued by this CA. Obviously this
1189      * isn't what we want in this situation. So this feature here exists
1190      * to allow one to explicitly configure CA certificates which are
1191      * used only for the server certificate chain.
1192      */
1193     if (!chain) {
1194         return APR_SUCCESS;
1195     }
1196 
1197     for (i = 0; (i < mctx->pks->cert_files->nelts) &&
1198          APR_ARRAY_IDX(mctx->pks->cert_files, i, const char *); i++) {
1199         if (strEQ(APR_ARRAY_IDX(mctx->pks->cert_files, i, const char *), chain)) {
1200             skip_first = TRUE;
1201             break;
1202         }
1203     }
1204 
1205     n = use_certificate_chain(mctx->ssl_ctx, (char *)chain, skip_first, NULL);
1206     if (n < 0) {
1207         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01903)
1208                 "Failed to configure CA certificate chain!");
1209         return ssl_die(s);
1210     }
1211 
1212     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01904)
1213                  "Configuring server certificate chain "
1214                  "(%d CA certificate%s)",
1215                  n, n == 1 ? "" : "s");
1216 
1217     return APR_SUCCESS;
1218 }
1219 
ssl_init_ctx(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx)1220 static apr_status_t ssl_init_ctx(server_rec *s,
1221                                  apr_pool_t *p,
1222                                  apr_pool_t *ptemp,
1223                                  modssl_ctx_t *mctx)
1224 {
1225     apr_status_t rv;
1226 
1227     if ((rv = ssl_init_ctx_protocol(s, p, ptemp, mctx)) != APR_SUCCESS) {
1228         return rv;
1229     }
1230 
1231     ssl_init_ctx_session_cache(s, p, ptemp, mctx);
1232 
1233     ssl_init_ctx_callbacks(s, p, ptemp, mctx);
1234 
1235     if ((rv = ssl_init_ctx_verify(s, p, ptemp, mctx)) != APR_SUCCESS) {
1236         return rv;
1237     }
1238 
1239     if ((rv = ssl_init_ctx_cipher_suite(s, p, ptemp, mctx)) != APR_SUCCESS) {
1240         return rv;
1241     }
1242 
1243     if ((rv = ssl_init_ctx_crl(s, p, ptemp, mctx)) != APR_SUCCESS) {
1244         return rv;
1245     }
1246 
1247     if (mctx->pks) {
1248         /* XXX: proxy support? */
1249         if ((rv = ssl_init_ctx_cert_chain(s, p, ptemp, mctx)) != APR_SUCCESS) {
1250             return rv;
1251         }
1252 #ifdef HAVE_TLSEXT
1253         if ((rv = ssl_init_ctx_tls_extensions(s, p, ptemp, mctx)) !=
1254             APR_SUCCESS) {
1255             return rv;
1256         }
1257 #endif
1258     }
1259 
1260     return APR_SUCCESS;
1261 }
1262 
ssl_check_public_cert(server_rec * s,apr_pool_t * ptemp,X509 * cert,const char * key_id)1263 static void ssl_check_public_cert(server_rec *s,
1264                                   apr_pool_t *ptemp,
1265                                   X509 *cert,
1266                                   const char *key_id)
1267 {
1268     int is_ca, pathlen;
1269 
1270     if (!cert) {
1271         return;
1272     }
1273 
1274     /*
1275      * Some information about the certificate(s)
1276      */
1277 
1278     if (modssl_X509_getBC(cert, &is_ca, &pathlen)) {
1279         if (is_ca) {
1280             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01906)
1281                          "%s server certificate is a CA certificate "
1282                          "(BasicConstraints: CA == TRUE !?)", key_id);
1283         }
1284 
1285         if (pathlen > 0) {
1286             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01907)
1287                          "%s server certificate is not a leaf certificate "
1288                          "(BasicConstraints: pathlen == %d > 0 !?)",
1289                          key_id, pathlen);
1290         }
1291     }
1292 
1293     if (modssl_X509_match_name(ptemp, cert, (const char *)s->server_hostname,
1294                                TRUE, s) == FALSE) {
1295         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(01909)
1296                      "%s server certificate does NOT include an ID "
1297                      "which matches the server name", key_id);
1298     }
1299 }
1300 
1301 /* prevent OpenSSL from showing its "Enter PEM pass phrase:" prompt */
ssl_no_passwd_prompt_cb(char * buf,int size,int rwflag,void * userdata)1302 static int ssl_no_passwd_prompt_cb(char *buf, int size, int rwflag,
1303                                    void *userdata) {
1304    return 0;
1305 }
1306 
modssl_DH_bits(DH * dh)1307 static APR_INLINE int modssl_DH_bits(DH *dh)
1308 {
1309 #if OPENSSL_VERSION_NUMBER < 0x30000000L
1310     return DH_bits(dh);
1311 #else
1312     return BN_num_bits(DH_get0_p(dh));
1313 #endif
1314 }
1315 
1316 /* SSL_CTX_use_PrivateKey_file() can fail either because the private
1317  * key was encrypted, or due to a mismatch between an already-loaded
1318  * cert and the key - a common misconfiguration - from calling
1319  * X509_check_private_key().  This macro is passed the last error code
1320  * off the OpenSSL stack and evaluates to true only for the first
1321  * case.  With OpenSSL < 3 the second case is identifiable by the
1322  * function code, but function codes are not used from 3.0. */
1323 #if OPENSSL_VERSION_NUMBER < 0x30000000L
1324 #define CHECK_PRIVKEY_ERROR(ec) (ERR_GET_FUNC(ec) != X509_F_X509_CHECK_PRIVATE_KEY)
1325 #else
1326 #define CHECK_PRIVKEY_ERROR(ec) (ERR_GET_LIB(ec) != ERR_LIB_X509            \
1327                                  || (ERR_GET_REASON(ec) != X509_R_KEY_TYPE_MISMATCH \
1328                                      && ERR_GET_REASON(ec) != X509_R_KEY_VALUES_MISMATCH \
1329                                      && ERR_GET_REASON(ec) != X509_R_UNKNOWN_KEY_TYPE))
1330 #endif
1331 
ssl_init_server_certs(server_rec * s,apr_pool_t * p,apr_pool_t * ptemp,modssl_ctx_t * mctx,apr_array_header_t * pphrases)1332 static apr_status_t ssl_init_server_certs(server_rec *s,
1333                                           apr_pool_t *p,
1334                                           apr_pool_t *ptemp,
1335                                           modssl_ctx_t *mctx,
1336                                           apr_array_header_t *pphrases)
1337 {
1338     SSLModConfigRec *mc = myModConfig(s);
1339     const char *vhost_id = mctx->sc->vhost_id, *key_id, *certfile, *keyfile;
1340     int i;
1341     X509 *cert;
1342     DH *dh;
1343 #ifdef HAVE_ECC
1344     EC_GROUP *ecparams = NULL;
1345     int nid;
1346     EC_KEY *eckey = NULL;
1347 #endif
1348 #ifndef HAVE_SSL_CONF_CMD
1349     SSL *ssl;
1350 #endif
1351 
1352     /* no OpenSSL default prompts for any of the SSL_CTX_use_* calls, please */
1353     SSL_CTX_set_default_passwd_cb(mctx->ssl_ctx, ssl_no_passwd_prompt_cb);
1354 
1355     /* Iterate over the SSLCertificateFile array */
1356     for (i = 0; (i < mctx->pks->cert_files->nelts) &&
1357                 (certfile = APR_ARRAY_IDX(mctx->pks->cert_files, i,
1358                                           const char *));
1359          i++) {
1360         EVP_PKEY *pkey;
1361         const char *engine_certfile = NULL;
1362 
1363         key_id = apr_psprintf(ptemp, "%s:%d", vhost_id, i);
1364 
1365         ERR_clear_error();
1366 
1367         /* first the certificate (public key) */
1368         if (modssl_is_engine_id(certfile)) {
1369             engine_certfile = certfile;
1370         }
1371         else if (mctx->cert_chain) {
1372             if ((SSL_CTX_use_certificate_file(mctx->ssl_ctx, certfile,
1373                                               SSL_FILETYPE_PEM) < 1)) {
1374                 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02561)
1375                              "Failed to configure certificate %s, check %s",
1376                              key_id, certfile);
1377                 ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1378                 return APR_EGENERAL;
1379             }
1380         } else {
1381             if ((SSL_CTX_use_certificate_chain_file(mctx->ssl_ctx,
1382                                                     certfile) < 1)) {
1383                 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02562)
1384                              "Failed to configure certificate %s (with chain),"
1385                              " check %s", key_id, certfile);
1386                 ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1387                 return APR_EGENERAL;
1388             }
1389         }
1390 
1391         /* and second, the private key */
1392         if (i < mctx->pks->key_files->nelts) {
1393             keyfile = APR_ARRAY_IDX(mctx->pks->key_files, i, const char *);
1394         } else {
1395             keyfile = certfile;
1396         }
1397 
1398         ERR_clear_error();
1399 
1400         if (modssl_is_engine_id(keyfile)) {
1401             apr_status_t rv;
1402 
1403             cert = NULL;
1404 
1405             if ((rv = modssl_load_engine_keypair(s, ptemp, vhost_id,
1406                                                  engine_certfile, keyfile,
1407                                                  &cert, &pkey))) {
1408                 return rv;
1409             }
1410 
1411             if (cert) {
1412                 if (SSL_CTX_use_certificate(mctx->ssl_ctx, cert) < 1) {
1413                     ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(10137)
1414                                  "Failed to configure engine certificate %s, check %s",
1415                                  key_id, certfile);
1416                     ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1417                     return APR_EGENERAL;
1418                 }
1419 
1420                 /* SSL_CTX now owns the cert. */
1421                 X509_free(cert);
1422             }
1423 
1424             if (SSL_CTX_use_PrivateKey(mctx->ssl_ctx, pkey) < 1) {
1425                 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(10130)
1426                              "Failed to configure private key %s from engine",
1427                              keyfile);
1428                 ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1429                 return APR_EGENERAL;
1430             }
1431 
1432             /* SSL_CTX now owns the key */
1433             EVP_PKEY_free(pkey);
1434         }
1435         else if ((SSL_CTX_use_PrivateKey_file(mctx->ssl_ctx, keyfile,
1436                                               SSL_FILETYPE_PEM) < 1)
1437                  && CHECK_PRIVKEY_ERROR(ERR_peek_last_error())) {
1438             ssl_asn1_t *asn1;
1439             const unsigned char *ptr;
1440 
1441             ERR_clear_error();
1442 
1443             /* perhaps it's an encrypted private key, so try again */
1444             ssl_load_encrypted_pkey(s, ptemp, i, keyfile, &pphrases);
1445 
1446             if (!(asn1 = ssl_asn1_table_get(mc->tPrivateKey, key_id)) ||
1447                 !(ptr = asn1->cpData) ||
1448                 !(pkey = d2i_AutoPrivateKey(NULL, &ptr, asn1->nData)) ||
1449                 (SSL_CTX_use_PrivateKey(mctx->ssl_ctx, pkey) < 1)) {
1450                 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02564)
1451                              "Failed to configure encrypted (?) private key %s,"
1452                              " check %s", key_id, keyfile);
1453                 ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1454                 return APR_EGENERAL;
1455             }
1456         }
1457 
1458         if (SSL_CTX_check_private_key(mctx->ssl_ctx) < 1) {
1459             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02565)
1460                          "Certificate and private key %s from %s and %s "
1461                          "do not match", key_id, certfile, keyfile);
1462             return APR_EGENERAL;
1463         }
1464 
1465 #ifdef HAVE_SSL_CONF_CMD
1466         /*
1467          * workaround for those OpenSSL versions where SSL_CTX_get0_certificate
1468          * is not yet available: create an SSL struct which we dispose of
1469          * as soon as we no longer need access to the cert. (Strictly speaking,
1470          * SSL_CTX_get0_certificate does not depend on the SSL_CONF stuff,
1471          * but there's no reliable way to check for its existence, so we
1472          * assume that if SSL_CONF is available, it's OpenSSL 1.0.2 or later,
1473          * and SSL_CTX_get0_certificate is implemented.)
1474          */
1475         if (!(cert = SSL_CTX_get0_certificate(mctx->ssl_ctx))) {
1476 #else
1477         ssl = SSL_new(mctx->ssl_ctx);
1478         if (ssl) {
1479             /* Workaround bug in SSL_get_certificate in OpenSSL 0.9.8y */
1480             SSL_set_connect_state(ssl);
1481             cert = SSL_get_certificate(ssl);
1482         }
1483         if (!ssl || !cert) {
1484 #endif
1485             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02566)
1486                          "Unable to retrieve certificate %s", key_id);
1487 #ifndef HAVE_SSL_CONF_CMD
1488             if (ssl)
1489                 SSL_free(ssl);
1490 #endif
1491             return APR_EGENERAL;
1492         }
1493 
1494         /* warn about potential cert issues */
1495         ssl_check_public_cert(s, ptemp, cert, key_id);
1496 
1497 #if defined(HAVE_OCSP_STAPLING) && !defined(SSL_CTRL_SET_CURRENT_CERT)
1498         /*
1499          * OpenSSL up to 1.0.1: configure stapling as we go. In 1.0.2
1500          * and later, there's SSL_CTX_set_current_cert, which allows
1501          * iterating over all certs in an SSL_CTX (including those possibly
1502          * loaded via SSLOpenSSLConfCmd Certificate), so for 1.0.2 and
1503          * later, we defer to the code in ssl_init_server_ctx.
1504          */
1505         if (!ssl_stapling_init_cert(s, p, ptemp, mctx, cert)) {
1506             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02567)
1507                          "Unable to configure certificate %s for stapling",
1508                          key_id);
1509         }
1510 #endif
1511 
1512 #ifndef HAVE_SSL_CONF_CMD
1513         SSL_free(ssl);
1514 #endif
1515 
1516         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02568)
1517                      "Certificate and private key %s configured from %s and %s",
1518                      key_id, certfile, keyfile);
1519     }
1520 
1521     /*
1522      * Try to read DH parameters from the (first) SSLCertificateFile
1523      */
1524     certfile = APR_ARRAY_IDX(mctx->pks->cert_files, 0, const char *);
1525     if (certfile && !modssl_is_engine_id(certfile)
1526         && (dh = ssl_dh_GetParamFromFile(certfile))) {
1527         /* ### This should be replaced with SSL_CTX_set0_tmp_dh_pkey()
1528          * for OpenSSL 3.0+. */
1529         SSL_CTX_set_tmp_dh(mctx->ssl_ctx, dh);
1530         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02540)
1531                      "Custom DH parameters (%d bits) for %s loaded from %s",
1532                      modssl_DH_bits(dh), vhost_id, certfile);
1533         DH_free(dh);
1534     }
1535 #if !MODSSL_USE_OPENSSL_PRE_1_1_API
1536     else {
1537         /* If no parameter is manually configured, enable auto
1538          * selection. */
1539         SSL_CTX_set_dh_auto(mctx->ssl_ctx, 1);
1540     }
1541 #endif
1542 
1543 #ifdef HAVE_ECC
1544     /*
1545      * Similarly, try to read the ECDH curve name from SSLCertificateFile...
1546      */
1547     if (certfile && !modssl_is_engine_id(certfile)
1548         && (ecparams = ssl_ec_GetParamFromFile(certfile))
1549         && (nid = EC_GROUP_get_curve_name(ecparams))
1550         && (eckey = EC_KEY_new_by_curve_name(nid))) {
1551         SSL_CTX_set_tmp_ecdh(mctx->ssl_ctx, eckey);
1552         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02541)
1553                      "ECDH curve %s for %s specified in %s",
1554                      OBJ_nid2sn(nid), vhost_id, certfile);
1555     }
1556     /*
1557      * ...otherwise, enable auto curve selection (OpenSSL 1.0.2)
1558      * or configure NIST P-256 (required to enable ECDHE for earlier versions)
1559      * ECDH is always enabled in 1.1.0 unless excluded from SSLCipherList
1560      */
1561 #if MODSSL_USE_OPENSSL_PRE_1_1_API
1562     else {
1563 #if defined(SSL_CTX_set_ecdh_auto)
1564         SSL_CTX_set_ecdh_auto(mctx->ssl_ctx, 1);
1565 #else
1566         eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1567         SSL_CTX_set_tmp_ecdh(mctx->ssl_ctx, eckey);
1568 #endif
1569     }
1570 #endif
1571     /* OpenSSL assures us that _free() is NULL-safe */
1572     EC_KEY_free(eckey);
1573     EC_GROUP_free(ecparams);
1574 #endif
1575 
1576     return APR_SUCCESS;
1577 }
1578 
1579 #ifdef HAVE_TLS_SESSION_TICKETS
1580 static apr_status_t ssl_init_ticket_key(server_rec *s,
1581                                         apr_pool_t *p,
1582                                         apr_pool_t *ptemp,
1583                                         modssl_ctx_t *mctx)
1584 {
1585     apr_status_t rv;
1586     apr_file_t *fp;
1587     apr_size_t len;
1588     char buf[TLSEXT_TICKET_KEY_LEN];
1589     char *path;
1590     modssl_ticket_key_t *ticket_key = mctx->ticket_key;
1591     int res;
1592 
1593     if (!ticket_key->file_path) {
1594         return APR_SUCCESS;
1595     }
1596 
1597     path = ap_server_root_relative(p, ticket_key->file_path);
1598 
1599     rv = apr_file_open(&fp, path, APR_READ|APR_BINARY,
1600                        APR_OS_DEFAULT, ptemp);
1601 
1602     if (rv != APR_SUCCESS) {
1603         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02286)
1604                      "Failed to open ticket key file %s: (%d) %pm",
1605                      path, rv, &rv);
1606         return ssl_die(s);
1607     }
1608 
1609     rv = apr_file_read_full(fp, &buf[0], TLSEXT_TICKET_KEY_LEN, &len);
1610 
1611     if (rv != APR_SUCCESS) {
1612         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02287)
1613                      "Failed to read %d bytes from %s: (%d) %pm",
1614                      TLSEXT_TICKET_KEY_LEN, path, rv, &rv);
1615         return ssl_die(s);
1616     }
1617 
1618     memcpy(ticket_key->key_name, buf, 16);
1619     memcpy(ticket_key->aes_key, buf + 32, 16);
1620 #if OPENSSL_VERSION_NUMBER < 0x30000000L
1621     memcpy(ticket_key->hmac_secret, buf + 16, 16);
1622     res = SSL_CTX_set_tlsext_ticket_key_cb(mctx->ssl_ctx,
1623                                            ssl_callback_SessionTicket);
1624 #else
1625     ticket_key->mac_params[0] =
1626         OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, buf + 16, 16);
1627     ticket_key->mac_params[1] =
1628         OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, "sha256", 0);
1629     ticket_key->mac_params[2] =
1630         OSSL_PARAM_construct_end();
1631     res = SSL_CTX_set_tlsext_ticket_key_evp_cb(mctx->ssl_ctx,
1632                                                ssl_callback_SessionTicket);
1633 #endif
1634     if (!res) {
1635         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01913)
1636                      "Unable to initialize TLS session ticket key callback "
1637                      "(incompatible OpenSSL version?)");
1638         ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1639         return ssl_die(s);
1640     }
1641 
1642     ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02288)
1643                  "TLS session ticket key for %s successfully loaded from %s",
1644                  (mySrvConfig(s))->vhost_id, path);
1645 
1646     return APR_SUCCESS;
1647 }
1648 #endif
1649 
1650 static BOOL load_x509_info(apr_pool_t *ptemp,
1651                            STACK_OF(X509_INFO) *sk,
1652                            const char *filename)
1653 {
1654     BIO *in;
1655 
1656     if (!(in = BIO_new(BIO_s_file()))) {
1657         return FALSE;
1658     }
1659 
1660     if (BIO_read_filename(in, filename) <= 0) {
1661         BIO_free(in);
1662         return FALSE;
1663     }
1664 
1665     ERR_clear_error();
1666 
1667     PEM_X509_INFO_read_bio(in, sk, NULL, NULL);
1668 
1669     BIO_free(in);
1670 
1671     return TRUE;
1672 }
1673 
1674 static apr_status_t ssl_init_proxy_certs(server_rec *s,
1675                                          apr_pool_t *p,
1676                                          apr_pool_t *ptemp,
1677                                          modssl_ctx_t *mctx)
1678 {
1679     int n, ncerts = 0;
1680     STACK_OF(X509_INFO) *sk;
1681     modssl_pk_proxy_t *pkp = mctx->pkp;
1682     STACK_OF(X509) *chain;
1683     X509_STORE_CTX *sctx;
1684     X509_STORE *store = SSL_CTX_get_cert_store(mctx->ssl_ctx);
1685 
1686 #if OPENSSL_VERSION_NUMBER >= 0x1010100fL && !defined(LIBRESSL_VERSION_NUMBER)
1687     /* For OpenSSL >=1.1.1, turn on client cert support which is
1688      * otherwise turned off by default (by design).
1689      * https://github.com/openssl/openssl/issues/6933 */
1690     SSL_CTX_set_post_handshake_auth(mctx->ssl_ctx, 1);
1691 #endif
1692 
1693     SSL_CTX_set_client_cert_cb(mctx->ssl_ctx,
1694                                ssl_callback_proxy_cert);
1695 
1696     if (!(pkp->cert_file || pkp->cert_path)) {
1697         return APR_SUCCESS;
1698     }
1699 
1700     sk = sk_X509_INFO_new_null();
1701 
1702     if (pkp->cert_file) {
1703         load_x509_info(ptemp, sk, pkp->cert_file);
1704     }
1705 
1706     if (pkp->cert_path) {
1707         ssl_init_ca_cert_path(s, ptemp, pkp->cert_path, NULL, sk);
1708     }
1709 
1710     if ((ncerts = sk_X509_INFO_num(sk)) <= 0) {
1711         sk_X509_INFO_free(sk);
1712         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(02206)
1713                      "no client certs found for SSL proxy");
1714         return APR_SUCCESS;
1715     }
1716 
1717     /* Check that all client certs have got certificates and private
1718      * keys. */
1719     for (n = 0; n < ncerts; n++) {
1720         X509_INFO *inf = sk_X509_INFO_value(sk, n);
1721 
1722         if (!inf->x509 || !inf->x_pkey || !inf->x_pkey->dec_pkey ||
1723             inf->enc_data) {
1724             sk_X509_INFO_free(sk);
1725             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, s, APLOGNO(02252)
1726                          "incomplete client cert configured for SSL proxy "
1727                          "(missing or encrypted private key?)");
1728             return ssl_die(s);
1729         }
1730 
1731         if (X509_check_private_key(inf->x509, inf->x_pkey->dec_pkey) != 1) {
1732             ssl_log_xerror(SSLLOG_MARK, APLOG_STARTUP, 0, ptemp, s, inf->x509,
1733                            APLOGNO(02326) "proxy client certificate and "
1734                            "private key do not match");
1735             ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
1736             return ssl_die(s);
1737         }
1738     }
1739 
1740     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02207)
1741                  "loaded %d client certs for SSL proxy",
1742                  ncerts);
1743     pkp->certs = sk;
1744 
1745 
1746     if (!pkp->ca_cert_file || !store) {
1747         return APR_SUCCESS;
1748     }
1749 
1750     /* If SSLProxyMachineCertificateChainFile is configured, load all
1751      * the CA certs and have OpenSSL attempt to construct a full chain
1752      * from each configured end-entity cert up to a root.  This will
1753      * allow selection of the correct cert given a list of root CA
1754      * names in the certificate request from the server.  */
1755     pkp->ca_certs = (STACK_OF(X509) **) apr_pcalloc(p, ncerts * sizeof(sk));
1756     sctx = X509_STORE_CTX_new();
1757 
1758     if (!sctx) {
1759         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02208)
1760                      "SSL proxy client cert initialization failed");
1761         ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1762         return ssl_die(s);
1763     }
1764 
1765     modssl_X509_STORE_load_locations(store, pkp->ca_cert_file, NULL);
1766 
1767     for (n = 0; n < ncerts; n++) {
1768         int i;
1769 
1770         X509_INFO *inf = sk_X509_INFO_value(pkp->certs, n);
1771         X509_STORE_CTX_init(sctx, store, inf->x509, NULL);
1772 
1773         /* Attempt to verify the client cert */
1774         if (X509_verify_cert(sctx) != 1) {
1775             int err = X509_STORE_CTX_get_error(sctx);
1776             ssl_log_xerror(SSLLOG_MARK, APLOG_WARNING, 0, ptemp, s, inf->x509,
1777                            APLOGNO(02270) "SSL proxy client cert chain "
1778                            "verification failed: %s :",
1779                            X509_verify_cert_error_string(err));
1780         }
1781 
1782         /* Clear X509_verify_cert errors */
1783         ERR_clear_error();
1784 
1785         /* Obtain a copy of the verified chain */
1786         chain = X509_STORE_CTX_get1_chain(sctx);
1787 
1788         if (chain != NULL) {
1789             /* Discard end entity cert from the chain */
1790             X509_free(sk_X509_shift(chain));
1791 
1792             if ((i = sk_X509_num(chain)) > 0) {
1793                 /* Store the chain for later use */
1794                 pkp->ca_certs[n] = chain;
1795             }
1796             else {
1797                 /* Discard empty chain */
1798                 sk_X509_pop_free(chain, X509_free);
1799                 pkp->ca_certs[n] = NULL;
1800             }
1801 
1802             ssl_log_xerror(SSLLOG_MARK, APLOG_DEBUG, 0, ptemp, s, inf->x509,
1803                            APLOGNO(02271)
1804                            "loaded %i intermediate CA%s for cert %i: ",
1805                            i, i == 1 ? "" : "s", n);
1806             if (i > 0) {
1807                 int j;
1808                 for (j = 0; j < i; j++) {
1809                     ssl_log_xerror(SSLLOG_MARK, APLOG_DEBUG, 0, ptemp, s,
1810                                    sk_X509_value(chain, j), APLOGNO(03039)
1811                                    "%i:", j);
1812                 }
1813             }
1814         }
1815 
1816         /* get ready for next X509_STORE_CTX_init */
1817         X509_STORE_CTX_cleanup(sctx);
1818     }
1819 
1820     X509_STORE_CTX_free(sctx);
1821 
1822     return APR_SUCCESS;
1823 }
1824 
1825 #define MODSSL_CFG_ITEM_FREE(func, item) \
1826     if (item) { \
1827         func(item); \
1828         item = NULL; \
1829     }
1830 
1831 static void ssl_init_ctx_cleanup(modssl_ctx_t *mctx)
1832 {
1833     MODSSL_CFG_ITEM_FREE(SSL_CTX_free, mctx->ssl_ctx);
1834 
1835 #ifdef HAVE_SRP
1836     if (mctx->srp_vbase != NULL) {
1837         SRP_VBASE_free(mctx->srp_vbase);
1838         mctx->srp_vbase = NULL;
1839     }
1840 #endif
1841 }
1842 
1843 static apr_status_t ssl_cleanup_proxy_ctx(void *data)
1844 {
1845     modssl_ctx_t *mctx = data;
1846 
1847     ssl_init_ctx_cleanup(mctx);
1848 
1849     if (mctx->pkp->certs) {
1850         int i = 0;
1851         int ncerts = sk_X509_INFO_num(mctx->pkp->certs);
1852 
1853         if (mctx->pkp->ca_certs) {
1854             for (i = 0; i < ncerts; i++) {
1855                 if (mctx->pkp->ca_certs[i] != NULL) {
1856                     sk_X509_pop_free(mctx->pkp->ca_certs[i], X509_free);
1857                 }
1858             }
1859         }
1860 
1861         sk_X509_INFO_pop_free(mctx->pkp->certs, X509_INFO_free);
1862         mctx->pkp->certs = NULL;
1863     }
1864 
1865     return APR_SUCCESS;
1866 }
1867 
1868 static apr_status_t ssl_init_proxy_ctx(server_rec *s,
1869                                        apr_pool_t *p,
1870                                        apr_pool_t *ptemp,
1871                                        modssl_ctx_t *proxy)
1872 {
1873     apr_status_t rv;
1874 
1875     if (proxy->ssl_ctx) {
1876         /* Merged/initialized already */
1877         return APR_SUCCESS;
1878     }
1879 
1880     apr_pool_cleanup_register(p, proxy,
1881                               ssl_cleanup_proxy_ctx,
1882                               apr_pool_cleanup_null);
1883 
1884     if ((rv = ssl_init_ctx(s, p, ptemp, proxy)) != APR_SUCCESS) {
1885         return rv;
1886     }
1887 
1888     if ((rv = ssl_init_proxy_certs(s, p, ptemp, proxy)) != APR_SUCCESS) {
1889         return rv;
1890     }
1891 
1892     return APR_SUCCESS;
1893 }
1894 
1895 static apr_status_t ssl_init_server_ctx(server_rec *s,
1896                                         apr_pool_t *p,
1897                                         apr_pool_t *ptemp,
1898                                         SSLSrvConfigRec *sc,
1899                                         apr_array_header_t *pphrases)
1900 {
1901     apr_status_t rv;
1902     modssl_pk_server_t *pks;
1903 #ifdef HAVE_SSL_CONF_CMD
1904     ssl_ctx_param_t *param = (ssl_ctx_param_t *)sc->server->ssl_ctx_param->elts;
1905     SSL_CONF_CTX *cctx = sc->server->ssl_ctx_config;
1906     int i;
1907 #endif
1908     int n;
1909 
1910     /*
1911      *  Check for problematic re-initializations
1912      */
1913     if (sc->server->ssl_ctx) {
1914         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02569)
1915                      "Illegal attempt to re-initialise SSL for server "
1916                      "(SSLEngine On should go in the VirtualHost, not in global scope.)");
1917         return APR_EGENERAL;
1918     }
1919 
1920     /* Allow others to provide certificate files */
1921     pks = sc->server->pks;
1922     n = pks->cert_files->nelts;
1923     ap_ssl_add_cert_files(s, p, pks->cert_files, pks->key_files);
1924     ssl_run_add_cert_files(s, p, pks->cert_files, pks->key_files);
1925 
1926     if (apr_is_empty_array(pks->cert_files)) {
1927         /* does someone propose a certiciate to fall back on here? */
1928         ap_ssl_add_fallback_cert_files(s, p, pks->cert_files, pks->key_files);
1929         ssl_run_add_fallback_cert_files(s, p, pks->cert_files, pks->key_files);
1930         if (n < pks->cert_files->nelts) {
1931             pks->service_unavailable = 1;
1932             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10085)
1933                          "Init: %s will respond with '503 Service Unavailable' for now. There "
1934                          "are no SSL certificates configured and no other module contributed any.",
1935                          ssl_util_vhostid(p, s));
1936         }
1937     }
1938 
1939     if (n < pks->cert_files->nelts) {
1940         /* additionally installed certs overrides any old chain configuration */
1941         sc->server->cert_chain = NULL;
1942     }
1943 
1944     if ((rv = ssl_init_ctx(s, p, ptemp, sc->server)) != APR_SUCCESS) {
1945         return rv;
1946     }
1947 
1948     if ((rv = ssl_init_server_certs(s, p, ptemp, sc->server, pphrases))
1949         != APR_SUCCESS) {
1950         return rv;
1951     }
1952 
1953 #ifdef HAVE_SSL_CONF_CMD
1954     SSL_CONF_CTX_set_ssl_ctx(cctx, sc->server->ssl_ctx);
1955     for (i = 0; i < sc->server->ssl_ctx_param->nelts; i++, param++) {
1956         ERR_clear_error();
1957         if (SSL_CONF_cmd(cctx, param->name, param->value) <= 0) {
1958             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02407)
1959                          "\"SSLOpenSSLConfCmd %s %s\" failed for %s",
1960                          param->name, param->value, sc->vhost_id);
1961             ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1962             return ssl_die(s);
1963         } else {
1964             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02556)
1965                          "\"SSLOpenSSLConfCmd %s %s\" applied to %s",
1966                          param->name, param->value, sc->vhost_id);
1967         }
1968     }
1969 
1970     if (SSL_CONF_CTX_finish(cctx) == 0) {
1971             ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02547)
1972                          "SSL_CONF_CTX_finish() failed");
1973             SSL_CONF_CTX_free(cctx);
1974             ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1975             return ssl_die(s);
1976     }
1977 #endif
1978 
1979     if (SSL_CTX_check_private_key(sc->server->ssl_ctx) != 1) {
1980         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02572)
1981                      "Failed to configure at least one certificate and key "
1982                      "for %s", sc->vhost_id);
1983         ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
1984         return ssl_die(s);
1985     }
1986 
1987 #if defined(HAVE_OCSP_STAPLING) && defined(SSL_CTRL_SET_CURRENT_CERT)
1988     /*
1989      * OpenSSL 1.0.2 and later allows iterating over all SSL_CTX certs
1990      * by means of SSL_CTX_set_current_cert. Enabling stapling at this
1991      * (late) point makes sure that we catch both certificates loaded
1992      * via SSLCertificateFile and SSLOpenSSLConfCmd Certificate.
1993      */
1994     do {
1995         X509 *cert;
1996         int i = 0;
1997         int ret = SSL_CTX_set_current_cert(sc->server->ssl_ctx,
1998                                            SSL_CERT_SET_FIRST);
1999         while (ret) {
2000             cert = SSL_CTX_get0_certificate(sc->server->ssl_ctx);
2001             if (!cert || !ssl_stapling_init_cert(s, p, ptemp, sc->server,
2002                                                  cert)) {
2003                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02604)
2004                              "Unable to configure certificate %s:%d "
2005                              "for stapling", sc->vhost_id, i);
2006             }
2007             ret = SSL_CTX_set_current_cert(sc->server->ssl_ctx,
2008                                            SSL_CERT_SET_NEXT);
2009             i++;
2010         }
2011     } while(0);
2012 #endif
2013 
2014 #ifdef HAVE_TLS_SESSION_TICKETS
2015     if ((rv = ssl_init_ticket_key(s, p, ptemp, sc->server)) != APR_SUCCESS) {
2016         return rv;
2017     }
2018 #endif
2019 
2020     SSL_CTX_set_timeout(sc->server->ssl_ctx,
2021                         sc->session_cache_timeout == UNSET ?
2022                         SSL_SESSION_CACHE_TIMEOUT : sc->session_cache_timeout);
2023 
2024     return APR_SUCCESS;
2025 }
2026 
2027 /*
2028  * Configure a particular server
2029  */
2030 apr_status_t ssl_init_ConfigureServer(server_rec *s,
2031                                       apr_pool_t *p,
2032                                       apr_pool_t *ptemp,
2033                                       SSLSrvConfigRec *sc,
2034                                       apr_array_header_t *pphrases)
2035 {
2036     SSLDirConfigRec *sdc = ap_get_module_config(s->lookup_defaults,
2037                                                 &ssl_module);
2038     apr_status_t rv;
2039 
2040     /* Initialize the server if SSL is enabled or optional.
2041      */
2042     if ((sc->enabled == SSL_ENABLED_TRUE) || (sc->enabled == SSL_ENABLED_OPTIONAL)) {
2043         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01914)
2044                      "Configuring server %s for SSL protocol", sc->vhost_id);
2045         if ((rv = ssl_init_server_ctx(s, p, ptemp, sc, pphrases))
2046             != APR_SUCCESS) {
2047             return rv;
2048         }
2049 
2050 	/* Initialize OCSP Responder certificate if OCSP enabled */
2051 	#ifndef OPENSSL_NO_OCSP
2052         	ssl_init_ocsp_certificates(s, sc->server);
2053 	#endif
2054 
2055     }
2056 
2057     sdc->proxy->sc = sc;
2058     if (sdc->proxy_enabled == TRUE) {
2059         rv = ssl_init_proxy_ctx(s, p, ptemp, sdc->proxy);
2060         if (rv != APR_SUCCESS) {
2061             return rv;
2062         }
2063     }
2064     else {
2065         sdc->proxy_enabled = FALSE;
2066     }
2067     sdc->proxy_post_config = 1;
2068 
2069     return APR_SUCCESS;
2070 }
2071 
2072 apr_status_t ssl_init_CheckServers(server_rec *base_server, apr_pool_t *p)
2073 {
2074     server_rec *s;
2075     SSLSrvConfigRec *sc;
2076 #ifndef HAVE_TLSEXT
2077     server_rec *ps;
2078     apr_hash_t *table;
2079     const char *key;
2080     apr_ssize_t klen;
2081 
2082     BOOL conflict = FALSE;
2083 #endif
2084 
2085     /*
2086      * Give out warnings when a server has HTTPS configured
2087      * for the HTTP port or vice versa
2088      */
2089     for (s = base_server; s; s = s->next) {
2090         sc = mySrvConfig(s);
2091 
2092         if ((sc->enabled == SSL_ENABLED_TRUE) && (s->port == DEFAULT_HTTP_PORT)) {
2093             ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
2094                          base_server, APLOGNO(01915)
2095                          "Init: (%s) You configured HTTPS(%d) "
2096                          "on the standard HTTP(%d) port!",
2097                          ssl_util_vhostid(p, s),
2098                          DEFAULT_HTTPS_PORT, DEFAULT_HTTP_PORT);
2099         }
2100 
2101         if ((sc->enabled == SSL_ENABLED_FALSE) && (s->port == DEFAULT_HTTPS_PORT)) {
2102             ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
2103                          base_server, APLOGNO(01916)
2104                          "Init: (%s) You configured HTTP(%d) "
2105                          "on the standard HTTPS(%d) port!",
2106                          ssl_util_vhostid(p, s),
2107                          DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT);
2108         }
2109     }
2110 
2111 #ifndef HAVE_TLSEXT
2112     /*
2113      * Give out warnings when more than one SSL-aware virtual server uses the
2114      * same IP:port and an OpenSSL version without support for TLS extensions
2115      * (SNI in particular) is used.
2116      */
2117     table = apr_hash_make(p);
2118 
2119     for (s = base_server; s; s = s->next) {
2120         char *addr;
2121 
2122         sc = mySrvConfig(s);
2123 
2124         if (!((sc->enabled == SSL_ENABLED_TRUE) && s->addrs)) {
2125             continue;
2126         }
2127 
2128         apr_sockaddr_ip_get(&addr, s->addrs->host_addr);
2129         key = apr_psprintf(p, "%s:%u", addr, s->addrs->host_port);
2130         klen = strlen(key);
2131 
2132         if ((ps = (server_rec *)apr_hash_get(table, key, klen))) {
2133             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, base_server, APLOGNO(02662)
2134                          "Init: SSL server IP/port conflict: "
2135                          "%s (%s:%d) vs. %s (%s:%d)",
2136                          ssl_util_vhostid(p, s),
2137                          (s->defn_name ? s->defn_name : "unknown"),
2138                          s->defn_line_number,
2139                          ssl_util_vhostid(p, ps),
2140                          (ps->defn_name ? ps->defn_name : "unknown"),
2141                          ps->defn_line_number);
2142             conflict = TRUE;
2143             continue;
2144         }
2145 
2146         apr_hash_set(table, key, klen, s);
2147     }
2148 
2149     if (conflict) {
2150         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, base_server, APLOGNO(01917)
2151                      "Init: Name-based SSL virtual hosts require "
2152                      "an OpenSSL version with support for TLS extensions "
2153                      "(RFC 6066 - Server Name Indication / SNI), "
2154                      "but the currently used library version (%s) is "
2155                      "lacking this feature", MODSSL_LIBRARY_DYNTEXT);
2156     }
2157 #endif
2158 
2159     return APR_SUCCESS;
2160 }
2161 
2162 int ssl_proxy_section_post_config(apr_pool_t *p, apr_pool_t *plog,
2163                                   apr_pool_t *ptemp, server_rec *s,
2164                                   ap_conf_vector_t *section_config)
2165 {
2166     SSLDirConfigRec *sdc = ap_get_module_config(s->lookup_defaults,
2167                                                 &ssl_module);
2168     SSLDirConfigRec *pdc = ap_get_module_config(section_config,
2169                                                 &ssl_module);
2170     if (pdc) {
2171         pdc->proxy->sc = mySrvConfig(s);
2172         ssl_config_proxy_merge(p, sdc, pdc);
2173         if (pdc->proxy_enabled) {
2174             apr_status_t rv;
2175 
2176             rv = ssl_init_proxy_ctx(s, p, ptemp, pdc->proxy);
2177             if (rv != APR_SUCCESS) {
2178                 return !OK;
2179             }
2180 
2181             rv = ssl_run_init_server(s, p, 1, pdc->proxy->ssl_ctx);
2182             if (rv != APR_SUCCESS) {
2183                 return !OK;
2184             }
2185         }
2186         pdc->proxy_post_config = 1;
2187     }
2188     return OK;
2189 }
2190 
2191 static int ssl_init_FindCAList_X509NameCmp(const X509_NAME * const *a,
2192                                            const X509_NAME * const *b)
2193 {
2194     return(X509_NAME_cmp(*a, *b));
2195 }
2196 
2197 static void ssl_init_PushCAList(STACK_OF(X509_NAME) *ca_list,
2198                                 server_rec *s, apr_pool_t *ptemp,
2199                                 const char *file)
2200 {
2201     int n;
2202     STACK_OF(X509_NAME) *sk;
2203 
2204     sk = (STACK_OF(X509_NAME) *)
2205              SSL_load_client_CA_file(file);
2206 
2207     if (!sk) {
2208         return;
2209     }
2210 
2211     for (n = 0; n < sk_X509_NAME_num(sk); n++) {
2212         X509_NAME *name = sk_X509_NAME_value(sk, n);
2213 
2214         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02209)
2215                      "CA certificate: %s",
2216                      modssl_X509_NAME_to_string(ptemp, name, 0));
2217 
2218         /*
2219          * note that SSL_load_client_CA_file() checks for duplicates,
2220          * but since we call it multiple times when reading a directory
2221          * we must also check for duplicates ourselves.
2222          */
2223 
2224         if (sk_X509_NAME_find(ca_list, name) < 0) {
2225             /* this will be freed when ca_list is */
2226             sk_X509_NAME_push(ca_list, name);
2227         }
2228         else {
2229             /* need to free this ourselves, else it will leak */
2230             X509_NAME_free(name);
2231         }
2232     }
2233 
2234     sk_X509_NAME_free(sk);
2235 }
2236 
2237 static apr_status_t ssl_init_ca_cert_path(server_rec *s,
2238                                           apr_pool_t *ptemp,
2239                                           const char *path,
2240                                           STACK_OF(X509_NAME) *ca_list,
2241                                           STACK_OF(X509_INFO) *xi_list)
2242 {
2243     apr_dir_t *dir;
2244     apr_finfo_t direntry;
2245     apr_int32_t finfo_flags = APR_FINFO_TYPE|APR_FINFO_NAME;
2246 
2247     if (!path || (!ca_list && !xi_list) ||
2248         (apr_dir_open(&dir, path, ptemp) != APR_SUCCESS)) {
2249         return APR_EGENERAL;
2250     }
2251 
2252     while ((apr_dir_read(&direntry, finfo_flags, dir)) == APR_SUCCESS) {
2253         const char *file;
2254         if (direntry.filetype == APR_DIR) {
2255             continue; /* don't try to load directories */
2256         }
2257         file = apr_pstrcat(ptemp, path, "/", direntry.name, NULL);
2258         if (ca_list) {
2259             ssl_init_PushCAList(ca_list, s, ptemp, file);
2260         }
2261         if (xi_list) {
2262             load_x509_info(ptemp, xi_list, file);
2263         }
2264     }
2265 
2266     apr_dir_close(dir);
2267 
2268     return APR_SUCCESS;
2269 }
2270 
2271 STACK_OF(X509_NAME) *ssl_init_FindCAList(server_rec *s,
2272                                          apr_pool_t *ptemp,
2273                                          const char *ca_file,
2274                                          const char *ca_path)
2275 {
2276     STACK_OF(X509_NAME) *ca_list;
2277 
2278     /*
2279      * Start with a empty stack/list where new
2280      * entries get added in sorted order.
2281      */
2282     ca_list = sk_X509_NAME_new(ssl_init_FindCAList_X509NameCmp);
2283 
2284     /*
2285      * Process CA certificate bundle file
2286      */
2287     if (ca_file) {
2288         ssl_init_PushCAList(ca_list, s, ptemp, ca_file);
2289         /*
2290          * If ca_list is still empty after trying to load ca_file
2291          * then the file failed to load, and users should hear about that.
2292          */
2293         if (sk_X509_NAME_num(ca_list) == 0) {
2294             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(02210)
2295                     "Failed to load SSLCACertificateFile: %s", ca_file);
2296             ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
2297         }
2298     }
2299 
2300     /*
2301      * Process CA certificate path files
2302      */
2303     if (ca_path &&
2304         ssl_init_ca_cert_path(s, ptemp,
2305                               ca_path, ca_list, NULL) != APR_SUCCESS) {
2306         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02211)
2307                      "Failed to open Certificate Path `%s'", ca_path);
2308         sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
2309         return NULL;
2310     }
2311 
2312     /*
2313      * Cleanup
2314      */
2315     (void) sk_X509_NAME_set_cmp_func(ca_list, NULL);
2316 
2317     return ca_list;
2318 }
2319 
2320 void ssl_init_Child(apr_pool_t *p, server_rec *s)
2321 {
2322     SSLModConfigRec *mc = myModConfig(s);
2323     mc->pid = getpid(); /* only call getpid() once per-process */
2324 
2325     /* XXX: there should be an ap_srand() function */
2326     srand((unsigned int)time(NULL));
2327 
2328     /* open the mutex lockfile */
2329     ssl_mutex_reinit(s, p);
2330 #ifdef HAVE_OCSP_STAPLING
2331     ssl_stapling_mutex_reinit(s, p);
2332 #endif
2333 }
2334 
2335 apr_status_t ssl_init_ModuleKill(void *data)
2336 {
2337     SSLSrvConfigRec *sc;
2338     server_rec *base_server = (server_rec *)data;
2339     server_rec *s;
2340 
2341     /*
2342      * Drop the session cache and mutex
2343      */
2344     ssl_scache_kill(base_server);
2345 
2346     /*
2347      * Free the non-pool allocated structures
2348      * in the per-server configurations
2349      */
2350     for (s = base_server; s; s = s->next) {
2351         sc = mySrvConfig(s);
2352 
2353         ssl_init_ctx_cleanup(sc->server);
2354 
2355 	/* Not Sure but possibly clear X509 trusted cert file */
2356 	#ifndef OPENSSL_NO_OCSP
2357 		sk_X509_pop_free(sc->server->ocsp_certs, X509_free);
2358 	#endif
2359 
2360     }
2361 
2362 #if MODSSL_USE_OPENSSL_PRE_1_1_API
2363     free_dh_params();
2364 #else
2365     free_bio_methods();
2366 #endif
2367 
2368     return APR_SUCCESS;
2369 }
2370