]> granicus.if.org Git - apache/blob - modules/ssl/ssl_engine_init.c
switch to APR 1.0 API (which is still in flux)
[apache] / modules / ssl / ssl_engine_init.c
1 /*                      _             _
2 **  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
3 ** | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
4 ** | | | | | | (_) | (_| |   \__ \__ \ |  www.modssl.org
5 ** |_| |_| |_|\___/ \__,_|___|___/___/_|  ftp.modssl.org
6 **                      |_____|
7 **  ssl_engine_init.c
8 **  Initialization of Servers
9 */
10
11 /* ====================================================================
12  * The Apache Software License, Version 1.1
13  *
14  * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
15  * reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  *
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  *
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in
26  *    the documentation and/or other materials provided with the
27  *    distribution.
28  *
29  * 3. The end-user documentation included with the redistribution,
30  *    if any, must include the following acknowledgment:
31  *       "This product includes software developed by the
32  *        Apache Software Foundation (http://www.apache.org/)."
33  *    Alternately, this acknowledgment may appear in the software itself,
34  *    if and wherever such third-party acknowledgments normally appear.
35  *
36  * 4. The names "Apache" and "Apache Software Foundation" must
37  *    not be used to endorse or promote products derived from this
38  *    software without prior written permission. For written
39  *    permission, please contact apache@apache.org.
40  *
41  * 5. Products derived from this software may not be called "Apache",
42  *    nor may "Apache" appear in their name, without prior written
43  *    permission of the Apache Software Foundation.
44  *
45  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
46  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
47  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
48  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
49  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
50  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
51  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
52  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
53  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
54  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
55  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56  * SUCH DAMAGE.
57  * ====================================================================
58  */
59                              /* ``Recursive, adj.;
60                                   see Recursive.''
61                                         -- Unknown   */
62 #include "mod_ssl.h"
63
64 /*  _________________________________________________________________
65 **
66 **  Module Initialization
67 **  _________________________________________________________________
68 */
69
70 static char *ssl_add_version_component(apr_pool_t *p,
71                                        server_rec *s,
72                                        char *name)
73 {
74     char *val = ssl_var_lookup(p, s, NULL, NULL, name);
75
76     if (val && *val) {
77         ap_add_version_component(p, val);
78     }
79
80     return val;
81 }
82
83 static char *version_components[] = {
84     "SSL_VERSION_PRODUCT",
85     "SSL_VERSION_INTERFACE",
86     "SSL_VERSION_LIBRARY",
87     NULL
88 };
89
90 static void ssl_add_version_components(apr_pool_t *p,
91                                        server_rec *s)
92 {
93     char *vals[sizeof(version_components)/sizeof(char *)];
94     int i;
95
96     for (i=0; version_components[i]; i++) {
97         vals[i] = ssl_add_version_component(p, s,
98                                             version_components[i]);
99     }
100
101     ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
102                  "Server: %s, Interface: %s, Library: %s",
103                  AP_SERVER_BASEVERSION,
104                  vals[1],  /* SSL_VERSION_INTERFACE */
105                  vals[2]); /* SSL_VERSION_LIBRARY */
106 }
107
108
109 /*
110  * Handle the Temporary RSA Keys and DH Params
111  */
112
113 #define MODSSL_TMP_KEY_FREE(mc, type, idx) \
114     if (mc->pTmpKeys[idx]) { \
115         type##_free((type *)mc->pTmpKeys[idx]); \
116         mc->pTmpKeys[idx] = NULL; \
117     }
118
119 #define MODSSL_TMP_KEYS_FREE(mc, type) \
120     MODSSL_TMP_KEY_FREE(mc, type, SSL_TMP_KEY_##type##_512); \
121     MODSSL_TMP_KEY_FREE(mc, type, SSL_TMP_KEY_##type##_1024)
122
123 static void ssl_tmp_keys_free(server_rec *s)
124 {
125     SSLModConfigRec *mc = myModConfig(s);
126
127     MODSSL_TMP_KEYS_FREE(mc, RSA);
128     MODSSL_TMP_KEYS_FREE(mc, DH);
129 }
130
131 static int ssl_tmp_key_init_rsa(server_rec *s,
132                                 int bits, int idx)
133 {
134     SSLModConfigRec *mc = myModConfig(s);
135
136     if (!(mc->pTmpKeys[idx] =
137           RSA_generate_key(bits, RSA_F4, NULL, NULL)))
138     {
139         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
140                      "Init: Failed to generate temporary "
141                      "%d bit RSA private key", bits);
142         return !OK;
143     }
144
145     return OK;
146 }
147
148 static int ssl_tmp_key_init_dh(server_rec *s,
149                                int bits, int idx)
150 {
151     SSLModConfigRec *mc = myModConfig(s);
152
153     if (!(mc->pTmpKeys[idx] =
154           ssl_dh_GetTmpParam(bits)))
155     {
156         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
157                      "Init: Failed to generate temporary "
158                      "%d bit DH parameters", bits);
159         return !OK;
160     }
161
162     return OK;
163 }
164
165 #define MODSSL_TMP_KEY_INIT_RSA(s, bits) \
166     ssl_tmp_key_init_rsa(s, bits, SSL_TMP_KEY_RSA_##bits)
167
168 #define MODSSL_TMP_KEY_INIT_DH(s, bits) \
169     ssl_tmp_key_init_dh(s, bits, SSL_TMP_KEY_DH_##bits)
170
171 static int ssl_tmp_keys_init(server_rec *s)
172 {
173     ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
174                  "Init: Generating temporary RSA private keys (512/1024 bits)");
175
176     if (MODSSL_TMP_KEY_INIT_RSA(s, 512) ||
177         MODSSL_TMP_KEY_INIT_RSA(s, 1024)) {
178         return !OK;
179     }
180
181     ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
182                  "Init: Generating temporary DH parameters (512/1024 bits)");
183
184     if (MODSSL_TMP_KEY_INIT_DH(s, 512) ||
185         MODSSL_TMP_KEY_INIT_DH(s, 1024)) {
186         return !OK;
187     }
188
189     return OK;
190 }
191
192 /*
193  *  Per-module initialization
194  */
195 int ssl_init_Module(apr_pool_t *p, apr_pool_t *plog,
196                     apr_pool_t *ptemp,
197                     server_rec *base_server)
198 {
199     SSLModConfigRec *mc = myModConfig(base_server);
200     SSLSrvConfigRec *sc;
201     server_rec *s;
202
203     /* We initialize mc->pid per-process in the child init,
204      * but it should be initialized for startup before we
205      * call ssl_rand_seed() below.
206      */
207     mc->pid = getpid(); 
208
209     /*
210      * Let us cleanup on restarts and exists
211      */
212     apr_pool_cleanup_register(p, base_server,
213                               ssl_init_ModuleKill,
214                               apr_pool_cleanup_null);
215
216     /*
217      * Any init round fixes the global config
218      */
219     ssl_config_global_create(base_server); /* just to avoid problems */
220     ssl_config_global_fix(mc);
221
222     /*
223      *  try to fix the configuration and open the dedicated SSL
224      *  logfile as early as possible
225      */
226     for (s = base_server; s; s = s->next) {
227         sc = mySrvConfig(s);
228
229         if (sc->server) {
230             sc->server->sc = sc;
231         }
232
233         if (sc->proxy) {
234             sc->proxy->sc = sc;
235         }
236
237         /*
238          * Create the server host:port string because we need it a lot
239          */
240         sc->vhost_id = ssl_util_vhostid(p, s);
241         sc->vhost_id_len = strlen(sc->vhost_id);
242
243 #if 0
244        /* If sc->enabled is UNSET, then SSL is optional on this vhost  */
245         /* Fix up stuff that may not have been set */
246         if (sc->enabled == UNSET) {
247             sc->enabled = FALSE;
248         }
249 #endif
250         if (sc->proxy_enabled == UNSET) {
251             sc->proxy_enabled = FALSE;
252         }
253
254         if (sc->session_cache_timeout == UNSET) {
255             sc->session_cache_timeout = SSL_SESSION_CACHE_TIMEOUT;
256         }
257
258         if (sc->server->pphrase_dialog_type == SSL_PPTYPE_UNSET) {
259             sc->server->pphrase_dialog_type = SSL_PPTYPE_BUILTIN;
260         }
261
262     }
263
264     /*
265      * SSL external crypto device ("engine") support
266      */
267 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
268     ssl_init_Engine(base_server, p);
269 #endif
270
271 #if APR_HAS_THREADS
272     ssl_util_thread_setup(p);
273 #endif
274
275     ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
276                  "Init: Initialized %s library", SSL_LIBRARY_NAME);
277
278     /*
279      * Seed the Pseudo Random Number Generator (PRNG)
280      * only need ptemp here; nothing inside allocated from the pool
281      * needs to live once we return from ssl_rand_seed().
282      */
283     ssl_rand_seed(base_server, ptemp, SSL_RSCTX_STARTUP, "Init: ");
284
285     /*
286      * read server private keys/public certs into memory.
287      * decrypting any encrypted keys via configured SSLPassPhraseDialogs
288      * anything that needs to live longer than ptemp needs to also survive
289      * restarts, in which case they'll live inside s->process->pool.
290      */
291     ssl_pphrase_Handle(base_server, ptemp);
292
293     if (ssl_tmp_keys_init(base_server)) {
294         return !OK;
295     }
296
297     /*
298      * initialize the mutex handling
299      */
300     if (!ssl_mutex_init(base_server, p)) {
301         return HTTP_INTERNAL_SERVER_ERROR;
302     }
303
304     /*
305      * initialize session caching
306      */
307     ssl_scache_init(base_server, p);
308
309     /*
310      *  initialize servers
311      */
312     ap_log_error(APLOG_MARK, APLOG_INFO, 0, base_server,
313                  "Init: Initializing (virtual) servers for SSL");
314
315     for (s = base_server; s; s = s->next) {
316         sc = mySrvConfig(s);
317         /*
318          * Either now skip this server when SSL is disabled for
319          * it or give out some information about what we're
320          * configuring.
321          */
322
323         /*
324          * Read the server certificate and key
325          */
326         ssl_init_ConfigureServer(s, p, ptemp, sc);
327     }
328
329     /*
330      * Configuration consistency checks
331      */
332     ssl_init_CheckServers(base_server, ptemp);
333
334     /*
335      *  Announce mod_ssl and SSL library in HTTP Server field
336      *  as ``mod_ssl/X.X.X OpenSSL/X.X.X''
337      */
338     ssl_add_version_components(p, base_server);
339
340     SSL_init_app_data2_idx(); /* for SSL_get_app_data2() at request time */
341
342     return OK;
343 }
344
345 /*
346  * Support for external a Crypto Device ("engine"), usually
347  * a hardware accellerator card for crypto operations.
348  */
349 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
350 void ssl_init_Engine(server_rec *s, apr_pool_t *p)
351 {
352     SSLModConfigRec *mc = myModConfig(s);
353     ENGINE *e;
354
355     if (mc->szCryptoDevice) {
356         if (!(e = ENGINE_by_id(mc->szCryptoDevice))) {
357             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
358                          "Init: Failed to load Crypto Device API `%s'",
359                          mc->szCryptoDevice);
360             ssl_die();
361         }
362
363         if (strEQ(mc->szCryptoDevice, "chil")) {
364             ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
365         }
366
367         if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
368             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
369                          "Init: Failed to enable Crypto Device API `%s'",
370                          mc->szCryptoDevice);
371             ssl_die();
372         }
373
374         ENGINE_free(e);
375     }
376 }
377 #endif
378
379 static void ssl_init_server_check(server_rec *s,
380                                   apr_pool_t *p,
381                                   apr_pool_t *ptemp,
382                                   modssl_ctx_t *mctx)
383 {
384     /*
385      * check for important parameters and the
386      * possibility that the user forgot to set them.
387      */
388     if (!mctx->pks->cert_files[0]) {
389         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
390                 "No SSL Certificate set [hint: SSLCertificateFile]");
391         ssl_die();
392     }
393
394     /*
395      *  Check for problematic re-initializations
396      */
397     if (mctx->pks->certs[SSL_AIDX_RSA] ||
398         mctx->pks->certs[SSL_AIDX_DSA])
399     {
400         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
401                 "Illegal attempt to re-initialise SSL for server "
402                 "(theoretically shouldn't happen!)");
403         ssl_die();
404     }
405 }
406
407 static void ssl_init_ctx_protocol(server_rec *s,
408                                   apr_pool_t *p,
409                                   apr_pool_t *ptemp,
410                                   modssl_ctx_t *mctx)
411 {
412     SSL_CTX *ctx = NULL;
413     SSL_METHOD *method = NULL;
414     char *cp;
415     int protocol = mctx->protocol;
416
417     /*
418      *  Create the new per-server SSL context
419      */
420     if (protocol == SSL_PROTOCOL_NONE) {
421         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
422                 "No SSL protocols available [hint: SSLProtocol]");
423         ssl_die();
424     }
425
426     cp = apr_pstrcat(p,
427                      (protocol & SSL_PROTOCOL_SSLV2 ? "SSLv2, " : ""),
428                      (protocol & SSL_PROTOCOL_SSLV3 ? "SSLv3, " : ""),
429                      (protocol & SSL_PROTOCOL_TLSV1 ? "TLSv1, " : ""),
430                      NULL);
431     cp[strlen(cp)-2] = NUL;
432
433     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
434                  "Creating new SSL context (protocols: %s)", cp);
435
436     if (protocol == SSL_PROTOCOL_SSLV2) {
437         method = mctx->pkp ?
438             SSLv2_client_method() : /* proxy */
439             SSLv2_server_method();  /* server */
440         ctx = SSL_CTX_new(method);  /* only SSLv2 is left */
441     }
442     else {
443         method = mctx->pkp ?
444             SSLv23_client_method() : /* proxy */
445             SSLv23_server_method();  /* server */
446         ctx = SSL_CTX_new(method); /* be more flexible */
447     }
448
449     mctx->ssl_ctx = ctx;
450
451     SSL_CTX_set_options(ctx, SSL_OP_ALL);
452
453     if (!(protocol & SSL_PROTOCOL_SSLV2)) {
454         SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
455     }
456
457     if (!(protocol & SSL_PROTOCOL_SSLV3)) {
458         SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);
459     }
460
461     if (!(protocol & SSL_PROTOCOL_TLSV1)) {
462         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1);
463     }
464
465     SSL_CTX_set_app_data(ctx, s);
466
467     /*
468      * Configure additional context ingredients
469      */
470     SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
471 }
472
473 static void ssl_init_ctx_session_cache(server_rec *s,
474                                        apr_pool_t *p,
475                                        apr_pool_t *ptemp,
476                                        modssl_ctx_t *mctx)
477 {
478     SSL_CTX *ctx = mctx->ssl_ctx;
479     SSLModConfigRec *mc = myModConfig(s);
480     long cache_mode = SSL_SESS_CACHE_OFF;
481
482     if (mc->nSessionCacheMode != SSL_SCMODE_NONE) {
483         /* SSL_SESS_CACHE_NO_INTERNAL_LOOKUP will force OpenSSL
484          * to ignore process local-caching and
485          * to always get/set/delete sessions using mod_ssl's callbacks.
486          */
487         cache_mode = SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL_LOOKUP;
488     }
489
490     SSL_CTX_set_session_cache_mode(ctx, cache_mode);
491
492     SSL_CTX_sess_set_new_cb(ctx,    ssl_callback_NewSessionCacheEntry);
493     SSL_CTX_sess_set_get_cb(ctx,    ssl_callback_GetSessionCacheEntry);
494     SSL_CTX_sess_set_remove_cb(ctx, ssl_callback_DelSessionCacheEntry);
495 }
496
497 static void ssl_init_ctx_callbacks(server_rec *s,
498                                    apr_pool_t *p,
499                                    apr_pool_t *ptemp,
500                                    modssl_ctx_t *mctx)
501 {
502     SSL_CTX *ctx = mctx->ssl_ctx;
503
504     SSL_CTX_set_tmp_rsa_callback(ctx, ssl_callback_TmpRSA);
505     SSL_CTX_set_tmp_dh_callback(ctx,  ssl_callback_TmpDH);
506
507     if (s->loglevel >= APLOG_DEBUG) {
508         /* this callback only logs if LogLevel >= info */
509         SSL_CTX_set_info_callback(ctx, ssl_callback_LogTracingState);
510     }
511 }
512
513 static void ssl_init_ctx_verify(server_rec *s,
514                                 apr_pool_t *p,
515                                 apr_pool_t *ptemp,
516                                 modssl_ctx_t *mctx)
517 {
518     SSL_CTX *ctx = mctx->ssl_ctx;
519
520     int verify = SSL_VERIFY_NONE;
521     STACK_OF(X509_NAME) *ca_list;
522
523     if (mctx->auth.verify_mode == SSL_CVERIFY_UNSET) {
524         mctx->auth.verify_mode = SSL_CVERIFY_NONE;
525     }
526
527     if (mctx->auth.verify_depth == UNSET) {
528         mctx->auth.verify_depth = 1;
529     }
530
531     /*
532      *  Configure callbacks for SSL context
533      */
534     if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
535         verify |= SSL_VERIFY_PEER_STRICT;
536     }
537
538     if ((mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL) ||
539         (mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL_NO_CA))
540     {
541         verify |= SSL_VERIFY_PEER;
542     }
543
544     SSL_CTX_set_verify(ctx, verify, ssl_callback_SSLVerify);
545
546     /*
547      * Configure Client Authentication details
548      */
549     if (mctx->auth.ca_cert_file || mctx->auth.ca_cert_path) {
550         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
551                      "Configuring client authentication");
552
553         if (!SSL_CTX_load_verify_locations(ctx,
554                          MODSSL_PCHAR_CAST mctx->auth.ca_cert_file,
555                          MODSSL_PCHAR_CAST mctx->auth.ca_cert_path))
556         {
557             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
558                     "Unable to configure verify locations "
559                     "for client authentication");
560             ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
561             ssl_die();
562         }
563
564         ca_list = ssl_init_FindCAList(s, ptemp,
565                                       mctx->auth.ca_cert_file,
566                                       mctx->auth.ca_cert_path);
567         if (!ca_list) {
568             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
569                     "Unable to determine list of available "
570                     "CA certificates for client authentication");
571             ssl_die();
572         }
573
574         SSL_CTX_set_client_CA_list(ctx, (STACK *)ca_list);
575     }
576
577     /*
578      * Give a warning when no CAs were configured but client authentication
579      * should take place. This cannot work.
580      */
581     if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
582         ca_list = (STACK_OF(X509_NAME) *)SSL_CTX_get_client_CA_list(ctx);
583
584         if (sk_X509_NAME_num(ca_list) == 0) {
585             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
586                          "Init: Oops, you want to request client "
587                          "authentication, but no CAs are known for "
588                          "verification!?  [Hint: SSLCACertificate*]");
589         }
590     }
591 }
592
593 static void ssl_init_ctx_cipher_suite(server_rec *s,
594                                       apr_pool_t *p,
595                                       apr_pool_t *ptemp,
596                                       modssl_ctx_t *mctx)
597 {
598     SSL_CTX *ctx = mctx->ssl_ctx;
599     const char *suite = mctx->auth.cipher_suite;
600
601     /*
602      *  Configure SSL Cipher Suite
603      */
604     if (!suite) {
605         return;
606     }
607
608     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
609                  "Configuring permitted SSL ciphers [%s]", 
610                  suite);
611
612     if (!SSL_CTX_set_cipher_list(ctx, MODSSL_PCHAR_CAST suite)) {
613         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
614                 "Unable to configure permitted SSL ciphers");
615         ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
616         ssl_die();
617     }
618 }
619
620 static void ssl_init_ctx_crl(server_rec *s,
621                              apr_pool_t *p,
622                              apr_pool_t *ptemp,
623                              modssl_ctx_t *mctx)
624 {
625     /*
626      * Configure Certificate Revocation List (CRL) Details
627      */
628
629     if (!(mctx->crl_file || mctx->crl_path)) {
630         return;
631     }
632
633     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
634                  "Configuring certificate revocation facility");
635
636     mctx->crl =
637         SSL_X509_STORE_create((char *)mctx->crl_file,
638                               (char *)mctx->crl_path);
639
640     if (!mctx->crl) {
641         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
642                 "Unable to configure X.509 CRL storage "
643                 "for certificate revocation");
644         ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
645         ssl_die();
646     }
647 }
648
649 static void ssl_init_ctx_cert_chain(server_rec *s,
650                                     apr_pool_t *p,
651                                     apr_pool_t *ptemp,
652                                     modssl_ctx_t *mctx)
653 {
654     BOOL skip_first = FALSE;
655     int i, n;
656     const char *chain = mctx->cert_chain;
657
658     /* 
659      * Optionally configure extra server certificate chain certificates.
660      * This is usually done by OpenSSL automatically when one of the
661      * server cert issuers are found under SSLCACertificatePath or in
662      * SSLCACertificateFile. But because these are intended for client
663      * authentication it can conflict. For instance when you use a
664      * Global ID server certificate you've to send out the intermediate
665      * CA certificate, too. When you would just configure this with
666      * SSLCACertificateFile and also use client authentication mod_ssl
667      * would accept all clients also issued by this CA. Obviously this
668      * isn't what we want in this situation. So this feature here exists
669      * to allow one to explicity configure CA certificates which are
670      * used only for the server certificate chain.
671      */
672     if (!chain) {
673         return;
674     }
675
676     for (i = 0; (i < SSL_AIDX_MAX) && mctx->pks->cert_files[i]; i++) {
677         if (strEQ(mctx->pks->cert_files[i], chain)) {
678             skip_first = TRUE;
679             break;
680         }
681     }
682
683     n = SSL_CTX_use_certificate_chain(mctx->ssl_ctx,
684                                       (char *)chain, 
685                                       skip_first, NULL);
686     if (n < 0) {
687         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
688                 "Failed to configure CA certificate chain!");
689         ssl_die();
690     }
691
692     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
693                  "Configuring server certificate chain "
694                  "(%d CA certificate%s)",
695                  n, n == 1 ? "" : "s");
696 }
697
698 static void ssl_init_ctx(server_rec *s,
699                          apr_pool_t *p,
700                          apr_pool_t *ptemp,
701                          modssl_ctx_t *mctx)
702 {
703     ssl_init_ctx_protocol(s, p, ptemp, mctx);
704
705     ssl_init_ctx_session_cache(s, p, ptemp, mctx);
706
707     ssl_init_ctx_callbacks(s, p, ptemp, mctx);
708
709     ssl_init_ctx_verify(s, p, ptemp, mctx);
710
711     ssl_init_ctx_cipher_suite(s, p, ptemp, mctx);
712
713     ssl_init_ctx_crl(s, p, ptemp, mctx);
714
715     if (mctx->pks) {
716         /* XXX: proxy support? */
717         ssl_init_ctx_cert_chain(s, p, ptemp, mctx);
718     }
719 }
720
721 static int ssl_server_import_cert(server_rec *s,
722                                   modssl_ctx_t *mctx,
723                                   const char *id,
724                                   int idx)
725 {
726     SSLModConfigRec *mc = myModConfig(s);
727     ssl_asn1_t *asn1;
728     unsigned char *ptr;
729     const char *type = ssl_asn1_keystr(idx);
730     X509 *cert;
731
732     if (!(asn1 = ssl_asn1_table_get(mc->tPublicCert, id))) {
733         return FALSE;
734     }
735
736     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
737                  "Configuring %s server certificate", type);
738
739     ptr = asn1->cpData;
740     if (!(cert = d2i_X509(NULL, &ptr, asn1->nData))) {
741         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
742                 "Unable to import %s server certificate", type);
743         ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
744         ssl_die();
745     }
746
747     if (SSL_CTX_use_certificate(mctx->ssl_ctx, cert) <= 0) {
748         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
749                 "Unable to configure %s server certificate", type);
750         ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
751         ssl_die();
752     }
753
754     mctx->pks->certs[idx] = cert;
755
756     return TRUE;
757 }
758
759 static int ssl_server_import_key(server_rec *s,
760                                  modssl_ctx_t *mctx,
761                                  const char *id,
762                                  int idx)
763 {
764     SSLModConfigRec *mc = myModConfig(s);
765     ssl_asn1_t *asn1;
766     unsigned char *ptr;
767     const char *type = ssl_asn1_keystr(idx);
768     int pkey_type = (idx == SSL_AIDX_RSA) ? EVP_PKEY_RSA : EVP_PKEY_DSA;
769     EVP_PKEY *pkey;
770
771     if (!(asn1 = ssl_asn1_table_get(mc->tPrivateKey, id))) {
772         return FALSE;
773     }
774
775     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
776                  "Configuring %s server private key", type);
777
778     ptr = asn1->cpData;
779     if (!(pkey = d2i_PrivateKey(pkey_type, NULL, &ptr, asn1->nData)))
780     {
781         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
782                 "Unable to import %s server private key", type);
783         ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
784         ssl_die();
785     }
786
787     if (SSL_CTX_use_PrivateKey(mctx->ssl_ctx, pkey) <= 0) {
788         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
789                 "Unable to configure %s server private key", type);
790         ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
791         ssl_die();
792     }
793
794     /*
795      * XXX: wonder if this is still needed, this is old todo doc.
796      * (see http://www.psy.uq.edu.au/~ftp/Crypto/ssleay/TODO.html)
797      */
798     if ((pkey_type == EVP_PKEY_DSA) && mctx->pks->certs[idx]) {
799         EVP_PKEY *pubkey = X509_get_pubkey(mctx->pks->certs[idx]);
800
801         if (pubkey && EVP_PKEY_missing_parameters(pubkey)) {
802             EVP_PKEY_copy_parameters(pubkey, pkey);
803             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
804                     "Copying DSA parameters from private key to certificate");
805             ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
806             EVP_PKEY_free(pubkey);
807         }
808     }
809
810     mctx->pks->keys[idx] = pkey;
811
812     return TRUE;
813 }
814
815 static void ssl_check_public_cert(server_rec *s,
816                                   apr_pool_t *ptemp,
817                                   X509 *cert,
818                                   int type)
819 {
820     int is_ca, pathlen;
821     char *cn;
822
823     if (!cert) {
824         return;
825     }
826
827     /*
828      * Some information about the certificate(s)
829      */
830
831     if (SSL_X509_isSGC(cert)) {
832         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
833                      "%s server certificate enables "
834                      "Server Gated Cryptography (SGC)", 
835                      ssl_asn1_keystr(type));
836     }
837
838     if (SSL_X509_getBC(cert, &is_ca, &pathlen)) {
839         if (is_ca) {
840             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
841                          "%s server certificate is a CA certificate "
842                          "(BasicConstraints: CA == TRUE !?)",
843                          ssl_asn1_keystr(type));
844         }
845
846         if (pathlen > 0) {
847             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
848                          "%s server certificate is not a leaf certificate "
849                          "(BasicConstraints: pathlen == %d > 0 !?)",
850                          ssl_asn1_keystr(type), pathlen);
851         }
852     }
853
854     if (SSL_X509_getCN(ptemp, cert, &cn)) {
855         int fnm_flags = APR_FNM_PERIOD|APR_FNM_CASE_BLIND;
856
857         if (apr_fnmatch_test(cn) &&
858             (apr_fnmatch(cn, s->server_hostname,
859                          fnm_flags) == APR_FNM_NOMATCH))
860         {
861             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
862                          "%s server certificate wildcard CommonName (CN) `%s' "
863                          "does NOT match server name!?",
864                          ssl_asn1_keystr(type), cn);
865         }
866         else if (strNE(s->server_hostname, cn)) {
867             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
868                          "%s server certificate CommonName (CN) `%s' "
869                          "does NOT match server name!?",
870                          ssl_asn1_keystr(type), cn);
871         }
872     }
873 }
874
875 static void ssl_init_server_certs(server_rec *s,
876                                   apr_pool_t *p,
877                                   apr_pool_t *ptemp,
878                                   modssl_ctx_t *mctx)
879 {
880     const char *rsa_id, *dsa_id;
881     const char *vhost_id = mctx->sc->vhost_id;
882     int i;
883     int have_rsa, have_dsa;
884
885     rsa_id = ssl_asn1_table_keyfmt(ptemp, vhost_id, SSL_AIDX_RSA);
886     dsa_id = ssl_asn1_table_keyfmt(ptemp, vhost_id, SSL_AIDX_DSA);
887
888     have_rsa = ssl_server_import_cert(s, mctx, rsa_id, SSL_AIDX_RSA);
889     have_dsa = ssl_server_import_cert(s, mctx, dsa_id, SSL_AIDX_DSA);
890
891     if (!(have_rsa || have_dsa)) {
892         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
893                 "Oops, no RSA or DSA server certificate found?!");
894         ssl_die();
895     }
896
897     for (i = 0; i < SSL_AIDX_MAX; i++) {
898         ssl_check_public_cert(s, ptemp, mctx->pks->certs[i], i);
899     }
900
901     have_rsa = ssl_server_import_key(s, mctx, rsa_id, SSL_AIDX_RSA);
902     have_dsa = ssl_server_import_key(s, mctx, dsa_id, SSL_AIDX_DSA);
903
904     if (!(have_rsa || have_dsa)) {
905         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
906                 "Oops, no RSA or DSA server private key found?!");
907         ssl_die();
908     }
909 }
910
911 static void ssl_init_proxy_certs(server_rec *s,
912                                  apr_pool_t *p,
913                                  apr_pool_t *ptemp,
914                                  modssl_ctx_t *mctx)
915 {
916     int ncerts = 0;
917     STACK_OF(X509_INFO) *sk;
918     modssl_pk_proxy_t *pkp = mctx->pkp;
919
920     SSL_CTX_set_client_cert_cb(mctx->ssl_ctx,
921                                ssl_callback_proxy_cert);
922
923     if (!(pkp->cert_file || pkp->cert_path)) {
924         return;
925     }
926
927     sk = sk_X509_INFO_new_null();
928
929     if (pkp->cert_file) {
930         SSL_X509_INFO_load_file(ptemp, sk, pkp->cert_file);
931     }
932
933     if (pkp->cert_path) {
934         SSL_X509_INFO_load_path(ptemp, sk, pkp->cert_path);
935     }
936
937     if ((ncerts = sk_X509_INFO_num(sk)) > 0) {
938         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
939                      "loaded %d client certs for SSL proxy",
940                      ncerts);
941
942         pkp->certs = sk;
943     }
944     else {
945         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
946                      "no client certs found for SSL proxy");
947         sk_X509_INFO_free(sk);
948     }
949 }
950
951 static void ssl_init_proxy_ctx(server_rec *s,
952                                apr_pool_t *p,
953                                apr_pool_t *ptemp,
954                                SSLSrvConfigRec *sc)
955 {
956     ssl_init_ctx(s, p, ptemp, sc->proxy);
957
958     ssl_init_proxy_certs(s, p, ptemp, sc->proxy);
959 }
960
961 static void ssl_init_server_ctx(server_rec *s,
962                                 apr_pool_t *p,
963                                 apr_pool_t *ptemp,
964                                 SSLSrvConfigRec *sc)
965 {
966     ssl_init_server_check(s, p, ptemp, sc->server);
967
968     ssl_init_ctx(s, p, ptemp, sc->server);
969
970     ssl_init_server_certs(s, p, ptemp, sc->server);
971 }
972
973 /*
974  * Configure a particular server
975  */
976 void ssl_init_ConfigureServer(server_rec *s,
977                               apr_pool_t *p,
978                               apr_pool_t *ptemp,
979                               SSLSrvConfigRec *sc)
980 {
981     /* A bit of a hack, but initialize the server if SSL is optional or
982      * not.
983      */
984     if (sc->enabled) {
985         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
986                      "Configuring server for SSL protocol");
987         ssl_init_server_ctx(s, p, ptemp, sc);
988     }
989
990     if (sc->proxy_enabled) {
991         ssl_init_proxy_ctx(s, p, ptemp, sc);
992     }
993 }
994
995 void ssl_init_CheckServers(server_rec *base_server, apr_pool_t *p)
996 {
997     server_rec *s, *ps;
998     SSLSrvConfigRec *sc;
999     apr_hash_t *table;
1000     const char *key;
1001     apr_ssize_t klen;
1002
1003     BOOL conflict = FALSE;
1004
1005     /*
1006      * Give out warnings when a server has HTTPS configured 
1007      * for the HTTP port or vice versa
1008      */
1009     for (s = base_server; s; s = s->next) {
1010         sc = mySrvConfig(s);
1011
1012         if ((sc->enabled == TRUE) && (s->port == DEFAULT_HTTP_PORT)) {
1013             ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1014                          base_server,
1015                          "Init: (%s) You configured HTTPS(%d) "
1016                          "on the standard HTTP(%d) port!",
1017                          ssl_util_vhostid(p, s),
1018                          DEFAULT_HTTPS_PORT, DEFAULT_HTTP_PORT);
1019         }
1020
1021         if (!sc->enabled && (s->port == DEFAULT_HTTPS_PORT)) {
1022             ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1023                          base_server,
1024                          "Init: (%s) You configured HTTP(%d) "
1025                          "on the standard HTTPS(%d) port!",
1026                          ssl_util_vhostid(p, s),
1027                          DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT);
1028         }
1029     }
1030
1031     /*
1032      * Give out warnings when more than one SSL-aware virtual server uses the
1033      * same IP:port. This doesn't work because mod_ssl then will always use
1034      * just the certificate/keys of one virtual host (which one cannot be said
1035      * easily - but that doesn't matter here).
1036      */
1037     table = apr_hash_make(p);
1038
1039     for (s = base_server; s; s = s->next) {
1040         sc = mySrvConfig(s);
1041
1042         if (!(sc->enabled && s->addrs)) {
1043             continue;
1044         }
1045
1046         key = apr_psprintf(p, "%pA:%u",
1047                            &s->addrs->host_addr, s->addrs->host_port);
1048         klen = strlen(key);
1049
1050         if ((ps = (server_rec *)apr_hash_get(table, key, klen))) {
1051             ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1052                          base_server,
1053                          "Init: SSL server IP/port conflict: "
1054                          "%s (%s:%d) vs. %s (%s:%d)",
1055                          ssl_util_vhostid(p, s), 
1056                          (s->defn_name ? s->defn_name : "unknown"),
1057                          s->defn_line_number,
1058                          ssl_util_vhostid(p, ps),
1059                          (ps->defn_name ? ps->defn_name : "unknown"), 
1060                          ps->defn_line_number);
1061             conflict = TRUE;
1062             continue;
1063         }
1064
1065         apr_hash_set(table, key, klen, s);
1066     }
1067
1068     if (conflict) {
1069         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, base_server,
1070                      "Init: You should not use name-based "
1071                      "virtual hosts in conjunction with SSL!!");
1072     }
1073 }
1074
1075 #ifdef SSLC_VERSION_NUMBER
1076 static int ssl_init_FindCAList_X509NameCmp(char **a, char **b)
1077 {
1078     return(X509_NAME_cmp((void*)*a, (void*)*b));
1079 }
1080 #else
1081 static int ssl_init_FindCAList_X509NameCmp(X509_NAME **a, X509_NAME **b)
1082 {
1083     return(X509_NAME_cmp(*a, *b));
1084 }
1085 #endif
1086
1087 static void ssl_init_PushCAList(STACK_OF(X509_NAME) *ca_list,
1088                                 server_rec *s, const char *file)
1089 {
1090     int n;
1091     STACK_OF(X509_NAME) *sk;
1092
1093     sk = (STACK_OF(X509_NAME) *)
1094              SSL_load_client_CA_file(MODSSL_PCHAR_CAST file);
1095
1096     if (!sk) {
1097         return;
1098     }
1099
1100     for (n = 0; n < sk_X509_NAME_num(sk); n++) {
1101         char name_buf[256];
1102         X509_NAME *name = sk_X509_NAME_value(sk, n);
1103
1104         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1105                      "CA certificate: %s",
1106                      X509_NAME_oneline(name, name_buf, sizeof(name_buf)));
1107
1108         /*
1109          * note that SSL_load_client_CA_file() checks for duplicates,
1110          * but since we call it multiple times when reading a directory
1111          * we must also check for duplicates ourselves.
1112          */
1113
1114         if (sk_X509_NAME_find(ca_list, name) < 0) {
1115             /* this will be freed when ca_list is */
1116             sk_X509_NAME_push(ca_list, name);
1117         }
1118         else {
1119             /* need to free this ourselves, else it will leak */
1120             X509_NAME_free(name);
1121         }
1122     }
1123
1124     sk_X509_NAME_free(sk);
1125 }
1126
1127 STACK_OF(X509_NAME) *ssl_init_FindCAList(server_rec *s,
1128                                          apr_pool_t *ptemp,
1129                                          const char *ca_file,
1130                                          const char *ca_path)
1131 {
1132     STACK_OF(X509_NAME) *ca_list;
1133
1134     /*
1135      * Start with a empty stack/list where new
1136      * entries get added in sorted order.
1137      */
1138     ca_list = sk_X509_NAME_new(ssl_init_FindCAList_X509NameCmp);
1139
1140     /*
1141      * Process CA certificate bundle file
1142      */
1143     if (ca_file) {
1144         ssl_init_PushCAList(ca_list, s, ca_file);
1145     }
1146
1147     /*
1148      * Process CA certificate path files
1149      */
1150     if (ca_path) {
1151         apr_dir_t *dir;
1152         apr_finfo_t direntry;
1153         apr_int32_t finfo_flags = APR_FINFO_TYPE|APR_FINFO_NAME;
1154         apr_status_t rv;
1155
1156         if ((rv = apr_dir_open(&dir, ca_path, ptemp)) != APR_SUCCESS) {
1157             ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1158                     "Failed to open SSLCACertificatePath `%s'",
1159                     ca_path);
1160             ssl_die();
1161         }
1162
1163         while ((apr_dir_read(&direntry, finfo_flags, dir)) == APR_SUCCESS) {
1164             const char *file;
1165             if (direntry.filetype == APR_DIR) {
1166                 continue; /* don't try to load directories */
1167             }
1168             file = apr_pstrcat(ptemp, ca_path, "/", direntry.name, NULL);
1169             ssl_init_PushCAList(ca_list, s, file);
1170         }
1171
1172         apr_dir_close(dir);
1173     }
1174
1175     /*
1176      * Cleanup
1177      */
1178     sk_X509_NAME_set_cmp_func(ca_list, NULL);
1179
1180     return ca_list;
1181 }
1182
1183 void ssl_init_Child(apr_pool_t *p, server_rec *s)
1184 {
1185     SSLModConfigRec *mc = myModConfig(s);
1186     mc->pid = getpid(); /* only call getpid() once per-process */
1187
1188     /* XXX: there should be an ap_srand() function */
1189     srand((unsigned int)time(NULL));
1190
1191     /* open the mutex lockfile */
1192     ssl_mutex_reinit(s, p);
1193 }
1194
1195 #define MODSSL_CFG_ITEM_FREE(func, item) \
1196     if (item) { \
1197         func(item); \
1198         item = NULL; \
1199     }
1200
1201 static void ssl_init_ctx_cleanup(modssl_ctx_t *mctx)
1202 {
1203     MODSSL_CFG_ITEM_FREE(X509_STORE_free, mctx->crl);
1204
1205     MODSSL_CFG_ITEM_FREE(SSL_CTX_free, mctx->ssl_ctx);
1206 }
1207
1208 static void ssl_init_ctx_cleanup_proxy(modssl_ctx_t *mctx)
1209 {
1210     ssl_init_ctx_cleanup(mctx);
1211
1212     if (mctx->pkp->certs) {
1213         sk_X509_INFO_pop_free(mctx->pkp->certs, X509_INFO_free);
1214     }
1215 }
1216
1217 static void ssl_init_ctx_cleanup_server(modssl_ctx_t *mctx)
1218 {
1219     int i;
1220
1221     ssl_init_ctx_cleanup(mctx);
1222
1223     for (i=0; i < SSL_AIDX_MAX; i++) {
1224         MODSSL_CFG_ITEM_FREE(X509_free,
1225                              mctx->pks->certs[i]);
1226
1227         MODSSL_CFG_ITEM_FREE(EVP_PKEY_free,
1228                              mctx->pks->keys[i]);
1229     }
1230 }
1231
1232 apr_status_t ssl_init_ModuleKill(void *data)
1233 {
1234     SSLSrvConfigRec *sc;
1235     server_rec *base_server = (server_rec *)data;
1236     server_rec *s;
1237
1238     /*
1239      * Drop the session cache and mutex
1240      */
1241     ssl_scache_kill(base_server);
1242
1243     /* 
1244      * Destroy the temporary keys and params
1245      */
1246     ssl_tmp_keys_free(base_server);
1247
1248     /*
1249      * Free the non-pool allocated structures
1250      * in the per-server configurations
1251      */
1252     for (s = base_server; s; s = s->next) {
1253         sc = mySrvConfig(s);
1254
1255         ssl_init_ctx_cleanup_proxy(sc->proxy);
1256
1257         ssl_init_ctx_cleanup_server(sc->server);
1258     }
1259
1260     return APR_SUCCESS;
1261 }
1262