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