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