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