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