diff --git a/CHANGES b/CHANGES
index d92dfea5498..ce28ef84323 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,6 +1,16 @@
-*- coding: utf-8 -*-
Changes with Apache 2.5.1
+ *) mod_authn_socache: Bind cache keys to the authentication domain.
+ The server name in the directory and server contexts now includes
+ the port, the key includes the name of the provider that produced
+ the entry, and Basic auth entries include the protection space
+ (AuthName), as Digest entries already included the realm.
+ Previously, the key separated neither providers nor protection
+ spaces, so distinct credential sources silently shared cache
+ entries. The AuthnCacheContext documentation now states which
+ differences the default context does not separate. [Hafiar]
+
*) mpm_event, mpm_worker, mpm_winnt, mpm_prefork, mpm_motorz: Added optional
functions to account for connections managed outside the MPM accept loop
(e.g., UDP).
diff --git a/docs/manual/mod/mod_authn_socache.xml b/docs/manual/mod/mod_authn_socache.xml
index aa9e59804ef..0649fe69245 100644
--- a/docs/manual/mod/mod_authn_socache.xml
+++ b/docs/manual/mod/mod_authn_socache.xml
@@ -184,20 +184,44 @@ AuthnCacheProvideFor dbd myprovider
directory
- This directive specifies a string to be used along with the supplied
- username (and realm in the case of Digest Authentication) in constructing
- a cache key. This serves to disambiguate identical usernames serving
- different authentication areas on the server.
+ This directive specifies a string to be used along with the name of
+ the provider that produced the entry, the supplied username, and the
+ realm (for Basic Authentication, the protection space named by
+ AuthName) in
+ constructing a cache key. This serves to disambiguate identical
+ usernames serving different authentication areas on the server.
Two special values for this are directory, which uses
- the directory context of the request as a string, and server
- which uses the virtual host name.
- The default is directory, which is also the most
- conservative setting. This is likely to be less than optimal, as it
- (for example) causes $app-base, $app-base/images,
- $app-base/scripts and $app-base/media each to
- have its own separate cache key. A better policy is to name the
+ the server (hostname and port) and the directory of the request URI,
+ and server, which uses the virtual host name and port.
+ The default is directory. The default separates
+ backend provider results only where the directory-like URL path, the
+ provider, or the AuthName differs. A configuration
+ that varies the credential source within a single directory and a
+ single AuthName — for
+ example Files
+ sections with different AuthUserFile settings — must give
+ each source its own AuthName or its own custom
+ AuthnCacheContext; otherwise the sources share
+ cache entries, and a password valid for one source is accepted for
+ the others.
+ The directory context causes $app-base,
+ $app-base/images, $app-base/scripts and
+ $app-base/media each to have its own separate cache
+ entries. Where a whole directory tree is a single authentication
+ area backed by one credential source, name the
AuthnCacheContext for the password
- provider: for example a htpasswd file or database table.
+ provider instead: for example a htpasswd file or database
+ table, and use that one context for the whole area.
+ A shared custom context is only safe where every request in its
+ scope is checked against the same credential source. If different
+ credential sources are used within the scope of one custom context
+ (different password files, database tables, or queries for
+ different resources), entries are shared between them, and a
+ password valid for one source will be accepted for the others.
+ Give each distinct credential source its own context.
Contexts can be shared across different areas of a server, where
credentials are shared. However, this has potential to become a vector
for cross-site or cross-application security breaches, so this directive
diff --git a/modules/aaa/mod_authn_socache.c b/modules/aaa/mod_authn_socache.c
index 757083e40fe..eea81e4badf 100644
--- a/modules/aaa/mod_authn_socache.c
+++ b/modules/aaa/mod_authn_socache.c
@@ -263,28 +263,57 @@ static const command_rec authn_cache_cmds[] =
};
static const char *construct_key(request_rec *r, const char *context,
- const char *user, const char *realm)
+ const char *provider, const char *user,
+ const char *realm)
{
- const char *slash = ap_strrchr_c(r->uri, '/');
/* handle "special" context values */
- if (!strcmp(context, directory) && slash) {
- char *new_context;
- new_context = apr_palloc(r->pool, slash - r->uri +
- strlen(r->server->server_hostname) + 1);
- strcpy(new_context, r->server->server_hostname);
- strncat(new_context, r->uri, slash - r->uri);
- context = new_context;
+ if (!strcmp(context, directory)) {
+ const char *slash = ap_strrchr_c(r->uri, '/');
+ /* The directory context identifies an entry by the server and
+ * the directory of the request URI. Within one directory,
+ * entries are separated by the provider and realm mixed into
+ * the key below; a configuration that varies the credential
+ * source within a single directory and realm (for example
+ * sections with different AuthUserFile settings) must
+ * use distinct AuthName values or a custom AuthnCacheContext
+ * to keep the sources apart, as the documentation states.
+ */
+ if (slash) {
+ context = apr_psprintf(r->pool, "%s:%u%.*s",
+ r->server->server_hostname,
+ (unsigned)ap_get_server_port(r),
+ (int)(slash - r->uri), r->uri);
+ }
+ else {
+ context = apr_psprintf(r->pool, "%s:%u%s",
+ r->server->server_hostname,
+ (unsigned)ap_get_server_port(r), r->uri);
+ }
}
else if (!strcmp(context, "server")) {
- context = r->server->server_hostname;
+ context = apr_psprintf(r->pool, "%s:%u",
+ r->server->server_hostname,
+ (unsigned)ap_get_server_port(r));
}
/* any other context value is literal */
- if (realm == NULL) { /* basic auth */
- return apr_pstrcat(r->pool, context, ":", user, NULL);
+ if (realm == NULL) {
+ /* Basic auth: the protection space (AuthName) is the realm. */
+ realm = ap_auth_name(r);
+ }
+
+ /* The key is bound to the provider that produced the entry, so a
+ * hash stored by one credential source is never validated against
+ * a request for another, and to the realm, so entries are not
+ * shared between protection spaces.
+ */
+ if (realm == NULL) {
+ return apr_pstrcat(r->pool, context, ":", provider, ":", user,
+ NULL);
}
- else { /* digest auth */
- return apr_pstrcat(r->pool, context, ":", user, ":", realm, NULL);
+ else {
+ return apr_pstrcat(r->pool, context, ":", provider, ":", user,
+ ":", realm, NULL);
}
}
@@ -323,7 +352,7 @@ static void ap_authn_cache_store(request_rec *r, const char *module,
/* We have the mutex, so go ahead */
/* first build our key and determine expiry time */
- key = construct_key(r, dcfg->context, user, realm);
+ key = construct_key(r, dcfg->context, module, user, realm);
expiry = apr_time_now() + dcfg->timeout;
/* store it */
@@ -367,14 +396,27 @@ static authn_status check_password(request_rec *r, const char *user,
authn_cache_dircfg *dcfg;
unsigned char val[MAX_VAL_LEN];
unsigned int vallen = MAX_VAL_LEN - 1;
+ int i;
dcfg = ap_get_module_config(r->per_dir_config, &authn_socache_module);
if (!configured || !dcfg->providers) {
return AUTH_USER_NOT_FOUND;
}
- key = construct_key(r, dcfg->context, user, NULL);
- rv = socache_provider->retrieve(socache_instance, r->server,
- (unsigned char*)key, strlen(key),
- val, &vallen, r->pool);
+ /* Entries are stored under the key of the provider that produced
+ * them; try each provider this configuration caches for.
+ */
+ rv = APR_NOTFOUND;
+ for (i = 0; i < dcfg->providers->nelts; i++) {
+ const char *provider = APR_ARRAY_IDX(dcfg->providers, i,
+ const char *);
+ vallen = MAX_VAL_LEN - 1;
+ key = construct_key(r, dcfg->context, provider, user, NULL);
+ rv = socache_provider->retrieve(socache_instance, r->server,
+ (unsigned char*)key, strlen(key),
+ val, &vallen, r->pool);
+ if (rv == APR_SUCCESS || !APR_STATUS_IS_NOTFOUND(rv)) {
+ break;
+ }
+ }
if (APR_STATUS_IS_NOTFOUND(rv)) {
/* not found - just return */
@@ -412,14 +454,24 @@ static authn_status get_realm_hash(request_rec *r, const char *user,
authn_cache_dircfg *dcfg;
unsigned char val[MAX_VAL_LEN];
unsigned int vallen = MAX_VAL_LEN - 1;
+ int i;
dcfg = ap_get_module_config(r->per_dir_config, &authn_socache_module);
if (!configured || !dcfg->providers) {
return AUTH_USER_NOT_FOUND;
}
- key = construct_key(r, dcfg->context, user, realm);
- rv = socache_provider->retrieve(socache_instance, r->server,
- (unsigned char*)key, strlen(key),
- val, &vallen, r->pool);
+ rv = APR_NOTFOUND;
+ for (i = 0; i < dcfg->providers->nelts; i++) {
+ const char *provider = APR_ARRAY_IDX(dcfg->providers, i,
+ const char *);
+ vallen = MAX_VAL_LEN - 1;
+ key = construct_key(r, dcfg->context, provider, user, realm);
+ rv = socache_provider->retrieve(socache_instance, r->server,
+ (unsigned char*)key, strlen(key),
+ val, &vallen, r->pool);
+ if (rv == APR_SUCCESS || !APR_STATUS_IS_NOTFOUND(rv)) {
+ break;
+ }
+ }
if (APR_STATUS_IS_NOTFOUND(rv)) {
/* not found - just return */
diff --git a/test/modules/aaa/conftest.py b/test/modules/aaa/conftest.py
index be9b8ba449f..4650e09367d 100644
--- a/test/modules/aaa/conftest.py
+++ b/test/modules/aaa/conftest.py
@@ -15,6 +15,21 @@ def pytest_report_header(config, start_path):
return f"mod_auth_digest [apache: {env.get_httpd_version()}, mpm: {env.mpm_module}, {env.prefix}]"
+def _socache_dir(docs, path, files_lines):
+ lines = [
+ f'',
+ ' AuthType Basic',
+ ' AuthName "socache-shared"',
+ ' AuthBasicProvider socache file',
+ ' AuthnCacheProvideFor file',
+ ' AuthnCacheTimeout 600',
+ ]
+ lines.extend(f" {l}" for l in files_lines)
+ lines.append(' Require valid-user')
+ lines.append('')
+ return lines
+
+
def _digest_dir(docs, path, extra_lines):
lines = [
f'',
@@ -102,6 +117,43 @@ def env(pytestconfig) -> AAATestEnv:
# AuthDigestProvider intentionally omitted: falls back to "file".
f'AuthUserFile "{pwfile}"',
]))
+ # mod_authn_socache areas (test_020): one directory whose two files
+ # are backed by different htpasswd files. In "byname" the files carry
+ # distinct AuthName values, in "byctx" distinct AuthnCacheContext
+ # values, and in "samename" neither, which the documentation states
+ # shares cache entries between the two sources.
+ conf.add('AuthnCacheSOCache shmcb')
+ conf.add('AuthnCacheEnable')
+ low = env.basic_pwfile_low
+ high = env.basic_pwfile_high
+ conf.add(_socache_dir(docs, "byname", [
+ '',
+ 'AuthName "lowarea"',
+ f'AuthUserFile "{low}"',
+ '',
+ '',
+ 'AuthName "higharea"',
+ f'AuthUserFile "{high}"',
+ '',
+ ]))
+ conf.add(_socache_dir(docs, "byctx", [
+ '',
+ f'AuthUserFile "{low}"',
+ 'AuthnCacheContext lowctx',
+ '',
+ '',
+ f'AuthUserFile "{high}"',
+ 'AuthnCacheContext highctx',
+ '',
+ ]))
+ conf.add(_socache_dir(docs, "samename", [
+ '',
+ f'AuthUserFile "{low}"',
+ '',
+ '',
+ f'AuthUserFile "{high}"',
+ '',
+ ]))
# A request which fails header validation (e.g. no Host on HTTP/1.1)
# is answered before the Digest module's post_read_request runs, so it
# has no per-request Digest record; an ErrorDocument redirecting it into
diff --git a/test/modules/aaa/env.py b/test/modules/aaa/env.py
index 87fcb667762..bee008967c3 100644
--- a/test/modules/aaa/env.py
+++ b/test/modules/aaa/env.py
@@ -15,7 +15,8 @@ class AAATestSetup(HttpdTestSetup):
def __init__(self, env: 'HttpdTestEnv'):
super().__init__(env=env)
self.add_source_dir(os.path.dirname(inspect.getfile(AAATestSetup)))
- self.add_modules(["auth_digest", "authn_file", "authn_core",
+ self.add_modules(["auth_digest", "auth_basic", "authn_socache",
+ "socache_shmcb", "authn_file", "authn_core",
"authz_core", "authz_user", "proxy", "proxy_http"])
@@ -26,6 +27,11 @@ class AAATestEnv(HttpdTestEnv):
DIGEST_PASSWORD = "digestpass2617"
DIGEST_USER2 = "otheruser"
DIGEST_PASSWORD2 = "otherpass2617"
+ # Basic auth accounts for the mod_authn_socache tests: the same user
+ # with a different password in each of two htpasswd files.
+ SOCACHE_USER = "socacheuser"
+ SOCACHE_PASSWORD_LOW = "lowpass2617"
+ SOCACHE_PASSWORD_HIGH = "highpass2617"
# DIGEST_USER's password in the second file, for a vhost with its own
# accounts under the same realm.
DIGEST_PASSWORD_VHOST2 = "vhost2pass2617"
@@ -35,10 +41,33 @@ def __init__(self, pytestconfig=None):
self.add_httpd_log_modules(["auth_digest", "authn_file", "authz_core"])
self._digest_pwfile = os.path.join(self.server_dir, "digest.passwd")
self._digest_pwfile2 = os.path.join(self.server_dir, "digest2.passwd")
+ self._basic_pwfile_low = os.path.join(self.server_dir, "basic-low.passwd")
+ self._basic_pwfile_high = os.path.join(self.server_dir, "basic-high.passwd")
def setup_httpd(self, setup: HttpdTestSetup = None):
super().setup_httpd(setup=AAATestSetup(env=self))
self._write_digest_pwfile()
+ self._write_basic_pwfiles()
+
+ def _write_basic_pwfiles(self):
+ import base64
+
+ def sha_entry(user, password):
+ digest = hashlib.sha1(password.encode()).digest()
+ return f"{user}:{{SHA}}{base64.b64encode(digest).decode()}\n"
+
+ with open(self._basic_pwfile_low, 'w') as fd:
+ fd.write(sha_entry(self.SOCACHE_USER, self.SOCACHE_PASSWORD_LOW))
+ with open(self._basic_pwfile_high, 'w') as fd:
+ fd.write(sha_entry(self.SOCACHE_USER, self.SOCACHE_PASSWORD_HIGH))
+
+ @property
+ def basic_pwfile_low(self) -> str:
+ return self._basic_pwfile_low
+
+ @property
+ def basic_pwfile_high(self) -> str:
+ return self._basic_pwfile_high
def _write_digest_pwfile(self):
def ha1(user, password):
diff --git a/test/modules/aaa/htdocs/socache/byctx/high.txt b/test/modules/aaa/htdocs/socache/byctx/high.txt
new file mode 100644
index 00000000000..83bd1e71a7b
--- /dev/null
+++ b/test/modules/aaa/htdocs/socache/byctx/high.txt
@@ -0,0 +1 @@
+socache-byctx-high
diff --git a/test/modules/aaa/htdocs/socache/byctx/low.txt b/test/modules/aaa/htdocs/socache/byctx/low.txt
new file mode 100644
index 00000000000..f417c09f49e
--- /dev/null
+++ b/test/modules/aaa/htdocs/socache/byctx/low.txt
@@ -0,0 +1 @@
+socache-byctx-low
diff --git a/test/modules/aaa/htdocs/socache/byname/high.txt b/test/modules/aaa/htdocs/socache/byname/high.txt
new file mode 100644
index 00000000000..2446a95d25a
--- /dev/null
+++ b/test/modules/aaa/htdocs/socache/byname/high.txt
@@ -0,0 +1 @@
+socache-byname-high
diff --git a/test/modules/aaa/htdocs/socache/byname/low.txt b/test/modules/aaa/htdocs/socache/byname/low.txt
new file mode 100644
index 00000000000..010626dbd07
--- /dev/null
+++ b/test/modules/aaa/htdocs/socache/byname/low.txt
@@ -0,0 +1 @@
+socache-byname-low
diff --git a/test/modules/aaa/htdocs/socache/samename/high.txt b/test/modules/aaa/htdocs/socache/samename/high.txt
new file mode 100644
index 00000000000..e702393329f
--- /dev/null
+++ b/test/modules/aaa/htdocs/socache/samename/high.txt
@@ -0,0 +1 @@
+socache-samename-high
diff --git a/test/modules/aaa/htdocs/socache/samename/low.txt b/test/modules/aaa/htdocs/socache/samename/low.txt
new file mode 100644
index 00000000000..24c1ff276e1
--- /dev/null
+++ b/test/modules/aaa/htdocs/socache/samename/low.txt
@@ -0,0 +1 @@
+socache-samename-low
diff --git a/test/modules/aaa/test_020_authn_socache.py b/test/modules/aaa/test_020_authn_socache.py
new file mode 100644
index 00000000000..af8b131593c
--- /dev/null
+++ b/test/modules/aaa/test_020_authn_socache.py
@@ -0,0 +1,67 @@
+"""mod_authn_socache cache-key separation.
+
+Each area under /socache/ is one directory whose low.txt and high.txt
+are backed by different htpasswd files holding the same user with a
+different password in each file. The areas differ only in how the two
+sources are told apart:
+
+- byname: distinct AuthName per file
+- byctx: distinct AuthnCacheContext per file
+- samename: neither; the mod_authn_socache documentation states that
+ the default context shares cache entries in this case
+"""
+
+from .env import AAATestEnv
+
+
+class TestAuthnSocache:
+
+ def url(self, env, path):
+ return env.mkurl("http", "aaa", path)
+
+ def get(self, env, path, password):
+ user = AAATestEnv.SOCACHE_USER
+ return env.curl_get(self.url(env, path),
+ options=["-u", f"{user}:{password}"])
+
+ def check_separated(self, env, area):
+ low = AAATestEnv.SOCACHE_PASSWORD_LOW
+ high = AAATestEnv.SOCACHE_PASSWORD_HIGH
+ r = self.get(env, f"/socache/{area}/low.txt", low)
+ assert r.response["status"] == 200
+ assert r.response["body"].decode() == f"socache-{area}-low\n"
+ # The password of the sibling source must not authenticate here,
+ # neither before nor after its own entry is cached.
+ r = self.get(env, f"/socache/{area}/high.txt", low)
+ assert r.response["status"] == 401
+ r = self.get(env, f"/socache/{area}/high.txt", high)
+ assert r.response["status"] == 200
+ assert r.response["body"].decode() == f"socache-{area}-high\n"
+ r = self.get(env, f"/socache/{area}/low.txt", high)
+ assert r.response["status"] == 401
+ # A wrong password is rejected even with a warm cache.
+ r = self.get(env, f"/socache/{area}/low.txt", "wrongpass2617")
+ assert r.response["status"] == 401
+ # The 401 responses above are the assertions, not failures.
+ env.httpd_error_log.ignore_recent(lognos=["AH01617"])
+
+ def test_socache_001_separated_by_authname(self, env):
+ self.check_separated(env, "byname")
+
+ def test_socache_002_separated_by_context(self, env):
+ self.check_separated(env, "byctx")
+
+ def test_socache_003_shared_when_undifferentiated(self, env):
+ # Same directory, same AuthName, no custom context: the entries
+ # are shared, as documented for the default AuthnCacheContext.
+ # The first successful login populates the entry, and the cached
+ # hash then also answers for the sibling source until it expires.
+ low = AAATestEnv.SOCACHE_PASSWORD_LOW
+ high = AAATestEnv.SOCACHE_PASSWORD_HIGH
+ r = self.get(env, "/socache/samename/low.txt", low)
+ assert r.response["status"] == 200
+ r = self.get(env, "/socache/samename/high.txt", low)
+ assert r.response["status"] == 200
+ r = self.get(env, "/socache/samename/high.txt", high)
+ assert r.response["status"] == 401
+ env.httpd_error_log.ignore_recent(lognos=["AH01617"])