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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * _ __ ___ ___ __| | ___ ___| | mod_ssl
19 * | '_ ` _ \ / _ \ / _` | / __/ __| | Apache Interface to OpenSSL
20 * | | | | | | (_) | (_| | \__ \__ \ |
21 * |_| |_| |_|\___/ \__,_|___|___/___/_|
24 * Apache API interface structures
27 #include "ssl_private.h"
30 #include "util_mutex.h"
31 #include "ap_provider.h"
36 * the table of configuration directives we provide
39 #define SSL_CMD_ALL(name, args, desc) \
40 AP_INIT_##args("SSL"#name, ssl_cmd_SSL##name, \
41 NULL, RSRC_CONF|OR_AUTHCFG, desc),
43 #define SSL_CMD_SRV(name, args, desc) \
44 AP_INIT_##args("SSL"#name, ssl_cmd_SSL##name, \
45 NULL, RSRC_CONF, desc),
47 #define SSL_CMD_DIR(name, type, args, desc) \
48 AP_INIT_##args("SSL"#name, ssl_cmd_SSL##name, \
49 NULL, OR_##type, desc),
51 #define AP_END_CMD { NULL }
53 static const command_rec ssl_config_cmds[] = {
55 * Global (main-server) context configuration directives
57 SSL_CMD_SRV(PassPhraseDialog, TAKE1,
58 "SSL dialog mechanism for the pass phrase query "
59 "('builtin', '|/path/to/pipe_program', "
60 "or 'exec:/path/to/cgi_program')")
61 SSL_CMD_SRV(SessionCache, TAKE1,
62 "SSL Session Cache storage "
63 "('none', 'nonenotnull', 'dbm:/path/to/file')")
64 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
65 SSL_CMD_SRV(CryptoDevice, TAKE1,
66 "SSL external Crypto Device usage "
69 SSL_CMD_SRV(RandomSeed, TAKE23,
70 "SSL Pseudo Random Number Generator (PRNG) seeding source "
71 "('startup|connect builtin|file:/path|exec:/path [bytes]')")
74 * Per-server context configuration directives
76 SSL_CMD_SRV(Engine, TAKE1,
77 "SSL switch for the protocol engine "
79 SSL_CMD_ALL(CipherSuite, TAKE1,
80 "Colon-delimited list of permitted SSL Ciphers "
81 "('XXX:...:XXX' - see manual)")
82 SSL_CMD_SRV(CertificateFile, TAKE1,
83 "SSL Server Certificate file "
84 "('/path/to/file' - PEM or DER encoded)")
85 SSL_CMD_SRV(CertificateKeyFile, TAKE1,
86 "SSL Server Private Key file "
87 "('/path/to/file' - PEM or DER encoded)")
88 SSL_CMD_SRV(CertificateChainFile, TAKE1,
89 "SSL Server CA Certificate Chain file "
90 "('/path/to/file' - PEM encoded)")
91 SSL_CMD_SRV(PKCS7CertificateFile, TAKE1,
92 "PKCS#7 file containing server certificate and chain"
93 " certificates ('/path/to/file' - PEM encoded)")
94 SSL_CMD_ALL(CACertificatePath, TAKE1,
95 "SSL CA Certificate path "
96 "('/path/to/dir' - contains PEM encoded files)")
97 SSL_CMD_ALL(CACertificateFile, TAKE1,
98 "SSL CA Certificate file "
99 "('/path/to/file' - PEM encoded)")
100 SSL_CMD_SRV(CADNRequestPath, TAKE1,
101 "SSL CA Distinguished Name path "
102 "('/path/to/dir' - symlink hashes to PEM of acceptable CA names to request)")
103 SSL_CMD_SRV(CADNRequestFile, TAKE1,
104 "SSL CA Distinguished Name file "
105 "('/path/to/file' - PEM encoded to derive acceptable CA names to request)")
106 SSL_CMD_SRV(CARevocationPath, TAKE1,
107 "SSL CA Certificate Revocation List (CRL) path "
108 "('/path/to/dir' - contains PEM encoded files)")
109 SSL_CMD_SRV(CARevocationFile, TAKE1,
110 "SSL CA Certificate Revocation List (CRL) file "
111 "('/path/to/file' - PEM encoded)")
112 SSL_CMD_ALL(VerifyClient, TAKE1,
113 "SSL Client verify type "
114 "('none', 'optional', 'require', 'optional_no_ca')")
115 SSL_CMD_ALL(VerifyDepth, TAKE1,
116 "SSL Client verify depth "
117 "('N' - number of intermediate certificates)")
118 SSL_CMD_SRV(SessionCacheTimeout, TAKE1,
119 "SSL Session Cache object lifetime "
120 "('N' - number of seconds)")
121 SSL_CMD_SRV(Protocol, RAW_ARGS,
122 "Enable or disable various SSL protocols"
123 "('[+-][SSLv2|SSLv3|TLSv1] ...' - see manual)")
124 SSL_CMD_SRV(HonorCipherOrder, FLAG,
125 "Use the server's cipher ordering preference")
126 SSL_CMD_ALL(UserName, TAKE1,
127 "Set user name to SSL variable value")
128 SSL_CMD_SRV(LogLevelDebugDump, TAKE1,
129 "Include I/O Dump when LogLevel is set to Debug "
130 "([ None (default) | IO (not bytes) | Bytes ])")
131 SSL_CMD_SRV(StrictSNIVHostCheck, FLAG,
132 "Strict SNI virtual host checking")
135 * Proxy configuration for remote SSL connections
137 SSL_CMD_SRV(ProxyEngine, FLAG,
138 "SSL switch for the proxy protocol engine "
140 SSL_CMD_SRV(ProxyProtocol, RAW_ARGS,
141 "SSL Proxy: enable or disable SSL protocol flavors "
142 "('[+-][SSLv2|SSLv3|TLSv1] ...' - see manual)")
143 SSL_CMD_SRV(ProxyCipherSuite, TAKE1,
144 "SSL Proxy: colon-delimited list of permitted SSL ciphers "
145 "('XXX:...:XXX' - see manual)")
146 SSL_CMD_SRV(ProxyVerify, TAKE1,
147 "SSL Proxy: whether to verify the remote certificate "
149 SSL_CMD_SRV(ProxyVerifyDepth, TAKE1,
150 "SSL Proxy: maximum certificate verification depth "
151 "('N' - number of intermediate certificates)")
152 SSL_CMD_SRV(ProxyCACertificateFile, TAKE1,
153 "SSL Proxy: file containing server certificates "
154 "('/path/to/file' - PEM encoded certificates)")
155 SSL_CMD_SRV(ProxyCACertificatePath, TAKE1,
156 "SSL Proxy: directory containing server certificates "
157 "('/path/to/dir' - contains PEM encoded certificates)")
158 SSL_CMD_SRV(ProxyCARevocationPath, TAKE1,
159 "SSL Proxy: CA Certificate Revocation List (CRL) path "
160 "('/path/to/dir' - contains PEM encoded files)")
161 SSL_CMD_SRV(ProxyCARevocationFile, TAKE1,
162 "SSL Proxy: CA Certificate Revocation List (CRL) file "
163 "('/path/to/file' - PEM encoded)")
164 SSL_CMD_SRV(ProxyMachineCertificateFile, TAKE1,
165 "SSL Proxy: file containing client certificates "
166 "('/path/to/file' - PEM encoded certificates)")
167 SSL_CMD_SRV(ProxyMachineCertificatePath, TAKE1,
168 "SSL Proxy: directory containing client certificates "
169 "('/path/to/dir' - contains PEM encoded certificates)")
170 SSL_CMD_SRV(ProxyCheckPeerExpire, FLAG,
171 "SSL Proxy: check the peers certificate expiration date")
172 SSL_CMD_SRV(ProxyCheckPeerCN, FLAG,
173 "SSL Proxy: check the peers certificate CN")
176 * Per-directory context configuration directives
178 SSL_CMD_DIR(Options, OPTIONS, RAW_ARGS,
179 "Set one or more options to configure the SSL engine"
180 "('[+-]option[=value] ...' - see manual)")
181 SSL_CMD_DIR(RequireSSL, AUTHCFG, NO_ARGS,
182 "Require the SSL protocol for the per-directory context "
184 SSL_CMD_DIR(Require, AUTHCFG, RAW_ARGS,
185 "Require a boolean expression to evaluate to true for granting access"
186 "(arbitrary complex boolean expression - see manual)")
187 SSL_CMD_DIR(RenegBufferSize, AUTHCFG, TAKE1,
188 "Configure the amount of memory that will be used for buffering the "
189 "request body if a per-location SSL renegotiation is required due to "
190 "changed access control requirements")
192 SSL_CMD_SRV(OCSPEnable, FLAG,
193 "Enable use of OCSP to verify certificate revocation ('on', 'off')")
194 SSL_CMD_SRV(OCSPDefaultResponder, TAKE1,
195 "URL of the default OCSP Responder")
196 SSL_CMD_SRV(OCSPOverrideResponder, FLAG,
197 "Force use of the default responder URL ('on', 'off')")
199 #ifdef HAVE_OCSP_STAPLING
201 * OCSP Stapling options
203 SSL_CMD_SRV(StaplingCache, TAKE1,
204 "SSL Stapling Response Cache storage "
205 "(`dbm:/path/to/file')")
206 SSL_CMD_SRV(UseStapling, FLAG,
207 "SSL switch for the OCSP Stapling protocol " "(`on', `off')")
208 SSL_CMD_SRV(StaplingResponseTimeSkew, TAKE1,
209 "SSL stapling option for maximum time difference in OCSP responses")
210 SSL_CMD_SRV(StaplingResponderTimeout, TAKE1,
211 "SSL stapling option for OCSP responder timeout")
212 SSL_CMD_SRV(StaplingResponseMaxAge, TAKE1,
213 "SSL stapling option for maximum age of OCSP responses")
214 SSL_CMD_SRV(StaplingStandardCacheTimeout, TAKE1,
215 "SSL stapling option for normal OCSP Response Cache Lifetime")
216 SSL_CMD_SRV(StaplingReturnResponderErrors, FLAG,
217 "SSL stapling switch to return Status Errors Back to Client"
219 SSL_CMD_SRV(StaplingFakeTryLater, FLAG,
220 "SSL stapling switch to send tryLater response to client on error "
222 SSL_CMD_SRV(StaplingErrorCacheTimeout, TAKE1,
223 "SSL stapling option for OCSP Response Error Cache Lifetime")
224 SSL_CMD_SRV(StaplingForceURL, TAKE1,
225 "SSL stapling option to Force the OCSP Stapling URL")
228 /* Deprecated directives. */
229 AP_INIT_RAW_ARGS("SSLLog", ap_set_deprecated, NULL, OR_ALL,
230 "SSLLog directive is no longer supported - use ErrorLog."),
231 AP_INIT_RAW_ARGS("SSLLogLevel", ap_set_deprecated, NULL, OR_ALL,
232 "SSLLogLevel directive is no longer supported - use LogLevel."),
238 * the various processing hooks
240 static apr_status_t ssl_cleanup_pre_config(void *data)
243 * Try to kill the internals of the SSL library.
246 #if OPENSSL_VERSION_NUMBER >= 0x00907001
247 /* Corresponds to OPENSSL_load_builtin_modules():
248 * XXX: borrowed from apps.h, but why not CONF_modules_free()
249 * which also invokes CONF_modules_finish()?
251 CONF_modules_unload(1);
254 /* Corresponds to SSL_library_init: */
256 #if HAVE_ENGINE_LOAD_BUILTIN_ENGINES
261 /* Don't call ERR_free_strings here; ERR_load_*_strings only
262 * actually load the error strings once per process due to static
263 * variable abuse in OpenSSL. */
265 /* Also don't call CRYPTO_cleanup_all_ex_data here; any registered
266 * ex_data indices may have been cached in static variables in
267 * OpenSSL; removing them may cause havoc. Notably, with OpenSSL
268 * versions >= 0.9.8f, COMP_CTX cleanups would not be run, which
269 * could result in a per-connection memory leak (!). */
272 * TODO: determine somewhere we can safely shove out diagnostics
273 * (when enabled) at this late stage in the game:
274 * CRYPTO_mem_leaks_fp(stderr);
279 static int ssl_hook_pre_config(apr_pool_t *pconf,
283 /* We must register the library in full, to ensure our configuration
284 * code can successfully test the SSL environment.
286 CRYPTO_malloc_init();
288 ERR_load_crypto_strings();
290 SSL_load_error_strings();
292 #if HAVE_ENGINE_LOAD_BUILTIN_ENGINES
293 ENGINE_load_builtin_engines();
296 OpenSSL_add_all_algorithms();
297 #if OPENSSL_VERSION_NUMBER >= 0x00907001
298 OPENSSL_load_builtin_modules();
303 * Let us cleanup the ssl library when the module is unloaded
305 apr_pool_cleanup_register(pconf, NULL, ssl_cleanup_pre_config,
306 apr_pool_cleanup_null);
308 /* Register us to handle mod_log_config %c/%x variables */
309 ssl_var_log_config_register(pconf);
311 /* Register to handle mod_status status page generation */
312 ssl_scache_status_register(pconf);
314 /* Register mutex type names so they can be configured with Mutex */
315 ap_mutex_register(pconf, ssl_cache_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
316 #ifdef HAVE_OCSP_STAPLING
317 ap_mutex_register(pconf, ssl_stapling_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
323 static SSLConnRec *ssl_init_connection_ctx(conn_rec *c)
325 SSLConnRec *sslconn = myConnConfig(c);
331 sslconn = apr_pcalloc(c->pool, sizeof(*sslconn));
333 sslconn->server = c->base_server;
335 myConnConfigSet(c, sslconn);
340 int ssl_proxy_enable(conn_rec *c)
344 SSLConnRec *sslconn = ssl_init_connection_ctx(c);
345 sc = mySrvConfig(sslconn->server);
347 if (!sc->proxy_enabled) {
348 ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c,
349 "SSL Proxy requested for %s but not enabled "
350 "[Hint: SSLProxyEngine]", sc->vhost_id);
355 sslconn->is_proxy = 1;
356 sslconn->disabled = 0;
361 int ssl_engine_disable(conn_rec *c)
365 SSLConnRec *sslconn = myConnConfig(c);
368 sc = mySrvConfig(sslconn->server);
371 sc = mySrvConfig(c->base_server);
373 if (sc->enabled == SSL_ENABLED_FALSE) {
377 sslconn = ssl_init_connection_ctx(c);
379 sslconn->disabled = 1;
384 int ssl_init_ssl_connection(conn_rec *c, request_rec *r)
388 SSLConnRec *sslconn = myConnConfig(c);
394 sslconn = ssl_init_connection_ctx(c);
396 server = sslconn->server;
397 sc = mySrvConfig(server);
400 * Seed the Pseudo Random Number Generator (PRNG)
402 ssl_rand_seed(server, c->pool, SSL_RSCTX_CONNECT, "");
404 mctx = sslconn->is_proxy ? sc->proxy : sc->server;
407 * Create a new SSL connection with the configured server SSL context and
408 * attach this to the socket. Additionally we register this attachment
409 * so we can detach later.
411 if (!(ssl = SSL_new(mctx->ssl_ctx))) {
412 ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c,
413 "Unable to create a new SSL connection from the SSL "
415 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, server);
419 return DECLINED; /* XXX */
422 vhost_md5 = ap_md5_binary(c->pool, (unsigned char *)sc->vhost_id,
425 if (!SSL_set_session_id_context(ssl, (unsigned char *)vhost_md5,
426 APR_MD5_DIGESTSIZE*2))
428 ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c,
429 "Unable to set session id context to '%s'", vhost_md5);
430 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, server);
434 return DECLINED; /* XXX */
437 SSL_set_app_data(ssl, c);
438 SSL_set_app_data2(ssl, NULL); /* will be request_rec */
443 * Configure callbacks for SSL connection
445 SSL_set_tmp_rsa_callback(ssl, ssl_callback_TmpRSA);
446 SSL_set_tmp_dh_callback(ssl, ssl_callback_TmpDH);
447 #ifndef OPENSSL_NO_EC
448 SSL_set_tmp_ecdh_callback(ssl, ssl_callback_TmpECDH);
451 SSL_set_verify_result(ssl, X509_V_OK);
453 ssl_io_filter_init(c, r, ssl);
458 static const char *ssl_hook_http_scheme(const request_rec *r)
460 SSLSrvConfigRec *sc = mySrvConfig(r->server);
462 if (sc->enabled == SSL_ENABLED_FALSE || sc->enabled == SSL_ENABLED_OPTIONAL) {
469 static apr_port_t ssl_hook_default_port(const request_rec *r)
471 SSLSrvConfigRec *sc = mySrvConfig(r->server);
473 if (sc->enabled == SSL_ENABLED_FALSE || sc->enabled == SSL_ENABLED_OPTIONAL) {
480 static int ssl_hook_pre_connection(conn_rec *c, void *csd)
483 SSLConnRec *sslconn = myConnConfig(c);
486 sc = mySrvConfig(sslconn->server);
489 sc = mySrvConfig(c->base_server);
492 * Immediately stop processing if SSL is disabled for this connection
494 if (!(sc && (sc->enabled == SSL_ENABLED_TRUE ||
495 (sslconn && sslconn->is_proxy))))
504 sslconn = ssl_init_connection_ctx(c);
507 if (sslconn->disabled) {
512 * Remember the connection information for
513 * later access inside callback functions
516 ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c,
517 "Connection to child %ld established "
518 "(server %s)", c->id, sc->vhost_id);
520 return ssl_init_ssl_connection(c, NULL);
524 * the module registration phase
527 static void ssl_register_hooks(apr_pool_t *p)
529 /* ssl_hook_ReadReq needs to use the BrowserMatch settings so must
530 * run after mod_setenvif's post_read_request hook. */
531 static const char *pre_prr[] = { "mod_setenvif.c", NULL };
533 ssl_io_filter_register(p);
535 ap_hook_pre_connection(ssl_hook_pre_connection,NULL,NULL, APR_HOOK_MIDDLE);
536 ap_hook_test_config (ssl_hook_ConfigTest, NULL,NULL, APR_HOOK_MIDDLE);
537 ap_hook_post_config (ssl_init_Module, NULL,NULL, APR_HOOK_MIDDLE);
538 ap_hook_http_scheme (ssl_hook_http_scheme, NULL,NULL, APR_HOOK_MIDDLE);
539 ap_hook_default_port (ssl_hook_default_port, NULL,NULL, APR_HOOK_MIDDLE);
540 ap_hook_pre_config (ssl_hook_pre_config, NULL,NULL, APR_HOOK_MIDDLE);
541 ap_hook_child_init (ssl_init_Child, NULL,NULL, APR_HOOK_MIDDLE);
542 ap_hook_check_authn (ssl_hook_UserCheck, NULL,NULL, APR_HOOK_FIRST,
543 AP_AUTH_INTERNAL_PER_CONF);
544 ap_hook_fixups (ssl_hook_Fixup, NULL,NULL, APR_HOOK_MIDDLE);
545 ap_hook_check_access (ssl_hook_Access, NULL,NULL, APR_HOOK_MIDDLE,
546 AP_AUTH_INTERNAL_PER_CONF);
547 ap_hook_check_authz (ssl_hook_Auth, NULL,NULL, APR_HOOK_MIDDLE,
548 AP_AUTH_INTERNAL_PER_CONF);
549 ap_hook_post_read_request(ssl_hook_ReadReq, pre_prr,NULL, APR_HOOK_MIDDLE);
553 APR_REGISTER_OPTIONAL_FN(ssl_proxy_enable);
554 APR_REGISTER_OPTIONAL_FN(ssl_engine_disable);
557 module AP_MODULE_DECLARE_DATA ssl_module = {
558 STANDARD20_MODULE_STUFF,
559 ssl_config_perdir_create, /* create per-dir config structures */
560 ssl_config_perdir_merge, /* merge per-dir config structures */
561 ssl_config_server_create, /* create per-server config structures */
562 ssl_config_server_merge, /* merge per-server config structures */
563 ssl_config_cmds, /* table of configuration directives */
564 ssl_register_hooks /* register hooks */