]> granicus.if.org Git - apache/blob - modules/ssl/ssl_engine_init.c
break SSL_CTX initialization into ssl_init_ctx function
[apache] / modules / ssl / ssl_engine_init.c
1 /*                      _             _
2 **  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
3 ** | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
4 ** | | | | | | (_) | (_| |   \__ \__ \ |  www.modssl.org
5 ** |_| |_| |_|\___/ \__,_|___|___/___/_|  ftp.modssl.org
6 **                      |_____|
7 **  ssl_engine_init.c
8 **  Initialization of Servers
9 */
10
11 /* ====================================================================
12  * The Apache Software License, Version 1.1
13  *
14  * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
15  * reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  *
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  *
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in
26  *    the documentation and/or other materials provided with the
27  *    distribution.
28  *
29  * 3. The end-user documentation included with the redistribution,
30  *    if any, must include the following acknowledgment:
31  *       "This product includes software developed by the
32  *        Apache Software Foundation (http://www.apache.org/)."
33  *    Alternately, this acknowledgment may appear in the software itself,
34  *    if and wherever such third-party acknowledgments normally appear.
35  *
36  * 4. The names "Apache" and "Apache Software Foundation" must
37  *    not be used to endorse or promote products derived from this
38  *    software without prior written permission. For written
39  *    permission, please contact apache@apache.org.
40  *
41  * 5. Products derived from this software may not be called "Apache",
42  *    nor may "Apache" appear in their name, without prior written
43  *    permission of the Apache Software Foundation.
44  *
45  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
46  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
47  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
48  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
49  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
50  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
51  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
52  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
53  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
54  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
55  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56  * SUCH DAMAGE.
57  * ====================================================================
58  */
59                              /* ``Recursive, adj.;
60                                   see Recursive.''
61                                         -- Unknown   */
62 #include "mod_ssl.h"
63
64 /*  _________________________________________________________________
65 **
66 **  Module Initialization
67 **  _________________________________________________________________
68 */
69
70 static char *ssl_add_version_component(apr_pool_t *p,
71                                        server_rec *s,
72                                        char *name)
73 {
74     char *val = ssl_var_lookup(p, s, NULL, NULL, name);
75
76     if (val && *val) {
77         ap_add_version_component(p, val);
78     }
79
80     return val;
81 }
82
83 static char *version_components[] = {
84     "SSL_VERSION_PRODUCT",
85     "SSL_VERSION_INTERFACE",
86     "SSL_VERSION_LIBRARY",
87     NULL
88 };
89
90 static void ssl_add_version_components(apr_pool_t *p,
91                                        server_rec *s)
92 {
93     char *vals[sizeof(version_components)/sizeof(char *)];
94     int i;
95
96     for (i=0; version_components[i]; i++) {
97         vals[i] = ssl_add_version_component(p, s,
98                                             version_components[i]);
99     }
100
101     ssl_log(s, SSL_LOG_INFO,
102             "Server: %s, Interface: %s, Library: %s",
103             AP_SERVER_BASEVERSION,
104             vals[1],  /* SSL_VERSION_INTERFACE */
105             vals[2]); /* SSL_VERSION_LIBRARY */
106 }
107
108
109 /*
110  *  Initialize SSL library
111  */
112 static void ssl_init_SSLLibrary(server_rec *s)
113 {
114     ssl_log(s, SSL_LOG_INFO,
115             "Init: Initializing %s library", SSL_LIBRARY_NAME);
116
117     CRYPTO_malloc_init();
118     SSL_load_error_strings();
119     SSL_library_init();
120 }
121
122 /*
123  * Handle the Temporary RSA Keys and DH Params
124  */
125
126 #define MODSSL_TMP_KEY_FREE(mc, type, idx) \
127     if (mc->pTmpKeys[idx]) { \
128         type##_free((type *)mc->pTmpKeys[idx]); \
129         mc->pTmpKeys[idx] = NULL; \
130     }
131
132 #define MODSSL_TMP_KEYS_FREE(mc, type) \
133     MODSSL_TMP_KEY_FREE(mc, type, SSL_TMP_KEY_##type##_512); \
134     MODSSL_TMP_KEY_FREE(mc, type, SSL_TMP_KEY_##type##_1024)
135
136 static void ssl_tmp_keys_free(server_rec *s)
137 {
138     SSLModConfigRec *mc = myModConfig(s);
139
140     MODSSL_TMP_KEYS_FREE(mc, RSA);
141     MODSSL_TMP_KEYS_FREE(mc, DH);
142 }
143
144 static void ssl_tmp_key_init_rsa(server_rec *s,
145                                  int bits, int idx)
146 {
147     SSLModConfigRec *mc = myModConfig(s);
148
149     if (!(mc->pTmpKeys[idx] =
150           RSA_generate_key(bits, RSA_F4, NULL, NULL)))
151     {
152         ssl_log(s, SSL_LOG_ERROR,
153                 "Init: Failed to generate temporary "
154                 "%d bit RSA private key", bits);
155         ssl_die();
156     }
157
158 }
159
160 static void ssl_tmp_key_init_dh(server_rec *s,
161                                 int bits, int idx)
162 {
163     SSLModConfigRec *mc = myModConfig(s);
164
165     if (!(mc->pTmpKeys[idx] =
166           ssl_dh_GetTmpParam(bits)))
167     {
168         ssl_log(s, SSL_LOG_ERROR,
169                 "Init: Failed to generate temporary "
170                 "%d bit DH parameters", bits);
171         ssl_die();
172     }
173 }
174
175 #define MODSSL_TMP_KEY_INIT_RSA(s, bits) \
176     ssl_tmp_key_init_rsa(s, bits, SSL_TMP_KEY_RSA_##bits)
177
178 #define MODSSL_TMP_KEY_INIT_DH(s, bits) \
179     ssl_tmp_key_init_dh(s, bits, SSL_TMP_KEY_DH_##bits)
180
181 static void ssl_tmp_keys_init(server_rec *s)
182 {
183     ssl_log(s, SSL_LOG_INFO,
184             "Init: Generating temporary RSA private keys (512/1024 bits)");
185
186     MODSSL_TMP_KEY_INIT_RSA(s, 512);
187     MODSSL_TMP_KEY_INIT_RSA(s, 1024);
188
189     ssl_log(s, SSL_LOG_INFO,
190             "Init: Generating temporary DH parameters (512/1024 bits)");
191
192     MODSSL_TMP_KEY_INIT_DH(s, 512);
193     MODSSL_TMP_KEY_INIT_DH(s, 1024);
194 }
195
196 /*
197  *  Per-module initialization
198  */
199 int ssl_init_Module(apr_pool_t *p, apr_pool_t *plog,
200                     apr_pool_t *ptemp,
201                     server_rec *base_server)
202 {
203     SSLModConfigRec *mc = myModConfig(base_server);
204     SSLSrvConfigRec *sc;
205     server_rec *s;
206
207     /*
208      * Let us cleanup on restarts and exists
209      */
210     apr_pool_cleanup_register(p, base_server,
211                               ssl_init_ModuleKill,
212                               apr_pool_cleanup_null);
213
214     /*
215      * Any init round fixes the global config
216      */
217     ssl_config_global_create(base_server); /* just to avoid problems */
218     ssl_config_global_fix(mc);
219
220     /*
221      *  try to fix the configuration and open the dedicated SSL
222      *  logfile as early as possible
223      */
224     for (s = base_server; s; s = s->next) {
225         sc = mySrvConfig(s);
226
227         /* Fix up stuff that may not have been set */
228         if (sc->bEnabled == UNSET) {
229             sc->bEnabled = FALSE;
230         }
231
232         if (sc->nSessionCacheTimeout == UNSET) {
233             sc->nSessionCacheTimeout = SSL_SESSION_CACHE_TIMEOUT;
234         }
235
236         if (sc->nPassPhraseDialogType == SSL_PPTYPE_UNSET) {
237             sc->nPassPhraseDialogType = SSL_PPTYPE_BUILTIN;
238         }
239
240         /* Open the dedicated SSL logfile */
241         ssl_log_open(base_server, s, p);
242     }
243
244     ssl_init_SSLLibrary(base_server);
245
246 #if APR_HAS_THREADS
247     ssl_util_thread_setup(base_server, p);
248 #endif
249
250     /*
251      * Seed the Pseudo Random Number Generator (PRNG)
252      * only need ptemp here; nothing inside allocated from the pool
253      * needs to live once we return from ssl_rand_seed().
254      */
255     ssl_rand_seed(base_server, ptemp, SSL_RSCTX_STARTUP, "Init: ");
256
257     /*
258      * read server private keys/public certs into memory.
259      * decrypting any encrypted keys via configured SSLPassPhraseDialogs
260      * anything that needs to live longer than ptemp needs to also survive
261      * restarts, in which case they'll live inside s->process->pool.
262      */
263     ssl_pphrase_Handle(base_server, ptemp);
264
265     ssl_tmp_keys_init(base_server);
266
267     /*
268      * SSL external crypto device ("engine") support
269      */
270 #ifdef SSL_EXPERIMENTAL_ENGINE
271     ssl_init_Engine(base_server, p);
272 #endif
273
274     /*
275      * Warn the user that he should use the session cache.
276      * But we can operate without it, of course.
277      */
278     if (mc->nSessionCacheMode == SSL_SCMODE_UNSET) {
279         ssl_log(base_server, SSL_LOG_WARN,
280                 "Init: Session Cache is not configured "
281                 "[hint: SSLSessionCache]");
282         mc->nSessionCacheMode = SSL_SCMODE_NONE;
283     }
284
285     /*
286      * initialize the mutex handling
287      */
288     if (!ssl_mutex_init(base_server, p)) {
289         return HTTP_INTERNAL_SERVER_ERROR;
290     }
291
292     /*
293      * initialize session caching
294      */
295     ssl_scache_init(base_server, p);
296
297     /*
298      *  initialize servers
299      */
300     ssl_log(base_server, SSL_LOG_INFO,
301             "Init: Initializing (virtual) servers for SSL");
302
303     for (s = base_server; s; s = s->next) {
304         sc = mySrvConfig(s);
305         /*
306          * Either now skip this server when SSL is disabled for
307          * it or give out some information about what we're
308          * configuring.
309          */
310         if (!sc->bEnabled) {
311             continue;
312         }
313
314         ssl_log(s, SSL_LOG_INFO,
315                 "Init: Configuring server %s for SSL protocol",
316                 ssl_util_vhostid(p, s));
317
318         /*
319          * Read the server certificate and key
320          */
321         ssl_init_ConfigureServer(s, p, ptemp, sc);
322     }
323
324     /*
325      * Configuration consistency checks
326      */
327     ssl_init_CheckServers(base_server, ptemp);
328
329     /*
330      *  Announce mod_ssl and SSL library in HTTP Server field
331      *  as ``mod_ssl/X.X.X OpenSSL/X.X.X''
332      */
333     ssl_add_version_components(p, base_server);
334
335     SSL_init_app_data2_idx(); /* for SSL_get_app_data2() at request time */
336
337     return OK;
338 }
339
340 /*
341  * Support for external a Crypto Device ("engine"), usually
342  * a hardware accellerator card for crypto operations.
343  */
344 #ifdef SSL_EXPERIMENTAL_ENGINE
345 void ssl_init_Engine(server_rec *s, apr_pool_t *p)
346 {
347     SSLModConfigRec *mc = myModConfig(s);
348     ENGINE *e;
349
350     if (mc->szCryptoDevice) {
351         if (!(e = ENGINE_by_id(mc->szCryptoDevice))) {
352             ssl_log(s, SSL_LOG_ERROR,
353                     "Init: Failed to load Crypto Device API `%s'",
354                     mc->szCryptoDevice);
355             ssl_die();
356         }
357
358         if (strEQ(mc->szCryptoDevice, "chil")) {
359             ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
360         }
361
362         if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
363             ssl_log(s, SSL_LOG_ERROR,
364                     "Init: Failed to enable Crypto Device API `%s'",
365                     mc->szCryptoDevice);
366             ssl_die();
367         }
368
369         ENGINE_free(e);
370     }
371 }
372 #endif
373
374 static SSL_CTX *ssl_init_ctx(server_rec *s,
375                              apr_pool_t *p,
376                              apr_pool_t *ptemp,
377                              SSLSrvConfigRec *sc)
378 {
379     SSL_CTX *ctx = NULL;
380     const char *vhost_id = sc->szVHostID;
381     char *cp;
382     int protocol = sc->nProtocol;
383
384     /*
385      *  Create the new per-server SSL context
386      */
387     if (protocol == SSL_PROTOCOL_NONE) {
388         ssl_log(s, SSL_LOG_ERROR,
389                 "Init: (%s) No SSL protocols available [hint: SSLProtocol]",
390                 vhost_id);
391         ssl_die();
392     }
393
394     cp = apr_pstrcat(p,
395                      (protocol & SSL_PROTOCOL_SSLV2 ? "SSLv2, " : ""),
396                      (protocol & SSL_PROTOCOL_SSLV3 ? "SSLv3, " : ""),
397                      (protocol & SSL_PROTOCOL_TLSV1 ? "TLSv1, " : ""),
398                      NULL);
399     cp[strlen(cp)-2] = NUL;
400
401     ssl_log(s, SSL_LOG_TRACE,
402             "Init: (%s) Creating new SSL context (protocols: %s)",
403             vhost_id, cp);
404
405     if (protocol == SSL_PROTOCOL_SSLV2) {
406         ctx = SSL_CTX_new(SSLv2_server_method());  /* only SSLv2 is left */
407     }
408     else {
409         ctx = SSL_CTX_new(SSLv23_server_method()); /* be more flexible */
410     }
411
412     sc->pSSLCtx = ctx;
413
414     SSL_CTX_set_options(ctx, SSL_OP_ALL);
415
416     if (!(protocol & SSL_PROTOCOL_SSLV2)) {
417         SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
418     }
419
420     if (!(protocol & SSL_PROTOCOL_SSLV3)) {
421         SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);
422     }
423
424     if (!(protocol & SSL_PROTOCOL_TLSV1)) {
425         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1);
426     }
427
428     SSL_CTX_set_app_data(ctx, s);
429
430     /*
431      * Configure additional context ingredients
432      */
433     SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
434
435     return ctx;
436 }
437
438 static void ssl_init_verify(server_rec *s,
439                             apr_pool_t *p,
440                             apr_pool_t *ptemp,
441                             SSLSrvConfigRec *sc)
442 {
443     SSL_CTX *ctx = sc->pSSLCtx;
444     const char *vhost_id = sc->szVHostID;
445
446     int verify = SSL_VERIFY_NONE;
447     STACK_OF(X509_NAME) *ca_list;
448
449     if (sc->nVerifyClient == SSL_CVERIFY_UNSET) {
450         sc->nVerifyClient = SSL_CVERIFY_NONE;
451     }
452
453     if (sc->nVerifyDepth == UNSET) {
454         sc->nVerifyDepth = 1;
455     }
456
457     /*
458      *  Configure callbacks for SSL context
459      */
460     if (sc->nVerifyClient == SSL_CVERIFY_REQUIRE) {
461         verify |= SSL_VERIFY_PEER_STRICT;
462     }
463
464     if ((sc->nVerifyClient == SSL_CVERIFY_OPTIONAL) ||
465         (sc->nVerifyClient == SSL_CVERIFY_OPTIONAL_NO_CA))
466     {
467         verify |= SSL_VERIFY_PEER;
468     }
469
470     SSL_CTX_set_verify(ctx, verify,  ssl_callback_SSLVerify);
471
472     /*
473      * Configure Client Authentication details
474      */
475     if (sc->szCACertificateFile || sc->szCACertificatePath) {
476         ssl_log(s, SSL_LOG_TRACE,
477                 "Init: (%s) Configuring client authentication", vhost_id);
478
479         if (!SSL_CTX_load_verify_locations(ctx,
480                                            sc->szCACertificateFile,
481                                            sc->szCACertificatePath))
482         {
483             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
484                     "Init: (%s) Unable to configure verify locations "
485                     "for client authentication", vhost_id);
486             ssl_die();
487         }
488
489         ca_list = ssl_init_FindCAList(s, ptemp,
490                                       sc->szCACertificateFile,
491                                       sc->szCACertificatePath);
492         if (!ca_list) {
493             ssl_log(s, SSL_LOG_ERROR,
494                     "Init: (%s) Unable to determine list of available "
495                     "CA certificates for client authentication",
496                     vhost_id);
497             ssl_die();
498         }
499
500         SSL_CTX_set_client_CA_list(ctx, (STACK *)ca_list);
501     }
502
503     /*
504      * Give a warning when no CAs were configured but client authentication
505      * should take place. This cannot work.
506      */
507     if (sc->nVerifyClient == SSL_CVERIFY_REQUIRE) {
508         ca_list = (STACK_OF(X509_NAME) *)SSL_CTX_get_client_CA_list(ctx);
509
510         if (sk_X509_NAME_num(ca_list) == 0) {
511             ssl_log(s, SSL_LOG_WARN,
512                     "Init: Ops, you want to request client authentication, "
513                     "but no CAs are known for verification!? "
514                     "[Hint: SSLCACertificate*]");
515         }
516     }
517 }
518
519 /*
520  * Configure a particular server
521  */
522 void ssl_init_ConfigureServer(server_rec *s,
523                               apr_pool_t *p,
524                               apr_pool_t *ptemp,
525                               SSLSrvConfigRec *sc)
526 {
527     SSLModConfigRec *mc = myModConfig(s);
528     char *cp;
529     const char *vhost_id, *rsa_id, *dsa_id;
530     EVP_PKEY *pkey;
531     SSL_CTX *ctx;
532     ssl_asn1_t *asn1;
533     unsigned char *ptr;
534     BOOL ok = FALSE;
535     int is_ca, pathlen;
536     int i, n;
537     long cache_mode;
538
539     /*
540      * Create the server host:port string because we need it a lot
541      */
542     sc->szVHostID = vhost_id = ssl_util_vhostid(p, s);
543     sc->nVHostID_length = strlen(sc->szVHostID);
544
545     /*
546      * Now check for important parameters and the
547      * possibility that the user forgot to set them.
548      */
549     if (!sc->szPublicCertFiles[0]) {
550         ssl_log(s, SSL_LOG_ERROR,
551                 "Init: (%s) No SSL Certificate set [hint: SSLCertificateFile]",
552                 vhost_id);
553         ssl_die();
554     }
555
556     /*
557      *  Check for problematic re-initializations
558      */
559     if (sc->pPublicCert[SSL_AIDX_RSA] ||
560         sc->pPublicCert[SSL_AIDX_DSA])
561     {
562         ssl_log(s, SSL_LOG_ERROR,
563                 "Init: (%s) Illegal attempt to re-initialise SSL for server "
564                 "(theoretically shouldn't happen!)", vhost_id);
565         ssl_die();
566     }
567
568     ctx = ssl_init_ctx(s, p, ptemp, sc);
569
570     if (mc->nSessionCacheMode == SSL_SCMODE_NONE) {
571         cache_mode = SSL_SESS_CACHE_OFF;
572     }
573     else {
574         /* SSL_SESS_CACHE_NO_INTERNAL_LOOKUP will force OpenSSL
575          * to ignore process local-caching and
576          * to always get/set/delete sessions using mod_ssl's callbacks.
577          */
578         cache_mode = SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL_LOOKUP;
579     }
580
581     SSL_CTX_set_session_cache_mode(ctx, cache_mode);
582
583     ssl_init_verify(s, p, ptemp, sc);
584
585     SSL_CTX_sess_set_new_cb(ctx,      ssl_callback_NewSessionCacheEntry);
586     SSL_CTX_sess_set_get_cb(ctx,      ssl_callback_GetSessionCacheEntry);
587     SSL_CTX_sess_set_remove_cb(ctx,   ssl_callback_DelSessionCacheEntry);
588
589     SSL_CTX_set_tmp_rsa_callback(ctx, ssl_callback_TmpRSA);
590     SSL_CTX_set_tmp_dh_callback(ctx,  ssl_callback_TmpDH);
591
592     if (sc->nLogLevel >= SSL_LOG_INFO) {
593         /* this callback only logs if SSLLogLevel >= info */
594         SSL_CTX_set_info_callback(ctx, ssl_callback_LogTracingState);
595     }
596
597     /*
598      *  Configure SSL Cipher Suite
599      */
600     if (sc->szCipherSuite) {
601         ssl_log(s, SSL_LOG_TRACE,
602                 "Init: (%s) Configuring permitted SSL ciphers [%s]", 
603                 vhost_id, sc->szCipherSuite);
604
605         if (!SSL_CTX_set_cipher_list(ctx, sc->szCipherSuite)) {
606             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
607                     "Init: (%s) Unable to configure permitted SSL ciphers",
608                     vhost_id);
609             ssl_die();
610         }
611     }
612
613
614     /*
615      * Configure Certificate Revocation List (CRL) Details
616      */
617     if (sc->szCARevocationFile || sc->szCARevocationPath) {
618         ssl_log(s, SSL_LOG_TRACE,
619                 "Init: (%s) Configuring certificate revocation facility",
620                 vhost_id);
621
622         sc->pRevocationStore =
623             SSL_X509_STORE_create((char *)sc->szCARevocationFile,
624                                   (char *)sc->szCARevocationPath);
625
626         if (!sc->pRevocationStore) {
627             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
628                     "Init: (%s) Unable to configure X.509 CRL storage "
629                     "for certificate revocation",
630                     vhost_id);
631             ssl_die();
632         }
633     }
634
635     /*
636      *  Configure server certificate(s)
637      */
638     rsa_id = ssl_asn1_table_keyfmt(ptemp, vhost_id, SSL_AIDX_RSA);
639     dsa_id = ssl_asn1_table_keyfmt(ptemp, vhost_id, SSL_AIDX_DSA);
640
641     if ((asn1 = ssl_asn1_table_get(mc->tPublicCert, rsa_id))) {
642         ssl_log(s, SSL_LOG_TRACE,
643                 "Init: (%s) Configuring RSA server certificate",
644                 vhost_id);
645
646         ptr = asn1->cpData;
647         if (!(sc->pPublicCert[SSL_AIDX_RSA] =
648               d2i_X509(NULL, &ptr, asn1->nData)))
649         {
650             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
651                     "Init: (%s) Unable to import RSA server certificate",
652                     vhost_id);
653             ssl_die();
654         }
655
656         if (SSL_CTX_use_certificate(ctx, sc->pPublicCert[SSL_AIDX_RSA]) <= 0) {
657             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
658                     "Init: (%s) Unable to configure RSA server certificate",
659                     vhost_id);
660             ssl_die();
661         }
662
663         ok = TRUE;
664     }
665
666     if ((asn1 = ssl_asn1_table_get(mc->tPublicCert, dsa_id))) {
667         ssl_log(s, SSL_LOG_TRACE,
668                 "Init: (%s) Configuring DSA server certificate",
669                 vhost_id);
670
671         ptr = asn1->cpData;
672         if (!(sc->pPublicCert[SSL_AIDX_DSA] =
673               d2i_X509(NULL, &ptr, asn1->nData)))
674         {
675             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
676                     "Init: (%s) Unable to import DSA server certificate",
677                     vhost_id);
678             ssl_die();
679         }
680
681         if (SSL_CTX_use_certificate(ctx, sc->pPublicCert[SSL_AIDX_DSA]) <= 0) {
682             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
683                     "Init: (%s) Unable to configure DSA server certificate",
684                     vhost_id);
685             ssl_die();
686         }
687
688         ok = TRUE;
689     }
690
691     if (!ok) {
692         ssl_log(s, SSL_LOG_ERROR,
693                 "Init: (%s) Ops, no RSA or DSA server certificate found?!",
694                 vhost_id);
695         ssl_log(s, SSL_LOG_ERROR,
696                 "Init: (%s) You have to perform a *full* server restart "
697                 "when you added or removed a certificate and/or key file",
698                 vhost_id);
699         ssl_die();
700     }
701
702     /*
703      * Some information about the certificate(s)
704      */
705     for (i = 0; i < SSL_AIDX_MAX; i++) {
706         if (sc->pPublicCert[i]) {
707             if (SSL_X509_isSGC(sc->pPublicCert[i])) {
708                 ssl_log(s, SSL_LOG_INFO,
709                         "Init: (%s) %s server certificate enables "
710                         "Server Gated Cryptography (SGC)", 
711                         vhost_id, ssl_asn1_keystr(i));
712             }
713
714             if (SSL_X509_getBC(sc->pPublicCert[i], &is_ca, &pathlen)) {
715                 if (is_ca) {
716                     ssl_log(s, SSL_LOG_WARN,
717                             "Init: (%s) %s server certificate "
718                             "is a CA certificate "
719                             "(BasicConstraints: CA == TRUE !?)",
720                             vhost_id, ssl_asn1_keystr(i));
721                 }
722
723                 if (pathlen > 0) {
724                     ssl_log(s, SSL_LOG_WARN,
725                             "Init: (%s) %s server certificate "
726                             "is not a leaf certificate "
727                             "(BasicConstraints: pathlen == %d > 0 !?)",
728                             vhost_id, ssl_asn1_keystr(i), pathlen);
729                 }
730             }
731
732             if (SSL_X509_getCN(p, sc->pPublicCert[i], &cp)) {
733                 int fnm_flags = FNM_PERIOD|FNM_CASE_BLIND;
734
735                 if (apr_is_fnmatch(cp) &&
736                     (apr_fnmatch(cp, s->server_hostname,
737                                  fnm_flags) == FNM_NOMATCH))
738                 {
739                     ssl_log(s, SSL_LOG_WARN,
740                             "Init: (%s) %s server certificate "
741                             "wildcard CommonName (CN) `%s' "
742                             "does NOT match server name!?",
743                             vhost_id, ssl_asn1_keystr(i), cp);
744                 }
745                 else if (strNE(s->server_hostname, cp)) {
746                     ssl_log(s, SSL_LOG_WARN,
747                             "Init: (%s) %s server certificate "
748                             "CommonName (CN) `%s' "
749                             "does NOT match server name!?",
750                             vhost_id, ssl_asn1_keystr(i), cp);
751                 }
752             }
753         }
754     }
755
756     /*
757      *  Configure server private key(s)
758      */
759     ok = FALSE;
760
761     if ((asn1 = ssl_asn1_table_get(mc->tPrivateKey, rsa_id))) {
762         ssl_log(s, SSL_LOG_TRACE,
763                 "Init: (%s) Configuring RSA server private key",
764                 vhost_id);
765
766         ptr = asn1->cpData;
767         if (!(sc->pPrivateKey[SSL_AIDX_RSA] = 
768               d2i_PrivateKey(EVP_PKEY_RSA, NULL, &ptr, asn1->nData)))
769         {
770             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
771                     "Init: (%s) Unable to import RSA server private key",
772                     vhost_id);
773             ssl_die();
774         }
775
776         if (SSL_CTX_use_PrivateKey(ctx, sc->pPrivateKey[SSL_AIDX_RSA]) <= 0) {
777             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
778                     "Init: (%s) Unable to configure RSA server private key",
779                     vhost_id);
780             ssl_die();
781         }
782
783         ok = TRUE;
784     }
785
786     if ((asn1 = ssl_asn1_table_get(mc->tPrivateKey, dsa_id))) {
787         ssl_log(s, SSL_LOG_TRACE,
788                 "Init: (%s) Configuring DSA server private key",
789                 vhost_id);
790
791         ptr = asn1->cpData;
792         if (!(sc->pPrivateKey[SSL_AIDX_DSA] = 
793               d2i_PrivateKey(EVP_PKEY_DSA, NULL, &ptr, asn1->nData)))
794         {
795             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
796                     "Init: (%s) Unable to import DSA server private key",
797                     vhost_id);
798             ssl_die();
799         }
800
801         if (SSL_CTX_use_PrivateKey(ctx, sc->pPrivateKey[SSL_AIDX_DSA]) <= 0) {
802             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLERR,
803                     "Init: (%s) Unable to configure DSA server private key",
804                     vhost_id);
805             ssl_die();
806         }
807
808         ok = TRUE;
809     }
810
811     if (!ok) {
812         ssl_log(s, SSL_LOG_ERROR,
813                 "Init: (%s) Ops, no RSA or DSA server private key found?!",
814                 vhost_id);
815         ssl_die();
816     }
817
818     /*
819      * Optionally copy DSA parameters for certificate from private key
820      * (see http://www.psy.uq.edu.au/~ftp/Crypto/ssleay/TODO.html)
821      */
822     if (sc->pPublicCert[SSL_AIDX_DSA] &&
823         sc->pPrivateKey[SSL_AIDX_DSA])
824     {
825         pkey = X509_get_pubkey(sc->pPublicCert[SSL_AIDX_DSA]);
826
827         if (pkey && (EVP_PKEY_key_type(pkey) == EVP_PKEY_DSA) &&
828             EVP_PKEY_missing_parameters(pkey))
829         {
830             EVP_PKEY_copy_parameters(pkey,
831                                      sc->pPrivateKey[SSL_AIDX_DSA]);
832         }
833     }
834
835     /* 
836      * Optionally configure extra server certificate chain certificates.
837      * This is usually done by OpenSSL automatically when one of the
838      * server cert issuers are found under SSLCACertificatePath or in
839      * SSLCACertificateFile. But because these are intended for client
840      * authentication it can conflict. For instance when you use a
841      * Global ID server certificate you've to send out the intermediate
842      * CA certificate, too. When you would just configure this with
843      * SSLCACertificateFile and also use client authentication mod_ssl
844      * would accept all clients also issued by this CA. Obviously this
845      * isn't what we want in this situation. So this feature here exists
846      * to allow one to explicity configure CA certificates which are
847      * used only for the server certificate chain.
848      */
849     if (sc->szCertificateChain) {
850         BOOL skip_first = FALSE;
851
852         for (i = 0; (i < SSL_AIDX_MAX) && sc->szPublicCertFiles[i]; i++) {
853             if (strEQ(sc->szPublicCertFiles[i], sc->szCertificateChain)) {
854                 skip_first = TRUE;
855                 break;
856             }
857         }
858
859         n = SSL_CTX_use_certificate_chain(ctx,
860                                           (char *)sc->szCertificateChain, 
861                                           skip_first, NULL);
862         if (n < 0) {
863             ssl_log(s, SSL_LOG_ERROR,
864                     "Init: (%s) Failed to configure CA certificate chain!",
865                     vhost_id);
866             ssl_die();
867         }
868
869         ssl_log(s, SSL_LOG_TRACE,
870                 "Init: (%s) Configuring server certificate chain "
871                 "(%d CA certificate%s)",
872                 vhost_id, n, n == 1 ? "" : "s");
873     }
874 }
875
876 void ssl_init_CheckServers(server_rec *base_server, apr_pool_t *p)
877 {
878     server_rec *s, *ps;
879     SSLSrvConfigRec *sc;
880     apr_hash_t *table;
881     const char *key;
882     apr_ssize_t klen;
883
884     BOOL conflict = FALSE;
885
886     /*
887      * Give out warnings when a server has HTTPS configured 
888      * for the HTTP port or vice versa
889      */
890     for (s = base_server; s; s = s->next) {
891         sc = mySrvConfig(s);
892
893         if (sc->bEnabled && (s->port == DEFAULT_HTTP_PORT)) {
894             ssl_log(base_server, SSL_LOG_WARN,
895                     "Init: (%s) You configured HTTPS(%d) "
896                     "on the standard HTTP(%d) port!",
897                     ssl_util_vhostid(p, s),
898                     DEFAULT_HTTPS_PORT, DEFAULT_HTTP_PORT);
899         }
900
901         if (!sc->bEnabled && (s->port == DEFAULT_HTTPS_PORT)) {
902             ssl_log(base_server, SSL_LOG_WARN,
903                     "Init: (%s) You configured HTTP(%d) "
904                     "on the standard HTTPS(%d) port!",
905                     ssl_util_vhostid(p, s),
906                     DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT);
907         }
908     }
909
910     /*
911      * Give out warnings when more than one SSL-aware virtual server uses the
912      * same IP:port. This doesn't work because mod_ssl then will always use
913      * just the certificate/keys of one virtual host (which one cannot be said
914      * easily - but that doesn't matter here).
915      */
916     table = apr_hash_make(p);
917
918     for (s = base_server; s; s = s->next) {
919         sc = mySrvConfig(s);
920
921         if (!sc->bEnabled) {
922             continue;
923         }
924
925         key = apr_psprintf(p, "%pA:%u",
926                            &s->addrs->host_addr, s->addrs->host_port);
927         klen = strlen(key);
928
929         if ((ps = (server_rec *)apr_hash_get(table, key, klen))) {
930             ssl_log(base_server, SSL_LOG_WARN,
931                     "Init: SSL server IP/port conflict: "
932                     "%s (%s:%d) vs. %s (%s:%d)",
933                     ssl_util_vhostid(p, s), 
934                     (s->defn_name ? s->defn_name : "unknown"),
935                     s->defn_line_number,
936                     ssl_util_vhostid(p, ps),
937                     (ps->defn_name ? ps->defn_name : "unknown"), 
938                     ps->defn_line_number);
939             conflict = TRUE;
940             continue;
941         }
942
943         apr_hash_set(table, key, klen, s);
944     }
945
946     if (conflict) {
947         ssl_log(base_server, SSL_LOG_WARN,
948                 "Init: You should not use name-based "
949                 "virtual hosts in conjunction with SSL!!");
950     }
951 }
952
953 static int ssl_init_FindCAList_X509NameCmp(X509_NAME **a, X509_NAME **b)
954 {
955     return(X509_NAME_cmp(*a, *b));
956 }
957
958 static void ssl_init_PushCAList(STACK_OF(X509_NAME) *ca_list,
959                                 server_rec *s, const char *file)
960 {
961     int n;
962     STACK_OF(X509_NAME) *sk;
963
964     sk = (STACK_OF(X509_NAME) *)SSL_load_client_CA_file(file);
965
966     if (!sk) {
967         return;
968     }
969
970     for (n = 0; n < sk_X509_NAME_num(sk); n++) {
971         char name_buf[256];
972         X509_NAME *name = sk_X509_NAME_value(sk, n);
973
974         ssl_log(s, SSL_LOG_TRACE,
975                 "CA certificate: %s",
976                 X509_NAME_oneline(name, name_buf, sizeof(name_buf)));
977
978         /*
979          * note that SSL_load_client_CA_file() checks for duplicates,
980          * but since we call it multiple times when reading a directory
981          * we must also check for duplicates ourselves.
982          */
983
984         if (sk_X509_NAME_find(ca_list, name) < 0) {
985             /* this will be freed when ca_list is */
986             sk_X509_NAME_push(ca_list, name);
987         }
988         else {
989             /* need to free this ourselves, else it will leak */
990             X509_NAME_free(name);
991         }
992     }
993
994     sk_X509_NAME_free(sk);
995 }
996
997 STACK_OF(X509_NAME) *ssl_init_FindCAList(server_rec *s,
998                                          apr_pool_t *ptemp,
999                                          const char *ca_file,
1000                                          const char *ca_path)
1001 {
1002     STACK_OF(X509_NAME) *ca_list;
1003
1004     /*
1005      * Start with a empty stack/list where new
1006      * entries get added in sorted order.
1007      */
1008     ca_list = sk_X509_NAME_new(ssl_init_FindCAList_X509NameCmp);
1009
1010     /*
1011      * Process CA certificate bundle file
1012      */
1013     if (ca_file) {
1014         ssl_init_PushCAList(ca_list, s, ca_file);
1015     }
1016
1017     /*
1018      * Process CA certificate path files
1019      */
1020     if (ca_path) {
1021         apr_dir_t *dir;
1022         apr_finfo_t direntry;
1023         apr_int32_t finfo_flags = APR_FINFO_MIN|APR_FINFO_NAME;
1024
1025         if (apr_dir_open(&dir, ca_path, ptemp) != APR_SUCCESS) {
1026             ssl_log(s, SSL_LOG_ERROR|SSL_ADD_ERRNO,
1027                     "Init: Failed to open SSLCACertificatePath `%s'",
1028                     ca_path);
1029             ssl_die();
1030         }
1031
1032         while ((apr_dir_read(&direntry, finfo_flags, dir)) == APR_SUCCESS) {
1033             const char *file;
1034             if (direntry.filetype == APR_DIR) {
1035                 continue; /* don't try to load directories */
1036             }
1037             file = apr_pstrcat(ptemp, ca_path, "/", direntry.name, NULL);
1038             ssl_init_PushCAList(ca_list, s, file);
1039         }
1040
1041         apr_dir_close(dir);
1042     }
1043
1044     /*
1045      * Cleanup
1046      */
1047     sk_X509_NAME_set_cmp_func(ca_list, NULL);
1048
1049     return ca_list;
1050 }
1051
1052 void ssl_init_Child(apr_pool_t *p, server_rec *s)
1053 {
1054     SSLModConfigRec *mc = myModConfig(s);
1055     mc->pid = getpid(); /* only call getpid() once per-process */
1056
1057     /* XXX: there should be an ap_srand() function */
1058     srand((unsigned int)time(NULL));
1059
1060     /* open the mutex lockfile */
1061     ssl_mutex_reinit(s, p);
1062 }
1063
1064 #define MODSSL_CFG_ITEM_FREE(func, item) \
1065     if (item) { \
1066         func(item); \
1067         item = NULL; \
1068     }
1069
1070 apr_status_t ssl_init_ModuleKill(void *data)
1071 {
1072     SSLSrvConfigRec *sc;
1073     server_rec *base_server = (server_rec *)data;
1074     server_rec *s;
1075
1076     /*
1077      * Drop the session cache and mutex
1078      */
1079     ssl_scache_kill(base_server);
1080
1081     /* 
1082      * Destroy the temporary keys and params
1083      */
1084     ssl_tmp_keys_free(base_server);
1085
1086     /*
1087      * Free the non-pool allocated structures
1088      * in the per-server configurations
1089      */
1090     for (s = base_server; s; s = s->next) {
1091         int i;
1092         sc = mySrvConfig(s);
1093
1094         for (i=0; i < SSL_AIDX_MAX; i++) {
1095             MODSSL_CFG_ITEM_FREE(X509_free,
1096                                  sc->pPublicCert[i]);
1097
1098             MODSSL_CFG_ITEM_FREE(EVP_PKEY_free,
1099                                  sc->pPrivateKey[i]);
1100         }
1101
1102         MODSSL_CFG_ITEM_FREE(X509_STORE_free,
1103                              sc->pRevocationStore);
1104
1105         MODSSL_CFG_ITEM_FREE(SSL_CTX_free,
1106                              sc->pSSLCtx);
1107     }
1108
1109     /*
1110      * Try to kill the internals of the SSL library.
1111      */
1112     ERR_free_strings();
1113     ERR_remove_state(0);
1114     EVP_cleanup();
1115
1116     return APR_SUCCESS;
1117 }
1118