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