]> granicus.if.org Git - apache/blob - modules/ssl/mod_ssl.c
Better illustrate the ordering of hook processing
[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 "mod_ssl_openssl.h"
30 #include "util_md5.h"
31 #include "util_mutex.h"
32 #include "ap_provider.h"
33
34 #include <assert.h>
35
36 #if HAVE_VALGRIND
37 #include <valgrind.h>
38 int ssl_running_on_valgrind = 0;
39 #endif
40
41 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ssl, SSL, int, pre_handshake,
42                                     (conn_rec *c,SSL *ssl,int is_proxy),
43                                     (c,ssl,is_proxy), OK, DECLINED);
44
45 /*
46  *  the table of configuration directives we provide
47  */
48
49 #define SSL_CMD_ALL(name, args, desc) \
50         AP_INIT_##args("SSL"#name, ssl_cmd_SSL##name, \
51                        NULL, RSRC_CONF|OR_AUTHCFG, desc),
52
53 #define SSL_CMD_SRV(name, args, desc) \
54         AP_INIT_##args("SSL"#name, ssl_cmd_SSL##name, \
55                        NULL, RSRC_CONF, desc),
56
57 #define SSL_CMD_DIR(name, type, args, desc) \
58         AP_INIT_##args("SSL"#name, ssl_cmd_SSL##name, \
59                        NULL, OR_##type, desc),
60
61 #define AP_END_CMD { NULL }
62
63 static const command_rec ssl_config_cmds[] = {
64     /*
65      * Global (main-server) context configuration directives
66      */
67     SSL_CMD_SRV(PassPhraseDialog, TAKE1,
68                 "SSL dialog mechanism for the pass phrase query "
69                 "('builtin', '|/path/to/pipe_program', "
70                 "or 'exec:/path/to/cgi_program')")
71     SSL_CMD_SRV(SessionCache, TAKE1,
72                 "SSL Session Cache storage "
73                 "('none', 'nonenotnull', 'dbm:/path/to/file')")
74 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
75     SSL_CMD_SRV(CryptoDevice, TAKE1,
76                 "SSL external Crypto Device usage "
77                 "('builtin', '...')")
78 #endif
79     SSL_CMD_SRV(RandomSeed, TAKE23,
80                 "SSL Pseudo Random Number Generator (PRNG) seeding source "
81                 "('startup|connect builtin|file:/path|exec:/path [bytes]')")
82
83     /*
84      * Per-server context configuration directives
85      */
86     SSL_CMD_SRV(Engine, TAKE1,
87                 "SSL switch for the protocol engine "
88                 "('on', 'off')")
89     SSL_CMD_SRV(FIPS, FLAG,
90                 "Enable FIPS-140 mode "
91                 "(`on', `off')")
92     SSL_CMD_ALL(CipherSuite, TAKE1,
93                 "Colon-delimited list of permitted SSL Ciphers "
94                 "('XXX:...:XXX' - see manual)")
95     SSL_CMD_SRV(CertificateFile, TAKE1,
96                 "SSL Server Certificate file "
97                 "('/path/to/file' - PEM or DER encoded)")
98     SSL_CMD_SRV(CertificateKeyFile, TAKE1,
99                 "SSL Server Private Key file "
100                 "('/path/to/file' - PEM or DER encoded)")
101     SSL_CMD_SRV(CertificateChainFile, TAKE1,
102                 "SSL Server CA Certificate Chain file "
103                 "('/path/to/file' - PEM encoded)")
104 #ifdef HAVE_TLS_SESSION_TICKETS
105     SSL_CMD_SRV(SessionTicketKeyFile, TAKE1,
106                 "TLS session ticket encryption/decryption key file (RFC 5077) "
107                 "('/path/to/file' - file with 48 bytes of random data)")
108 #endif
109     SSL_CMD_ALL(CACertificatePath, TAKE1,
110                 "SSL CA Certificate path "
111                 "('/path/to/dir' - contains PEM encoded files)")
112     SSL_CMD_ALL(CACertificateFile, TAKE1,
113                 "SSL CA Certificate file "
114                 "('/path/to/file' - PEM encoded)")
115     SSL_CMD_SRV(CADNRequestPath, TAKE1,
116                 "SSL CA Distinguished Name path "
117                 "('/path/to/dir' - symlink hashes to PEM of acceptable CA names to request)")
118     SSL_CMD_SRV(CADNRequestFile, TAKE1,
119                 "SSL CA Distinguished Name file "
120                 "('/path/to/file' - PEM encoded to derive acceptable CA names to request)")
121     SSL_CMD_SRV(CARevocationPath, TAKE1,
122                 "SSL CA Certificate Revocation List (CRL) path "
123                 "('/path/to/dir' - contains PEM encoded files)")
124     SSL_CMD_SRV(CARevocationFile, TAKE1,
125                 "SSL CA Certificate Revocation List (CRL) file "
126                 "('/path/to/file' - PEM encoded)")
127     SSL_CMD_SRV(CARevocationCheck, TAKE1,
128                 "SSL CA Certificate Revocation List (CRL) checking mode")
129     SSL_CMD_ALL(VerifyClient, TAKE1,
130                 "SSL Client verify type "
131                 "('none', 'optional', 'require', 'optional_no_ca')")
132     SSL_CMD_ALL(VerifyDepth, TAKE1,
133                 "SSL Client verify depth "
134                 "('N' - number of intermediate certificates)")
135     SSL_CMD_SRV(SessionCacheTimeout, TAKE1,
136                 "SSL Session Cache object lifetime "
137                 "('N' - number of seconds)")
138 #ifdef OPENSSL_NO_SSL3
139 #define SSLv3_PROTO_PREFIX ""
140 #else
141 #define SSLv3_PROTO_PREFIX "SSLv3|"
142 #endif
143 #ifdef HAVE_TLSV1_X
144 #define SSL_PROTOCOLS SSLv3_PROTO_PREFIX "TLSv1|TLSv1.1|TLSv1.2"
145 #else
146 #define SSL_PROTOCOLS SSLv3_PROTO_PREFIX "TLSv1"
147 #endif
148     SSL_CMD_SRV(Protocol, RAW_ARGS,
149                 "Enable or disable various SSL protocols "
150                 "('[+-][" SSL_PROTOCOLS "] ...' - see manual)")
151     SSL_CMD_SRV(HonorCipherOrder, FLAG,
152                 "Use the server's cipher ordering preference")
153     SSL_CMD_SRV(Compression, FLAG,
154                 "Enable SSL level compression "
155                 "(`on', `off')")
156     SSL_CMD_SRV(SessionTickets, FLAG,
157                 "Enable or disable TLS session tickets"
158                 "(`on', `off')")
159     SSL_CMD_SRV(InsecureRenegotiation, FLAG,
160                 "Enable support for insecure renegotiation")
161     SSL_CMD_ALL(UserName, TAKE1,
162                 "Set user name to SSL variable value")
163     SSL_CMD_SRV(StrictSNIVHostCheck, FLAG,
164                 "Strict SNI virtual host checking")
165
166 #ifdef HAVE_SRP
167     SSL_CMD_SRV(SRPVerifierFile, TAKE1,
168                 "SRP verifier file "
169                 "('/path/to/file' - created by srptool)")
170     SSL_CMD_SRV(SRPUnknownUserSeed, TAKE1,
171                 "SRP seed for unknown users (to avoid leaking a user's existence) "
172                 "('some secret text')")
173 #endif
174
175     /*
176      * Proxy configuration for remote SSL connections
177      */
178     SSL_CMD_SRV(ProxyEngine, FLAG,
179                 "SSL switch for the proxy protocol engine "
180                 "('on', 'off')")
181     SSL_CMD_SRV(ProxyProtocol, RAW_ARGS,
182                "SSL Proxy: enable or disable SSL protocol flavors "
183                 "('[+-][" SSL_PROTOCOLS "] ...' - see manual)")
184     SSL_CMD_SRV(ProxyCipherSuite, TAKE1,
185                "SSL Proxy: colon-delimited list of permitted SSL ciphers "
186                "('XXX:...:XXX' - see manual)")
187     SSL_CMD_SRV(ProxyVerify, TAKE1,
188                "SSL Proxy: whether to verify the remote certificate "
189                "('on' or 'off')")
190     SSL_CMD_SRV(ProxyVerifyDepth, TAKE1,
191                "SSL Proxy: maximum certificate verification depth "
192                "('N' - number of intermediate certificates)")
193     SSL_CMD_SRV(ProxyCACertificateFile, TAKE1,
194                "SSL Proxy: file containing server certificates "
195                "('/path/to/file' - PEM encoded certificates)")
196     SSL_CMD_SRV(ProxyCACertificatePath, TAKE1,
197                "SSL Proxy: directory containing server certificates "
198                "('/path/to/dir' - contains PEM encoded certificates)")
199     SSL_CMD_SRV(ProxyCARevocationPath, TAKE1,
200                 "SSL Proxy: CA Certificate Revocation List (CRL) path "
201                 "('/path/to/dir' - contains PEM encoded files)")
202     SSL_CMD_SRV(ProxyCARevocationFile, TAKE1,
203                 "SSL Proxy: CA Certificate Revocation List (CRL) file "
204                 "('/path/to/file' - PEM encoded)")
205     SSL_CMD_SRV(ProxyCARevocationCheck, TAKE1,
206                 "SSL Proxy: CA Certificate Revocation List (CRL) checking mode")
207     SSL_CMD_SRV(ProxyMachineCertificateFile, TAKE1,
208                "SSL Proxy: file containing client certificates "
209                "('/path/to/file' - PEM encoded certificates)")
210     SSL_CMD_SRV(ProxyMachineCertificatePath, TAKE1,
211                "SSL Proxy: directory containing client certificates "
212                "('/path/to/dir' - contains PEM encoded certificates)")
213     SSL_CMD_SRV(ProxyMachineCertificateChainFile, TAKE1,
214                "SSL Proxy: file containing issuing certificates "
215                "of the client certificate "
216                "(`/path/to/file' - PEM encoded certificates)")
217     SSL_CMD_SRV(ProxyCheckPeerExpire, FLAG,
218                 "SSL Proxy: check the peer certificate's expiration date")
219     SSL_CMD_SRV(ProxyCheckPeerCN, FLAG,
220                 "SSL Proxy: check the peer certificate's CN")
221     SSL_CMD_SRV(ProxyCheckPeerName, FLAG,
222                 "SSL Proxy: check the peer certificate's name "
223                 "(must be present in subjectAltName extension or CN")
224
225     /*
226      * Per-directory context configuration directives
227      */
228     SSL_CMD_DIR(Options, OPTIONS, RAW_ARGS,
229                "Set one or more options to configure the SSL engine"
230                "('[+-]option[=value] ...' - see manual)")
231     SSL_CMD_DIR(RequireSSL, AUTHCFG, NO_ARGS,
232                "Require the SSL protocol for the per-directory context "
233                "(no arguments)")
234     SSL_CMD_DIR(Require, AUTHCFG, RAW_ARGS,
235                "Require a boolean expression to evaluate to true for granting access"
236                "(arbitrary complex boolean expression - see manual)")
237     SSL_CMD_DIR(RenegBufferSize, AUTHCFG, TAKE1,
238                 "Configure the amount of memory that will be used for buffering the "
239                 "request body if a per-location SSL renegotiation is required due to "
240                 "changed access control requirements")
241
242     SSL_CMD_SRV(OCSPEnable, FLAG,
243                "Enable use of OCSP to verify certificate revocation ('on', 'off')")
244     SSL_CMD_SRV(OCSPDefaultResponder, TAKE1,
245                "URL of the default OCSP Responder")
246     SSL_CMD_SRV(OCSPOverrideResponder, FLAG,
247                "Force use of the default responder URL ('on', 'off')")
248     SSL_CMD_SRV(OCSPResponseTimeSkew, TAKE1,
249                 "Maximum time difference in OCSP responses")
250     SSL_CMD_SRV(OCSPResponseMaxAge, TAKE1,
251                 "Maximum age of OCSP responses")
252     SSL_CMD_SRV(OCSPResponderTimeout, TAKE1,
253                 "OCSP responder query timeout")
254     SSL_CMD_SRV(OCSPUseRequestNonce, FLAG,
255                 "Whether OCSP queries use a nonce or not ('on', 'off')")
256
257 #ifdef HAVE_OCSP_STAPLING
258     /*
259      * OCSP Stapling options
260      */
261     SSL_CMD_SRV(StaplingCache, TAKE1,
262                 "SSL Stapling Response Cache storage "
263                 "(`dbm:/path/to/file')")
264     SSL_CMD_SRV(UseStapling, FLAG,
265                 "SSL switch for the OCSP Stapling protocol " "(`on', `off')")
266     SSL_CMD_SRV(StaplingResponseTimeSkew, TAKE1,
267                 "SSL stapling option for maximum time difference in OCSP responses")
268     SSL_CMD_SRV(StaplingResponderTimeout, TAKE1,
269                 "SSL stapling option for OCSP responder timeout")
270     SSL_CMD_SRV(StaplingResponseMaxAge, TAKE1,
271                 "SSL stapling option for maximum age of OCSP responses")
272     SSL_CMD_SRV(StaplingStandardCacheTimeout, TAKE1,
273                 "SSL stapling option for normal OCSP Response Cache Lifetime")
274     SSL_CMD_SRV(StaplingReturnResponderErrors, FLAG,
275                 "SSL stapling switch to return Status Errors Back to Client"
276                 "(`on', `off')")
277     SSL_CMD_SRV(StaplingFakeTryLater, FLAG,
278                 "SSL stapling switch to send tryLater response to client on error "
279                 "(`on', `off')")
280     SSL_CMD_SRV(StaplingErrorCacheTimeout, TAKE1,
281                 "SSL stapling option for OCSP Response Error Cache Lifetime")
282     SSL_CMD_SRV(StaplingForceURL, TAKE1,
283                 "SSL stapling option to Force the OCSP Stapling URL")
284 #endif
285
286 #ifdef HAVE_SSL_CONF_CMD
287     SSL_CMD_SRV(OpenSSLConfCmd, TAKE2,
288                 "OpenSSL configuration command")
289 #endif
290
291     /* Deprecated directives. */
292     AP_INIT_RAW_ARGS("SSLLog", ap_set_deprecated, NULL, OR_ALL,
293       "SSLLog directive is no longer supported - use ErrorLog."),
294     AP_INIT_RAW_ARGS("SSLLogLevel", ap_set_deprecated, NULL, OR_ALL,
295       "SSLLogLevel directive is no longer supported - use LogLevel."),
296
297     AP_END_CMD
298 };
299
300 /*
301  *  the various processing hooks
302  */
303 static apr_status_t ssl_cleanup_pre_config(void *data)
304 {
305     /*
306      * Try to kill the internals of the SSL library.
307      */
308     /* Corresponds to OPENSSL_load_builtin_modules():
309      * XXX: borrowed from apps.h, but why not CONF_modules_free()
310      * which also invokes CONF_modules_finish()?
311      */
312     CONF_modules_unload(1);
313     /* Corresponds to SSL_library_init: */
314     EVP_cleanup();
315 #if HAVE_ENGINE_LOAD_BUILTIN_ENGINES
316     ENGINE_cleanup();
317 #endif
318 #if OPENSSL_VERSION_NUMBER >= 0x1000000fL
319     ERR_remove_thread_state(NULL);
320 #else
321     ERR_remove_state(0);
322 #endif
323
324     /* Don't call ERR_free_strings in earlier versions, ERR_load_*_strings only
325      * actually loaded the error strings once per process due to static
326      * variable abuse in OpenSSL. */
327 #if (OPENSSL_VERSION_NUMBER >= 0x00090805f)
328     ERR_free_strings();
329 #endif
330
331     /* Also don't call CRYPTO_cleanup_all_ex_data here; any registered
332      * ex_data indices may have been cached in static variables in
333      * OpenSSL; removing them may cause havoc.  Notably, with OpenSSL
334      * versions >= 0.9.8f, COMP_CTX cleanups would not be run, which
335      * could result in a per-connection memory leak (!). */
336
337     /*
338      * TODO: determine somewhere we can safely shove out diagnostics
339      *       (when enabled) at this late stage in the game:
340      * CRYPTO_mem_leaks_fp(stderr);
341      */
342     return APR_SUCCESS;
343 }
344
345 static int ssl_hook_pre_config(apr_pool_t *pconf,
346                                apr_pool_t *plog,
347                                apr_pool_t *ptemp)
348 {
349
350 #if HAVE_VALGRIND
351      ssl_running_on_valgrind = RUNNING_ON_VALGRIND;
352 #endif
353
354     /* We must register the library in full, to ensure our configuration
355      * code can successfully test the SSL environment.
356      */
357     CRYPTO_malloc_init();
358     ERR_load_crypto_strings();
359     SSL_load_error_strings();
360     SSL_library_init();
361 #if HAVE_ENGINE_LOAD_BUILTIN_ENGINES
362     ENGINE_load_builtin_engines();
363 #endif
364     OpenSSL_add_all_algorithms();
365     OPENSSL_load_builtin_modules();
366
367     if (OBJ_txt2nid("id-on-dnsSRV") == NID_undef) {
368         (void)OBJ_create("1.3.6.1.5.5.7.8.7", "id-on-dnsSRV",
369                          "SRVName otherName form");
370     }
371
372     /*
373      * Let us cleanup the ssl library when the module is unloaded
374      */
375     apr_pool_cleanup_register(pconf, NULL, ssl_cleanup_pre_config,
376                                            apr_pool_cleanup_null);
377
378     /* Register us to handle mod_log_config %c/%x variables */
379     ssl_var_log_config_register(pconf);
380
381     /* Register to handle mod_status status page generation */
382     ssl_scache_status_register(pconf);
383
384     /* Register mutex type names so they can be configured with Mutex */
385     ap_mutex_register(pconf, SSL_CACHE_MUTEX_TYPE, NULL, APR_LOCK_DEFAULT, 0);
386 #ifdef HAVE_OCSP_STAPLING
387     ap_mutex_register(pconf, SSL_STAPLING_CACHE_MUTEX_TYPE, NULL,
388                       APR_LOCK_DEFAULT, 0);
389     ap_mutex_register(pconf, SSL_STAPLING_REFRESH_MUTEX_TYPE, NULL,
390                       APR_LOCK_DEFAULT, 0);
391 #endif
392
393     return OK;
394 }
395
396 static SSLConnRec *ssl_init_connection_ctx(conn_rec *c)
397 {
398     SSLConnRec *sslconn = myConnConfig(c);
399     SSLSrvConfigRec *sc;
400
401     if (sslconn) {
402         return sslconn;
403     }
404
405     sslconn = apr_pcalloc(c->pool, sizeof(*sslconn));
406
407     sslconn->server = c->base_server;
408     sslconn->verify_depth = UNSET;
409     sc = mySrvConfig(c->base_server);
410     sslconn->cipher_suite = sc->server->auth.cipher_suite;
411
412     myConnConfigSet(c, sslconn);
413
414     return sslconn;
415 }
416
417 static int ssl_proxy_enable(conn_rec *c)
418 {
419     SSLSrvConfigRec *sc;
420
421     SSLConnRec *sslconn = ssl_init_connection_ctx(c);
422     sc = mySrvConfig(sslconn->server);
423
424     if (!sc->proxy_enabled) {
425         ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(01961)
426                       "SSL Proxy requested for %s but not enabled "
427                       "[Hint: SSLProxyEngine]", sc->vhost_id);
428
429         return 0;
430     }
431
432     sslconn->is_proxy = 1;
433     sslconn->disabled = 0;
434
435     return 1;
436 }
437
438 static int ssl_engine_disable(conn_rec *c)
439 {
440     SSLSrvConfigRec *sc;
441
442     SSLConnRec *sslconn = myConnConfig(c);
443
444     if (sslconn) {
445         sc = mySrvConfig(sslconn->server);
446     }
447     else {
448         sc = mySrvConfig(c->base_server);
449     }
450     if (sc->enabled == SSL_ENABLED_FALSE) {
451         return 0;
452     }
453
454     sslconn = ssl_init_connection_ctx(c);
455
456     sslconn->disabled = 1;
457
458     return 1;
459 }
460
461 int ssl_init_ssl_connection(conn_rec *c, request_rec *r)
462 {
463     SSLSrvConfigRec *sc;
464     SSL *ssl;
465     SSLConnRec *sslconn = myConnConfig(c);
466     char *vhost_md5;
467     int rc;
468     modssl_ctx_t *mctx;
469     server_rec *server;
470
471     if (!sslconn) {
472         sslconn = ssl_init_connection_ctx(c);
473     }
474     server = sslconn->server;
475     sc = mySrvConfig(server);
476
477     /*
478      * Seed the Pseudo Random Number Generator (PRNG)
479      */
480     ssl_rand_seed(server, c->pool, SSL_RSCTX_CONNECT, "");
481
482     mctx = sslconn->is_proxy ? sc->proxy : sc->server;
483
484     /*
485      * Create a new SSL connection with the configured server SSL context and
486      * attach this to the socket. Additionally we register this attachment
487      * so we can detach later.
488      */
489     if (!(ssl = SSL_new(mctx->ssl_ctx))) {
490         ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(01962)
491                       "Unable to create a new SSL connection from the SSL "
492                       "context");
493         ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, server);
494
495         c->aborted = 1;
496
497         return DECLINED; /* XXX */
498     }
499
500     rc = ssl_run_pre_handshake(c, ssl, sslconn->is_proxy ? 1 : 0);
501     if (rc != OK && rc != DECLINED) {
502         return rc;
503     }
504
505     vhost_md5 = ap_md5_binary(c->pool, (unsigned char *)sc->vhost_id,
506                               sc->vhost_id_len);
507
508     if (!SSL_set_session_id_context(ssl, (unsigned char *)vhost_md5,
509                                     APR_MD5_DIGESTSIZE*2))
510     {
511         ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(01963)
512                       "Unable to set session id context to '%s'", vhost_md5);
513         ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, server);
514
515         c->aborted = 1;
516
517         return DECLINED; /* XXX */
518     }
519
520     SSL_set_app_data(ssl, c);
521     modssl_set_app_data2(ssl, NULL); /* will be request_rec */
522
523     sslconn->ssl = ssl;
524
525     SSL_set_verify_result(ssl, X509_V_OK);
526
527     ssl_io_filter_init(c, r, ssl);
528
529     return APR_SUCCESS;
530 }
531
532 static const char *ssl_hook_http_scheme(const request_rec *r)
533 {
534     SSLSrvConfigRec *sc = mySrvConfig(r->server);
535
536     if (sc->enabled == SSL_ENABLED_FALSE || sc->enabled == SSL_ENABLED_OPTIONAL) {
537         return NULL;
538     }
539
540     return "https";
541 }
542
543 static apr_port_t ssl_hook_default_port(const request_rec *r)
544 {
545     SSLSrvConfigRec *sc = mySrvConfig(r->server);
546
547     if (sc->enabled == SSL_ENABLED_FALSE || sc->enabled == SSL_ENABLED_OPTIONAL) {
548         return 0;
549     }
550
551     return 443;
552 }
553
554 static int ssl_hook_pre_connection(conn_rec *c, void *csd)
555 {
556
557     SSLSrvConfigRec *sc;
558     SSLConnRec *sslconn = myConnConfig(c);
559
560     if (sslconn) {
561         sc = mySrvConfig(sslconn->server);
562     }
563     else {
564         sc = mySrvConfig(c->base_server);
565     }
566     /*
567      * Immediately stop processing if SSL is disabled for this connection
568      */
569     if (c->master || !(sc && (sc->enabled == SSL_ENABLED_TRUE ||
570                               (sslconn && sslconn->is_proxy))))
571     {
572         return DECLINED;
573     }
574
575     /*
576      * Create SSL context
577      */
578     if (!sslconn) {
579         sslconn = ssl_init_connection_ctx(c);
580     }
581
582     if (sslconn->disabled) {
583         return DECLINED;
584     }
585
586     /*
587      * Remember the connection information for
588      * later access inside callback functions
589      */
590
591     ap_log_cerror(APLOG_MARK, APLOG_INFO, 0, c, APLOGNO(01964)
592                   "Connection to child %ld established "
593                   "(server %s)", c->id, sc->vhost_id);
594
595     return ssl_init_ssl_connection(c, NULL);
596 }
597
598 static int ssl_hook_process_connection(conn_rec* c)
599 {
600     SSLConnRec *sslconn = myConnConfig(c);
601
602     if (sslconn && !sslconn->disabled) {
603         /* On an active SSL connection, let the input filters initialize
604          * themselves which triggers the handshake, which again triggers
605          * all kinds of useful things such as SNI and ALPN.
606          */
607         apr_bucket_brigade* temp;
608
609         temp = apr_brigade_create(c->pool, c->bucket_alloc);
610         ap_get_brigade(c->input_filters, temp,
611                        AP_MODE_INIT, APR_BLOCK_READ, 0);
612         apr_brigade_destroy(temp);
613     }
614     
615     return DECLINED;
616 }
617
618 /*
619  *  the module registration phase
620  */
621
622 static void ssl_register_hooks(apr_pool_t *p)
623 {
624     /* ssl_hook_ReadReq needs to use the BrowserMatch settings so must
625      * run after mod_setenvif's post_read_request hook. */
626     static const char *pre_prr[] = { "mod_setenvif.c", NULL };
627
628     ssl_io_filter_register(p);
629
630     ap_hook_pre_connection(ssl_hook_pre_connection,NULL,NULL, APR_HOOK_MIDDLE);
631     ap_hook_process_connection(ssl_hook_process_connection, 
632                                                    NULL, NULL, APR_HOOK_MIDDLE);
633     ap_hook_test_config   (ssl_hook_ConfigTest,    NULL,NULL, APR_HOOK_MIDDLE);
634     ap_hook_post_config   (ssl_init_Module,        NULL,NULL, APR_HOOK_MIDDLE);
635     ap_hook_http_scheme   (ssl_hook_http_scheme,   NULL,NULL, APR_HOOK_MIDDLE);
636     ap_hook_default_port  (ssl_hook_default_port,  NULL,NULL, APR_HOOK_MIDDLE);
637     ap_hook_pre_config    (ssl_hook_pre_config,    NULL,NULL, APR_HOOK_MIDDLE);
638     ap_hook_child_init    (ssl_init_Child,         NULL,NULL, APR_HOOK_MIDDLE);
639     ap_hook_post_read_request(ssl_hook_ReadReq, pre_prr,NULL, APR_HOOK_MIDDLE);
640     ap_hook_check_access  (ssl_hook_Access,        NULL,NULL, APR_HOOK_MIDDLE,
641                            AP_AUTH_INTERNAL_PER_CONF);
642     ap_hook_check_authn   (ssl_hook_UserCheck,     NULL,NULL, APR_HOOK_FIRST,
643                            AP_AUTH_INTERNAL_PER_CONF);
644     ap_hook_check_authz   (ssl_hook_Auth,          NULL,NULL, APR_HOOK_MIDDLE,
645                            AP_AUTH_INTERNAL_PER_CONF);
646     ap_hook_fixups        (ssl_hook_Fixup,         NULL,NULL, APR_HOOK_MIDDLE);
647
648     ssl_var_register(p);
649
650     APR_REGISTER_OPTIONAL_FN(ssl_proxy_enable);
651     APR_REGISTER_OPTIONAL_FN(ssl_engine_disable);
652
653     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ssl",
654                               AUTHZ_PROVIDER_VERSION,
655                               &ssl_authz_provider_require_ssl,
656                               AP_AUTH_INTERNAL_PER_CONF);
657
658     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ssl-verify-client",
659                               AUTHZ_PROVIDER_VERSION,
660                               &ssl_authz_provider_verify_client,
661                               AP_AUTH_INTERNAL_PER_CONF);
662
663 }
664
665 module AP_MODULE_DECLARE_DATA ssl_module = {
666     STANDARD20_MODULE_STUFF,
667     ssl_config_perdir_create,   /* create per-dir    config structures */
668     ssl_config_perdir_merge,    /* merge  per-dir    config structures */
669     ssl_config_server_create,   /* create per-server config structures */
670     ssl_config_server_merge,    /* merge  per-server config structures */
671     ssl_config_cmds,            /* table of configuration directives   */
672     ssl_register_hooks          /* register hooks */
673 };