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