]> granicus.if.org Git - apache/blob - modules/ssl/mod_ssl.c
FINALLY Correct ap_http_method()! It is NOT a method, it's a SCHEME!
[apache] / modules / ssl / mod_ssl.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  *  mod_ssl.c
23  *  Apache API interface structures
24  */
25
26 #include "ssl_private.h"
27 #include "mod_ssl.h"
28 #include "util_md5.h"
29 #include <assert.h>
30
31 /*
32  *  the table of configuration directives we provide
33  */
34
35 #define SSL_CMD_ALL(name, args, desc) \
36         AP_INIT_##args("SSL"#name, ssl_cmd_SSL##name, \
37                        NULL, RSRC_CONF|OR_AUTHCFG, desc),
38
39 #define SSL_CMD_SRV(name, args, desc) \
40         AP_INIT_##args("SSL"#name, ssl_cmd_SSL##name, \
41                        NULL, RSRC_CONF, desc),
42
43 #define SSL_CMD_DIR(name, type, args, desc) \
44         AP_INIT_##args("SSL"#name, ssl_cmd_SSL##name, \
45                        NULL, OR_##type, desc),
46
47 #define AP_END_CMD { NULL }
48
49 const char ssl_valid_ssl_mutex_string[] =
50     "Valid SSLMutex mechanisms are: `none', `default'"
51 #if APR_HAS_FLOCK_SERIALIZE
52     ", `flock:/path/to/file'"
53 #endif
54 #if APR_HAS_FCNTL_SERIALIZE
55     ", `fcntl:/path/to/file'"
56 #endif
57 #if APR_HAS_SYSVSEM_SERIALIZE && !defined(PERCHILD_MPM)
58     ", `sysvsem'"
59 #endif
60 #if APR_HAS_POSIXSEM_SERIALIZE
61     ", `posixsem'"
62 #endif
63 #if APR_HAS_PROC_PTHREAD_SERIALIZE
64     ", `pthread'"
65 #endif
66 #if APR_HAS_FLOCK_SERIALIZE || APR_HAS_FCNTL_SERIALIZE
67     ", `file:/path/to/file'"
68 #endif
69 #if (APR_HAS_SYSVSEM_SERIALIZE && !defined(PERCHILD_MPM)) || APR_HAS_POSIXSEM_SERIALIZE
70     ", `sem'"
71 #endif
72     " ";
73
74 static const command_rec ssl_config_cmds[] = {
75     /*
76      * Global (main-server) context configuration directives
77      */
78     SSL_CMD_SRV(Mutex, TAKE1, ssl_valid_ssl_mutex_string)
79     SSL_CMD_SRV(PassPhraseDialog, TAKE1,
80                 "SSL dialog mechanism for the pass phrase query "
81                 "(`builtin', `|/path/to/pipe_program`, "
82                 "or `exec:/path/to/cgi_program')")
83     SSL_CMD_SRV(SessionCache, TAKE1,
84                 "SSL Session Cache storage "
85                 "(`none', `dbm:/path/to/file')")
86 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
87     SSL_CMD_SRV(CryptoDevice, TAKE1,
88                 "SSL external Crypto Device usage "
89                 "(`builtin', `...')")
90 #endif
91     SSL_CMD_SRV(RandomSeed, TAKE23,
92                 "SSL Pseudo Random Number Generator (PRNG) seeding source "
93                 "(`startup|connect builtin|file:/path|exec:/path [bytes]')")
94
95     /*
96      * Per-server context configuration directives
97      */
98     SSL_CMD_SRV(Engine, TAKE1,
99                 "SSL switch for the protocol engine "
100                 "(`on', `off')")
101     SSL_CMD_ALL(CipherSuite, TAKE1,
102                 "Colon-delimited list of permitted SSL Ciphers "
103                 "(`XXX:...:XXX' - see manual)")
104     SSL_CMD_SRV(CertificateFile, TAKE1,
105                 "SSL Server Certificate file "
106                 "(`/path/to/file' - PEM or DER encoded)")
107     SSL_CMD_SRV(CertificateKeyFile, TAKE1,
108                 "SSL Server Private Key file "
109                 "(`/path/to/file' - PEM or DER encoded)")
110     SSL_CMD_SRV(CertificateChainFile, TAKE1,
111                 "SSL Server CA Certificate Chain file "
112                 "(`/path/to/file' - PEM encoded)")
113     SSL_CMD_ALL(CACertificatePath, TAKE1,
114                 "SSL CA Certificate path "
115                 "(`/path/to/dir' - contains PEM encoded files)")
116     SSL_CMD_ALL(CACertificateFile, TAKE1,
117                 "SSL CA Certificate file "
118                 "(`/path/to/file' - PEM encoded)")
119     SSL_CMD_SRV(CARevocationPath, TAKE1,
120                 "SSL CA Certificate Revocation List (CRL) path "
121                 "(`/path/to/dir' - contains PEM encoded files)")
122     SSL_CMD_SRV(CARevocationFile, TAKE1,
123                 "SSL CA Certificate Revocation List (CRL) file "
124                 "(`/path/to/file' - PEM encoded)")
125     SSL_CMD_ALL(VerifyClient, TAKE1,
126                 "SSL Client verify type "
127                 "(`none', `optional', `require', `optional_no_ca')")
128     SSL_CMD_ALL(VerifyDepth, TAKE1,
129                 "SSL Client verify depth "
130                 "(`N' - number of intermediate certificates)")
131     SSL_CMD_SRV(SessionCacheTimeout, TAKE1,
132                 "SSL Session Cache object lifetime "
133                 "(`N' - number of seconds)")
134     SSL_CMD_SRV(Protocol, RAW_ARGS,
135                 "Enable or disable various SSL protocols"
136                 "(`[+-][SSLv2|SSLv3|TLSv1] ...' - see manual)")
137     SSL_CMD_SRV(HonorCipherOrder, FLAG,
138                 "Use the server's cipher ordering preference")
139     SSL_CMD_ALL(UserName, TAKE1,
140                 "Set user name to SSL variable value")
141
142     /* 
143      * Proxy configuration for remote SSL connections
144      */
145     SSL_CMD_SRV(ProxyEngine, FLAG,
146                 "SSL switch for the proxy protocol engine "
147                 "(`on', `off')")
148     SSL_CMD_SRV(ProxyProtocol, RAW_ARGS,
149                "SSL Proxy: enable or disable SSL protocol flavors "
150                "(`[+-][SSLv2|SSLv3|TLSv1] ...' - see manual)")
151     SSL_CMD_SRV(ProxyCipherSuite, TAKE1,
152                "SSL Proxy: colon-delimited list of permitted SSL ciphers "
153                "(`XXX:...:XXX' - see manual)")
154     SSL_CMD_SRV(ProxyVerify, TAKE1,
155                "SSL Proxy: whether to verify the remote certificate "
156                "(`on' or `off')")
157     SSL_CMD_SRV(ProxyVerifyDepth, TAKE1,
158                "SSL Proxy: maximum certificate verification depth "
159                "(`N' - number of intermediate certificates)")
160     SSL_CMD_SRV(ProxyCACertificateFile, TAKE1,
161                "SSL Proxy: file containing server certificates "
162                "(`/path/to/file' - PEM encoded certificates)")
163     SSL_CMD_SRV(ProxyCACertificatePath, TAKE1,
164                "SSL Proxy: directory containing server certificates "
165                "(`/path/to/dir' - contains PEM encoded certificates)")
166     SSL_CMD_SRV(ProxyCARevocationPath, TAKE1,
167                 "SSL Proxy: CA Certificate Revocation List (CRL) path "
168                 "(`/path/to/dir' - contains PEM encoded files)")
169     SSL_CMD_SRV(ProxyCARevocationFile, TAKE1,
170                 "SSL Proxy: CA Certificate Revocation List (CRL) file "
171                 "(`/path/to/file' - PEM encoded)")
172     SSL_CMD_SRV(ProxyMachineCertificateFile, TAKE1,
173                "SSL Proxy: file containing client certificates "
174                "(`/path/to/file' - PEM encoded certificates)")
175     SSL_CMD_SRV(ProxyMachineCertificatePath, TAKE1,
176                "SSL Proxy: directory containing client certificates "
177                "(`/path/to/dir' - contains PEM encoded certificates)")
178
179     /*
180      * Per-directory context configuration directives
181      */
182     SSL_CMD_DIR(Options, OPTIONS, RAW_ARGS,
183                "Set one or more options to configure the SSL engine"
184                "(`[+-]option[=value] ...' - see manual)")
185     SSL_CMD_DIR(RequireSSL, AUTHCFG, NO_ARGS,
186                "Require the SSL protocol for the per-directory context "
187                "(no arguments)")
188     SSL_CMD_DIR(Require, AUTHCFG, RAW_ARGS,
189                "Require a boolean expression to evaluate to true for granting access"
190                "(arbitrary complex boolean expression - see manual)")
191
192     /* Deprecated directives. */
193     AP_INIT_RAW_ARGS("SSLLog", ap_set_deprecated, NULL, OR_ALL, 
194       "SSLLog directive is no longer supported - use ErrorLog."),
195     AP_INIT_RAW_ARGS("SSLLogLevel", ap_set_deprecated, NULL, OR_ALL, 
196       "SSLLogLevel directive is no longer supported - use LogLevel."),
197     
198     AP_END_CMD
199 };
200
201 /*
202  *  the various processing hooks
203  */
204 static apr_status_t ssl_cleanup_pre_config(void *data)
205 {
206     /*
207      * Try to kill the internals of the SSL library.
208      */
209 #ifdef HAVE_OPENSSL
210 #if OPENSSL_VERSION_NUMBER >= 0x00907001
211     /* Corresponds to OPENSSL_load_builtin_modules():
212      * XXX: borrowed from apps.h, but why not CONF_modules_free()
213      * which also invokes CONF_modules_finish()?
214      */
215     CONF_modules_unload(1);
216 #endif
217 #endif
218     /* Corresponds to SSL_library_init: */
219     EVP_cleanup();
220 #if HAVE_ENGINE_LOAD_BUILTIN_ENGINES
221     ENGINE_cleanup();
222 #endif
223 #ifdef HAVE_OPENSSL
224 #if OPENSSL_VERSION_NUMBER >= 0x00907001
225     CRYPTO_cleanup_all_ex_data();
226 #endif
227 #endif
228     ERR_remove_state(0);
229
230     /* Don't call ERR_free_strings here; ERR_load_*_strings only
231      * actually load the error strings once per process due to static
232      * variable abuse in OpenSSL. */
233
234     /* 
235      * TODO: determine somewhere we can safely shove out diagnostics 
236      *       (when enabled) at this late stage in the game:
237      * CRYPTO_mem_leaks_fp(stderr);
238      */
239     return APR_SUCCESS;
240 }
241
242 static int ssl_hook_pre_config(apr_pool_t *pconf,
243                                apr_pool_t *plog,
244                                apr_pool_t *ptemp)
245 {
246     /* We must register the library in full, to ensure our configuration 
247      * code can successfully test the SSL environment.
248      */
249     CRYPTO_malloc_init();
250 #ifdef HAVE_OPENSSL
251     ERR_load_crypto_strings();
252 #endif
253     SSL_load_error_strings();
254     SSL_library_init();
255 #if HAVE_ENGINE_LOAD_BUILTIN_ENGINES
256     ENGINE_load_builtin_engines();
257 #endif
258 #ifdef HAVE_OPENSSL
259 #if OPENSSL_VERSION_NUMBER >= 0x00907001
260     OPENSSL_load_builtin_modules();
261 #endif
262 #endif
263
264     /*
265      * Let us cleanup the ssl library when the module is unloaded
266      */
267     apr_pool_cleanup_register(pconf, NULL, ssl_cleanup_pre_config,
268                                            apr_pool_cleanup_null);
269
270     /* Register us to handle mod_log_config %c/%x variables */
271     ssl_var_log_config_register(pconf);
272
273     /* Register to handle mod_status status page generation */
274     ssl_scache_status_register(pconf);
275
276     return OK;
277 }
278
279 static SSLConnRec *ssl_init_connection_ctx(conn_rec *c)
280 {
281     SSLConnRec *sslconn = myConnConfig(c);
282
283     if (sslconn) {
284         return sslconn;
285     }
286
287     sslconn = apr_pcalloc(c->pool, sizeof(*sslconn));
288
289     myConnConfigSet(c, sslconn);
290
291     return sslconn;
292 }
293
294 int ssl_proxy_enable(conn_rec *c)
295 {
296     SSLSrvConfigRec *sc = mySrvConfig(c->base_server);
297
298     SSLConnRec *sslconn = ssl_init_connection_ctx(c);
299
300     if (!sc->proxy_enabled) {
301         ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c,
302                       "SSL Proxy requested for %s but not enabled "
303                       "[Hint: SSLProxyEngine]", sc->vhost_id);
304
305         return 0;
306     }
307
308     sslconn->is_proxy = 1;
309     sslconn->disabled = 0;
310
311     return 1;
312 }
313
314 int ssl_engine_disable(conn_rec *c)
315 {
316     SSLSrvConfigRec *sc = mySrvConfig(c->base_server);
317
318     SSLConnRec *sslconn;
319
320     if (sc->enabled == SSL_ENABLED_FALSE) {
321         return 0;
322     }
323
324     sslconn = ssl_init_connection_ctx(c);
325
326     sslconn->disabled = 1;
327
328     return 1;
329 }
330
331 int ssl_init_ssl_connection(conn_rec *c)
332 {
333     SSLSrvConfigRec *sc = mySrvConfig(c->base_server);
334     SSL *ssl;
335     SSLConnRec *sslconn = myConnConfig(c);
336     char *vhost_md5;
337     modssl_ctx_t *mctx;
338
339     /*
340      * Seed the Pseudo Random Number Generator (PRNG)
341      */
342     ssl_rand_seed(c->base_server, c->pool, SSL_RSCTX_CONNECT, "");
343
344     if (!sslconn) {
345         sslconn = ssl_init_connection_ctx(c);
346     }
347
348     mctx = sslconn->is_proxy ? sc->proxy : sc->server;
349
350     /*
351      * Create a new SSL connection with the configured server SSL context and
352      * attach this to the socket. Additionally we register this attachment
353      * so we can detach later.
354      */
355     if (!(ssl = SSL_new(mctx->ssl_ctx))) {
356         ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c,
357                       "Unable to create a new SSL connection from the SSL "
358                       "context");
359         ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, c->base_server);
360
361         c->aborted = 1;
362
363         return DECLINED; /* XXX */
364     }
365
366     vhost_md5 = ap_md5_binary(c->pool, (unsigned char *)sc->vhost_id,
367                               sc->vhost_id_len);
368
369     if (!SSL_set_session_id_context(ssl, (unsigned char *)vhost_md5,
370                                     APR_MD5_DIGESTSIZE*2))
371     {
372         ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c,
373                       "Unable to set session id context to `%s'", vhost_md5);
374         ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, c->base_server);
375
376         c->aborted = 1;
377
378         return DECLINED; /* XXX */
379     }
380
381     SSL_set_app_data(ssl, c);
382     SSL_set_app_data2(ssl, NULL); /* will be request_rec */
383
384     sslconn->ssl = ssl;
385
386     /*
387      *  Configure callbacks for SSL connection
388      */
389     SSL_set_tmp_rsa_callback(ssl, ssl_callback_TmpRSA);
390     SSL_set_tmp_dh_callback(ssl,  ssl_callback_TmpDH);
391
392     SSL_set_verify_result(ssl, X509_V_OK);
393
394     ssl_io_filter_init(c, ssl);
395
396     return APR_SUCCESS;
397 }
398
399 static const char *ssl_hook_http_scheme(const request_rec *r)
400 {
401     SSLSrvConfigRec *sc = mySrvConfig(r->server);
402
403     if (sc->enabled == SSL_ENABLED_FALSE || sc->enabled == SSL_ENABLED_OPTIONAL) {
404         return NULL;
405     }
406
407     return "https";
408 }
409
410 static apr_port_t ssl_hook_default_port(const request_rec *r)
411 {
412     SSLSrvConfigRec *sc = mySrvConfig(r->server);
413
414     if (sc->enabled == SSL_ENABLED_FALSE || sc->enabled == SSL_ENABLED_OPTIONAL) {
415         return 0;
416     }
417
418     return 443;
419 }
420
421 static int ssl_hook_pre_connection(conn_rec *c, void *csd)
422 {
423     SSLSrvConfigRec *sc = mySrvConfig(c->base_server);
424     SSLConnRec *sslconn = myConnConfig(c);
425
426     /*
427      * Immediately stop processing if SSL is disabled for this connection
428      */
429     if (!(sc && (sc->enabled == SSL_ENABLED_TRUE ||
430                  (sslconn && sslconn->is_proxy))))
431     {
432         return DECLINED;
433     }
434
435     /*
436      * Create SSL context
437      */
438     if (!sslconn) {
439         sslconn = ssl_init_connection_ctx(c);
440     }
441
442     if (sslconn->disabled) {
443         return DECLINED;
444     }
445
446     /*
447      * Remember the connection information for
448      * later access inside callback functions
449      */
450
451     ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c,
452                   "Connection to child %ld established "
453                   "(server %s)", c->id, sc->vhost_id);
454
455     return ssl_init_ssl_connection(c);
456 }
457
458
459 static void ssl_hook_Insert_Filter(request_rec *r)
460 {
461     SSLSrvConfigRec *sc = mySrvConfig(r->server);
462
463     if (sc->enabled == SSL_ENABLED_OPTIONAL) {
464         ap_add_output_filter("UPGRADE_FILTER", NULL, r, r->connection);
465     }
466 }
467
468 /*
469  *  the module registration phase
470  */
471
472 static void ssl_register_hooks(apr_pool_t *p)
473 {
474     ssl_io_filter_register(p);
475
476     ap_hook_pre_connection(ssl_hook_pre_connection,NULL,NULL, APR_HOOK_MIDDLE);
477     ap_hook_test_config   (ssl_hook_ConfigTest,    NULL,NULL, APR_HOOK_MIDDLE);
478     ap_hook_post_config   (ssl_init_Module,        NULL,NULL, APR_HOOK_MIDDLE);
479     ap_hook_http_scheme   (ssl_hook_http_scheme,   NULL,NULL, APR_HOOK_MIDDLE);
480     ap_hook_default_port  (ssl_hook_default_port,  NULL,NULL, APR_HOOK_MIDDLE);
481     ap_hook_pre_config    (ssl_hook_pre_config,    NULL,NULL, APR_HOOK_MIDDLE);
482     ap_hook_child_init    (ssl_init_Child,         NULL,NULL, APR_HOOK_MIDDLE);
483     ap_hook_translate_name(ssl_hook_Translate,     NULL,NULL, APR_HOOK_MIDDLE);
484     ap_hook_check_user_id (ssl_hook_UserCheck,     NULL,NULL, APR_HOOK_FIRST);
485     ap_hook_fixups        (ssl_hook_Fixup,         NULL,NULL, APR_HOOK_MIDDLE);
486     ap_hook_access_checker(ssl_hook_Access,        NULL,NULL, APR_HOOK_MIDDLE);
487     ap_hook_auth_checker  (ssl_hook_Auth,          NULL,NULL, APR_HOOK_MIDDLE);
488     ap_hook_post_read_request(ssl_hook_ReadReq,    NULL,NULL, APR_HOOK_MIDDLE);
489     ap_hook_insert_filter (ssl_hook_Insert_Filter, NULL,NULL, APR_HOOK_MIDDLE);
490 /*    ap_hook_handler       (ssl_hook_Upgrade,       NULL,NULL, APR_HOOK_MIDDLE); */
491
492     ssl_var_register();
493
494     APR_REGISTER_OPTIONAL_FN(ssl_proxy_enable);
495     APR_REGISTER_OPTIONAL_FN(ssl_engine_disable);
496 }
497
498 module AP_MODULE_DECLARE_DATA ssl_module = {
499     STANDARD20_MODULE_STUFF,
500     ssl_config_perdir_create,   /* create per-dir    config structures */
501     ssl_config_perdir_merge,    /* merge  per-dir    config structures */
502     ssl_config_server_create,   /* create per-server config structures */
503     ssl_config_server_merge,    /* merge  per-server config structures */
504     ssl_config_cmds,            /* table of configuration directives   */
505     ssl_register_hooks          /* register hooks */
506 };