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