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