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