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