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