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