1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 * mod_auth_digest: MD5 digest authentication
62 * Originally by Alexei Kosut <akosut@nueva.pvt.k12.ca.us>
63 * Updated to RFC-2617 by Ronald Tschalär <ronald@innovation.ch>
64 * based on mod_auth, by Rob McCool and Robert S. Thau
66 * This module an updated version of modules/standard/mod_digest.c
67 * It is still fairly new and problems may turn up - submit problem
68 * reports to the Apache bug-database, or send them directly to me
69 * at ronald@innovation.ch.
71 * Requires either /dev/random (or equivalent) or the truerand library,
72 * available for instance from
73 * ftp://research.att.com/dist/mab/librand.shar
76 * - qop=auth-int (when streams and trailer support available)
77 * - nonce-format configurability
78 * - Proxy-Authorization-Info header is set by this module, but is
79 * currently ignored by mod_proxy (needs patch to mod_proxy)
80 * - generating the secret takes a while (~ 8 seconds) if using the
82 * - The source of the secret should be run-time directive (with server
83 * scope: RSRC_CONF). However, that could be tricky when trying to
84 * choose truerand vs. file...
85 * - shared-mem not completely tested yet. Seems to work ok for me,
86 * but... (definitely won't work on Windoze)
87 * - Sharing a realm among multiple servers has following problems:
88 * o Server name and port can't be included in nonce-hash
89 * (we need two nonce formats, which must be configured explicitly)
90 * o Nonce-count check can't be for equal, or then nonce-count checking
91 * must be disabled. What we could do is the following:
92 * (expected < received) ? set expected = received : issue error
93 * The only problem is that it allows replay attacks when somebody
94 * captures a packet sent to one server and sends it to another
95 * one. Should we add "AuthDigestNcCheck Strict"?
96 * - expired nonces give amaya fits.
100 #include "ap_config_auto.h"
103 #include "http_config.h"
104 #include "http_conf_globals.h"
105 #include "http_core.h"
106 #include "http_request.h"
107 #include "http_log.h"
108 #include "http_protocol.h"
109 #include "util_uri.h"
110 #include "util_md5.h"
112 #include "ap_base64.h"
114 #include "apr_time.h"
115 #include "apr_errno.h"
116 #include "apr_lock.h"
117 #include "apr_strings.h"
120 #if APR_HAS_SHARED_MEMORY
121 #include "apr_shmem.h"
123 /* just provide dummies - the code does run-time checks anyway */
124 typedef void apr_shmem_t;
125 typedef void apr_shm_name_t;
127 apr_status_t apr_shm_init(apr_shmem_t **m, apr_size_t reqsize, const char *file, apr_pool_t *cont) {
130 apr_status_t apr_shm_destroy(apr_shmem_t *m) {
133 void *apr_shm_malloc(apr_shmem_t *c, apr_size_t reqsize) {
136 void *apr_shm_calloc(apr_shmem_t *shared, apr_size_t size) {
139 apr_status_t apr_shm_free(apr_shmem_t *shared, void *free) {
142 apr_status_t apr_get_shm_name(apr_shmem_t *c, apr_shm_name_t **name) {
145 apr_status_t apr_set_shm_name(apr_shmem_t *c, apr_shm_name_t *name) {
148 apr_status_t apr_open_shmem(apr_shmem_t *c) {
151 apr_status_t apr_shm_avail(apr_shmem_t *c, apr_size_t *avail) {
157 /* struct to hold the configuration info */
159 typedef struct digest_config_struct {
160 const char *dir_name;
164 const char **qop_list;
165 AP_SHA1_CTX nonce_ctx;
166 apr_time_t nonce_lifetime;
167 const char *nonce_format;
169 const char *algorithm;
175 #define DFLT_ALGORITHM "MD5"
177 #define DFLT_NONCE_LIFE (300*AP_USEC_PER_SEC)
178 #define NEXTNONCE_DELTA (30*AP_USEC_PER_SEC)
181 #define NONCE_TIME_LEN (((sizeof(apr_time_t)+2)/3)*4)
182 #define NONCE_HASH_LEN (2*SHA_DIGESTSIZE)
183 #define NONCE_LEN (NONCE_TIME_LEN + NONCE_HASH_LEN)
185 #define SECRET_LEN 20
188 /* client list definitions */
190 typedef struct hash_entry {
191 unsigned long key; /* the key for this entry */
192 struct hash_entry *next; /* next entry in the bucket */
193 unsigned long nonce_count; /* for nonce-count checking */
194 char ha1[2*MD5_DIGESTSIZE+1]; /* for algorithm=MD5-sess */
195 char last_nonce[NONCE_LEN+1]; /* for one-time nonce's */
198 static struct hash_table {
199 client_entry **table;
200 unsigned long tbl_len;
201 unsigned long num_entries;
202 unsigned long num_created;
203 unsigned long num_removed;
204 unsigned long num_renewed;
208 /* struct to hold a parsed Authorization header */
210 enum hdr_sts { NO_HEADER, NOT_DIGEST, INVALID, VALID };
212 typedef struct digest_header_struct {
215 const char *username;
219 const char *algorithm;
222 unsigned long opaque_num;
223 const char *message_qop;
224 const char *nonce_count;
225 /* the following fields are not (directly) from the header */
226 apr_time_t nonce_time;
227 enum hdr_sts auth_hdr_sts;
228 const char *raw_request_uri;
229 uri_components *psd_request_uri;
231 client_entry *client;
235 /* (mostly) nonce stuff */
237 typedef union time_union {
239 unsigned char arr[sizeof(apr_time_t)];
243 static unsigned char secret[SECRET_LEN];
244 static int call_cnt = 0;
247 /* client-list, opaque, and one-time-nonce stuff */
249 static apr_shmem_t *client_shm = NULL;
250 static unsigned long *opaque_cntr;
251 static apr_time_t *otn_counter; /* one-time-nonce counter */
252 static apr_lock_t *client_lock = NULL;
253 static apr_lock_t *opaque_lock = NULL;
254 static char client_lock_name[L_tmpnam];
255 static char opaque_lock_name[L_tmpnam];
257 #define DEF_SHMEM_SIZE 1000L /* ~ 12 entries */
258 #define DEF_NUM_BUCKETS 15L
261 static long shmem_size = DEF_SHMEM_SIZE;
262 static long num_buckets = DEF_NUM_BUCKETS;
265 module MODULE_VAR_EXPORT auth_digest_module;
268 * initialization code
271 static apr_status_t cleanup_tables(void *not_used)
273 ap_log_rerror(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
274 "Digest: cleaning up shared memory");
278 apr_shm_destroy(client_shm);
283 apr_destroy_lock(client_lock);
288 apr_destroy_lock(opaque_lock);
295 static void initialize_secret(server_rec *s)
299 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, s,
300 "Digest: generating secret for digest authentication ...");
302 /* TODO - make sure this func works (compiles?) on win32 */
303 status = apr_generate_random_bytes(secret, sizeof(secret));
305 if(!(status == APR_SUCCESS)) {
307 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, 0, s,
308 "Digest: error generating secret: %s",
309 apr_strerror(status, buf, sizeof(buf)));
313 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, s, "Digest: done");
316 static void log_error_and_cleanup(char *msg, apr_status_t sts, server_rec *s)
318 ap_log_error(APLOG_MARK, APLOG_ERR, sts, s,
319 "Digest: %s - all nonce-count checking, one-time nonces, and "
320 "MD5-sess algorithm disabled", msg);
322 cleanup_tables(NULL);
325 static void initialize_tables(server_rec *s, apr_pool_t *ctx)
330 /* set up client list */
332 sts = apr_shm_init(&client_shm, shmem_size, tmpnam(NULL), ctx);
333 if (sts != APR_SUCCESS) {
334 log_error_and_cleanup("failed to create shared memory segments", sts, s);
338 client_list = apr_shm_malloc(client_shm, sizeof(*client_list) +
339 sizeof(client_entry*)*num_buckets);
341 log_error_and_cleanup("failed to allocate shared memory", -1, s);
344 client_list->table = (client_entry**) (client_list + 1);
345 for (idx=0; idx<num_buckets; idx++)
346 client_list->table[idx] = NULL;
347 client_list->tbl_len = num_buckets;
348 client_list->num_entries = 0;
350 tmpnam(client_lock_name);
351 sts = apr_create_lock(&client_lock, APR_READWRITE, APR_LOCKALL,
352 client_lock_name, ctx);
353 if (sts != APR_SUCCESS) {
354 log_error_and_cleanup("failed to create lock", sts, s);
361 opaque_cntr = apr_shm_malloc(client_shm, sizeof(*opaque_cntr));
362 if (opaque_cntr == NULL) {
363 log_error_and_cleanup("failed to allocate shared memory", -1, s);
368 tmpnam(opaque_lock_name);
369 sts = apr_create_lock(&opaque_lock, APR_MUTEX, APR_LOCKALL,
370 opaque_lock_name, ctx);
371 if (sts != APR_SUCCESS) {
372 log_error_and_cleanup("failed to create lock", sts, s);
377 /* setup one-time-nonce counter */
379 otn_counter = apr_shm_malloc(client_shm, sizeof(*otn_counter));
380 if (otn_counter == NULL) {
381 log_error_and_cleanup("failed to allocate shared memory", -1, s);
392 static void initialize_module(apr_pool_t *p, apr_pool_t *plog,
393 apr_pool_t *ptemp, server_rec *s)
395 /* keep from doing the init more than once at startup, and delay
396 * the init until the second round
401 /* only initialize the secret on startup, not on restarts */
403 initialize_secret(s);
405 /* Disable shmem until pools/init gets sorted out - remove next line when fixed */
406 #define APR_HAS_SHARED_MEMORY 0
408 #if APR_HAS_SHARED_MEMORY
409 /* Note: this stuff is currently fixed for the lifetime of the server,
410 * i.e. even across restarts. This means that A) any shmem-size
411 * configuration changes are ignored, and B) certain optimizations,
412 * such as only allocating the smallest necessary entry for each
413 * client, can't be done. However, the alternative is a nightmare:
414 * we can't call apr_shm_destroy on a graceful restart because there
415 * will be children using the tables, and we also don't know when the
416 * last child dies. Therefore we can never clean up the old stuff,
417 * creating a creeping memory leak.
419 initialize_tables(s, p);
420 apr_register_cleanup(p, NULL, cleanup_tables, apr_null_cleanup);
421 #endif /* APR_HAS_SHARED_MEMORY */
424 static void initialize_child(apr_pool_t *p, server_rec *s)
431 if ((sts = apr_child_init_lock(&client_lock, client_lock_name, p))
433 || (sts = apr_child_init_lock(&opaque_lock, opaque_lock_name, p))
435 log_error_and_cleanup("failed to create lock", sts, s);
444 static void *create_digest_dir_config(apr_pool_t *p, char *dir)
446 digest_config_rec *conf;
448 if (dir == NULL) return NULL;
450 conf = (digest_config_rec *) apr_pcalloc(p, sizeof(digest_config_rec));
452 conf->qop_list = apr_palloc(p, sizeof(char*));
453 conf->qop_list[0] = NULL;
454 conf->nonce_lifetime = DFLT_NONCE_LIFE;
455 conf->dir_name = apr_pstrdup(p, dir);
456 conf->algorithm = DFLT_ALGORITHM;
462 static const char *set_realm(cmd_parms *cmd, void *config, const char *realm)
464 digest_config_rec *conf = (digest_config_rec *) config;
466 /* The core already handles the realm, but it's just too convenient to
467 * grab it ourselves too and cache some setups. However, we need to
468 * let the core get at it too, which is why we decline at the end -
469 * this relies on the fact that http_core is last in the list.
473 /* we precompute the part of the nonce hash that is constant (well,
474 * the host:port would be too, but that varies for .htaccess files
475 * and directives outside a virtual host section)
477 ap_SHA1Init(&conf->nonce_ctx);
478 ap_SHA1Update_binary(&conf->nonce_ctx, secret, sizeof(secret));
479 ap_SHA1Update_binary(&conf->nonce_ctx, (const unsigned char *) realm,
485 static const char *set_digest_file(cmd_parms *cmd, void *config,
488 ((digest_config_rec *) config)->pwfile = file;
492 static const char *set_group_file(cmd_parms *cmd, void *config,
495 ((digest_config_rec *) config)->grpfile = file;
499 static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
501 digest_config_rec *conf = (digest_config_rec *) config;
505 if (!strcasecmp(op, "none")) {
506 if (conf->qop_list[0] == NULL) {
507 conf->qop_list = apr_palloc(cmd->pool, 2 * sizeof(char*));
508 conf->qop_list[1] = NULL;
510 conf->qop_list[0] = "none";
514 if (!strcasecmp(op, "auth-int"))
515 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, cmd->server,
516 "Digest: WARNING: qop `auth-int' currently only works "
517 "correctly for responses with no entity");
518 else if (strcasecmp(op, "auth"))
519 return apr_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
521 for (cnt=0; conf->qop_list[cnt] != NULL; cnt++)
523 tmp = apr_palloc(cmd->pool, (cnt+2)*sizeof(char*));
524 memcpy(tmp, conf->qop_list, cnt*sizeof(char*));
525 tmp[cnt] = apr_pstrdup(cmd->pool, op);
527 conf->qop_list = tmp;
532 static const char *set_nonce_lifetime(cmd_parms *cmd, void *config,
538 lifetime = strtol(t, &endptr, 10);
539 if (endptr < (t+strlen(t)) && !ap_isspace(*endptr))
540 return apr_pstrcat(cmd->pool, "Invalid time in AuthDigestNonceLifetime: ", t, NULL);
542 ((digest_config_rec *) config)->nonce_lifetime = lifetime * AP_USEC_PER_SEC;
546 static const char *set_nonce_format(cmd_parms *cmd, void *config,
549 ((digest_config_rec *) config)->nonce_format = fmt;
550 return "AuthDigestNonceFormat is not implemented (yet)";
553 static const char *set_nc_check(cmd_parms *cmd, void *config, int flag)
555 if (flag && !client_shm)
556 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0,
557 cmd->server, "Digest: WARNING: nonce-count checking "
558 "is not supported on platforms without shared-memory "
559 "support - disabling check");
561 ((digest_config_rec *) config)->check_nc = flag;
565 static const char *set_algorithm(cmd_parms *cmd, void *config, const char *alg)
567 if (!strcasecmp(alg, "MD5-sess")) {
569 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0,
570 cmd->server, "Digest: WARNING: algorithm `MD5-sess' "
571 "is not supported on platforms without shared-memory "
572 "support - reverting to MD5");
576 else if (strcasecmp(alg, "MD5"))
577 return apr_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
579 ((digest_config_rec *) config)->algorithm = alg;
583 static const char *set_uri_list(cmd_parms *cmd, void *config, const char *uri)
585 digest_config_rec *c = (digest_config_rec *) config;
587 c->uri_list[strlen(c->uri_list)-1] = '\0';
588 c->uri_list = apr_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
591 c->uri_list = apr_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
595 static const char *set_shmem_size(cmd_parms *cmd, void *config,
596 const char *size_str)
601 size = strtol(size_str, &endptr, 10);
602 while (ap_isspace(*endptr)) endptr++;
603 if (*endptr == '\0' || *endptr == 'b' || *endptr == 'B')
605 else if (*endptr == 'k' || *endptr == 'K')
607 else if (*endptr == 'm' || *endptr == 'M')
610 return apr_pstrcat(cmd->pool, "Invalid size in AuthDigestShmemSize: ",
613 min = sizeof(*client_list) + sizeof(client_entry*) + sizeof(client_entry);
615 return apr_psprintf(cmd->pool, "size in AuthDigestShmemSize too small: "
616 "%ld < %ld", size, min, NULL);
619 num_buckets = (size - sizeof(*client_list)) /
620 (sizeof(client_entry*) + HASH_DEPTH * sizeof(client_entry));
621 if (num_buckets == 0)
623 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, 0, cmd->server,
624 "Digest: Set shmem-size: %ld, num-buckets: %ld", shmem_size,
630 static const command_rec digest_cmds[] =
632 {"AuthName", set_realm, NULL, OR_AUTHCFG, TAKE1,
633 "The authentication realm (e.g. \"Members Only\")"},
634 {"AuthDigestFile", set_digest_file, NULL, OR_AUTHCFG, TAKE1,
635 "The name of the file containing the usernames and password hashes"},
636 {"AuthDigestGroupFile", set_group_file, NULL, OR_AUTHCFG, TAKE1,
637 "The name of the file containing the group names and members"},
638 {"AuthDigestQop", set_qop, NULL, OR_AUTHCFG, ITERATE,
639 "A list of quality-of-protection options"},
640 {"AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG, TAKE1,
641 "Maximum lifetime of the server nonce (seconds)"},
642 {"AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG, TAKE1,
643 "The format to use when generating the server nonce"},
644 {"AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG, FLAG,
645 "Whether or not to check the nonce-count sent by the client"},
646 {"AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG, TAKE1,
647 "The algorithm used for the hash calculation"},
648 {"AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG, ITERATE,
649 "A list of URI's which belong to the same protection space as the current URI"},
650 {"AuthDigestShmemSize", set_shmem_size, NULL, RSRC_CONF, TAKE1,
651 "The amount of shared memory to allocate for keeping track of clients"},
659 * Each client is assigned a number, which is transfered in the opaque
660 * field of the WWW-Authenticate and Authorization headers. The number
661 * is just a simple counter which is incremented for each new client.
662 * Clients can't forge this number because it is hashed up into the
663 * server nonce, and that is checked.
665 * The clients are kept in a simple hash table, which consists of an
666 * array of client_entry's, each with a linked list of entries hanging
667 * off it. The client's number modulo the size of the array gives the
670 * The clients are garbage collected whenever a new client is allocated
671 * but there is not enough space left in the shared memory segment. A
672 * simple semi-LRU is used for this: whenever a client entry is accessed
673 * it is moved to the beginning of the linked list in its bucket (this
674 * also makes for faster lookups for current clients). The garbage
675 * collecter then just removes the oldest entry (i.e. the one at the
676 * end of the list) in each bucket.
678 * The main advantages of the above scheme are that it's easy to implement
679 * and it keeps the hash table evenly balanced (i.e. same number of entries
680 * in each bucket). The major disadvantage is that you may be throwing
681 * entries out which are in active use. This is not tragic, as these
682 * clients will just be sent a new client id (opaque field) and nonce
683 * with a stale=true (i.e. it will just look like the nonce expired,
684 * thereby forcing an extra round trip). If the shared memory segment
685 * has enough headroom over the current client set size then this should
686 * not occur too often.
688 * To help tune the size of the shared memory segment (and see if the
689 * above algorithm is really sufficient) a set of counters is kept
690 * indicating the number of clients held, the number of garbage collected
691 * clients, and the number of erroneously purged clients. These are printed
692 * out at each garbage collection run. Note that access to the counters is
693 * not synchronized because they are just indicaters, and whether they are
694 * off by a few doesn't matter; and for the same reason no attempt is made
695 * to guarantee the num_renewed is correct in the face of clients spoofing
700 * Get the client given its client number (the key). Returns the entry,
701 * or NULL if its not found.
703 * Access to the list itself is synchronized via locks. However, access
704 * to the entry returned by get_client() is NOT synchronized. This means
705 * that there are potentially problems if a client uses multiple,
706 * simultaneous connections to access url's within the same protection
707 * space. However, these problems are not new: when using multiple
708 * connections you have no guarantee of the order the requests are
709 * processed anyway, so you have problems with the nonce-count and
710 * one-time nonces anyway.
712 static client_entry *get_client(unsigned long key, const request_rec *r)
715 client_entry *entry, *prev = NULL;
718 if (!key || !client_shm) return NULL;
720 bucket = key % client_list->tbl_len;
721 entry = client_list->table[bucket];
723 apr_lock(client_lock /*, MM_LOCK_RD */);
725 while(entry && key != entry->key) {
730 if (entry && prev) { /* move entry to front of list */
731 prev->next = entry->next;
732 entry->next = client_list->table[bucket];
733 client_list->table[bucket] = entry;
736 apr_unlock(client_lock);
739 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, 0, r,
740 "get_client(): client %lu found", key);
742 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, 0, r,
743 "get_client(): client %lu not found", key);
749 /* A simple garbage-collecter to remove unused clients. It removes the
750 * last entry in each bucket and updates the counters. Returns the
751 * number of removed entries.
755 client_entry *entry, *prev;
756 unsigned long num_removed = 0, idx;
758 /* garbage collect all last entries */
760 for (idx=0; idx<client_list->tbl_len; idx++) {
761 entry = client_list->table[idx];
763 while (entry->next) { /* find last entry */
767 if (prev) prev->next = NULL; /* cut list */
768 else client_list->table[idx] = NULL;
769 if (entry) { /* remove entry */
770 apr_shm_free(client_shm, entry);
775 /* update counters and log */
777 client_list->num_entries -= num_removed;
778 client_list->num_removed += num_removed;
785 * Add a new client to the list. Returns the entry if successful, NULL
786 * otherwise. This triggers the garbage collection if memory is low.
788 static client_entry *add_client(unsigned long key, client_entry *info,
795 if (!key || !client_shm) return NULL;
797 bucket = key % client_list->tbl_len;
798 entry = client_list->table[bucket];
800 apr_lock(client_lock /*, MM_LOCK_RW */);
802 /* try to allocate a new entry */
804 entry = apr_shm_malloc(client_shm, sizeof(client_entry));
806 long num_removed = gc();
807 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, s,
808 "Digest: gc'd %ld client entries. Total new clients: "
809 "%ld; Total removed clients: %ld; Total renewed clients: "
811 client_list->num_created - client_list->num_renewed,
812 client_list->num_removed, client_list->num_renewed);
813 entry = apr_shm_malloc(client_shm, sizeof(client_entry));
814 if (!entry) return NULL; /* give up */
817 /* now add the entry */
819 memcpy(entry, info, sizeof(client_entry));
821 entry->next = client_list->table[bucket];
822 client_list->table[bucket] = entry;
823 client_list->num_created++;
824 client_list->num_entries++;
826 apr_unlock(client_lock);
828 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, 0, s,
829 "allocated new client %lu", key);
836 * Authorization header parser code
839 /* Parse the Authorization header, if it exists */
840 static int get_digest_rec(request_rec *r, digest_header_rec *resp)
842 const char *auth_line;
847 auth_line = apr_table_get(r->headers_in,
848 r->proxyreq ? "Proxy-Authorization"
851 resp->auth_hdr_sts = NO_HEADER;
855 resp->scheme = ap_getword_white(r->pool, &auth_line);
856 if (strcasecmp(resp->scheme, "Digest")) {
857 resp->auth_hdr_sts = NOT_DIGEST;
861 l = strlen(auth_line);
863 key = apr_palloc(r->pool, l+1);
864 value = apr_palloc(r->pool, l+1);
866 while (auth_line[0] != '\0') {
870 while (ap_isspace(auth_line[0])) auth_line++;
872 while (auth_line[0] != '=' && auth_line[0] != ','
873 && auth_line[0] != '\0' && !ap_isspace(auth_line[0]))
874 key[vk++] = *auth_line++;
876 while (ap_isspace(auth_line[0])) auth_line++;
880 if (auth_line[0] == '=') {
882 while (ap_isspace(auth_line[0])) auth_line++;
885 if (auth_line[0] == '\"') { /* quoted string */
887 while (auth_line[0] != '\"' && auth_line[0] != '\0') {
888 if (auth_line[0] == '\\' && auth_line[1] != '\0')
889 auth_line++; /* escaped char */
890 value[vv++] = *auth_line++;
892 if (auth_line[0] != '\0') auth_line++;
895 while (auth_line[0] != ',' && auth_line[0] != '\0'
896 && !ap_isspace(auth_line[0]))
897 value[vv++] = *auth_line++;
902 while (auth_line[0] != ',' && auth_line[0] != '\0') auth_line++;
903 if (auth_line[0] != '\0') auth_line++;
905 if (!strcasecmp(key, "username"))
906 resp->username = apr_pstrdup(r->pool, value);
907 else if (!strcasecmp(key, "realm"))
908 resp->realm = apr_pstrdup(r->pool, value);
909 else if (!strcasecmp(key, "nonce"))
910 resp->nonce = apr_pstrdup(r->pool, value);
911 else if (!strcasecmp(key, "uri"))
912 resp->uri = apr_pstrdup(r->pool, value);
913 else if (!strcasecmp(key, "response"))
914 resp->digest = apr_pstrdup(r->pool, value);
915 else if (!strcasecmp(key, "algorithm"))
916 resp->algorithm = apr_pstrdup(r->pool, value);
917 else if (!strcasecmp(key, "cnonce"))
918 resp->cnonce = apr_pstrdup(r->pool, value);
919 else if (!strcasecmp(key, "opaque"))
920 resp->opaque = apr_pstrdup(r->pool, value);
921 else if (!strcasecmp(key, "qop"))
922 resp->message_qop = apr_pstrdup(r->pool, value);
923 else if (!strcasecmp(key, "nc"))
924 resp->nonce_count = apr_pstrdup(r->pool, value);
927 if (!resp->username || !resp->realm || !resp->nonce || !resp->uri
929 || (resp->message_qop && (!resp->cnonce || !resp->nonce_count))) {
930 resp->auth_hdr_sts = INVALID;
935 resp->opaque_num = (unsigned long) strtol(resp->opaque, NULL, 16);
937 resp->auth_hdr_sts = VALID;
942 /* Because the browser may preemptively send auth info, incrementing the
943 * nonce-count when it does, and because the client does not get notified
944 * if the URI didn't need authentication after all, we need to be sure to
945 * update the nonce-count each time we receive an Authorization header no
946 * matter what the final outcome of the request. Furthermore this is a
947 * convenient place to get the request-uri (before any subrequests etc
948 * are initiated) and to initialize the request_config.
950 * Note that this must be called after mod_proxy had its go so that
951 * r->proxyreq is set correctly.
953 static int parse_hdr_and_update_nc(request_rec *r)
955 digest_header_rec *resp;
958 if (!ap_is_initial_req(r))
961 resp = apr_pcalloc(r->pool, sizeof(digest_header_rec));
962 resp->raw_request_uri = r->unparsed_uri;
963 resp->psd_request_uri = &r->parsed_uri;
964 resp->needed_auth = 0;
965 ap_set_module_config(r->request_config, &auth_digest_module, resp);
967 res = get_digest_rec(r, resp);
968 resp->client = get_client(resp->opaque_num, r);
969 if (res == OK && resp->client)
970 resp->client->nonce_count++;
977 * Nonce generation code
980 /* The hash part of the nonce is a SHA-1 hash of the time, realm, server host
981 * and port, opaque, and our secret.
983 static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
984 const server_rec *server,
985 const digest_config_rec *conf)
987 const char *hex = "0123456789abcdef";
988 unsigned char sha1[SHA_DIGESTSIZE];
992 memcpy(&ctx, &conf->nonce_ctx, sizeof(ctx));
994 ap_SHA1Update_binary(&ctx, (const unsigned char *) server->server_hostname,
995 strlen(server->server_hostname));
996 ap_SHA1Update_binary(&ctx, (const unsigned char *) &server->port,
997 sizeof(server->port));
999 ap_SHA1Update_binary(&ctx, (const unsigned char *) timestr, strlen(timestr));
1001 ap_SHA1Update_binary(&ctx, (const unsigned char *) opaque,
1003 ap_SHA1Final(sha1, &ctx);
1005 for (idx=0; idx<SHA_DIGESTSIZE; idx++) {
1006 *hash++ = hex[sha1[idx] >> 4];
1007 *hash++ = hex[sha1[idx] & 0xF];
1014 /* The nonce has the format b64(time)+hash .
1016 static const char *gen_nonce(apr_pool_t *p, apr_time_t now, const char *opaque,
1017 const server_rec *server,
1018 const digest_config_rec *conf)
1020 char *nonce = apr_palloc(p, NONCE_LEN+1);
1024 if (conf->nonce_lifetime != 0)
1026 else if (otn_counter)
1027 /* this counter is not synch'd, because it doesn't really matter
1028 * if it counts exactly.
1030 t.time = (*otn_counter)++;
1033 len = ap_base64encode_binary(nonce, t.arr, sizeof(t.arr));
1034 gen_nonce_hash(nonce+NONCE_TIME_LEN, nonce, opaque, server, conf);
1041 * Opaque and hash-table management
1045 * Generate a new client entry, add it to the list, and return the
1046 * entry. Returns NULL if failed.
1048 static client_entry *gen_client(const request_rec *r)
1051 client_entry new_entry = { 0, NULL, 0, "", "" }, *entry;
1053 if (!opaque_cntr) return NULL;
1055 apr_lock(opaque_lock /*, MM_LOCK_RW */);
1056 op = (*opaque_cntr)++;
1057 apr_unlock(opaque_lock);
1059 if (!(entry = add_client(op, &new_entry, r->server))) {
1060 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1061 "Digest: failed to allocate client entry - ignoring "
1073 * If you want to use algorithm=MD5-sess you must write get_userpw_hash()
1074 * yourself (see below). The dummy provided here just uses the hash from
1075 * the auth-file, i.e. it is only useful for testing client implementations
1080 * get_userpw_hash() will be called each time a new session needs to be
1081 * generated and is expected to return the equivalent of
1083 * h_urp = ap_md5(r->pool,
1084 * apr_pstrcat(r->pool, username, ":", ap_auth_name(r), ":", passwd))
1086 * (unsigned char *) apr_pstrcat(r->pool, h_urp, ":", resp->nonce, ":",
1087 * resp->cnonce, NULL));
1089 * or put differently, it must return
1091 * MD5(MD5(username ":" realm ":" password) ":" nonce ":" cnonce)
1093 * If something goes wrong, the failure must be logged and NULL returned.
1095 * You must implement this yourself, which will probably consist of code
1096 * contacting the password server with the necessary information (typically
1097 * the username, realm, nonce, and cnonce) and receiving the hash from it.
1099 * TBD: This function should probably be in a seperate source file so that
1100 * people need not modify mod_auth_digest.c each time they install a new
1101 * version of apache.
1103 static const char *get_userpw_hash(const request_rec *r,
1104 const digest_header_rec *resp,
1105 const digest_config_rec *conf)
1107 return ap_md5(r->pool,
1108 (unsigned char *) apr_pstrcat(r->pool, conf->ha1, ":", resp->nonce,
1109 ":", resp->cnonce, NULL));
1113 /* Retrieve current session H(A1). If there is none and "generate" is
1114 * true then a new session for MD5-sess is generated and stored in the
1115 * client struct; if generate is false, or a new session could not be
1116 * generated then NULL is returned (in case of failure to generate the
1117 * failure reason will have been logged already).
1119 static const char *get_session_HA1(const request_rec *r,
1120 digest_header_rec *resp,
1121 const digest_config_rec *conf,
1124 const char *ha1 = NULL;
1126 /* return the current sessions if there is one */
1127 if (resp->opaque && resp->client && resp->client->ha1[0])
1128 return resp->client->ha1;
1132 /* generate a new session */
1134 resp->client = gen_client(r);
1136 ha1 = get_userpw_hash(r, resp, conf);
1138 memcpy(resp->client->ha1, ha1, sizeof(resp->client->ha1));
1145 static void clear_session(const digest_header_rec *resp)
1148 resp->client->ha1[0] = '\0';
1153 * Authorization challenge generation code (for WWW-Authenticate)
1156 static const char *guess_domain(apr_pool_t *p, const char *uri,
1157 const char *filename, const char *dir)
1159 size_t u_len = strlen(uri), f_len = strlen(filename), d_len = strlen(dir);
1163 /* Because of things like mod_alias and mod_rewrite and the fact that
1164 * protection is often on a directory basis (not a location basis) it
1165 * is hard to determine the uri to put in the domain attribute.
1167 * What we do is the following: first we see if the directory is
1168 * a prefix for the uri - if this is the case we assume that therefore
1169 * a <Location> directive was protecting this uri and we can use it
1172 if (u_len >= d_len && !memcmp(uri, dir, d_len))
1175 /* Now we check for <Files ...>, and if we find one we send back a
1176 * dummy uri - this is the only way to specify that the protection
1177 * space only covers a single uri.
1180 /* This doesn't work for Amaya (ok, it's of arguable validity in
1181 * the first place), so just return the file name instead
1182 return "http://0.0.0.0/";
1186 /* Next we find the largest common common suffix of the request-uri
1187 * and the final file name, ignoring any extensions; this gives us a
1188 * hint as to where any rewriting could've occured (assuming that some
1189 * prefix of the uri is rewritten, not a suffix).
1191 u = uri + u_len - 1; /* strip any extension */
1192 while (u > uri && *u != '/') u--;
1193 while (*u && *u != '.') u++;
1197 f = filename + f_len - 1; /* strip any extension */
1198 while (f > filename && *f != '/') f--;
1199 while (*f && *f != '.') f++;
1203 while (*f == *u && f > filename && u > uri) u--, f--;
1206 while (*f && *f != '/') f++, u++; /* suffix must start with / */
1208 /* Now, if the directory reaches into this common suffix then we can
1209 * take the uri with the same reach.
1211 if ((unsigned long) (f-filename) < d_len) {
1212 char *tmp = apr_pstrdup(p, uri);
1213 tmp[(u-uri)+(d_len-(f-filename))] = '\0';
1217 return ""; /* give up */
1221 static const char *ltox(apr_pool_t *p, unsigned long num)
1224 return apr_psprintf(p, "%lx", num);
1229 static void note_digest_auth_failure(request_rec *r,
1230 const digest_config_rec *conf,
1231 digest_header_rec *resp, int stale)
1233 const char *qop, *opaque, *opaque_param, *domain, *nonce;
1238 if (conf->qop_list[0] == NULL) {
1239 qop = ", qop=\"auth\"";
1240 } else if (!strcasecmp(conf->qop_list[0], "none")) {
1243 qop = apr_pstrcat(r->pool, ", qop=\"", conf->qop_list[0], NULL);
1244 for (cnt=1; conf->qop_list[cnt] != NULL; cnt++)
1245 qop = apr_pstrcat(r->pool, qop, ",", conf->qop_list[cnt], NULL);
1246 qop = apr_pstrcat(r->pool, qop, "\"", NULL);
1251 if (resp->opaque == NULL) {
1253 if ((conf->check_nc || conf->nonce_lifetime == 0
1254 || !strcasecmp(conf->algorithm, "MD5-sess"))
1255 && (resp->client = gen_client(r)) != NULL)
1256 opaque = ltox(r->pool, resp->client->key);
1258 opaque = ""; /* opaque not needed */
1260 else if (resp->client == NULL) {
1261 /* client info was gc'd */
1262 resp->client = gen_client(r);
1263 if (resp->client != NULL) {
1264 opaque = ltox(r->pool, resp->client->key);
1266 client_list->num_renewed++;
1269 opaque = ""; /* ??? */
1272 opaque = resp->opaque;
1273 /* we're generating a new nonce, so reset the nonce-count */
1274 resp->client->nonce_count = 0;
1278 opaque_param = apr_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
1280 opaque_param = NULL;
1284 nonce = gen_nonce(r->pool, r->request_time, opaque, r->server, conf);
1285 if (resp->client && conf->nonce_lifetime == 0)
1286 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1288 /* Setup MD5-sess stuff. Note that we just clear out the session
1289 * info here, since we can't generate a new session until the request
1290 * from the client comes in with the cnonce.
1293 if (!strcasecmp(conf->algorithm, "MD5-sess"))
1294 clear_session(resp);
1296 /* setup domain attribute. We want to send this attribute wherever
1297 * possible so that the client won't send the Authorization header
1298 * unneccessarily (it's usually > 200 bytes!).
1302 domain = NULL; /* don't send domain for proxy requests */
1303 else if (conf->uri_list)
1304 domain = conf->uri_list;
1306 /* They didn't specify any domain, so let's guess at it */
1307 domain = guess_domain(r->pool, resp->psd_request_uri->path, r->filename,
1309 if (domain[0] == '/' && domain[1] == '\0')
1310 domain = NULL; /* "/" is the default, so no need to send it */
1312 domain = apr_pstrcat(r->pool, ", domain=\"", domain, "\"", NULL);
1315 apr_table_mergen(r->err_headers_out,
1316 r->proxyreq ? "Proxy-Authenticate" : "WWW-Authenticate",
1317 apr_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%s\", "
1318 "algorithm=%s%s%s%s%s",
1319 ap_auth_name(r), nonce, conf->algorithm,
1320 opaque_param ? opaque_param : "",
1321 domain ? domain : "",
1322 stale ? ", stale=true" : "", qop));
1328 * Authorization header verification code
1331 static const char *get_hash(request_rec *r, const char *user,
1332 const char *realm, const char *auth_pwfile)
1335 char l[MAX_STRING_LEN];
1340 if ((sts = ap_pcfg_openfile(&f, r->pool, auth_pwfile)) != APR_SUCCESS) {
1341 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
1342 "Digest: Could not open password file: %s", auth_pwfile);
1345 while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
1346 if ((l[0] == '#') || (!l[0]))
1349 w = ap_getword(r->pool, &rpw, ':');
1350 x = ap_getword(r->pool, &rpw, ':');
1352 if (x && w && !strcmp(user, w) && !strcmp(realm, x)) {
1353 ap_cfg_closefile(f);
1354 return apr_pstrdup(r->pool, rpw);
1357 ap_cfg_closefile(f);
1361 static int check_nc(const request_rec *r, const digest_header_rec *resp,
1362 const digest_config_rec *conf)
1365 const char *snc = resp->nonce_count;
1368 if (!conf->check_nc || !client_shm)
1371 nc = strtol(snc, &endptr, 16);
1372 if (endptr < (snc+strlen(snc)) && !ap_isspace(*endptr)) {
1373 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1374 "Digest: invalid nc %s received - not a number", snc);
1381 if (nc != resp->client->nonce_count) {
1382 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1383 "Digest: Warning, possible replay attack: nonce-count "
1384 "check failed: %lu != %lu", nc,
1385 resp->client->nonce_count);
1392 static int check_nonce(request_rec *r, digest_header_rec *resp,
1393 const digest_config_rec *conf)
1397 time_rec nonce_time;
1398 char tmp, hash[NONCE_HASH_LEN+1];
1400 if (strlen(resp->nonce) != NONCE_LEN) {
1401 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1402 "Digest: invalid nonce %s received - length is not %d",
1403 resp->nonce, NONCE_LEN);
1404 note_digest_auth_failure(r, conf, resp, 1);
1405 return HTTP_UNAUTHORIZED;
1408 tmp = resp->nonce[NONCE_TIME_LEN];
1409 resp->nonce[NONCE_TIME_LEN] = '\0';
1410 len = ap_base64decode_binary(nonce_time.arr, resp->nonce);
1411 gen_nonce_hash(hash, resp->nonce, resp->opaque, r->server, conf);
1412 resp->nonce[NONCE_TIME_LEN] = tmp;
1413 resp->nonce_time = nonce_time.time;
1415 if (strcmp(hash, resp->nonce+NONCE_TIME_LEN)) {
1416 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1417 "Digest: invalid nonce %s received - hash is not %s",
1419 note_digest_auth_failure(r, conf, resp, 1);
1420 return HTTP_UNAUTHORIZED;
1423 dt = r->request_time - nonce_time.time;
1424 if (conf->nonce_lifetime > 0 && dt < 0) {
1425 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1426 "Digest: invalid nonce %s received - user attempted "
1427 "time travel", resp->nonce);
1428 note_digest_auth_failure(r, conf, resp, 1);
1429 return HTTP_UNAUTHORIZED;
1432 if (conf->nonce_lifetime > 0) {
1433 if (dt > conf->nonce_lifetime) {
1434 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,r,
1435 "Digest: user %s: nonce expired (%.2lf seconds old - max lifetime %.2lf) - sending new nonce",
1436 r->user, ((double)dt)/AP_USEC_PER_SEC,
1437 ((double)(conf->nonce_lifetime))/AP_USEC_PER_SEC);
1438 note_digest_auth_failure(r, conf, resp, 1);
1439 return HTTP_UNAUTHORIZED;
1442 else if (conf->nonce_lifetime == 0 && resp->client) {
1443 if (memcmp(resp->client->last_nonce, resp->nonce, NONCE_LEN)) {
1444 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
1445 "Digest: user %s: one-time-nonce mismatch - sending "
1446 "new nonce", r->user);
1447 note_digest_auth_failure(r, conf, resp, 1);
1448 return HTTP_UNAUTHORIZED;
1451 /* else (lifetime < 0) => never expires */
1456 /* The actual MD5 code... whee */
1459 static const char *old_digest(const request_rec *r,
1460 const digest_header_rec *resp, const char *ha1)
1464 ha2 = ap_md5(r->pool, (unsigned char *)apr_pstrcat(r->pool, r->method, ":",
1466 return ap_md5(r->pool,
1467 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1472 static const char *new_digest(const request_rec *r,
1473 digest_header_rec *resp,
1474 const digest_config_rec *conf)
1476 const char *ha1, *ha2, *a2;
1478 if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
1479 ha1 = get_session_HA1(r, resp, conf, 1);
1486 if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int"))
1487 a2 = apr_pstrcat(r->pool, r->method, ":", resp->uri, ":",
1488 ap_md5(r->pool, (const unsigned char*) ""), NULL); /* TBD */
1490 a2 = apr_pstrcat(r->pool, r->method, ":", resp->uri, NULL);
1491 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1493 return ap_md5(r->pool,
1494 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1495 ":", resp->nonce_count, ":",
1497 resp->message_qop, ":", ha2,
1502 static void copy_uri_components(uri_components *dst, uri_components *src,
1504 if (src->scheme && src->scheme[0] != '\0')
1505 dst->scheme = src->scheme;
1507 dst->scheme = (char *) "http";
1509 if (src->hostname && src->hostname[0] != '\0') {
1510 dst->hostname = apr_pstrdup(r->pool, src->hostname);
1511 ap_unescape_url(dst->hostname);
1514 dst->hostname = (char *) ap_get_server_name(r);
1516 if (src->port_str && src->port_str[0] != '\0')
1517 dst->port = src->port;
1519 dst->port = ap_get_server_port(r);
1521 if (src->path && src->path[0] != '\0') {
1522 dst->path = apr_pstrdup(r->pool, src->path);
1523 ap_unescape_url(dst->path);
1526 dst->path = src->path;
1528 if (src->query && src->query[0] != '\0') {
1529 dst->query = apr_pstrdup(r->pool, src->query);
1530 ap_unescape_url(dst->query);
1533 dst->query = src->query;
1536 /* These functions return 0 if client is OK, and proper error status
1537 * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
1538 * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
1539 * couldn't figure out how to tell if the client is authorized or not.
1541 * If they return DECLINED, and all other modules also decline, that's
1542 * treated by the server core as a configuration error, logged and
1546 /* Determine user ID, and check if the attributes are correct, if it
1547 * really is that user, if the nonce is correct, etc.
1550 static int authenticate_digest_user(request_rec *r)
1552 digest_config_rec *conf;
1553 digest_header_rec *resp;
1554 request_rec *mainreq;
1558 /* do we require Digest auth for this URI? */
1560 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest"))
1563 if (!ap_auth_name(r)) {
1564 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1565 "Digest: need AuthName: %s", r->uri);
1566 return HTTP_INTERNAL_SERVER_ERROR;
1570 /* get the client response and mark */
1573 while (mainreq->main != NULL) mainreq = mainreq->main;
1574 while (mainreq->prev != NULL) mainreq = mainreq->prev;
1575 resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1576 &auth_digest_module);
1577 resp->needed_auth = 1;
1582 conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1583 &auth_digest_module);
1586 /* check for existence and syntax of Auth header */
1588 if (resp->auth_hdr_sts != VALID) {
1589 if (resp->auth_hdr_sts == NOT_DIGEST)
1590 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1591 "Digest: client used wrong authentication scheme "
1592 "`%s': %s", resp->scheme, r->uri);
1593 else if (resp->auth_hdr_sts == INVALID)
1594 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1595 "Digest: missing user, realm, nonce, uri, digest, "
1596 "cnonce, or nonce_count in authorization header: %s",
1598 /* else (resp->auth_hdr_sts == NO_HEADER) */
1599 note_digest_auth_failure(r, conf, resp, 0);
1600 return HTTP_UNAUTHORIZED;
1603 r->user = (char *) resp->username;
1604 r->ap_auth_type = (char *) "Digest";
1606 /* check the auth attributes */
1608 if (strcmp(resp->uri, resp->raw_request_uri)) {
1609 /* Hmm, the simple match didn't work (probably a proxy modified the
1610 * request-uri), so lets do a more sophisticated match
1612 uri_components r_uri, d_uri;
1614 copy_uri_components(&r_uri, resp->psd_request_uri, r);
1615 if (ap_parse_uri_components(r->pool, resp->uri, &d_uri) != HTTP_OK) {
1616 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1617 "Digest: invalid uri <%s> in Authorization header",
1619 return HTTP_BAD_REQUEST;
1623 ap_unescape_url(d_uri.hostname);
1625 ap_unescape_url(d_uri.path);
1627 ap_unescape_url(d_uri.query);
1629 if (r->method_number == M_CONNECT) {
1630 if (strcmp(resp->uri, r_uri.hostinfo)) {
1631 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1632 "Digest: uri mismatch - <%s> does not match "
1633 "request-uri <%s>", resp->uri, r_uri.hostinfo);
1634 return HTTP_BAD_REQUEST;
1638 /* check hostname matches, if present */
1639 (d_uri.hostname && d_uri.hostname[0] != '\0'
1640 && strcasecmp(d_uri.hostname, r_uri.hostname))
1641 /* check port matches, if present */
1642 || (d_uri.port_str && d_uri.port != r_uri.port)
1643 /* check that server-port is default port if no port present */
1644 || (d_uri.hostname && d_uri.hostname[0] != '\0'
1645 && !d_uri.port_str && r_uri.port != ap_default_port(r))
1646 /* check that path matches */
1647 || (d_uri.path != r_uri.path
1648 /* either exact match */
1649 && (!d_uri.path || !r_uri.path
1650 || strcmp(d_uri.path, r_uri.path))
1651 /* or '*' matches empty path in scheme://host */
1652 && !(d_uri.path && !r_uri.path && resp->psd_request_uri->hostname
1653 && d_uri.path[0] == '*' && d_uri.path[1] == '\0'))
1654 /* check that query matches */
1655 || (d_uri.query != r_uri.query
1656 && (!d_uri.query || !r_uri.query
1657 || strcmp(d_uri.query, r_uri.query)))
1659 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1660 "Digest: uri mismatch - <%s> does not match "
1661 "request-uri <%s>", resp->uri, resp->raw_request_uri);
1662 return HTTP_BAD_REQUEST;
1666 if (resp->opaque && resp->opaque_num == 0) {
1667 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1668 "Digest: received invalid opaque - got `%s'",
1670 note_digest_auth_failure(r, conf, resp, 0);
1671 return HTTP_UNAUTHORIZED;
1674 if (strcmp(resp->realm, conf->realm)) {
1675 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1676 "Digest: realm mismatch - got `%s' but expected `%s'",
1677 resp->realm, conf->realm);
1678 note_digest_auth_failure(r, conf, resp, 0);
1679 return HTTP_UNAUTHORIZED;
1682 if (resp->algorithm != NULL
1683 && strcasecmp(resp->algorithm, "MD5")
1684 && strcasecmp(resp->algorithm, "MD5-sess")) {
1685 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1686 "Digest: unknown algorithm `%s' received: %s",
1687 resp->algorithm, r->uri);
1688 note_digest_auth_failure(r, conf, resp, 0);
1689 return HTTP_UNAUTHORIZED;
1695 if (!(conf->ha1 = get_hash(r, r->user, conf->realm, conf->pwfile))) {
1696 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1697 "Digest: user `%s' in realm `%s' not found: %s",
1698 r->user, conf->realm, r->uri);
1699 note_digest_auth_failure(r, conf, resp, 0);
1700 return HTTP_UNAUTHORIZED;
1704 if (resp->message_qop == NULL) {
1705 /* old (rfc-2069) style digest */
1706 if (strcmp(resp->digest, old_digest(r, resp, conf->ha1))) {
1707 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1708 "Digest: user %s: password mismatch: %s", r->user,
1710 note_digest_auth_failure(r, conf, resp, 0);
1711 return HTTP_UNAUTHORIZED;
1715 const char *exp_digest;
1717 for (idx=0; conf->qop_list[idx] != NULL; idx++) {
1718 if (!strcasecmp(conf->qop_list[idx], resp->message_qop)) {
1725 && !(conf->qop_list[0] == NULL
1726 && !strcasecmp(resp->message_qop, "auth"))) {
1727 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1728 "Digest: invalid qop `%s' received: %s",
1729 resp->message_qop, r->uri);
1730 note_digest_auth_failure(r, conf, resp, 0);
1731 return HTTP_UNAUTHORIZED;
1734 exp_digest = new_digest(r, resp, conf);
1736 /* we failed to allocate a client struct */
1737 return HTTP_INTERNAL_SERVER_ERROR;
1739 if (strcmp(resp->digest, exp_digest)) {
1740 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1741 "Digest: user %s: password mismatch: %s", r->user,
1743 note_digest_auth_failure(r, conf, resp, 0);
1744 return HTTP_UNAUTHORIZED;
1748 if (check_nc(r, resp, conf) != OK) {
1749 note_digest_auth_failure(r, conf, resp, 0);
1750 return HTTP_UNAUTHORIZED;
1753 /* Note: this check is done last so that a "stale=true" can be
1754 generated if the nonce is old */
1755 if ((res = check_nonce(r, resp, conf)))
1766 static apr_table_t *groups_for_user(request_rec *r, const char *user,
1767 const char *grpfile)
1770 apr_table_t *grps = apr_make_table(r->pool, 15);
1772 char l[MAX_STRING_LEN];
1773 const char *group_name, *ll, *w;
1776 if ((sts = ap_pcfg_openfile(&f, r->pool, grpfile)) != APR_SUCCESS) {
1777 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
1778 "Digest: Could not open group file: %s", grpfile);
1782 if (apr_create_pool(&sp, r->pool) != APR_SUCCESS)
1785 while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
1786 if ((l[0] == '#') || (!l[0]))
1791 group_name = ap_getword(sp, &ll, ':');
1794 w = ap_getword_conf(sp, &ll);
1795 if (!strcmp(w, user)) {
1796 apr_table_setn(grps, apr_pstrdup(r->pool, group_name), "in");
1802 ap_cfg_closefile(f);
1803 apr_destroy_pool(sp);
1808 static int digest_check_auth(request_rec *r)
1810 const digest_config_rec *conf =
1811 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1812 &auth_digest_module);
1813 const char *user = r->user;
1814 int m = r->method_number;
1815 int method_restricted = 0;
1818 apr_table_t *grpstatus;
1819 const apr_array_header_t *reqs_arr;
1822 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest"))
1825 reqs_arr = ap_requires(r);
1826 /* If there is no "requires" directive, then any user will do.
1830 reqs = (require_line *) reqs_arr->elts;
1833 grpstatus = groups_for_user(r, user, conf->grpfile);
1837 for (x = 0; x < reqs_arr->nelts; x++) {
1839 if (!(reqs[x].method_mask & (1 << m)))
1842 method_restricted = 1;
1844 t = reqs[x].requirement;
1845 w = ap_getword_white(r->pool, &t);
1846 if (!strcasecmp(w, "valid-user"))
1848 else if (!strcasecmp(w, "user")) {
1850 w = ap_getword_conf(r->pool, &t);
1851 if (!strcmp(user, w))
1855 else if (!strcasecmp(w, "group")) {
1860 w = ap_getword_conf(r->pool, &t);
1861 if (apr_table_get(grpstatus, w))
1866 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1867 "Digest: access to %s failed, reason: unknown require "
1868 "directive \"%s\"", r->uri, reqs[x].requirement);
1873 if (!method_restricted)
1876 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1877 "Digest: access to %s failed, reason: user %s not allowed access",
1880 note_digest_auth_failure(r, conf,
1881 (digest_header_rec *) ap_get_module_config(r->request_config,
1882 &auth_digest_module),
1884 return HTTP_UNAUTHORIZED;
1889 * Authorization-Info header code
1893 static const char *hdr(const apr_table_t *tbl, const char *name)
1895 const char *val = apr_table_get(tbl, name);
1903 static int add_auth_info(request_rec *r)
1905 const digest_config_rec *conf =
1906 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1907 &auth_digest_module);
1908 digest_header_rec *resp =
1909 (digest_header_rec *) ap_get_module_config(r->request_config,
1910 &auth_digest_module);
1911 const char *ai = NULL, *digest = NULL, *nextnonce = "";
1913 if (resp == NULL || !resp->needed_auth || conf == NULL)
1919 if (resp->message_qop == NULL) {
1920 /* old client, so calc rfc-2069 digest */
1923 /* most of this totally bogus because the handlers don't set the
1924 * headers until the final handler phase (I wonder why this phase
1925 * is called fixup when there's almost nothing you can fix up...)
1927 * Because it's basically impossible to get this right (e.g. the
1928 * Content-length is never set yet when we get here, and we can't
1929 * calc the entity hash) it's best to just leave this #def'd out.
1931 char date[AP_RFC822_DATE_LEN];
1932 apr_rfc822_date(date, r->request_time);
1935 (unsigned char *) apr_pstrcat(r->pool, resp->raw_request_uri,
1937 r->content_type ? r->content_type : ap_default_type(r), ":",
1938 hdr(r->headers_out, "Content-Length"), ":",
1939 r->content_encoding ? r->content_encoding : "", ":",
1940 hdr(r->headers_out, "Last-Modified"), ":",
1941 r->no_cache && !apr_table_get(r->headers_out, "Expires") ?
1943 hdr(r->headers_out, "Expires"),
1947 (unsigned char *)apr_pstrcat(r->pool, conf->ha1, ":",
1952 ap_md5(r->pool, (unsigned char *) ""), /* H(entity) - TBD */
1960 if (conf->nonce_lifetime > 0) {
1961 /* send nextnonce if current nonce will expire in less than 30 secs */
1962 if ((r->request_time - resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
1963 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"",
1964 gen_nonce(r->pool, r->request_time,
1965 resp->opaque, r->server, conf),
1968 resp->client->nonce_count = 0;
1971 else if (conf->nonce_lifetime == 0 && resp->client) {
1972 const char *nonce = gen_nonce(r->pool, 0, resp->opaque, r->server,
1974 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
1975 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1977 /* else nonce never expires, hence no nextnonce */
1980 /* do rfc-2069 digest
1982 if (conf->qop_list[0] && !strcasecmp(conf->qop_list[0], "none")
1983 && resp->message_qop == NULL) {
1984 /* use only RFC-2069 format */
1986 ai = apr_pstrcat(r->pool, "digest=\"", digest, "\"", nextnonce,NULL);
1991 const char *resp_dig, *ha1, *a2, *ha2;
1993 /* calculate rspauth attribute
1995 if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
1996 ha1 = get_session_HA1(r, resp, conf, 0);
1998 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1999 "Digest: internal error: couldn't find session "
2000 "info for user %s", resp->username);
2007 if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int"))
2008 a2 = apr_pstrcat(r->pool, ":", resp->uri, ":",
2009 ap_md5(r->pool, (const unsigned char *) ""), NULL); /* TBD */
2011 a2 = apr_pstrcat(r->pool, ":", resp->uri, NULL);
2012 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
2014 resp_dig = ap_md5(r->pool,
2015 (unsigned char *)apr_pstrcat(r->pool, ha1, ":",
2017 resp->nonce_count, ":",
2020 resp->message_qop : "",
2023 /* assemble Authentication-Info header
2025 ai = apr_pstrcat(r->pool,
2026 "rspauth=\"", resp_dig, "\"",
2028 resp->cnonce ? ", cnonce=\"" : "",
2029 resp->cnonce ? ap_escape_quotes(r->pool, resp->cnonce) :
2031 resp->cnonce ? "\"" : "",
2032 resp->nonce_count ? ", nc=" : "",
2033 resp->nonce_count ? resp->nonce_count : "",
2034 resp->message_qop ? ", qop=" : "",
2035 resp->message_qop ? resp->message_qop : "",
2036 digest ? "digest=\"" : "",
2037 digest ? digest : "",
2043 apr_table_mergen(r->headers_out,
2044 r->proxyreq ? "Proxy-Authentication-Info"
2045 : "Authentication-Info",
2051 static void register_hooks(void)
2053 static const char * const cfgPost[]={ "http_core.c", NULL };
2054 static const char * const parsePre[]={ "mod_proxy.c", NULL };
2056 ap_hook_post_config(initialize_module, NULL, cfgPost, AP_HOOK_MIDDLE);
2057 ap_hook_child_init(initialize_child, NULL, NULL, AP_HOOK_MIDDLE);
2058 ap_hook_post_read_request(parse_hdr_and_update_nc, parsePre, NULL, AP_HOOK_MIDDLE);
2059 ap_hook_check_user_id(authenticate_digest_user, NULL, NULL, AP_HOOK_MIDDLE);
2060 ap_hook_auth_checker(digest_check_auth, NULL, NULL, AP_HOOK_MIDDLE);
2061 ap_hook_fixups(add_auth_info, NULL, NULL, AP_HOOK_MIDDLE);
2064 module MODULE_VAR_EXPORT auth_digest_module =
2066 STANDARD20_MODULE_STUFF,
2067 create_digest_dir_config, /* dir config creater */
2068 NULL, /* dir merger --- default is to override */
2069 NULL, /* server config */
2070 NULL, /* merge server config */
2071 digest_cmds, /* command table */
2072 NULL, /* handlers */
2073 register_hooks /* register hooks */