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