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