Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changes-entries/authn_socache_key.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
*) mod_authn_socache: Keep cached credentials separate for each
AuthType, AuthName and authn provider, and for each server port
unless AuthnCacheContext names a custom context. [Hafiar]
49 changes: 37 additions & 12 deletions docs/manual/mod/mod_authn_socache.xml
Original file line number Diff line number Diff line change
Expand Up @@ -232,20 +232,45 @@ AuthnCacheProvideFor dbd myprovider
<contextlist><context>directory</context></contextlist>

<usage>
<p>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.</p>
<p>This directive specifies a string to be used along with the name of
the provider that produced the entry, the <directive
module="mod_authn_core">AuthType</directive>, the supplied username,
and the realm (for Basic Authentication, the protection space named by
<directive module="mod_authn_core">AuthName</directive>) in
constructing a cache key. This serves to disambiguate identical
usernames serving different authentication areas on the server.</p>
<p>Two special values for this are <code>directory</code>, which uses
the directory context of the request as a string, and <code>server</code>
which uses the virtual host name.</p>
<p>The default is <code>directory</code>, which is also the most
conservative setting. This is likely to be less than optimal, as it
(for example) causes <var>$app-base</var>, <var>$app-base/images</var>,
<var>$app-base/scripts</var> and <var>$app-base/media</var> 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 <code>server</code>, which uses the virtual host name and port.</p>
<p>The default is <code>directory</code>. The default separates
backend provider results only where the directory-like URL path, the
provider, or the <directive
module="mod_authn_core">AuthName</directive> differs. A configuration
that varies the credential source within a single directory and a
single <directive module="mod_authn_core">AuthName</directive> — for
example <directive module="core" type="section">Files</directive>
sections with different <directive
module="mod_authn_file">AuthUserFile</directive> settings — must give
each source its own <directive
module="mod_authn_core">AuthName</directive> or its own custom
<directive>AuthnCacheContext</directive>; otherwise the sources share
cache entries, and a password valid for one source is accepted for
the others.</p>
<p>The <code>directory</code> context causes <var>$app-base</var>,
<var>$app-base/images</var>, <var>$app-base/scripts</var> and
<var>$app-base/media</var> 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
<directive>AuthnCacheContext</directive> for the password
provider: for example a <var>htpasswd</var> file or database table.</p>
provider instead: for example a <var>htpasswd</var> file or database
table, and use that one context for the whole area.</p>
<p>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.</p>
<p>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
Expand Down
110 changes: 87 additions & 23 deletions modules/aaa/mod_authn_socache.c
Original file line number Diff line number Diff line change
Expand Up @@ -267,28 +267,69 @@ 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, '/');
const char *type = ap_auth_type(r);
char *ltype = apr_pstrdup(r->pool, type ? type : "");

/* AuthType is not case-sensitive. */
ap_str_tolower(ltype);

/* 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 port is that configured for the server, not
* ap_get_server_port(), which the client can choose in the
* Host header.
*
* 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
* <Files> 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)r->server->port,
(int)(slash - r->uri), r->uri);
}
else {
context = apr_psprintf(r->pool, "%s:%u%s",
r->server->server_hostname,
(unsigned)r->server->port, r->uri);
}
}
else if (!strcmp(context, "server")) {
context = r->server->server_hostname;
context = apr_psprintf(r->pool, "%s:%u",
r->server->server_hostname,
(unsigned)r->server->port);
}
/* 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);
}
else { /* digest auth */
return apr_pstrcat(r->pool, context, ":", user, ":", realm, NULL);

/* 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. It is bound to the auth type
* since what is cached differs between them: a password hash for
* Basic, the hash of user, realm and password for Digest.
*/
if (realm == NULL) {
return apr_pstrcat(r->pool, context, ":", provider, ":", ltype,
":", user, NULL);
}
else {
return apr_pstrcat(r->pool, context, ":", provider, ":", ltype,
":", user, ":", realm, NULL);
}
}

Expand Down Expand Up @@ -327,7 +368,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 */
Expand Down Expand Up @@ -371,14 +412,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 */
Expand Down Expand Up @@ -416,14 +470,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 */
Expand Down
109 changes: 104 additions & 5 deletions test/modules/aaa/test_016_authn_socache.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,16 @@ def basic_pwfile2(cls, env):
def digest_pwfile(cls, env):
return os.path.join(env.server_dir, "socache-digest.passwd")

def url(self, env, name, fname="secret.txt"):
return env.mkurl("http", "aaa", f"/socache/{name}/{fname}")

def basic(self, env, name, user, password, fname="secret.txt"):
def url(self, env, name, fname="secret.txt", port=None):
url = env.mkurl("http", "aaa", f"/socache/{name}/{fname}")
if port:
url = url.replace(f":{env.http_port}/", f":{port}/")
return url

def basic(self, env, name, user, password, fname="secret.txt",
port=None):
"""The status of a Basic authenticated request."""
r = env.curl_get(self.url(env, name, fname),
r = env.curl_get(self.url(env, name, fname, port),
options=["-u", f"{user}:{password}"])
assert r.exit_code == 0, r.stderr
if r.response["status"] == 200:
Expand Down Expand Up @@ -160,6 +164,8 @@ def _class_scope(cls, env, request, basic_pwfile, basic_pwfile2,
# Caches for a provider which is not the one in use.
("other", ['AuthnCacheProvideFor dbm']),
("none", []),
# The provider in use is not the first one cached for.
("second", ['AuthnCacheProvideFor dbm file']),
("dir1", cached),
("dir2", cached),
("literal1", cached + ['AuthnCacheContext shared']),
Expand All @@ -175,6 +181,7 @@ def _class_scope(cls, env, request, basic_pwfile, basic_pwfile2,
for name, other_lines in [
("files", []),
("files-context", ['AuthnCacheContext other-file']),
("files-authname", ['AuthName "AAA Other Realm"']),
]:
conf.add(_directory(env, name, [
*_basic_lines(basic_pwfile, cached),
Expand All @@ -186,9 +193,22 @@ def _class_scope(cls, env, request, basic_pwfile, basic_pwfile2,
for name, cache_lines in [
("digest", cached),
("digest-none", []),
("mixed-digest", cached + ['AuthnCacheContext mixed']),
]:
conf.add(_directory(env, name,
_digest_lines(digest_pwfile, cache_lines)))
# Basic, with the context and AuthName of "mixed-digest".
conf.add(_directory(env, "mixed-basic", [
*_basic_lines(basic_pwfile,
cached + ['AuthnCacheContext mixed']),
f'AuthName "{AAATestEnv.REALM}"',
]))
# A second server of the same name on another port, to which the
# sections above apply as well.
conf.add(f'Listen {env.http_port2}')
conf.start_vhost(domains=[f"aaa.{env.http_tld}"],
port=env.http_port2, doc_root=env.server_docs_dir)
conf.end_vhost()
with env.preserved_test_conf():
conf.install()
assert env.apache_restart() == 0
Expand Down Expand Up @@ -376,6 +396,85 @@ def test_authn_socache_174_files_context(
assert self.basic(env, "files-context", user, P1) == 200
assert self.basic(env, "files-context", user, P2, OTHER) == 200

def test_authn_socache_175_files_authname(
self, env, basic_pwfile, basic_pwfile2):
"""An AuthName of its own keeps the entries for a document with
a different password file apart from those of the rest of the
directory."""
user = "user175"
AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
AAATestEnv.write_basic_pwfile(basic_pwfile2, {user: P2})
for _ in range(2):
# first from the password files, then from the cache
assert self.basic(env, "files-authname", user, P1) == 200
assert self.basic(env, "files-authname", user, P1, OTHER) == 401
assert self.basic(env, "files-authname", user, P2, OTHER) == 200
assert self.basic(env, "files-authname", user, P2) == 401
AAATestEnv.write_basic_pwfile(basic_pwfile, {})
AAATestEnv.write_basic_pwfile(basic_pwfile2, {})
assert self.basic(env, "files-authname", user, P1) == 200
assert self.basic(env, "files-authname", user, P2, OTHER) == 200

def test_authn_socache_176_second_provider(self, env, basic_pwfile):
"""An entry is found whichever of the providers named by
AuthnCacheProvideFor stored it."""
user = "user176"
AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
assert self.basic(env, "second", user, P1) == 200
AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P2})
assert self.basic(env, "second", user, P1) == 200
assert self.basic(env, "second", user, P2) == 401

def test_authn_socache_177_host_port(self, env, basic_pwfile):
"""The port a client puts in the Host header has no part in
finding an entry, so cannot be used to avoid or fill the
cache."""
user = "user177"
AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
assert self.basic(env, "basic", user, P1) == 200
AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P2})
for port in 1, 65535:
r = env.curl_get(self.url(env, "basic"), options=[
"-u", f"{user}:{P1}",
"-H", f"Host: aaa.{env.http_tld}:{port}"])
assert r.response["status"] == 200

@pytest.mark.parametrize("name", ["basic", "server1"])
def test_authn_socache_178_server_port(self, env, basic_pwfile, name):
"""Servers of the same name on different ports do not share
entries, with the "directory" or the "server" AuthnCacheContext."""
user = f"user178{name}"
port2 = env.http_port2
AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
assert self.basic(env, name, user, P1) == 200
AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P2})
assert self.basic(env, name, user, P1, port=port2) == 401
assert self.basic(env, name, user, P2, port=port2) == 200
AAATestEnv.write_basic_pwfile(basic_pwfile, {})
assert self.basic(env, name, user, P1) == 200
assert self.basic(env, name, user, P2, port=port2) == 200

@pytest.mark.parametrize("first", ["basic", "digest"])
def test_authn_socache_179_auth_type(
self, env, basic_pwfile, digest_pwfile, first):
"""Basic and Digest locations with the same AuthnCacheContext
and AuthName do not share entries, which are of no use to each
other."""
user = f"user179{first}"
AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
env.write_digest_pwfile(digest_pwfile, {user: P1})
if first == "basic":
assert self.basic(env, "mixed-basic", user, P1) == 200
assert self.digest(env, "mixed-digest", user, P1) == 200
else:
assert self.digest(env, "mixed-digest", user, P1) == 200
assert self.basic(env, "mixed-basic", user, P1) == 200
# and both are now cached
AAATestEnv.write_basic_pwfile(basic_pwfile, {})
env.write_digest_pwfile(digest_pwfile, {})
assert self.basic(env, "mixed-basic", user, P1) == 200
assert self.digest(env, "mixed-digest", user, P1) == 200


class TestAuthnSocacheHtaccess(_SocacheBase):
"""AuthnCacheProvideFor given only in .htaccess files."""
Expand Down
Loading