]> granicus.if.org Git - apache/blob - modules/ssl/ssl_engine_init.c
switch from SSLSrvConfigRec* to modssl_ctx_t* in the ssl_init_ctx*
[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-2002 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     ssl_log(s, SSL_LOG_INFO,
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  *  Initialize SSL library
111  */
112 static void ssl_init_SSLLibrary(server_rec *s)
113 {
114     ssl_log(s, SSL_LOG_INFO,
115             "Init: Initializing %s library", SSL_LIBRARY_NAME);
116
117     CRYPTO_malloc_init();
118     SSL_load_error_strings();
119     SSL_library_init();
120 }
121
122 /*
123  * Handle the Temporary RSA Keys and DH Params
124  */
125
126 #define MODSSL_TMP_KEY_FREE(mc, type, idx) \
127     if (mc->pTmpKeys[idx]) { \
128         type##_free((type *)mc->pTmpKeys[idx]); \
129         mc->pTmpKeys[idx] = NULL; \
130     }
131
132 #define MODSSL_TMP_KEYS_FREE(mc, type) \
133     MODSSL_TMP_KEY_FREE(mc, type, SSL_TMP_KEY_##type##_512); \
134     MODSSL_TMP_KEY_FREE(mc, type, SSL_TMP_KEY_##type##_1024)
135
136 static void ssl_tmp_keys_free(server_rec *s)
137 {
138     SSLModConfigRec *mc = myModConfig(s);
139
140     MODSSL_TMP_KEYS_FREE(mc, RSA);
141     MODSSL_TMP_KEYS_FREE(mc, DH);
142 }
143
144 static void ssl_tmp_key_init_rsa(server_rec *s,
145                                  int bits, int idx)
146 {
147     SSLModConfigRec *mc = myModConfig(s);
148
149     if (!(mc->pTmpKeys[idx] =
150           RSA_generate_key(bits, RSA_F4, NULL, NULL)))
151     {
152         ssl_log(s, SSL_LOG_ERROR,
153                 "Init: Failed to generate temporary "
154                 "%d bit RSA private key", bits);
155         ssl_die();
156     }
157
158 }
159
160 static void ssl_tmp_key_init_dh(server_rec *s,
161                                 int bits, int idx)
162 {
163     SSLModConfigRec *mc = myModConfig(s);
164
165     if (!(mc->pTmpKeys[idx] =
166           ssl_dh_GetTmpParam(bits)))
167     {
168         ssl_log(s, SSL_LOG_ERROR,
169                 "Init: Failed to generate temporary "
170                 "%d bit DH parameters", bits);
171         ssl_die();
172     }
173 }
174
175 #define MODSSL_TMP_KEY_INIT_RSA(s, bits) \
176     ssl_tmp_key_init_rsa(s, bits, SSL_TMP_KEY_RSA_##bits)
177
178 #define MODSSL_TMP_KEY_INIT_DH(s, bits) \
179     ssl_tmp_key_init_dh(s, bits, SSL_TMP_KEY_DH_##bits)
180
181 static void ssl_tmp_keys_init(server_rec *s)
182 {
183     ssl_log(s, SSL_LOG_INFO,
184             "Init: Generating temporary RSA private keys (512/1024 bits)");
185
186     MODSSL_TMP_KEY_INIT_RSA(s, 512);
187     MODSSL_TMP_KEY_INIT_RSA(s, 1024);
188
189     ssl_log(s, SSL_LOG_INFO,
190             "Init: Generating temporary DH parameters (512/1024 bits)");
191
192     MODSSL_TMP_KEY_INIT_DH(s, 512);
193     MODSSL_TMP_KEY_INIT_DH(s, 1024);
194 }
195
196 /*
197  *  Per-module initialization
198  */
199 int ssl_init_Module(apr_pool_t *p, apr_pool_t *plog,
200                     apr_pool_t *ptemp,
201                     server_rec *base_server)
202 {
203     SSLModConfigRec *mc = myModConfig(base_server);
204     SSLSrvConfigRec *sc;
205     server_rec *s;
206
207     /*
208      * Let us cleanup on restarts and exists
209      */
210     apr_pool_cleanup_register(p, base_server,
211                               ssl_init_ModuleKill,
212                               apr_pool_cleanup_null);
213
214     /*
215      * Any init round fixes the global config
216      */
217     ssl_config_global_create(base_server); /* just to avoid problems */
218     ssl_config_global_fix(mc);
219
220     /*
221      *  try to fix the configuration and open the dedicated SSL
222      *  logfile as early as possible
223      */
224     for (s = base_server; s; s = s->next) {
225         sc = mySrvConfig(s);
226
227         if (sc->server) {
228             sc->server->sc = sc;
229         }
230
231         /*
232          * Create the server host:port string because we need it a lot
233          */
234         sc->vhost_id = ssl_util_vhostid(p, s);
235         sc->vhost_id_len = strlen(sc->vhost_id);
236
237         /* Fix up stuff that may not have been set */
238         if (sc->enabled == UNSET) {
239             sc->enabled = FALSE;
240         }
241
242         if (sc->session_cache_timeout == UNSET) {
243             sc->session_cache_timeout = SSL_SESSION_CACHE_TIMEOUT;
244         }
245
246         if (sc->server->pphrase_dialog_type == SSL_PPTYPE_UNSET) {
247             sc->server->pphrase_dialog_type = SSL_PPTYPE_BUILTIN;
248         }
249
250         /* Open the dedicated SSL logfile */
251         ssl_log_open(base_server, s, p);
252     }
253
254     ssl_init_SSLLibrary(base_server);
255
256 #if APR_HAS_THREADS
257     ssl_util_thread_setup(base_server, p);
258 #endif
259
260     /*
261      * Seed the Pseudo Random Number Generator (PRNG)
262      * only need ptemp here; nothing inside allocated from the pool
263      * needs to live once we return from ssl_rand_seed().
264      */
265     ssl_rand_seed(base_server, ptemp, SSL_RSCTX_STARTUP, "Init: ");
266
267     /*
268      * read server private keys/public certs into memory.
269      * decrypting any encrypted keys via configured SSLPassPhraseDialogs
270      * anything that needs to live longer than ptemp needs to also survive
271      * restarts, in which case they'll live inside s->process->pool.
272      */
273     ssl_pphrase_Handle(base_server, ptemp);
274
275     ssl_tmp_keys_init(base_server);
276
277     /*
278      * SSL external crypto device ("engine") support
279      */
280 #ifdef SSL_EXPERIMENTAL_ENGINE
281     ssl_init_Engine(base_server, p);
282 #endif
283
284     /*
285      * initialize the mutex handling
286      */
287     if (!ssl_mutex_init(base_server, p)) {
288         return HTTP_INTERNAL_SERVER_ERROR;
289     }
290
291     /*
292      * initialize session caching
293      */
294     ssl_scache_init(base_server, p);
295
296     /*
297      *  initialize servers
298      */
299     ssl_log(base_server, SSL_LOG_INFO,
300             "Init: Initializing (virtual) servers for SSL");
301
302     for (s = base_server; s; s = s->next) {
303         sc = mySrvConfig(s);
304         /*
305          * Either now skip this server when SSL is disabled for
306          * it or give out some information about what we're
307          * configuring.
308          */
309         if (!sc->enabled) {
310             continue;
311         }
312
313         ssl_log(s, SSL_LOG_INFO|SSL_INIT,
314                 "Configuring server for SSL protocol");
315
316         /*
317          * Read the server certificate and key
318          */
319         ssl_init_ConfigureServer(s, p, ptemp, sc);
320     }
321
322     /*
323      * Configuration consistency checks
324      */
325     ssl_init_CheckServers(base_server, ptemp);
326
327     /*
328      *  Announce mod_ssl and SSL library in HTTP Server field
329      *  as ``mod_ssl/X.X.X OpenSSL/X.X.X''
330      */
331     ssl_add_version_components(p, base_server);
332
333     SSL_init_app_data2_idx(); /* for SSL_get_app_data2() at request time */
334
335     return OK;
336 }
337
338 /*
339  * Support for external a Crypto Device ("engine"), usually
340  * a hardware accellerator card for crypto operations.
341  */
342 #ifdef SSL_EXPERIMENTAL_ENGINE
343 void ssl_init_Engine(server_rec *s, apr_pool_t *p)
344 {
345     SSLModConfigRec *mc = myModConfig(s);
346     ENGINE *e;
347
348     if (mc->szCryptoDevice) {
349         if (!(e = ENGINE_by_id(mc->szCryptoDevice))) {
350             ssl_log(s, SSL_LOG_ERROR,
351                     "Init: Failed to load Crypto Device API `%s'",
352                     mc->szCryptoDevice);
353             ssl_die();
354         }
355
356         if (strEQ(mc->szCryptoDevice, "chil")) {
357             ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
358         }
359
360         if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
361             ssl_log(s, SSL_LOG_ERROR,
362                     "Init: Failed to enable Crypto Device API `%s'",
363                     mc->szCryptoDevice);
364             ssl_die();
365         }
366
367         ENGINE_free(e);
368     }
369 }
370 #endif
371
372 static void ssl_init_server_check(server_rec *s,
373                                   apr_pool_t *p,
374                                   apr_pool_t *ptemp,
375                                   modssl_ctx_t *mctx)
376 {
377     /*
378      * check for important parameters and the
379      * possibility that the user forgot to set them.
380      */
381     if (!mctx->pks->cert_files[0]) {
382         ssl_log(s, SSL_LOG_ERROR|SSL_INIT,
383                 "No SSL Certificate set [hint: SSLCertificateFile]");
384         ssl_die();
385     }
386
387     /*
388      *  Check for problematic re-initializations
389      */
390     if (mctx->pks->certs[SSL_AIDX_RSA] ||
391         mctx->pks->certs[SSL_AIDX_DSA])
392     {
393         ssl_log(s, SSL_LOG_ERROR|SSL_INIT,
394                 "Illegal attempt to re-initialise SSL for server "
395                 "(theoretically shouldn't happen!)");
396         ssl_die();
397     }
398 }
399
400 static void ssl_init_ctx(server_rec *s,
401                          apr_pool_t *p,
402                          apr_pool_t *ptemp,
403                          modssl_ctx_t *mctx)
404 {
405     SSL_CTX *ctx = NULL;
406     char *cp;
407     int protocol = mctx->protocol;
408
409     /*
410      *  Create the new per-server SSL context
411      */
412     if (protocol == SSL_PROTOCOL_NONE) {
413         ssl_log(s, SSL_LOG_ERROR|SSL_INIT,
414                 "No SSL protocols available [hint: SSLProtocol]");
415         ssl_die();
416     }
417
418     cp = apr_pstrcat(p,
419                      (protocol & SSL_PROTOCOL_SSLV2 ? "SSLv2, " : ""),
420                      (protocol & SSL_PROTOCOL_SSLV3 ? "SSLv3, " : ""),
421                      (protocol & SSL_PROTOCOL_TLSV1 ? "TLSv1, " : ""),
422                      NULL);
423     cp[strlen(cp)-2] = NUL;
424
425     ssl_log(s, SSL_LOG_TRACE|SSL_INIT,
426             "Creating new SSL context (protocols: %s)", cp);
427
428     if (protocol == SSL_PROTOCOL_SSLV2) {
429         ctx = SSL_CTX_new(SSLv2_server_method());  /* only SSLv2 is left */
430     }
431     else {
432         ctx = SSL_CTX_new(SSLv23_server_method()); /* be more flexible */
433     }
434
435     mctx->ssl_ctx = ctx;
436
437     SSL_CTX_set_options(ctx, SSL_OP_ALL);
438
439     if (!(protocol & SSL_PROTOCOL_SSLV2)) {
440         SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
441     }
442
443     if (!(protocol & SSL_PROTOCOL_SSLV3)) {
444         SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);
445     }
446
447     if (!(protocol & SSL_PROTOCOL_TLSV1)) {
448         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1);
449     }
450
451     SSL_CTX_set_app_data(ctx, s);
452
453     /*
454      * Configure additional context ingredients
455      */
456     SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
457 }
458
459 static void ssl_init_ctx_session_cache(server_rec *s,
460                                        apr_pool_t *p,
461                                        apr_pool_t *ptemp,
462                                        modssl_ctx_t *mctx)
463 {
464     SSL_CTX *ctx = mctx->ssl_ctx;
465     SSLModConfigRec *mc = myModConfig(s);
466     long cache_mode = SSL_SESS_CACHE_OFF;
467
468     if (mc->nSessionCacheMode != SSL_SCMODE_NONE) {
469         /* SSL_SESS_CACHE_NO_INTERNAL_LOOKUP will force OpenSSL
470          * to ignore process local-caching and
471          * to always get/set/delete sessions using mod_ssl's callbacks.
472          */
473         cache_mode = SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL_LOOKUP;
474     }
475
476     SSL_CTX_set_session_cache_mode(ctx, cache_mode);
477
478     SSL_CTX_sess_set_new_cb(ctx,    ssl_callback_NewSessionCacheEntry);
479     SSL_CTX_sess_set_get_cb(ctx,    ssl_callback_GetSessionCacheEntry);
480     SSL_CTX_sess_set_remove_cb(ctx, ssl_callback_DelSessionCacheEntry);
481 }
482
483 static void ssl_init_ctx_callbacks(server_rec *s,
484                                    apr_pool_t *p,
485                                    apr_pool_t *ptemp,
486                                    modssl_ctx_t *mctx)
487 {
488     SSL_CTX *ctx = mctx->ssl_ctx;
489
490     SSL_CTX_set_tmp_rsa_callback(ctx, ssl_callback_TmpRSA);
491     SSL_CTX_set_tmp_dh_callback(ctx,  ssl_callback_TmpDH);
492
493     if (mctx->sc->log_level >= SSL_LOG_INFO) {
494         /* this callback only logs if SSLLogLevel >= info */
495         SSL_CTX_set_info_callback(ctx, ssl_callback_LogTracingState);
496     }
497 }
498
499 static void ssl_init_ctx_verify(server_rec *s,
500                                 apr_pool_t *p,
501                                 apr_pool_t *ptemp,
502                                 modssl_ctx_t *mctx)
503 {
504     SSL_CTX *ctx = mctx->ssl_ctx;
505
506     int verify = SSL_VERIFY_NONE;
507     STACK_OF(X509_NAME) *ca_list;
508
509     if (mctx->auth.verify_mode == SSL_CVERIFY_UNSET) {
510         mctx->auth.verify_mode = SSL_CVERIFY_NONE;
511     }
512
513     if (mctx->auth.verify_depth == UNSET) {
514         mctx->auth.verify_depth = 1;
515     }
516
517     /*
518      *  Configure callbacks for SSL context
519      */
520     if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
521         verify |= SSL_VERIFY_PEER_STRICT;
522     }
523
524     if ((mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL) ||
525         (mctx->auth.verify_mode == SSL_CVERIFY_OPTIONAL_NO_CA))
526     {
527         verify |= SSL_VERIFY_PEER;
528     }
529
530     SSL_CTX_set_verify(ctx, verify,  ssl_callback_SSLVerify);
531
532     /*
533      * Configure Client Authentication details
534      */
535     if (mctx->auth.ca_cert_file || mctx->auth.ca_cert_path) {
536         ssl_log(s, SSL_LOG_TRACE|SSL_INIT,
537                 "Configuring client authentication");
538
539         if (!SSL_CTX_load_verify_locations(ctx,
540                                            mctx->auth.ca_cert_file,
541                                            mctx->auth.ca_cert_path))
542         {
543             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR|SSL_INIT,
544                     "Unable to configure verify locations "
545                     "for client authentication");
546             ssl_die();
547         }
548
549         ca_list = ssl_init_FindCAList(s, ptemp,
550                                       mctx->auth.ca_cert_file,
551                                       mctx->auth.ca_cert_path);
552         if (!ca_list) {
553             ssl_log(s, SSL_LOG_ERROR|SSL_INIT,
554                     "Unable to determine list of available "
555                     "CA certificates for client authentication");
556             ssl_die();
557         }
558
559         SSL_CTX_set_client_CA_list(ctx, (STACK *)ca_list);
560     }
561
562     /*
563      * Give a warning when no CAs were configured but client authentication
564      * should take place. This cannot work.
565      */
566     if (mctx->auth.verify_mode == SSL_CVERIFY_REQUIRE) {
567         ca_list = (STACK_OF(X509_NAME) *)SSL_CTX_get_client_CA_list(ctx);
568
569         if (sk_X509_NAME_num(ca_list) == 0) {
570             ssl_log(s, SSL_LOG_WARN,
571                     "Init: Oops, you want to request client authentication, "
572                     "but no CAs are known for verification!? "
573                     "[Hint: SSLCACertificate*]");
574         }
575     }
576 }
577
578 static void ssl_init_ctx_cipher_suite(server_rec *s,
579                                       apr_pool_t *p,
580                                       apr_pool_t *ptemp,
581                                       modssl_ctx_t *mctx)
582 {
583     SSL_CTX *ctx = mctx->ssl_ctx;
584     const char *suite = mctx->auth.cipher_suite;
585
586     /*
587      *  Configure SSL Cipher Suite
588      */
589     if (!suite) {
590         return;
591     }
592
593     ssl_log(s, SSL_LOG_TRACE|SSL_INIT,
594             "Configuring permitted SSL ciphers [%s]", 
595             suite);
596
597     if (!SSL_CTX_set_cipher_list(ctx, suite)) {
598         ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR|SSL_INIT,
599                 "Unable to configure permitted SSL ciphers");
600         ssl_die();
601     }
602 }
603
604 static void ssl_init_ctx_crl(server_rec *s,
605                              apr_pool_t *p,
606                              apr_pool_t *ptemp,
607                              modssl_ctx_t *mctx)
608 {
609     /*
610      * Configure Certificate Revocation List (CRL) Details
611      */
612
613     if (!(mctx->crl_file || mctx->crl_path)) {
614         return;
615     }
616
617     ssl_log(s, SSL_LOG_TRACE|SSL_INIT,
618             "Configuring certificate revocation facility");
619
620     mctx->crl =
621         SSL_X509_STORE_create((char *)mctx->crl_file,
622                               (char *)mctx->crl_path);
623
624     if (!mctx->crl) {
625         ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR|SSL_INIT,
626                 "Unable to configure X.509 CRL storage "
627                 "for certificate revocation");
628         ssl_die();
629     }
630 }
631
632 static void ssl_init_ctx_cert_chain(server_rec *s,
633                                     apr_pool_t *p,
634                                     apr_pool_t *ptemp,
635                                     modssl_ctx_t *mctx)
636 {
637     BOOL skip_first = TRUE;
638     int i, n;
639     const char *chain = mctx->cert_chain;
640
641     /* 
642      * Optionally configure extra server certificate chain certificates.
643      * This is usually done by OpenSSL automatically when one of the
644      * server cert issuers are found under SSLCACertificatePath or in
645      * SSLCACertificateFile. But because these are intended for client
646      * authentication it can conflict. For instance when you use a
647      * Global ID server certificate you've to send out the intermediate
648      * CA certificate, too. When you would just configure this with
649      * SSLCACertificateFile and also use client authentication mod_ssl
650      * would accept all clients also issued by this CA. Obviously this
651      * isn't what we want in this situation. So this feature here exists
652      * to allow one to explicity configure CA certificates which are
653      * used only for the server certificate chain.
654      */
655     if (!chain) {
656         return;
657     }
658
659     for (i = 0; (i < SSL_AIDX_MAX) && mctx->pks->cert_files[i]; i++) {
660         if (strEQ(mctx->pks->cert_files[i], chain)) {
661             skip_first = TRUE;
662             break;
663         }
664     }
665
666     n = SSL_CTX_use_certificate_chain(mctx->ssl_ctx,
667                                       (char *)chain, 
668                                       skip_first, NULL);
669     if (n < 0) {
670         ssl_log(s, SSL_LOG_ERROR|SSL_INIT,
671                 "Failed to configure CA certificate chain!");
672         ssl_die();
673     }
674
675     ssl_log(s, SSL_LOG_TRACE|SSL_INIT,
676             "Configuring server certificate chain "
677             "(%d CA certificate%s)",
678             n, n == 1 ? "" : "s");
679 }
680
681 static int ssl_server_import_cert(server_rec *s,
682                                   modssl_ctx_t *mctx,
683                                   const char *id,
684                                   int idx)
685 {
686     SSLModConfigRec *mc = myModConfig(s);
687     ssl_asn1_t *asn1;
688     unsigned char *ptr;
689     const char *type = ssl_asn1_keystr(idx);
690     X509 *cert;
691
692     if (!(asn1 = ssl_asn1_table_get(mc->tPublicCert, id))) {
693         return FALSE;
694     }
695
696     ssl_log(s, SSL_LOG_TRACE|SSL_INIT,
697             "Configuring %s server certificate", type);
698
699     ptr = asn1->cpData;
700     if (!(cert = d2i_X509(NULL, &ptr, asn1->nData))) {
701         ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR|SSL_INIT,
702                 "Unable to import %s server certificate", type);
703         ssl_die();
704     }
705
706     if (SSL_CTX_use_certificate(mctx->ssl_ctx, cert) <= 0) {
707         ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR|SSL_INIT,
708                 "Unable to configure %s server certificate", type);
709         ssl_die();
710     }
711
712     mctx->pks->certs[idx] = cert;
713
714     return TRUE;
715 }
716
717 static int ssl_server_import_key(server_rec *s,
718                                  modssl_ctx_t *mctx,
719                                  const char *id,
720                                  int idx)
721 {
722     SSLModConfigRec *mc = myModConfig(s);
723     ssl_asn1_t *asn1;
724     unsigned char *ptr;
725     const char *type = ssl_asn1_keystr(idx);
726     int pkey_type = (idx == SSL_AIDX_RSA) ? EVP_PKEY_RSA : EVP_PKEY_DSA;
727     EVP_PKEY *pkey;
728
729     if (!(asn1 = ssl_asn1_table_get(mc->tPrivateKey, id))) {
730         return FALSE;
731     }
732
733     ssl_log(s, SSL_LOG_TRACE|SSL_INIT,
734             "Configuring %s server private key", type);
735
736     ptr = asn1->cpData;
737     if (!(pkey = d2i_PrivateKey(pkey_type, NULL, &ptr, asn1->nData)))
738     {
739         ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR|SSL_INIT,
740                 "Unable to import %s server private key", type);
741         ssl_die();
742     }
743
744     if (SSL_CTX_use_PrivateKey(mctx->ssl_ctx, pkey) <= 0) {
745         ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR|SSL_INIT,
746                 "Unable to configure %s server private key", type);
747         ssl_die();
748     }
749
750     /*
751      * XXX: wonder if this is still needed, this is old todo doc.
752      * (see http://www.psy.uq.edu.au/~ftp/Crypto/ssleay/TODO.html)
753      */
754     if ((pkey_type == EVP_PKEY_DSA) && mctx->pks->certs[idx]) {
755         EVP_PKEY *pubkey = X509_get_pubkey(mctx->pks->certs[idx]);
756
757         if (pubkey && EVP_PKEY_missing_parameters(pubkey)) {
758             EVP_PKEY_copy_parameters(pubkey, pkey);
759             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR|SSL_INIT,
760                     "Copying DSA parameters from private key to certificate");
761         }
762     }
763
764     mctx->pks->keys[idx] = pkey;
765
766     return TRUE;
767 }
768
769 static void ssl_check_public_cert(server_rec *s,
770                                   apr_pool_t *ptemp,
771                                   X509 *cert,
772                                   int type)
773 {
774     int is_ca, pathlen;
775     char *cn;
776
777     if (!cert) {
778         return;
779     }
780
781     /*
782      * Some information about the certificate(s)
783      */
784
785     if (SSL_X509_isSGC(cert)) {
786         ssl_log(s, SSL_LOG_INFO|SSL_INIT,
787                 "%s server certificate enables "
788                 "Server Gated Cryptography (SGC)", 
789                 ssl_asn1_keystr(type));
790     }
791
792     if (SSL_X509_getBC(cert, &is_ca, &pathlen)) {
793         if (is_ca) {
794             ssl_log(s, SSL_LOG_WARN|SSL_INIT,
795                     "%s server certificate is a CA certificate "
796                     "(BasicConstraints: CA == TRUE !?)",
797                     ssl_asn1_keystr(type));
798         }
799
800         if (pathlen > 0) {
801             ssl_log(s, SSL_LOG_WARN|SSL_INIT,
802                     "%s server certificate is not a leaf certificate "
803                     "(BasicConstraints: pathlen == %d > 0 !?)",
804                     ssl_asn1_keystr(type), pathlen);
805         }
806     }
807
808     if (SSL_X509_getCN(ptemp, cert, &cn)) {
809         int fnm_flags = FNM_PERIOD|FNM_CASE_BLIND;
810
811         if (apr_is_fnmatch(cn) &&
812             (apr_fnmatch(cn, s->server_hostname,
813                          fnm_flags) == FNM_NOMATCH))
814         {
815             ssl_log(s, SSL_LOG_WARN|SSL_INIT,
816                     "%s server certificate wildcard CommonName (CN) `%s' "
817                     "does NOT match server name!?",
818                     ssl_asn1_keystr(type), cn);
819         }
820         else if (strNE(s->server_hostname, cn)) {
821             ssl_log(s, SSL_LOG_WARN|SSL_INIT,
822                     "%s server certificate CommonName (CN) `%s' "
823                     "does NOT match server name!?",
824                     ssl_asn1_keystr(type), cn);
825         }
826     }
827 }
828
829 static void ssl_init_server_certs(server_rec *s,
830                                   apr_pool_t *p,
831                                   apr_pool_t *ptemp,
832                                   modssl_ctx_t *mctx)
833 {
834     const char *rsa_id, *dsa_id;
835     const char *vhost_id = mctx->sc->vhost_id;
836     int i;
837     int have_rsa, have_dsa;
838
839     rsa_id = ssl_asn1_table_keyfmt(ptemp, vhost_id, SSL_AIDX_RSA);
840     dsa_id = ssl_asn1_table_keyfmt(ptemp, vhost_id, SSL_AIDX_DSA);
841
842     have_rsa = ssl_server_import_cert(s, mctx, rsa_id, SSL_AIDX_RSA);
843     have_dsa = ssl_server_import_cert(s, mctx, dsa_id, SSL_AIDX_DSA);
844
845     if (!(have_rsa || have_dsa)) {
846         ssl_log(s, SSL_LOG_ERROR|SSL_INIT,
847                 "Oops, no RSA or DSA server certificate found?!");
848         ssl_die();
849     }
850
851     for (i = 0; i < SSL_AIDX_MAX; i++) {
852         ssl_check_public_cert(s, ptemp, mctx->pks->certs[i], i);
853     }
854
855     have_rsa = ssl_server_import_key(s, mctx, rsa_id, SSL_AIDX_RSA);
856     have_dsa = ssl_server_import_key(s, mctx, dsa_id, SSL_AIDX_DSA);
857
858     if (!(have_rsa || have_dsa)) {
859         ssl_log(s, SSL_LOG_ERROR|SSL_INIT,
860                 "Oops, no RSA or DSA server private key found?!");
861         ssl_die();
862     }
863 }
864
865 /*
866  * Configure a particular server
867  */
868 void ssl_init_ConfigureServer(server_rec *s,
869                               apr_pool_t *p,
870                               apr_pool_t *ptemp,
871                               SSLSrvConfigRec *sc)
872 {
873     ssl_init_server_check(s, p, ptemp, sc->server);
874
875     ssl_init_ctx(s, p, ptemp, sc->server);
876
877     ssl_init_ctx_session_cache(s, p, ptemp, sc->server);
878
879     ssl_init_ctx_callbacks(s, p, ptemp, sc->server);
880
881     ssl_init_ctx_verify(s, p, ptemp, sc->server);
882
883     ssl_init_ctx_cipher_suite(s, p, ptemp, sc->server);
884
885     ssl_init_ctx_crl(s, p, ptemp, sc->server);
886
887     ssl_init_ctx_cert_chain(s, p, ptemp, sc->server);
888
889     ssl_init_server_certs(s, p, ptemp, sc->server);
890 }
891
892 void ssl_init_CheckServers(server_rec *base_server, apr_pool_t *p)
893 {
894     server_rec *s, *ps;
895     SSLSrvConfigRec *sc;
896     apr_hash_t *table;
897     const char *key;
898     apr_ssize_t klen;
899
900     BOOL conflict = FALSE;
901
902     /*
903      * Give out warnings when a server has HTTPS configured 
904      * for the HTTP port or vice versa
905      */
906     for (s = base_server; s; s = s->next) {
907         sc = mySrvConfig(s);
908
909         if (sc->enabled && (s->port == DEFAULT_HTTP_PORT)) {
910             ssl_log(base_server, SSL_LOG_WARN,
911                     "Init: (%s) You configured HTTPS(%d) "
912                     "on the standard HTTP(%d) port!",
913                     ssl_util_vhostid(p, s),
914                     DEFAULT_HTTPS_PORT, DEFAULT_HTTP_PORT);
915         }
916
917         if (!sc->enabled && (s->port == DEFAULT_HTTPS_PORT)) {
918             ssl_log(base_server, SSL_LOG_WARN,
919                     "Init: (%s) You configured HTTP(%d) "
920                     "on the standard HTTPS(%d) port!",
921                     ssl_util_vhostid(p, s),
922                     DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT);
923         }
924     }
925
926     /*
927      * Give out warnings when more than one SSL-aware virtual server uses the
928      * same IP:port. This doesn't work because mod_ssl then will always use
929      * just the certificate/keys of one virtual host (which one cannot be said
930      * easily - but that doesn't matter here).
931      */
932     table = apr_hash_make(p);
933
934     for (s = base_server; s; s = s->next) {
935         sc = mySrvConfig(s);
936
937         if (!sc->enabled) {
938             continue;
939         }
940
941         key = apr_psprintf(p, "%pA:%u",
942                            &s->addrs->host_addr, s->addrs->host_port);
943         klen = strlen(key);
944
945         if ((ps = (server_rec *)apr_hash_get(table, key, klen))) {
946             ssl_log(base_server, SSL_LOG_WARN,
947                     "Init: SSL server IP/port conflict: "
948                     "%s (%s:%d) vs. %s (%s:%d)",
949                     ssl_util_vhostid(p, s), 
950                     (s->defn_name ? s->defn_name : "unknown"),
951                     s->defn_line_number,
952                     ssl_util_vhostid(p, ps),
953                     (ps->defn_name ? ps->defn_name : "unknown"), 
954                     ps->defn_line_number);
955             conflict = TRUE;
956             continue;
957         }
958
959         apr_hash_set(table, key, klen, s);
960     }
961
962     if (conflict) {
963         ssl_log(base_server, SSL_LOG_WARN,
964                 "Init: You should not use name-based "
965                 "virtual hosts in conjunction with SSL!!");
966     }
967 }
968
969 static int ssl_init_FindCAList_X509NameCmp(X509_NAME **a, X509_NAME **b)
970 {
971     return(X509_NAME_cmp(*a, *b));
972 }
973
974 static void ssl_init_PushCAList(STACK_OF(X509_NAME) *ca_list,
975                                 server_rec *s, const char *file)
976 {
977     int n;
978     STACK_OF(X509_NAME) *sk;
979
980     sk = (STACK_OF(X509_NAME) *)SSL_load_client_CA_file(file);
981
982     if (!sk) {
983         return;
984     }
985
986     for (n = 0; n < sk_X509_NAME_num(sk); n++) {
987         char name_buf[256];
988         X509_NAME *name = sk_X509_NAME_value(sk, n);
989
990         ssl_log(s, SSL_LOG_TRACE,
991                 "CA certificate: %s",
992                 X509_NAME_oneline(name, name_buf, sizeof(name_buf)));
993
994         /*
995          * note that SSL_load_client_CA_file() checks for duplicates,
996          * but since we call it multiple times when reading a directory
997          * we must also check for duplicates ourselves.
998          */
999
1000         if (sk_X509_NAME_find(ca_list, name) < 0) {
1001             /* this will be freed when ca_list is */
1002             sk_X509_NAME_push(ca_list, name);
1003         }
1004         else {
1005             /* need to free this ourselves, else it will leak */
1006             X509_NAME_free(name);
1007         }
1008     }
1009
1010     sk_X509_NAME_free(sk);
1011 }
1012
1013 STACK_OF(X509_NAME) *ssl_init_FindCAList(server_rec *s,
1014                                          apr_pool_t *ptemp,
1015                                          const char *ca_file,
1016                                          const char *ca_path)
1017 {
1018     STACK_OF(X509_NAME) *ca_list;
1019
1020     /*
1021      * Start with a empty stack/list where new
1022      * entries get added in sorted order.
1023      */
1024     ca_list = sk_X509_NAME_new(ssl_init_FindCAList_X509NameCmp);
1025
1026     /*
1027      * Process CA certificate bundle file
1028      */
1029     if (ca_file) {
1030         ssl_init_PushCAList(ca_list, s, ca_file);
1031     }
1032
1033     /*
1034      * Process CA certificate path files
1035      */
1036     if (ca_path) {
1037         apr_dir_t *dir;
1038         apr_finfo_t direntry;
1039         apr_int32_t finfo_flags = APR_FINFO_MIN|APR_FINFO_NAME;
1040
1041         if (apr_dir_open(&dir, ca_path, ptemp) != APR_SUCCESS) {
1042             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_ERRNO|SSL_INIT,
1043                     "Failed to open SSLCACertificatePath `%s'",
1044                     ca_path);
1045             ssl_die();
1046         }
1047
1048         while ((apr_dir_read(&direntry, finfo_flags, dir)) == APR_SUCCESS) {
1049             const char *file;
1050             if (direntry.filetype == APR_DIR) {
1051                 continue; /* don't try to load directories */
1052             }
1053             file = apr_pstrcat(ptemp, ca_path, "/", direntry.name, NULL);
1054             ssl_init_PushCAList(ca_list, s, file);
1055         }
1056
1057         apr_dir_close(dir);
1058     }
1059
1060     /*
1061      * Cleanup
1062      */
1063     sk_X509_NAME_set_cmp_func(ca_list, NULL);
1064
1065     return ca_list;
1066 }
1067
1068 void ssl_init_Child(apr_pool_t *p, server_rec *s)
1069 {
1070     SSLModConfigRec *mc = myModConfig(s);
1071     mc->pid = getpid(); /* only call getpid() once per-process */
1072
1073     /* XXX: there should be an ap_srand() function */
1074     srand((unsigned int)time(NULL));
1075
1076     /* open the mutex lockfile */
1077     ssl_mutex_reinit(s, p);
1078 }
1079
1080 #define MODSSL_CFG_ITEM_FREE(func, item) \
1081     if (item) { \
1082         func(item); \
1083         item = NULL; \
1084     }
1085
1086 apr_status_t ssl_init_ModuleKill(void *data)
1087 {
1088     SSLSrvConfigRec *sc;
1089     server_rec *base_server = (server_rec *)data;
1090     server_rec *s;
1091
1092     /*
1093      * Drop the session cache and mutex
1094      */
1095     ssl_scache_kill(base_server);
1096
1097     /* 
1098      * Destroy the temporary keys and params
1099      */
1100     ssl_tmp_keys_free(base_server);
1101
1102     /*
1103      * Free the non-pool allocated structures
1104      * in the per-server configurations
1105      */
1106     for (s = base_server; s; s = s->next) {
1107         int i;
1108         sc = mySrvConfig(s);
1109
1110         for (i=0; i < SSL_AIDX_MAX; i++) {
1111             MODSSL_CFG_ITEM_FREE(X509_free,
1112                                  sc->server->pks->certs[i]);
1113
1114             MODSSL_CFG_ITEM_FREE(EVP_PKEY_free,
1115                                  sc->server->pks->keys[i]);
1116         }
1117
1118         MODSSL_CFG_ITEM_FREE(X509_STORE_free,
1119                              sc->server->crl);
1120
1121         MODSSL_CFG_ITEM_FREE(SSL_CTX_free,
1122                              sc->server->ssl_ctx);
1123     }
1124
1125     /*
1126      * Try to kill the internals of the SSL library.
1127      */
1128     ERR_free_strings();
1129     ERR_remove_state(0);
1130     EVP_cleanup();
1131
1132     return APR_SUCCESS;
1133 }
1134