mod_auth_digest.c revision 58fd79b56eb624bf011772994e9761d3c2e228c1
* 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * ==================================================================== * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * Portions of this software are based upon public domain software * originally written at the National Center for Supercomputing Applications, * University of Illinois, Urbana-Champaign. * mod_auth_digest: MD5 digest authentication * Originally by Alexei Kosut <akosut@nueva.pvt.k12.ca.us> * Updated to RFC-2617 by Ronald Tschal�r <ronald@innovation.ch> * based on mod_auth, by Rob McCool and Robert S. Thau * It is still fairly new and problems may turn up - submit problem * reports to the Apache bug-database, or send them directly to me * at ronald@innovation.ch. * Requires either /dev/random (or equivalent) or the truerand library, * available for instance from * - qop=auth-int (when streams and trailer support available) * - nonce-format configurability * - Proxy-Authorization-Info header is set by this module, but is * currently ignored by mod_proxy (needs patch to mod_proxy) * - generating the secret takes a while (~ 8 seconds) if using the * - The source of the secret should be run-time directive (with server * scope: RSRC_CONF). However, that could be tricky when trying to * choose truerand vs. file... * - shared-mem not completely tested yet. Seems to work ok for me, * but... (definitely won't work on Windoze) * - Sharing a realm among multiple servers has following problems: * o Server name and port can't be included in nonce-hash * (we need two nonce formats, which must be configured explicitly) * o Nonce-count check can't be for equal, or then nonce-count checking * must be disabled. What we could do is the following: * (expected < received) ? set expected = received : issue error * The only problem is that it allows replay attacks when somebody * captures a packet sent to one server and sends it to another * one. Should we add "AuthDigestNcCheck Strict"? * - expired nonces give amaya fits. /* Disable shmem until pools/init gets sorted out * remove following two lines when fixed /* struct to hold the configuration info */ /* client list definitions */ unsigned long key;
/* the key for this entry */ unsigned long nonce_count;
/* for nonce-count checking */ /* struct to hold a parsed Authorization header */ /* the following fields are not (directly) from the header */ /* (mostly) nonce stuff */ /* client-list, opaque, and one-time-nonce stuff */ "Digest: cleaning up shared memory");
"Digest: generating secret for digest authentication ...");
"Digest: error generating secret: %s",
"Digest: %s - all nonce-count checking, one-time nonces, and " "MD5-sess algorithm disabled",
msg);
/* FIXME: get the client_lock_name from a directive so we're portable * to non-process-inheriting operating systems, like Win32. */ /* FIXME: get the opaque_lock_name from a directive so we're portable * to non-process-inheriting operating systems, like Win32. */ /* setup one-time-nonce counter */ #
endif /* APR_HAS_SHARED_MEMORY */ /* initialize_module() will be called twice, and if it's a DSO * then all static data from the first call will be lost. Only * set up our static data on the second call. */ /* Note: this stuff is currently fixed for the lifetime of the server, * i.e. even across restarts. This means that A) any shmem-size * configuration changes are ignored, and B) certain optimizations, * such as only allocating the smallest necessary entry for each * client, can't be done. However, the alternative is a nightmare: * we can't call apr_shm_destroy on a graceful restart because there * will be children using the tables, and we also don't know when the * last child dies. Therefore we can never clean up the old stuff, * creating a creeping memory leak. #
endif /* APR_HAS_SHARED_MEMORY */ /* FIXME: get the client_lock_name from a directive so we're portable * to non-process-inheriting operating systems, like Win32. */ /* FIXME: get the opaque_lock_name from a directive so we're portable * to non-process-inheriting operating systems, like Win32. */ /* The core already handles the realm, but it's just too convenient to * grab it ourselves too and cache some setups. However, we need to * let the core get at it too, which is why we decline at the end - * this relies on the fact that http_core is last in the list. /* we precompute the part of the nonce hash that is constant (well, * the host:port would be too, but that varies for .htaccess files * and directives outside a virtual host section) "Digest: WARNING: qop `auth-int' currently only works " "correctly for responses with no entity");
"Invalid time in AuthDigestNonceLifetime: ",
return "AuthDigestNonceFormat is not implemented (yet)";
cmd->
server,
"Digest: WARNING: nonce-count checking " "is not supported on platforms without shared-memory " "support - disabling check");
cmd->
server,
"Digest: WARNING: algorithm `MD5-sess' " "is not supported on platforms without shared-memory " "support - reverting to MD5");
"Digest: Set shmem-size: %ld, num-buckets: %ld",
shmem_size,
"The authentication realm (e.g. \"Members Only\")"),
"The name of the file containing the usernames and password hashes"),
"The name of the file containing the group names and members"),
"A list of quality-of-protection options"),
"Maximum lifetime of the server nonce (seconds)"),
"The format to use when generating the server nonce"),
"Whether or not to check the nonce-count sent by the client"),
"The algorithm used for the hash calculation"),
"A list of URI's which belong to the same protection space as the current URI"),
"The amount of shared memory to allocate for keeping track of clients"),
* Each client is assigned a number, which is transfered in the opaque * field of the WWW-Authenticate and Authorization headers. The number * is just a simple counter which is incremented for each new client. * Clients can't forge this number because it is hashed up into the * server nonce, and that is checked. * The clients are kept in a simple hash table, which consists of an * array of client_entry's, each with a linked list of entries hanging * off it. The client's number modulo the size of the array gives the * The clients are garbage collected whenever a new client is allocated * but there is not enough space left in the shared memory segment. A * simple semi-LRU is used for this: whenever a client entry is accessed * it is moved to the beginning of the linked list in its bucket (this * also makes for faster lookups for current clients). The garbage * collecter then just removes the oldest entry (i.e. the one at the * end of the list) in each bucket. * The main advantages of the above scheme are that it's easy to implement * and it keeps the hash table evenly balanced (i.e. same number of entries * in each bucket). The major disadvantage is that you may be throwing * entries out which are in active use. This is not tragic, as these * clients will just be sent a new client id (opaque field) and nonce * with a stale=true (i.e. it will just look like the nonce expired, * thereby forcing an extra round trip). If the shared memory segment * has enough headroom over the current client set size then this should * To help tune the size of the shared memory segment (and see if the * above algorithm is really sufficient) a set of counters is kept * indicating the number of clients held, the number of garbage collected * clients, and the number of erroneously purged clients. These are printed * out at each garbage collection run. Note that access to the counters is * not synchronized because they are just indicaters, and whether they are * off by a few doesn't matter; and for the same reason no attempt is made * to guarantee the num_renewed is correct in the face of clients spoofing * Get the client given its client number (the key). Returns the entry, * or NULL if it's not found. * Access to the list itself is synchronized via locks. However, access * to the entry returned by get_client() is NOT synchronized. This means * that there are potentially problems if a client uses multiple, * simultaneous connections to access url's within the same protection * space. However, these problems are not new: when using multiple * connections you have no guarantee of the order the requests are * processed anyway, so you have problems with the nonce-count and * one-time nonces anyway. if (
entry &&
prev) {
/* move entry to front of list */ "get_client(): client %lu found",
key);
"get_client(): client %lu not found",
key);
/* A simple garbage-collecter to remove unused clients. It removes the * last entry in each bucket and updates the counters. Returns the * number of removed entries. /* garbage collect all last entries */ if (
entry) {
/* remove entry */ /* update counters and log */ * Add a new client to the list. Returns the entry if successful, NULL * otherwise. This triggers the garbage collection if memory is low. /* try to allocate a new entry */ "Digest: gc'd %ld client entries. Total new clients: " "%ld; Total removed clients: %ld; Total renewed clients: " return NULL;
/* give up */ "allocated new client %lu",
key);
* Authorization header parser code /* Parse the Authorization header, if it exists */ if (
auth_line[0] ==
'\"') {
/* quoted string */ /* Because the browser may preemptively send auth info, incrementing the * nonce-count when it does, and because the client does not get notified * if the URI didn't need authentication after all, we need to be sure to * update the nonce-count each time we receive an Authorization header no * matter what the final outcome of the request. Furthermore this is a * convenient place to get the request-uri (before any subrequests etc * are initiated) and to initialize the request_config. * Note that this must be called after mod_proxy had its go so that * r->proxyreq is set correctly. /* The hash part of the nonce is a SHA-1 hash of the time, realm, server host * and port, opaque, and our secret. const char *
hex =
"0123456789abcdef";
apr_sha1_update_binary(&ctx, (const unsigned char *) server->server_hostname, strlen(server->server_hostname)); apr_sha1_update_binary(&ctx, (const unsigned char *) &server->port, /* The nonce has the format b64(time)+hash . /* this counter is not synch'd, because it doesn't really matter /* XXX: WHAT IS THIS CONSTANT? */ * Opaque and hash-table management * Generate a new client entry, add it to the list, and return the * entry. Returns NULL if failed. "Digest: failed to allocate client entry - ignoring " * If you want to use algorithm=MD5-sess you must write get_userpw_hash() * yourself (see below). The dummy provided here just uses the hash from * the auth-file, i.e. it is only useful for testing client implementations * get_userpw_hash() will be called each time a new session needs to be * generated and is expected to return the equivalent of * h_urp = ap_md5(r->pool, * apr_pstrcat(r->pool, username, ":", ap_auth_name(r), ":", passwd)) * (unsigned char *) apr_pstrcat(r->pool, h_urp, ":", resp->nonce, ":", * or put differently, it must return * MD5(MD5(username ":" realm ":" password) ":" nonce ":" cnonce) * If something goes wrong, the failure must be logged and NULL returned. * You must implement this yourself, which will probably consist of code * contacting the password server with the necessary information (typically * the username, realm, nonce, and cnonce) and receiving the hash from it. * TBD: This function should probably be in a seperate source file so that /* Retrieve current session H(A1). If there is none and "generate" is * true then a new session for MD5-sess is generated and stored in the * client struct; if generate is false, or a new session could not be * generated then NULL is returned (in case of failure to generate the * failure reason will have been logged already). /* return the current sessions if there is one */ /* generate a new session */ * Authorization challenge generation code (for WWW-Authenticate) /* Because of things like mod_alias and mod_rewrite and the fact that * protection is often on a directory basis (not a location basis) it * is hard to determine the uri to put in the domain attribute. * What we do is the following: first we see if the directory is * a prefix for the uri - if this is the case we assume that therefore * a <Location> directive was protecting this uri and we can use it /* Now we check for <Files ...>, and if we find one we send back a * dummy uri - this is the only way to specify that the protection * space only covers a single uri. /* This doesn't work for Amaya (ok, it's of arguable validity in * the first place), so just return the file name instead /* Next we find the largest common common suffix of the request-uri * and the final file name, ignoring any extensions; this gives us a * hint as to where any rewriting could've occured (assuming that some * prefix of the uri is rewritten, not a suffix). u =
uri +
u_len -
1;
/* strip any extension */ while (u >
uri && *u !=
'/') {
while (*u && *u !=
'.') {
while (*f && *f !=
'.') {
while (*f && *f !=
'/') {
u++;
/* suffix must start with / */ /* Now, if the directory reaches into this common suffix then we can * take the uri with the same reach. opaque =
"";
/* opaque not needed */ /* client info was gc'd */ /* we're generating a new nonce, so reset the nonce-count */ /* Setup MD5-sess stuff. Note that we just clear out the session * info here, since we can't generate a new session until the request * from the client comes in with the cnonce. /* setup domain attribute. We want to send this attribute wherever * possible so that the client won't send the Authorization header * unneccessarily (it's usually > 200 bytes!). domain =
NULL;
/* don't send domain for proxy requests */ /* They didn't specify any domain, so let's guess at it */ domain =
NULL;
/* "/" is the default, so no need to send it */ ?
"Proxy-Authenticate" :
"WWW-Authenticate",
"nonce=\"%s\", algorithm=%s%s%s%s%s",
* Authorization header verification code "Digest: Could not open password file: %s",
auth_pwfile);
if ((l[0] ==
'#') || (!l[0])) {
"Digest: invalid nc %s received - not a number",
snc);
"Digest: Warning, possible replay attack: nonce-count " "check failed: %lu != %lu",
nc,
"Digest: invalid nonce %s received - length is not %d",
"Digest: invalid nonce %s received - hash is not %s",
"Digest: invalid nonce %s received - user attempted " "Digest: user %s: nonce expired (%.2f seconds old " "- max lifetime %.2f) - sending new nonce",
"Digest: user %s: one-time-nonce mismatch - sending " /* else (lifetime < 0) => never expires */ /* The actual MD5 code... whee */ /* These functions return 0 if client is OK, and proper error status * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we * couldn't figure out how to tell if the client is authorized or not. * If they return DECLINED, and all other modules also decline, that's * treated by the server core as a configuration error, logged and /* Determine user ID, and check if the attributes are correct, if it * really is that user, if the nonce is correct, etc. /* do we require Digest auth for this URI? */ "Digest: need AuthName: %s", r->
uri);
/* get the client response and mark */ /* check for existence and syntax of Auth header */ "Digest: client used wrong authentication scheme " "Digest: missing user, realm, nonce, uri, digest, " "cnonce, or nonce_count in authorization header: %s",
/* else (resp->auth_hdr_sts == NO_HEADER) */ /* check the auth attributes */ /* Hmm, the simple match didn't work (probably a proxy modified the * request-uri), so lets do a more sophisticated match "Digest: invalid uri <%s> in Authorization header",
"Digest: uri mismatch - <%s> does not match " /* check hostname matches, if present */ /* check port matches, if present */ /* check that server-port is default port if no port present */ /* check that path matches */ /* or '*' matches empty path in scheme://host */ /* check that query matches */ "Digest: uri mismatch - <%s> does not match " "Digest: received invalid opaque - got `%s'",
"Digest: realm mismatch - got `%s' but expected `%s'",
"Digest: unknown algorithm `%s' received: %s",
"Digest: user `%s' in realm `%s' not found: %s",
/* old (rfc-2069) style digest */ "Digest: user %s: password mismatch: %s", r->
user,
"Digest: invalid qop `%s' received: %s",
/* we failed to allocate a client struct */ "Digest: user %s: password mismatch: %s", r->
user,
/* Note: this check is done last so that a "stale=true" can be generated if the nonce is old */ "Digest: Could not open group file: %s",
grpfile);
if ((l[0] ==
'#') || (!l[0])) {
/* If there is no "requires" directive, then any user will do. "Digest: access to %s failed, reason: unknown " "require directive \"%s\"",
"Digest: access to %s failed, reason: user %s not " * Authorization-Info header code /* old client, so calc rfc-2069 digest */ /* most of this totally bogus because the handlers don't set the * headers until the final handler phase (I wonder why this phase * is called fixup when there's almost nothing you can fix up...) * Because it's basically impossible to get this right (e.g. the * Content-length is never set yet when we get here, and we can't * calc the entity hash) it's best to just leave this #def'd out. ap_md5(r->
pool, (
unsigned char *)
""),
/* H(entity) - TBD */ /* send nextnonce if current nonce will expire in less than 30 secs */ /* else nonce never expires, hence no nextnonce */ /* use only RFC-2069 format */ /* calculate rspauth attribute "Digest: internal error: couldn't find session " /* assemble Authentication-Info header ?
"Proxy-Authentication-Info" NULL,
/* dir merger --- default is to override */ NULL,
/* server config */ NULL,
/* merge server config */