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