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