1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * mod_auth_digest: MD5 digest authentication
20 * Originally by Alexei Kosut <akosut@nueva.pvt.k12.ca.us>
21 * Updated to RFC-2617 by Ronald Tschalär <ronald@innovation.ch>
22 * based on mod_auth, by Rob McCool and Robert S. Thau
24 * This module an updated version of modules/standard/mod_digest.c
25 * It is still fairly new and problems may turn up - submit problem
26 * reports to the Apache bug-database, or send them directly to me
27 * at ronald@innovation.ch.
29 * Requires either /dev/random (or equivalent) or the truerand library,
30 * available for instance from
31 * ftp://research.att.com/dist/mab/librand.shar
34 * - qop=auth-int (when streams and trailer support available)
35 * - nonce-format configurability
36 * - Proxy-Authorization-Info header is set by this module, but is
37 * currently ignored by mod_proxy (needs patch to mod_proxy)
38 * - generating the secret takes a while (~ 8 seconds) if using the
40 * - The source of the secret should be run-time directive (with server
41 * scope: RSRC_CONF). However, that could be tricky when trying to
42 * choose truerand vs. file...
43 * - shared-mem not completely tested yet. Seems to work ok for me,
44 * but... (definitely won't work on Windoze)
45 * - Sharing a realm among multiple servers has following problems:
46 * o Server name and port can't be included in nonce-hash
47 * (we need two nonce formats, which must be configured explicitly)
48 * o Nonce-count check can't be for equal, or then nonce-count checking
49 * must be disabled. What we could do is the following:
50 * (expected < received) ? set expected = received : issue error
51 * The only problem is that it allows replay attacks when somebody
52 * captures a packet sent to one server and sends it to another
53 * one. Should we add "AuthDigestNcCheck Strict"?
54 * - expired nonces give amaya fits.
58 #include "apr_base64.h"
61 #include "apr_errno.h"
62 #include "apr_global_mutex.h"
63 #include "apr_strings.h"
65 #define APR_WANT_STRFUNC
68 #include "ap_config.h"
70 #include "http_config.h"
71 #include "http_core.h"
72 #include "http_request.h"
74 #include "http_protocol.h"
80 /* Disable shmem until pools/init gets sorted out
81 * remove following two lines when fixed
83 #undef APR_HAS_SHARED_MEMORY
84 #define APR_HAS_SHARED_MEMORY 0
86 /* struct to hold the configuration info */
88 typedef struct digest_config_struct {
94 apr_sha1_ctx_t nonce_ctx;
95 apr_time_t nonce_lifetime;
96 const char *nonce_format;
98 const char *algorithm;
104 #define DFLT_ALGORITHM "MD5"
106 #define DFLT_NONCE_LIFE apr_time_from_sec(300)
107 #define NEXTNONCE_DELTA apr_time_from_sec(30)
110 #define NONCE_TIME_LEN (((sizeof(apr_time_t)+2)/3)*4)
111 #define NONCE_HASH_LEN (2*APR_SHA1_DIGESTSIZE)
112 #define NONCE_LEN (int )(NONCE_TIME_LEN + NONCE_HASH_LEN)
114 #define SECRET_LEN 20
117 /* client list definitions */
119 typedef struct hash_entry {
120 unsigned long key; /* the key for this entry */
121 struct hash_entry *next; /* next entry in the bucket */
122 unsigned long nonce_count; /* for nonce-count checking */
123 char ha1[2*MD5_DIGESTSIZE+1]; /* for algorithm=MD5-sess */
124 char last_nonce[NONCE_LEN+1]; /* for one-time nonce's */
127 static struct hash_table {
128 client_entry **table;
129 unsigned long tbl_len;
130 unsigned long num_entries;
131 unsigned long num_created;
132 unsigned long num_removed;
133 unsigned long num_renewed;
137 /* struct to hold a parsed Authorization header */
139 enum hdr_sts { NO_HEADER, NOT_DIGEST, INVALID, VALID };
141 typedef struct digest_header_struct {
144 const char *username;
149 const char *algorithm;
152 unsigned long opaque_num;
153 const char *message_qop;
154 const char *nonce_count;
155 /* the following fields are not (directly) from the header */
156 apr_time_t nonce_time;
157 enum hdr_sts auth_hdr_sts;
158 const char *raw_request_uri;
159 apr_uri_t *psd_request_uri;
161 client_entry *client;
165 /* (mostly) nonce stuff */
167 typedef union time_union {
169 unsigned char arr[sizeof(apr_time_t)];
172 static unsigned char secret[SECRET_LEN];
174 /* client-list, opaque, and one-time-nonce stuff */
176 static apr_shm_t *client_shm = NULL;
177 static apr_rmm_t *client_rmm = NULL;
178 static unsigned long *opaque_cntr;
179 static apr_time_t *otn_counter; /* one-time-nonce counter */
180 static apr_global_mutex_t *client_lock = NULL;
181 static apr_global_mutex_t *opaque_lock = NULL;
182 static char client_lock_name[L_tmpnam];
183 static char opaque_lock_name[L_tmpnam];
185 #define DEF_SHMEM_SIZE 1000L /* ~ 12 entries */
186 #define DEF_NUM_BUCKETS 15L
189 static long shmem_size = DEF_SHMEM_SIZE;
190 static long num_buckets = DEF_NUM_BUCKETS;
193 module AP_MODULE_DECLARE_DATA auth_digest_module;
196 * initialization code
199 static apr_status_t cleanup_tables(void *not_used)
201 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
202 "Digest: cleaning up shared memory");
206 apr_shm_destroy(client_shm);
211 apr_global_mutex_destroy(client_lock);
216 apr_global_mutex_destroy(opaque_lock);
223 static apr_status_t initialize_secret(server_rec *s)
227 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
228 "Digest: generating secret for digest authentication ...");
231 status = apr_generate_random_bytes(secret, sizeof(secret));
233 #error APR random number support is missing; you probably need to install the truerand library.
236 if (status != APR_SUCCESS) {
238 ap_log_error(APLOG_MARK, APLOG_CRIT, status, s,
239 "Digest: error generating secret: %s",
240 apr_strerror(status, buf, sizeof(buf)));
244 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, "Digest: done");
249 static void log_error_and_cleanup(char *msg, apr_status_t sts, server_rec *s)
251 ap_log_error(APLOG_MARK, APLOG_ERR, sts, s,
252 "Digest: %s - all nonce-count checking, one-time nonces, and "
253 "MD5-sess algorithm disabled", msg);
255 cleanup_tables(NULL);
258 #if APR_HAS_SHARED_MEMORY
260 static void initialize_tables(server_rec *s, apr_pool_t *ctx)
265 /* set up client list */
267 sts = apr_shm_create(&client_shm, shmem_size, tmpnam(NULL), ctx);
268 if (sts != APR_SUCCESS) {
269 log_error_and_cleanup("failed to create shared memory segments", sts, s);
273 client_list = apr_rmm_malloc(client_rmm, sizeof(*client_list) +
274 sizeof(client_entry*)*num_buckets);
276 log_error_and_cleanup("failed to allocate shared memory", -1, s);
279 client_list->table = (client_entry**) (client_list + 1);
280 for (idx = 0; idx < num_buckets; idx++) {
281 client_list->table[idx] = NULL;
283 client_list->tbl_len = num_buckets;
284 client_list->num_entries = 0;
286 tmpnam(client_lock_name);
287 /* FIXME: get the client_lock_name from a directive so we're portable
288 * to non-process-inheriting operating systems, like Win32. */
289 sts = apr_global_mutex_create(&client_lock, client_lock_name,
290 APR_LOCK_DEFAULT, ctx);
291 if (sts != APR_SUCCESS) {
292 log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
299 opaque_cntr = apr_rmm_malloc(client_rmm, sizeof(*opaque_cntr));
300 if (opaque_cntr == NULL) {
301 log_error_and_cleanup("failed to allocate shared memory", -1, s);
306 tmpnam(opaque_lock_name);
307 /* FIXME: get the opaque_lock_name from a directive so we're portable
308 * to non-process-inheriting operating systems, like Win32. */
309 sts = apr_global_mutex_create(&opaque_lock, opaque_lock_name,
310 APR_LOCK_DEFAULT, ctx);
311 if (sts != APR_SUCCESS) {
312 log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
317 /* setup one-time-nonce counter */
319 otn_counter = apr_rmm_malloc(client_rmm, sizeof(*otn_counter));
320 if (otn_counter == NULL) {
321 log_error_and_cleanup("failed to allocate shared memory", -1, s);
332 #endif /* APR_HAS_SHARED_MEMORY */
335 static int initialize_module(apr_pool_t *p, apr_pool_t *plog,
336 apr_pool_t *ptemp, server_rec *s)
339 const char *userdata_key = "auth_digest_init";
341 /* initialize_module() will be called twice, and if it's a DSO
342 * then all static data from the first call will be lost. Only
343 * set up our static data on the second call. */
344 apr_pool_userdata_get(&data, userdata_key, s->process->pool);
346 apr_pool_userdata_set((const void *)1, userdata_key,
347 apr_pool_cleanup_null, s->process->pool);
350 if (initialize_secret(s) != APR_SUCCESS) {
354 #if APR_HAS_SHARED_MEMORY
355 /* Note: this stuff is currently fixed for the lifetime of the server,
356 * i.e. even across restarts. This means that A) any shmem-size
357 * configuration changes are ignored, and B) certain optimizations,
358 * such as only allocating the smallest necessary entry for each
359 * client, can't be done. However, the alternative is a nightmare:
360 * we can't call apr_shm_destroy on a graceful restart because there
361 * will be children using the tables, and we also don't know when the
362 * last child dies. Therefore we can never clean up the old stuff,
363 * creating a creeping memory leak.
365 initialize_tables(s, p);
366 apr_pool_cleanup_register(p, NULL, cleanup_tables, apr_pool_cleanup_null);
367 #endif /* APR_HAS_SHARED_MEMORY */
371 static void initialize_child(apr_pool_t *p, server_rec *s)
379 /* FIXME: get the client_lock_name from a directive so we're portable
380 * to non-process-inheriting operating systems, like Win32. */
381 sts = apr_global_mutex_child_init(&client_lock, client_lock_name, p);
382 if (sts != APR_SUCCESS) {
383 log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
386 /* FIXME: get the opaque_lock_name from a directive so we're portable
387 * to non-process-inheriting operating systems, like Win32. */
388 sts = apr_global_mutex_child_init(&opaque_lock, opaque_lock_name, p);
389 if (sts != APR_SUCCESS) {
390 log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
399 static void *create_digest_dir_config(apr_pool_t *p, char *dir)
401 digest_config_rec *conf;
407 conf = (digest_config_rec *) apr_pcalloc(p, sizeof(digest_config_rec));
409 conf->qop_list = apr_palloc(p, sizeof(char*));
410 conf->qop_list[0] = NULL;
411 conf->nonce_lifetime = DFLT_NONCE_LIFE;
412 conf->dir_name = apr_pstrdup(p, dir);
413 conf->algorithm = DFLT_ALGORITHM;
419 static const char *set_realm(cmd_parms *cmd, void *config, const char *realm)
421 digest_config_rec *conf = (digest_config_rec *) config;
423 /* The core already handles the realm, but it's just too convenient to
424 * grab it ourselves too and cache some setups. However, we need to
425 * let the core get at it too, which is why we decline at the end -
426 * this relies on the fact that http_core is last in the list.
430 /* we precompute the part of the nonce hash that is constant (well,
431 * the host:port would be too, but that varies for .htaccess files
432 * and directives outside a virtual host section)
434 apr_sha1_init(&conf->nonce_ctx);
435 apr_sha1_update_binary(&conf->nonce_ctx, secret, sizeof(secret));
436 apr_sha1_update_binary(&conf->nonce_ctx, (const unsigned char *) realm,
442 static const char *set_digest_file(cmd_parms *cmd, void *config,
445 ((digest_config_rec *) config)->pwfile = file;
449 static const char *set_group_file(cmd_parms *cmd, void *config,
452 ((digest_config_rec *) config)->grpfile = file;
456 static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
458 digest_config_rec *conf = (digest_config_rec *) config;
462 if (!strcasecmp(op, "none")) {
463 if (conf->qop_list[0] == NULL) {
464 conf->qop_list = apr_palloc(cmd->pool, 2 * sizeof(char*));
465 conf->qop_list[1] = NULL;
467 conf->qop_list[0] = "none";
471 if (!strcasecmp(op, "auth-int")) {
472 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
473 "Digest: WARNING: qop `auth-int' currently only works "
474 "correctly for responses with no entity");
476 else if (strcasecmp(op, "auth")) {
477 return apr_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
480 for (cnt = 0; conf->qop_list[cnt] != NULL; cnt++)
483 tmp = apr_palloc(cmd->pool, (cnt + 2) * sizeof(char*));
484 memcpy(tmp, conf->qop_list, cnt*sizeof(char*));
485 tmp[cnt] = apr_pstrdup(cmd->pool, op);
487 conf->qop_list = tmp;
492 static const char *set_nonce_lifetime(cmd_parms *cmd, void *config,
498 lifetime = strtol(t, &endptr, 10);
499 if (endptr < (t+strlen(t)) && !apr_isspace(*endptr)) {
500 return apr_pstrcat(cmd->pool,
501 "Invalid time in AuthDigestNonceLifetime: ",
505 ((digest_config_rec *) config)->nonce_lifetime = apr_time_from_sec(lifetime);
509 static const char *set_nonce_format(cmd_parms *cmd, void *config,
512 ((digest_config_rec *) config)->nonce_format = fmt;
513 return "AuthDigestNonceFormat is not implemented (yet)";
516 static const char *set_nc_check(cmd_parms *cmd, void *config, int flag)
518 if (flag && !client_shm)
519 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
520 cmd->server, "Digest: WARNING: nonce-count checking "
521 "is not supported on platforms without shared-memory "
522 "support - disabling check");
524 ((digest_config_rec *) config)->check_nc = flag;
528 static const char *set_algorithm(cmd_parms *cmd, void *config, const char *alg)
530 if (!strcasecmp(alg, "MD5-sess")) {
532 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
533 cmd->server, "Digest: WARNING: algorithm `MD5-sess' "
534 "is not supported on platforms without shared-memory "
535 "support - reverting to MD5");
539 else if (strcasecmp(alg, "MD5")) {
540 return apr_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
543 ((digest_config_rec *) config)->algorithm = alg;
547 static const char *set_uri_list(cmd_parms *cmd, void *config, const char *uri)
549 digest_config_rec *c = (digest_config_rec *) config;
551 c->uri_list[strlen(c->uri_list)-1] = '\0';
552 c->uri_list = apr_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
555 c->uri_list = apr_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
560 static const char *set_shmem_size(cmd_parms *cmd, void *config,
561 const char *size_str)
566 size = strtol(size_str, &endptr, 10);
567 while (apr_isspace(*endptr)) endptr++;
568 if (*endptr == '\0' || *endptr == 'b' || *endptr == 'B') {
571 else if (*endptr == 'k' || *endptr == 'K') {
574 else if (*endptr == 'm' || *endptr == 'M') {
578 return apr_pstrcat(cmd->pool, "Invalid size in AuthDigestShmemSize: ",
582 min = sizeof(*client_list) + sizeof(client_entry*) + sizeof(client_entry);
584 return apr_psprintf(cmd->pool, "size in AuthDigestShmemSize too small: "
585 "%ld < %ld", size, min);
589 num_buckets = (size - sizeof(*client_list)) /
590 (sizeof(client_entry*) + HASH_DEPTH * sizeof(client_entry));
591 if (num_buckets == 0) {
594 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
595 "Digest: Set shmem-size: %ld, num-buckets: %ld", shmem_size,
601 static const command_rec digest_cmds[] =
603 AP_INIT_TAKE1("AuthName", set_realm, NULL, OR_AUTHCFG,
604 "The authentication realm (e.g. \"Members Only\")"),
605 AP_INIT_TAKE1("AuthDigestFile", set_digest_file, NULL, OR_AUTHCFG,
606 "The name of the file containing the usernames and password hashes"),
607 AP_INIT_TAKE1("AuthDigestGroupFile", set_group_file, NULL, OR_AUTHCFG,
608 "The name of the file containing the group names and members"),
609 AP_INIT_ITERATE("AuthDigestQop", set_qop, NULL, OR_AUTHCFG,
610 "A list of quality-of-protection options"),
611 AP_INIT_TAKE1("AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG,
612 "Maximum lifetime of the server nonce (seconds)"),
613 AP_INIT_TAKE1("AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG,
614 "The format to use when generating the server nonce"),
615 AP_INIT_FLAG("AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG,
616 "Whether or not to check the nonce-count sent by the client"),
617 AP_INIT_TAKE1("AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG,
618 "The algorithm used for the hash calculation"),
619 AP_INIT_ITERATE("AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG,
620 "A list of URI's which belong to the same protection space as the current URI"),
621 AP_INIT_TAKE1("AuthDigestShmemSize", set_shmem_size, NULL, RSRC_CONF,
622 "The amount of shared memory to allocate for keeping track of clients"),
630 * Each client is assigned a number, which is transfered in the opaque
631 * field of the WWW-Authenticate and Authorization headers. The number
632 * is just a simple counter which is incremented for each new client.
633 * Clients can't forge this number because it is hashed up into the
634 * server nonce, and that is checked.
636 * The clients are kept in a simple hash table, which consists of an
637 * array of client_entry's, each with a linked list of entries hanging
638 * off it. The client's number modulo the size of the array gives the
641 * The clients are garbage collected whenever a new client is allocated
642 * but there is not enough space left in the shared memory segment. A
643 * simple semi-LRU is used for this: whenever a client entry is accessed
644 * it is moved to the beginning of the linked list in its bucket (this
645 * also makes for faster lookups for current clients). The garbage
646 * collecter then just removes the oldest entry (i.e. the one at the
647 * end of the list) in each bucket.
649 * The main advantages of the above scheme are that it's easy to implement
650 * and it keeps the hash table evenly balanced (i.e. same number of entries
651 * in each bucket). The major disadvantage is that you may be throwing
652 * entries out which are in active use. This is not tragic, as these
653 * clients will just be sent a new client id (opaque field) and nonce
654 * with a stale=true (i.e. it will just look like the nonce expired,
655 * thereby forcing an extra round trip). If the shared memory segment
656 * has enough headroom over the current client set size then this should
657 * not occur too often.
659 * To help tune the size of the shared memory segment (and see if the
660 * above algorithm is really sufficient) a set of counters is kept
661 * indicating the number of clients held, the number of garbage collected
662 * clients, and the number of erroneously purged clients. These are printed
663 * out at each garbage collection run. Note that access to the counters is
664 * not synchronized because they are just indicaters, and whether they are
665 * off by a few doesn't matter; and for the same reason no attempt is made
666 * to guarantee the num_renewed is correct in the face of clients spoofing
671 * Get the client given its client number (the key). Returns the entry,
672 * or NULL if it's not found.
674 * Access to the list itself is synchronized via locks. However, access
675 * to the entry returned by get_client() is NOT synchronized. This means
676 * that there are potentially problems if a client uses multiple,
677 * simultaneous connections to access url's within the same protection
678 * space. However, these problems are not new: when using multiple
679 * connections you have no guarantee of the order the requests are
680 * processed anyway, so you have problems with the nonce-count and
681 * one-time nonces anyway.
683 static client_entry *get_client(unsigned long key, const request_rec *r)
686 client_entry *entry, *prev = NULL;
689 if (!key || !client_shm) return NULL;
691 bucket = key % client_list->tbl_len;
692 entry = client_list->table[bucket];
694 apr_global_mutex_lock(client_lock);
696 while (entry && key != entry->key) {
701 if (entry && prev) { /* move entry to front of list */
702 prev->next = entry->next;
703 entry->next = client_list->table[bucket];
704 client_list->table[bucket] = entry;
707 apr_global_mutex_unlock(client_lock);
710 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
711 "get_client(): client %lu found", key);
714 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
715 "get_client(): client %lu not found", key);
722 /* A simple garbage-collecter to remove unused clients. It removes the
723 * last entry in each bucket and updates the counters. Returns the
724 * number of removed entries.
728 client_entry *entry, *prev;
729 unsigned long num_removed = 0, idx;
731 /* garbage collect all last entries */
733 for (idx = 0; idx < client_list->tbl_len; idx++) {
734 entry = client_list->table[idx];
736 while (entry->next) { /* find last entry */
741 prev->next = NULL; /* cut list */
744 client_list->table[idx] = NULL;
746 if (entry) { /* remove entry */
747 apr_rmm_free(client_rmm, (apr_rmm_off_t)entry);
752 /* update counters and log */
754 client_list->num_entries -= num_removed;
755 client_list->num_removed += num_removed;
762 * Add a new client to the list. Returns the entry if successful, NULL
763 * otherwise. This triggers the garbage collection if memory is low.
765 static client_entry *add_client(unsigned long key, client_entry *info,
772 if (!key || !client_shm) {
776 bucket = key % client_list->tbl_len;
777 entry = client_list->table[bucket];
779 apr_global_mutex_lock(client_lock);
781 /* try to allocate a new entry */
783 entry = (client_entry *)apr_rmm_malloc(client_rmm, sizeof(client_entry));
785 long num_removed = gc();
786 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
787 "Digest: gc'd %ld client entries. Total new clients: "
788 "%ld; Total removed clients: %ld; Total renewed clients: "
790 client_list->num_created - client_list->num_renewed,
791 client_list->num_removed, client_list->num_renewed);
792 entry = (client_entry *)apr_rmm_malloc(client_rmm, sizeof(client_entry));
794 return NULL; /* give up */
798 /* now add the entry */
800 memcpy(entry, info, sizeof(client_entry));
802 entry->next = client_list->table[bucket];
803 client_list->table[bucket] = entry;
804 client_list->num_created++;
805 client_list->num_entries++;
807 apr_global_mutex_unlock(client_lock);
809 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
810 "allocated new client %lu", key);
817 * Authorization header parser code
820 /* Parse the Authorization header, if it exists */
821 static int get_digest_rec(request_rec *r, digest_header_rec *resp)
823 const char *auth_line;
828 auth_line = apr_table_get(r->headers_in,
829 (PROXYREQ_PROXY == r->proxyreq)
830 ? "Proxy-Authorization"
833 resp->auth_hdr_sts = NO_HEADER;
837 resp->scheme = ap_getword_white(r->pool, &auth_line);
838 if (strcasecmp(resp->scheme, "Digest")) {
839 resp->auth_hdr_sts = NOT_DIGEST;
843 l = strlen(auth_line);
845 key = apr_palloc(r->pool, l+1);
846 value = apr_palloc(r->pool, l+1);
848 while (auth_line[0] != '\0') {
852 while (apr_isspace(auth_line[0])) {
856 while (auth_line[0] != '=' && auth_line[0] != ','
857 && auth_line[0] != '\0' && !apr_isspace(auth_line[0])) {
858 key[vk++] = *auth_line++;
861 while (apr_isspace(auth_line[0])) {
867 if (auth_line[0] == '=') {
869 while (apr_isspace(auth_line[0])) {
874 if (auth_line[0] == '\"') { /* quoted string */
876 while (auth_line[0] != '\"' && auth_line[0] != '\0') {
877 if (auth_line[0] == '\\' && auth_line[1] != '\0') {
878 auth_line++; /* escaped char */
880 value[vv++] = *auth_line++;
882 if (auth_line[0] != '\0') {
887 while (auth_line[0] != ',' && auth_line[0] != '\0'
888 && !apr_isspace(auth_line[0])) {
889 value[vv++] = *auth_line++;
895 while (auth_line[0] != ',' && auth_line[0] != '\0') {
898 if (auth_line[0] != '\0') {
902 if (!strcasecmp(key, "username"))
903 resp->username = apr_pstrdup(r->pool, value);
904 else if (!strcasecmp(key, "realm"))
905 resp->realm = apr_pstrdup(r->pool, value);
906 else if (!strcasecmp(key, "nonce"))
907 resp->nonce = apr_pstrdup(r->pool, value);
908 else if (!strcasecmp(key, "uri"))
909 resp->uri = apr_pstrdup(r->pool, value);
910 else if (!strcasecmp(key, "response"))
911 resp->digest = apr_pstrdup(r->pool, value);
912 else if (!strcasecmp(key, "algorithm"))
913 resp->algorithm = apr_pstrdup(r->pool, value);
914 else if (!strcasecmp(key, "cnonce"))
915 resp->cnonce = apr_pstrdup(r->pool, value);
916 else if (!strcasecmp(key, "opaque"))
917 resp->opaque = apr_pstrdup(r->pool, value);
918 else if (!strcasecmp(key, "qop"))
919 resp->message_qop = apr_pstrdup(r->pool, value);
920 else if (!strcasecmp(key, "nc"))
921 resp->nonce_count = apr_pstrdup(r->pool, value);
924 if (!resp->username || !resp->realm || !resp->nonce || !resp->uri
926 || (resp->message_qop && (!resp->cnonce || !resp->nonce_count))) {
927 resp->auth_hdr_sts = INVALID;
932 resp->opaque_num = (unsigned long) strtol(resp->opaque, NULL, 16);
935 resp->auth_hdr_sts = VALID;
940 /* Because the browser may preemptively send auth info, incrementing the
941 * nonce-count when it does, and because the client does not get notified
942 * if the URI didn't need authentication after all, we need to be sure to
943 * update the nonce-count each time we receive an Authorization header no
944 * matter what the final outcome of the request. Furthermore this is a
945 * convenient place to get the request-uri (before any subrequests etc
946 * are initiated) and to initialize the request_config.
948 * Note that this must be called after mod_proxy had its go so that
949 * r->proxyreq is set correctly.
951 static int parse_hdr_and_update_nc(request_rec *r)
953 digest_header_rec *resp;
956 if (!ap_is_initial_req(r)) {
960 resp = apr_pcalloc(r->pool, sizeof(digest_header_rec));
961 resp->raw_request_uri = r->unparsed_uri;
962 resp->psd_request_uri = &r->parsed_uri;
963 resp->needed_auth = 0;
964 resp->method = r->method;
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++;
978 * Nonce generation code
981 /* The hash part of the nonce is a SHA-1 hash of the time, realm, server host
982 * and port, opaque, and our secret.
984 static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
985 const server_rec *server,
986 const digest_config_rec *conf)
988 const char *hex = "0123456789abcdef";
989 unsigned char sha1[APR_SHA1_DIGESTSIZE];
993 memcpy(&ctx, &conf->nonce_ctx, sizeof(ctx));
995 apr_sha1_update_binary(&ctx, (const unsigned char *) server->server_hostname,
996 strlen(server->server_hostname));
997 apr_sha1_update_binary(&ctx, (const unsigned char *) &server->port,
998 sizeof(server->port));
1000 apr_sha1_update_binary(&ctx, (const unsigned char *) timestr, strlen(timestr));
1002 apr_sha1_update_binary(&ctx, (const unsigned char *) opaque,
1005 apr_sha1_final(sha1, &ctx);
1007 for (idx=0; idx<APR_SHA1_DIGESTSIZE; idx++) {
1008 *hash++ = hex[sha1[idx] >> 4];
1009 *hash++ = hex[sha1[idx] & 0xF];
1016 /* The nonce has the format b64(time)+hash .
1018 static const char *gen_nonce(apr_pool_t *p, apr_time_t now, const char *opaque,
1019 const server_rec *server,
1020 const digest_config_rec *conf)
1022 char *nonce = apr_palloc(p, NONCE_LEN+1);
1026 if (conf->nonce_lifetime != 0) {
1029 else if (otn_counter) {
1030 /* this counter is not synch'd, because it doesn't really matter
1031 * if it counts exactly.
1033 t.time = (*otn_counter)++;
1036 /* XXX: WHAT IS THIS CONSTANT? */
1039 len = apr_base64_encode_binary(nonce, t.arr, sizeof(t.arr));
1040 gen_nonce_hash(nonce+NONCE_TIME_LEN, nonce, opaque, server, conf);
1047 * Opaque and hash-table management
1051 * Generate a new client entry, add it to the list, and return the
1052 * entry. Returns NULL if failed.
1054 static client_entry *gen_client(const request_rec *r)
1057 client_entry new_entry = { 0, NULL, 0, "", "" }, *entry;
1063 apr_global_mutex_lock(opaque_lock);
1064 op = (*opaque_cntr)++;
1065 apr_global_mutex_lock(opaque_lock);
1067 if (!(entry = add_client(op, &new_entry, r->server))) {
1068 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1069 "Digest: failed to allocate client entry - ignoring "
1081 * If you want to use algorithm=MD5-sess you must write get_userpw_hash()
1082 * yourself (see below). The dummy provided here just uses the hash from
1083 * the auth-file, i.e. it is only useful for testing client implementations
1088 * get_userpw_hash() will be called each time a new session needs to be
1089 * generated and is expected to return the equivalent of
1091 * h_urp = ap_md5(r->pool,
1092 * apr_pstrcat(r->pool, username, ":", ap_auth_name(r), ":", passwd))
1094 * (unsigned char *) apr_pstrcat(r->pool, h_urp, ":", resp->nonce, ":",
1095 * resp->cnonce, NULL));
1097 * or put differently, it must return
1099 * MD5(MD5(username ":" realm ":" password) ":" nonce ":" cnonce)
1101 * If something goes wrong, the failure must be logged and NULL returned.
1103 * You must implement this yourself, which will probably consist of code
1104 * contacting the password server with the necessary information (typically
1105 * the username, realm, nonce, and cnonce) and receiving the hash from it.
1107 * TBD: This function should probably be in a seperate source file so that
1108 * people need not modify mod_auth_digest.c each time they install a new
1109 * version of apache.
1111 static const char *get_userpw_hash(const request_rec *r,
1112 const digest_header_rec *resp,
1113 const digest_config_rec *conf)
1115 return ap_md5(r->pool,
1116 (unsigned char *) apr_pstrcat(r->pool, conf->ha1, ":", resp->nonce,
1117 ":", resp->cnonce, NULL));
1121 /* Retrieve current session H(A1). If there is none and "generate" is
1122 * true then a new session for MD5-sess is generated and stored in the
1123 * client struct; if generate is false, or a new session could not be
1124 * generated then NULL is returned (in case of failure to generate the
1125 * failure reason will have been logged already).
1127 static const char *get_session_HA1(const request_rec *r,
1128 digest_header_rec *resp,
1129 const digest_config_rec *conf,
1132 const char *ha1 = NULL;
1134 /* return the current sessions if there is one */
1135 if (resp->opaque && resp->client && resp->client->ha1[0]) {
1136 return resp->client->ha1;
1138 else if (!generate) {
1142 /* generate a new session */
1143 if (!resp->client) {
1144 resp->client = gen_client(r);
1147 ha1 = get_userpw_hash(r, resp, conf);
1149 memcpy(resp->client->ha1, ha1, sizeof(resp->client->ha1));
1157 static void clear_session(const digest_header_rec *resp)
1160 resp->client->ha1[0] = '\0';
1165 * Authorization challenge generation code (for WWW-Authenticate)
1168 static const char *ltox(apr_pool_t *p, unsigned long num)
1171 return apr_psprintf(p, "%lx", num);
1178 static void note_digest_auth_failure(request_rec *r,
1179 const digest_config_rec *conf,
1180 digest_header_rec *resp, int stale)
1182 const char *qop, *opaque, *opaque_param, *domain, *nonce;
1187 if (conf->qop_list[0] == NULL) {
1188 qop = ", qop=\"auth\"";
1190 else if (!strcasecmp(conf->qop_list[0], "none")) {
1194 qop = apr_pstrcat(r->pool, ", qop=\"", conf->qop_list[0], NULL);
1195 for (cnt = 1; conf->qop_list[cnt] != NULL; cnt++) {
1196 qop = apr_pstrcat(r->pool, qop, ",", conf->qop_list[cnt], NULL);
1198 qop = apr_pstrcat(r->pool, qop, "\"", NULL);
1203 if (resp->opaque == NULL) {
1205 if ((conf->check_nc || conf->nonce_lifetime == 0
1206 || !strcasecmp(conf->algorithm, "MD5-sess"))
1207 && (resp->client = gen_client(r)) != NULL) {
1208 opaque = ltox(r->pool, resp->client->key);
1211 opaque = ""; /* opaque not needed */
1214 else if (resp->client == NULL) {
1215 /* client info was gc'd */
1216 resp->client = gen_client(r);
1217 if (resp->client != NULL) {
1218 opaque = ltox(r->pool, resp->client->key);
1220 client_list->num_renewed++;
1223 opaque = ""; /* ??? */
1227 opaque = resp->opaque;
1228 /* we're generating a new nonce, so reset the nonce-count */
1229 resp->client->nonce_count = 0;
1233 opaque_param = apr_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
1236 opaque_param = NULL;
1241 nonce = gen_nonce(r->pool, r->request_time, opaque, r->server, conf);
1242 if (resp->client && conf->nonce_lifetime == 0) {
1243 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1246 /* Setup MD5-sess stuff. Note that we just clear out the session
1247 * info here, since we can't generate a new session until the request
1248 * from the client comes in with the cnonce.
1251 if (!strcasecmp(conf->algorithm, "MD5-sess")) {
1252 clear_session(resp);
1255 /* setup domain attribute. We want to send this attribute wherever
1256 * possible so that the client won't send the Authorization header
1257 * unneccessarily (it's usually > 200 bytes!).
1260 /* don't send domain
1261 * - for proxy requests
1262 * - if it's no specified
1264 if (r->proxyreq || !conf->uri_list) {
1268 domain = conf->uri_list;
1271 apr_table_mergen(r->err_headers_out,
1272 (PROXYREQ_PROXY == r->proxyreq)
1273 ? "Proxy-Authenticate" : "WWW-Authenticate",
1274 apr_psprintf(r->pool, "Digest realm=\"%s\", "
1275 "nonce=\"%s\", algorithm=%s%s%s%s%s",
1276 ap_auth_name(r), nonce, conf->algorithm,
1277 opaque_param ? opaque_param : "",
1278 domain ? domain : "",
1279 stale ? ", stale=true" : "", qop));
1285 * Authorization header verification code
1288 static const char *get_hash(request_rec *r, const char *user,
1289 const char *realm, const char *auth_pwfile)
1292 char l[MAX_STRING_LEN];
1297 if ((sts = ap_pcfg_openfile(&f, r->pool, auth_pwfile)) != APR_SUCCESS) {
1298 ap_log_rerror(APLOG_MARK, APLOG_ERR, sts, r,
1299 "Digest: Could not open password file: %s", auth_pwfile);
1302 while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
1303 if ((l[0] == '#') || (!l[0])) {
1307 w = ap_getword(r->pool, &rpw, ':');
1308 x = ap_getword(r->pool, &rpw, ':');
1310 if (x && w && !strcmp(user, w) && !strcmp(realm, x)) {
1311 ap_cfg_closefile(f);
1312 return apr_pstrdup(r->pool, rpw);
1315 ap_cfg_closefile(f);
1319 static int check_nc(const request_rec *r, const digest_header_rec *resp,
1320 const digest_config_rec *conf)
1323 const char *snc = resp->nonce_count;
1326 if (!conf->check_nc || !client_shm) {
1330 nc = strtol(snc, &endptr, 16);
1331 if (endptr < (snc+strlen(snc)) && !apr_isspace(*endptr)) {
1332 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1333 "Digest: invalid nc %s received - not a number", snc);
1337 if (!resp->client) {
1341 if (nc != resp->client->nonce_count) {
1342 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1343 "Digest: Warning, possible replay attack: nonce-count "
1344 "check failed: %lu != %lu", nc,
1345 resp->client->nonce_count);
1352 static int check_nonce(request_rec *r, digest_header_rec *resp,
1353 const digest_config_rec *conf)
1357 time_rec nonce_time;
1358 char tmp, hash[NONCE_HASH_LEN+1];
1360 if (strlen(resp->nonce) != NONCE_LEN) {
1361 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1362 "Digest: invalid nonce %s received - length is not %d",
1363 resp->nonce, NONCE_LEN);
1364 note_digest_auth_failure(r, conf, resp, 1);
1365 return HTTP_UNAUTHORIZED;
1368 tmp = resp->nonce[NONCE_TIME_LEN];
1369 resp->nonce[NONCE_TIME_LEN] = '\0';
1370 len = apr_base64_decode_binary(nonce_time.arr, resp->nonce);
1371 gen_nonce_hash(hash, resp->nonce, resp->opaque, r->server, conf);
1372 resp->nonce[NONCE_TIME_LEN] = tmp;
1373 resp->nonce_time = nonce_time.time;
1375 if (strcmp(hash, resp->nonce+NONCE_TIME_LEN)) {
1376 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1377 "Digest: invalid nonce %s received - hash is not %s",
1379 note_digest_auth_failure(r, conf, resp, 1);
1380 return HTTP_UNAUTHORIZED;
1383 dt = r->request_time - nonce_time.time;
1384 if (conf->nonce_lifetime > 0 && dt < 0) {
1385 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1386 "Digest: invalid nonce %s received - user attempted "
1387 "time travel", resp->nonce);
1388 note_digest_auth_failure(r, conf, resp, 1);
1389 return HTTP_UNAUTHORIZED;
1392 if (conf->nonce_lifetime > 0) {
1393 if (dt > conf->nonce_lifetime) {
1394 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0,r,
1395 "Digest: user %s: nonce expired (%.2f seconds old "
1396 "- max lifetime %.2f) - sending new nonce",
1397 r->user, (double)apr_time_sec(dt),
1398 (double)apr_time_sec(conf->nonce_lifetime));
1399 note_digest_auth_failure(r, conf, resp, 1);
1400 return HTTP_UNAUTHORIZED;
1403 else if (conf->nonce_lifetime == 0 && resp->client) {
1404 if (memcmp(resp->client->last_nonce, resp->nonce, NONCE_LEN)) {
1405 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1406 "Digest: user %s: one-time-nonce mismatch - sending "
1407 "new nonce", r->user);
1408 note_digest_auth_failure(r, conf, resp, 1);
1409 return HTTP_UNAUTHORIZED;
1412 /* else (lifetime < 0) => never expires */
1417 /* The actual MD5 code... whee */
1420 static const char *old_digest(const request_rec *r,
1421 const digest_header_rec *resp, const char *ha1)
1425 ha2 = ap_md5(r->pool, (unsigned char *)apr_pstrcat(r->pool, resp->method, ":",
1427 return ap_md5(r->pool,
1428 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1433 static const char *new_digest(const request_rec *r,
1434 digest_header_rec *resp,
1435 const digest_config_rec *conf)
1437 const char *ha1, *ha2, *a2;
1439 if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
1440 ha1 = get_session_HA1(r, resp, conf, 1);
1449 if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int")) {
1450 a2 = apr_pstrcat(r->pool, resp->method, ":", resp->uri, ":",
1451 ap_md5(r->pool, (const unsigned char*) ""), NULL);
1455 a2 = apr_pstrcat(r->pool, resp->method, ":", resp->uri, NULL);
1457 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1459 return ap_md5(r->pool,
1460 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1461 ":", resp->nonce_count, ":",
1463 resp->message_qop, ":", ha2,
1468 static void copy_uri_components(apr_uri_t *dst,
1469 apr_uri_t *src, request_rec *r) {
1470 if (src->scheme && src->scheme[0] != '\0') {
1471 dst->scheme = src->scheme;
1474 dst->scheme = (char *) "http";
1477 if (src->hostname && src->hostname[0] != '\0') {
1478 dst->hostname = apr_pstrdup(r->pool, src->hostname);
1479 ap_unescape_url(dst->hostname);
1482 dst->hostname = (char *) ap_get_server_name(r);
1485 if (src->port_str && src->port_str[0] != '\0') {
1486 dst->port = src->port;
1489 dst->port = ap_get_server_port(r);
1492 if (src->path && src->path[0] != '\0') {
1493 dst->path = apr_pstrdup(r->pool, src->path);
1494 ap_unescape_url(dst->path);
1497 dst->path = src->path;
1500 if (src->query && src->query[0] != '\0') {
1501 dst->query = apr_pstrdup(r->pool, src->query);
1502 ap_unescape_url(dst->query);
1505 dst->query = src->query;
1508 dst->hostinfo = src->hostinfo;
1511 /* These functions return 0 if client is OK, and proper error status
1512 * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
1513 * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
1514 * couldn't figure out how to tell if the client is authorized or not.
1516 * If they return DECLINED, and all other modules also decline, that's
1517 * treated by the server core as a configuration error, logged and
1521 /* Determine user ID, and check if the attributes are correct, if it
1522 * really is that user, if the nonce is correct, etc.
1525 static int authenticate_digest_user(request_rec *r)
1527 digest_config_rec *conf;
1528 digest_header_rec *resp;
1529 request_rec *mainreq;
1533 /* do we require Digest auth for this URI? */
1535 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest")) {
1539 if (!ap_auth_name(r)) {
1540 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1541 "Digest: need AuthName: %s", r->uri);
1542 return HTTP_INTERNAL_SERVER_ERROR;
1546 /* get the client response and mark */
1549 while (mainreq->main != NULL) {
1550 mainreq = mainreq->main;
1552 while (mainreq->prev != NULL) {
1553 mainreq = mainreq->prev;
1555 resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1556 &auth_digest_module);
1557 resp->needed_auth = 1;
1562 conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1563 &auth_digest_module);
1566 /* check for existence and syntax of Auth header */
1568 if (resp->auth_hdr_sts != VALID) {
1569 if (resp->auth_hdr_sts == NOT_DIGEST) {
1570 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1571 "Digest: client used wrong authentication scheme "
1572 "`%s': %s", resp->scheme, r->uri);
1574 else if (resp->auth_hdr_sts == INVALID) {
1575 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1576 "Digest: missing user, realm, nonce, uri, digest, "
1577 "cnonce, or nonce_count in authorization header: %s",
1580 /* else (resp->auth_hdr_sts == NO_HEADER) */
1581 note_digest_auth_failure(r, conf, resp, 0);
1582 return HTTP_UNAUTHORIZED;
1585 r->user = (char *) resp->username;
1586 r->ap_auth_type = (char *) "Digest";
1588 /* check the auth attributes */
1590 if (strcmp(resp->uri, resp->raw_request_uri)) {
1591 /* Hmm, the simple match didn't work (probably a proxy modified the
1592 * request-uri), so lets do a more sophisticated match
1594 apr_uri_t r_uri, d_uri;
1596 copy_uri_components(&r_uri, resp->psd_request_uri, r);
1597 if (apr_uri_parse(r->pool, resp->uri, &d_uri) != APR_SUCCESS) {
1598 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1599 "Digest: invalid uri <%s> in Authorization header",
1601 return HTTP_BAD_REQUEST;
1604 if (d_uri.hostname) {
1605 ap_unescape_url(d_uri.hostname);
1608 ap_unescape_url(d_uri.path);
1611 ap_unescape_url(d_uri.query);
1613 else if (r_uri.query) {
1614 /* MSIE compatibility hack. MSIE has some RFC issues - doesn't
1615 * include the query string in the uri Authorization component
1616 * or when computing the response component. the second part
1617 * works out ok, since we can hash the header and get the same
1618 * result. however, the uri from the request line won't match
1619 * the uri Authorization component since the header lacks the
1620 * query string, leaving us incompatable with a (broken) MSIE.
1622 * the workaround is to fake a query string match if in the proper
1623 * environment - BrowserMatch MSIE, for example. the cool thing
1624 * is that if MSIE ever fixes itself the simple match ought to
1625 * work and this code won't be reached anyway, even if the
1626 * environment is set.
1629 if (apr_table_get(r->subprocess_env,
1630 "AuthDigestEnableQueryStringHack")) {
1631 d_uri.query = r_uri.query;
1635 if (r->method_number == M_CONNECT) {
1636 if (!r_uri.hostinfo || strcmp(resp->uri, r_uri.hostinfo)) {
1637 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1638 "Digest: uri mismatch - <%s> does not match "
1639 "request-uri <%s>", resp->uri, r_uri.hostinfo);
1640 return HTTP_BAD_REQUEST;
1644 /* check hostname matches, if present */
1645 (d_uri.hostname && d_uri.hostname[0] != '\0'
1646 && strcasecmp(d_uri.hostname, r_uri.hostname))
1647 /* check port matches, if present */
1648 || (d_uri.port_str && d_uri.port != r_uri.port)
1649 /* check that server-port is default port if no port present */
1650 || (d_uri.hostname && d_uri.hostname[0] != '\0'
1651 && !d_uri.port_str && r_uri.port != ap_default_port(r))
1652 /* check that path matches */
1653 || (d_uri.path != r_uri.path
1654 /* either exact match */
1655 && (!d_uri.path || !r_uri.path
1656 || strcmp(d_uri.path, r_uri.path))
1657 /* or '*' matches empty path in scheme://host */
1658 && !(d_uri.path && !r_uri.path && resp->psd_request_uri->hostname
1659 && d_uri.path[0] == '*' && d_uri.path[1] == '\0'))
1660 /* check that query matches */
1661 || (d_uri.query != r_uri.query
1662 && (!d_uri.query || !r_uri.query
1663 || strcmp(d_uri.query, r_uri.query)))
1665 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1666 "Digest: uri mismatch - <%s> does not match "
1667 "request-uri <%s>", resp->uri, resp->raw_request_uri);
1668 return HTTP_BAD_REQUEST;
1672 if (resp->opaque && resp->opaque_num == 0) {
1673 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1674 "Digest: received invalid opaque - got `%s'",
1676 note_digest_auth_failure(r, conf, resp, 0);
1677 return HTTP_UNAUTHORIZED;
1680 if (strcmp(resp->realm, conf->realm)) {
1681 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1682 "Digest: realm mismatch - got `%s' but expected `%s'",
1683 resp->realm, conf->realm);
1684 note_digest_auth_failure(r, conf, resp, 0);
1685 return HTTP_UNAUTHORIZED;
1688 if (resp->algorithm != NULL
1689 && strcasecmp(resp->algorithm, "MD5")
1690 && strcasecmp(resp->algorithm, "MD5-sess")) {
1691 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1692 "Digest: unknown algorithm `%s' received: %s",
1693 resp->algorithm, r->uri);
1694 note_digest_auth_failure(r, conf, resp, 0);
1695 return HTTP_UNAUTHORIZED;
1698 if (!conf->pwfile) {
1702 if (!(conf->ha1 = get_hash(r, r->user, conf->realm, conf->pwfile))) {
1703 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1704 "Digest: user `%s' in realm `%s' not found: %s",
1705 r->user, conf->realm, r->uri);
1706 note_digest_auth_failure(r, conf, resp, 0);
1707 return HTTP_UNAUTHORIZED;
1711 if (resp->message_qop == NULL) {
1712 /* old (rfc-2069) style digest */
1713 if (strcmp(resp->digest, old_digest(r, resp, conf->ha1))) {
1714 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1715 "Digest: user %s: password mismatch: %s", r->user,
1717 note_digest_auth_failure(r, conf, resp, 0);
1718 return HTTP_UNAUTHORIZED;
1722 const char *exp_digest;
1724 for (idx = 0; conf->qop_list[idx] != NULL; idx++) {
1725 if (!strcasecmp(conf->qop_list[idx], resp->message_qop)) {
1732 && !(conf->qop_list[0] == NULL
1733 && !strcasecmp(resp->message_qop, "auth"))) {
1734 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1735 "Digest: invalid qop `%s' received: %s",
1736 resp->message_qop, r->uri);
1737 note_digest_auth_failure(r, conf, resp, 0);
1738 return HTTP_UNAUTHORIZED;
1741 exp_digest = new_digest(r, resp, conf);
1743 /* we failed to allocate a client struct */
1744 return HTTP_INTERNAL_SERVER_ERROR;
1746 if (strcmp(resp->digest, exp_digest)) {
1747 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1748 "Digest: user %s: password mismatch: %s", r->user,
1750 note_digest_auth_failure(r, conf, resp, 0);
1751 return HTTP_UNAUTHORIZED;
1755 if (check_nc(r, resp, conf) != OK) {
1756 note_digest_auth_failure(r, conf, resp, 0);
1757 return HTTP_UNAUTHORIZED;
1760 /* Note: this check is done last so that a "stale=true" can be
1761 generated if the nonce is old */
1762 if ((res = check_nonce(r, resp, conf))) {
1774 static apr_table_t *groups_for_user(request_rec *r, const char *user,
1775 const char *grpfile)
1778 apr_table_t *grps = apr_table_make(r->pool, 15);
1780 char l[MAX_STRING_LEN];
1781 const char *group_name, *ll, *w;
1784 if ((sts = ap_pcfg_openfile(&f, r->pool, grpfile)) != APR_SUCCESS) {
1785 ap_log_rerror(APLOG_MARK, APLOG_ERR, sts, r,
1786 "Digest: Could not open group file: %s", grpfile);
1790 if (apr_pool_create(&sp, r->pool) != APR_SUCCESS) {
1794 while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
1795 if ((l[0] == '#') || (!l[0])) {
1801 group_name = ap_getword(sp, &ll, ':');
1804 w = ap_getword_conf(sp, &ll);
1805 if (!strcmp(w, user)) {
1806 apr_table_setn(grps, apr_pstrdup(r->pool, group_name), "in");
1812 ap_cfg_closefile(f);
1813 apr_pool_destroy(sp);
1818 static int digest_check_auth(request_rec *r)
1820 const digest_config_rec *conf =
1821 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1822 &auth_digest_module);
1823 const char *user = r->user;
1824 int m = r->method_number;
1825 int method_restricted = 0;
1828 apr_table_t *grpstatus;
1829 const apr_array_header_t *reqs_arr;
1832 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest")) {
1836 reqs_arr = ap_requires(r);
1837 /* If there is no "requires" directive, then any user will do.
1842 reqs = (require_line *) reqs_arr->elts;
1844 if (conf->grpfile) {
1845 grpstatus = groups_for_user(r, user, conf->grpfile);
1851 for (x = 0; x < reqs_arr->nelts; x++) {
1853 if (!(reqs[x].method_mask & (AP_METHOD_BIT << m))) {
1857 method_restricted = 1;
1859 t = reqs[x].requirement;
1860 w = ap_getword_white(r->pool, &t);
1861 if (!strcasecmp(w, "valid-user")) {
1864 else if (!strcasecmp(w, "user")) {
1866 w = ap_getword_conf(r->pool, &t);
1867 if (!strcmp(user, w)) {
1872 else if (!strcasecmp(w, "group")) {
1878 w = ap_getword_conf(r->pool, &t);
1879 if (apr_table_get(grpstatus, w)) {
1885 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1886 "Digest: access to %s failed, reason: unknown "
1887 "require directive \"%s\"",
1888 r->uri, reqs[x].requirement);
1893 if (!method_restricted) {
1897 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1898 "Digest: access to %s failed, reason: user %s not "
1899 "allowed access", r->uri, user);
1901 note_digest_auth_failure(r, conf,
1902 (digest_header_rec *) ap_get_module_config(r->request_config,
1903 &auth_digest_module),
1905 return HTTP_UNAUTHORIZED;
1910 * Authorization-Info header code
1914 static const char *hdr(const apr_table_t *tbl, const char *name)
1916 const char *val = apr_table_get(tbl, name);
1926 static int add_auth_info(request_rec *r)
1928 const digest_config_rec *conf =
1929 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1930 &auth_digest_module);
1931 digest_header_rec *resp =
1932 (digest_header_rec *) ap_get_module_config(r->request_config,
1933 &auth_digest_module);
1934 const char *ai = NULL, *digest = NULL, *nextnonce = "";
1936 if (resp == NULL || !resp->needed_auth || conf == NULL) {
1943 if (resp->message_qop == NULL) {
1944 /* old client, so calc rfc-2069 digest */
1947 /* most of this totally bogus because the handlers don't set the
1948 * headers until the final handler phase (I wonder why this phase
1949 * is called fixup when there's almost nothing you can fix up...)
1951 * Because it's basically impossible to get this right (e.g. the
1952 * Content-length is never set yet when we get here, and we can't
1953 * calc the entity hash) it's best to just leave this #def'd out.
1955 char date[APR_RFC822_DATE_LEN];
1956 apr_rfc822_date(date, r->request_time);
1959 (unsigned char *) apr_pstrcat(r->pool, resp->raw_request_uri,
1961 r->content_type ? r->content_type : ap_default_type(r), ":",
1962 hdr(r->headers_out, "Content-Length"), ":",
1963 r->content_encoding ? r->content_encoding : "", ":",
1964 hdr(r->headers_out, "Last-Modified"), ":",
1965 r->no_cache && !apr_table_get(r->headers_out, "Expires") ?
1967 hdr(r->headers_out, "Expires"),
1971 (unsigned char *)apr_pstrcat(r->pool, conf->ha1, ":",
1976 ap_md5(r->pool, (unsigned char *) ""), /* H(entity) - TBD */
1984 if (conf->nonce_lifetime > 0) {
1985 /* send nextnonce if current nonce will expire in less than 30 secs */
1986 if ((r->request_time - resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
1987 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"",
1988 gen_nonce(r->pool, r->request_time,
1989 resp->opaque, r->server, conf),
1992 resp->client->nonce_count = 0;
1995 else if (conf->nonce_lifetime == 0 && resp->client) {
1996 const char *nonce = gen_nonce(r->pool, 0, resp->opaque, r->server,
1998 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
1999 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
2001 /* else nonce never expires, hence no nextnonce */
2004 /* do rfc-2069 digest
2006 if (conf->qop_list[0] && !strcasecmp(conf->qop_list[0], "none")
2007 && resp->message_qop == NULL) {
2008 /* use only RFC-2069 format */
2010 ai = apr_pstrcat(r->pool, "digest=\"", digest, "\"", nextnonce,NULL);
2017 const char *resp_dig, *ha1, *a2, *ha2;
2019 /* calculate rspauth attribute
2021 if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
2022 ha1 = get_session_HA1(r, resp, conf, 0);
2024 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2025 "Digest: internal error: couldn't find session "
2026 "info for user %s", resp->username);
2034 if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int")) {
2035 a2 = apr_pstrcat(r->pool, ":", resp->uri, ":",
2036 ap_md5(r->pool,(const unsigned char *) ""), NULL);
2040 a2 = apr_pstrcat(r->pool, ":", resp->uri, NULL);
2042 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
2044 resp_dig = ap_md5(r->pool,
2045 (unsigned char *)apr_pstrcat(r->pool, ha1, ":",
2047 resp->nonce_count, ":",
2050 resp->message_qop : "",
2053 /* assemble Authentication-Info header
2055 ai = apr_pstrcat(r->pool,
2056 "rspauth=\"", resp_dig, "\"",
2058 resp->cnonce ? ", cnonce=\"" : "",
2060 ? ap_escape_quotes(r->pool, resp->cnonce)
2062 resp->cnonce ? "\"" : "",
2063 resp->nonce_count ? ", nc=" : "",
2064 resp->nonce_count ? resp->nonce_count : "",
2065 resp->message_qop ? ", qop=" : "",
2066 resp->message_qop ? resp->message_qop : "",
2067 digest ? "digest=\"" : "",
2068 digest ? digest : "",
2074 apr_table_mergen(r->headers_out,
2075 (PROXYREQ_PROXY == r->proxyreq)
2076 ? "Proxy-Authentication-Info"
2077 : "Authentication-Info",
2085 static void register_hooks(apr_pool_t *p)
2087 static const char * const cfgPost[]={ "http_core.c", NULL };
2088 static const char * const parsePre[]={ "mod_proxy.c", NULL };
2090 ap_hook_post_config(initialize_module, NULL, cfgPost, APR_HOOK_MIDDLE);
2091 ap_hook_child_init(initialize_child, NULL, NULL, APR_HOOK_MIDDLE);
2092 ap_hook_post_read_request(parse_hdr_and_update_nc, parsePre, NULL, APR_HOOK_MIDDLE);
2093 ap_hook_check_user_id(authenticate_digest_user, NULL, NULL, APR_HOOK_MIDDLE);
2094 ap_hook_auth_checker(digest_check_auth, NULL, NULL, APR_HOOK_MIDDLE);
2095 ap_hook_fixups(add_auth_info, NULL, NULL, APR_HOOK_MIDDLE);
2098 module AP_MODULE_DECLARE_DATA auth_digest_module =
2100 STANDARD20_MODULE_STUFF,
2101 create_digest_dir_config, /* dir config creater */
2102 NULL, /* dir merger --- default is to override */
2103 NULL, /* server config */
2104 NULL, /* merge server config */
2105 digest_cmds, /* command table */
2106 register_hooks /* register hooks */