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.
30 * - qop=auth-int (when streams and trailer support available)
31 * - nonce-format configurability
32 * - Proxy-Authorization-Info header is set by this module, but is
33 * currently ignored by mod_proxy (needs patch to mod_proxy)
34 * - The source of the secret should be run-time directive (with server
36 * - shared-mem not completely tested yet. Seems to work ok for me,
37 * but... (definitely won't work on Windoze)
38 * - Sharing a realm among multiple servers has following problems:
39 * o Server name and port can't be included in nonce-hash
40 * (we need two nonce formats, which must be configured explicitly)
41 * o Nonce-count check can't be for equal, or then nonce-count checking
42 * must be disabled. What we could do is the following:
43 * (expected < received) ? set expected = received : issue error
44 * The only problem is that it allows replay attacks when somebody
45 * captures a packet sent to one server and sends it to another
46 * one. Should we add "AuthDigestNcCheck Strict"?
47 * - expired nonces give amaya fits.
48 * - MD5-sess and auth-int are not yet implemented. An incomplete
49 * implementation has been removed and can be retrieved from svn history.
53 #include "apr_base64.h"
56 #include "apr_errno.h"
57 #include "apr_global_mutex.h"
58 #include "apr_strings.h"
60 #define APR_WANT_STRFUNC
63 #include "ap_config.h"
65 #include "http_config.h"
66 #include "http_core.h"
67 #include "http_request.h"
69 #include "http_protocol.h"
72 #include "util_mutex.h"
75 #include "ap_provider.h"
83 /* struct to hold the configuration info */
85 typedef struct digest_config_struct {
87 authn_provider_list *providers;
89 apr_array_header_t *qop_list;
90 apr_sha1_ctx_t nonce_ctx;
91 apr_time_t nonce_lifetime;
93 const char *algorithm;
99 #define DFLT_ALGORITHM "MD5"
101 #define DFLT_NONCE_LIFE apr_time_from_sec(300)
102 #define NEXTNONCE_DELTA apr_time_from_sec(30)
105 #define NONCE_TIME_LEN (((sizeof(apr_time_t)+2)/3)*4)
106 #define NONCE_HASH_LEN (2*APR_SHA1_DIGESTSIZE)
107 #define NONCE_LEN (int )(NONCE_TIME_LEN + NONCE_HASH_LEN)
109 #define SECRET_LEN 20
110 #define RETAINED_DATA_ID "mod_auth_digest"
113 /* client list definitions */
115 typedef struct hash_entry {
116 unsigned long key; /* the key for this entry */
117 struct hash_entry *next; /* next entry in the bucket */
118 unsigned long nonce_count; /* for nonce-count checking */
119 char last_nonce[NONCE_LEN+1]; /* for one-time nonce's */
122 static struct hash_table {
123 client_entry **table;
124 unsigned long tbl_len;
125 unsigned long num_entries;
126 unsigned long num_created;
127 unsigned long num_removed;
128 unsigned long num_renewed;
132 /* struct to hold a parsed Authorization header */
134 enum hdr_sts { NO_HEADER, NOT_DIGEST, INVALID, VALID };
136 typedef struct digest_header_struct {
139 const char *username;
144 const char *algorithm;
147 unsigned long opaque_num;
148 const char *message_qop;
149 const char *nonce_count;
150 /* the following fields are not (directly) from the header */
151 const char *raw_request_uri;
152 apr_uri_t *psd_request_uri;
153 apr_time_t nonce_time;
154 enum hdr_sts auth_hdr_sts;
156 client_entry *client;
160 /* (mostly) nonce stuff */
162 typedef union time_union {
164 unsigned char arr[sizeof(apr_time_t)];
167 static unsigned char *secret;
169 /* client-list, opaque, and one-time-nonce stuff */
171 static apr_shm_t *client_shm = NULL;
172 static apr_rmm_t *client_rmm = NULL;
173 static unsigned long *opaque_cntr;
174 static apr_time_t *otn_counter; /* one-time-nonce counter */
175 static apr_global_mutex_t *client_lock = NULL;
176 static apr_global_mutex_t *opaque_lock = NULL;
177 static const char *client_mutex_type = "authdigest-client";
178 static const char *opaque_mutex_type = "authdigest-opaque";
179 static const char *client_shm_filename;
181 #define DEF_SHMEM_SIZE 1000L /* ~ 12 entries */
182 #define DEF_NUM_BUCKETS 15L
185 static apr_size_t shmem_size = DEF_SHMEM_SIZE;
186 static unsigned long num_buckets = DEF_NUM_BUCKETS;
189 module AP_MODULE_DECLARE_DATA auth_digest_module;
192 * initialization code
195 static apr_status_t cleanup_tables(void *not_used)
197 ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, APLOGNO(01756)
198 "cleaning up shared memory");
201 apr_rmm_destroy(client_rmm);
206 apr_shm_destroy(client_shm);
211 apr_global_mutex_destroy(client_lock);
216 apr_global_mutex_destroy(opaque_lock);
225 static void log_error_and_cleanup(char *msg, apr_status_t sts, server_rec *s)
227 ap_log_error(APLOG_MARK, APLOG_ERR, sts, s, APLOGNO(01760)
228 "%s - all nonce-count checking and one-time nonces "
231 cleanup_tables(NULL);
234 #if APR_HAS_SHARED_MEMORY
236 static int initialize_tables(server_rec *s, apr_pool_t *ctx)
241 /* set up client list */
243 /* Create the shared memory segment */
246 * Create a unique filename using our pid. This information is
247 * stashed in the global variable so the children inherit it.
249 client_shm_filename = ap_runtime_dir_relative(ctx, "authdigest_shm");
250 client_shm_filename = ap_append_pid(ctx, client_shm_filename, ".");
252 /* Use anonymous shm by default, fall back on name-based. */
253 sts = apr_shm_create(&client_shm, shmem_size, NULL, ctx);
254 if (APR_STATUS_IS_ENOTIMPL(sts)) {
255 /* For a name-based segment, remove it first in case of a
256 * previous unclean shutdown. */
257 apr_shm_remove(client_shm_filename, ctx);
259 /* Now create that segment */
260 sts = apr_shm_create(&client_shm, shmem_size,
261 client_shm_filename, ctx);
264 if (APR_SUCCESS != sts) {
265 ap_log_error(APLOG_MARK, APLOG_ERR, sts, s, APLOGNO(01762)
266 "Failed to create shared memory segment on file %s",
267 client_shm_filename);
268 log_error_and_cleanup("failed to initialize shm", sts, s);
269 return HTTP_INTERNAL_SERVER_ERROR;
272 sts = apr_rmm_init(&client_rmm,
273 NULL, /* no lock, we'll do the locking ourselves */
274 apr_shm_baseaddr_get(client_shm),
276 if (sts != APR_SUCCESS) {
277 log_error_and_cleanup("failed to initialize rmm", sts, s);
281 client_list = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(*client_list) +
282 sizeof(client_entry*)*num_buckets));
284 log_error_and_cleanup("failed to allocate shared memory", -1, s);
287 client_list->table = (client_entry**) (client_list + 1);
288 for (idx = 0; idx < num_buckets; idx++) {
289 client_list->table[idx] = NULL;
291 client_list->tbl_len = num_buckets;
292 client_list->num_entries = 0;
294 sts = ap_global_mutex_create(&client_lock, NULL, client_mutex_type, NULL,
296 if (sts != APR_SUCCESS) {
297 log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
304 opaque_cntr = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(*opaque_cntr)));
305 if (opaque_cntr == NULL) {
306 log_error_and_cleanup("failed to allocate shared memory", -1, s);
311 sts = ap_global_mutex_create(&opaque_lock, NULL, opaque_mutex_type, NULL,
313 if (sts != APR_SUCCESS) {
314 log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
319 /* setup one-time-nonce counter */
321 otn_counter = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(*otn_counter)));
322 if (otn_counter == NULL) {
323 log_error_and_cleanup("failed to allocate shared memory", -1, s);
334 #endif /* APR_HAS_SHARED_MEMORY */
336 static int pre_init(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
341 rv = ap_mutex_register(pconf, client_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
342 if (rv != APR_SUCCESS)
344 rv = ap_mutex_register(pconf, opaque_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
345 if (rv != APR_SUCCESS)
348 retained = ap_retained_data_get(RETAINED_DATA_ID);
349 if (retained == NULL) {
350 retained = ap_retained_data_create(RETAINED_DATA_ID, SECRET_LEN);
351 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(01757)
352 "generating secret for digest authentication");
354 rv = apr_generate_random_bytes(retained, SECRET_LEN);
356 #error APR random number support is missing
358 if (rv != APR_SUCCESS) {
359 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(01758)
360 "error generating secret");
368 static int initialize_module(apr_pool_t *p, apr_pool_t *plog,
369 apr_pool_t *ptemp, server_rec *s)
371 /* initialize_module() will be called twice, and if it's a DSO
372 * then all static data from the first call will be lost. Only
373 * set up our static data on the second call. */
374 if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG)
377 #if APR_HAS_SHARED_MEMORY
378 /* Note: this stuff is currently fixed for the lifetime of the server,
379 * i.e. even across restarts. This means that A) any shmem-size
380 * configuration changes are ignored, and B) certain optimizations,
381 * such as only allocating the smallest necessary entry for each
382 * client, can't be done. However, the alternative is a nightmare:
383 * we can't call apr_shm_destroy on a graceful restart because there
384 * will be children using the tables, and we also don't know when the
385 * last child dies. Therefore we can never clean up the old stuff,
386 * creating a creeping memory leak.
388 if (initialize_tables(s, p) != OK) {
391 /* Call cleanup_tables on exit or restart */
392 apr_pool_cleanup_register(p, NULL, cleanup_tables, apr_pool_cleanup_null);
393 #endif /* APR_HAS_SHARED_MEMORY */
397 static void initialize_child(apr_pool_t *p, server_rec *s)
405 /* Get access to rmm in child */
406 sts = apr_rmm_attach(&client_rmm,
408 apr_shm_baseaddr_get(client_shm),
410 if (sts != APR_SUCCESS) {
411 log_error_and_cleanup("failed to attach to rmm", sts, s);
415 sts = apr_global_mutex_child_init(&client_lock,
416 apr_global_mutex_lockfile(client_lock),
418 if (sts != APR_SUCCESS) {
419 log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
422 sts = apr_global_mutex_child_init(&opaque_lock,
423 apr_global_mutex_lockfile(opaque_lock),
425 if (sts != APR_SUCCESS) {
426 log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
435 static void *create_digest_dir_config(apr_pool_t *p, char *dir)
437 digest_config_rec *conf;
443 conf = (digest_config_rec *) apr_pcalloc(p, sizeof(digest_config_rec));
445 conf->qop_list = apr_array_make(p, 2, sizeof(char *));
446 conf->nonce_lifetime = DFLT_NONCE_LIFE;
447 conf->dir_name = apr_pstrdup(p, dir);
448 conf->algorithm = DFLT_ALGORITHM;
454 static const char *set_realm(cmd_parms *cmd, void *config, const char *realm)
456 digest_config_rec *conf = (digest_config_rec *) config;
460 /* check that we got random numbers */
461 for (i = 0; i < SECRET_LEN; i++) {
465 ap_assert(i < SECRET_LEN);
468 /* The core already handles the realm, but it's just too convenient to
469 * grab it ourselves too and cache some setups. However, we need to
470 * let the core get at it too, which is why we decline at the end -
471 * this relies on the fact that http_core is last in the list.
475 /* we precompute the part of the nonce hash that is constant (well,
476 * the host:port would be too, but that varies for .htaccess files
477 * and directives outside a virtual host section)
479 apr_sha1_init(&conf->nonce_ctx);
480 apr_sha1_update_binary(&conf->nonce_ctx, secret, SECRET_LEN);
481 apr_sha1_update_binary(&conf->nonce_ctx, (const unsigned char *) realm,
487 static const char *add_authn_provider(cmd_parms *cmd, void *config,
490 digest_config_rec *conf = (digest_config_rec*)config;
491 authn_provider_list *newp;
493 newp = apr_pcalloc(cmd->pool, sizeof(authn_provider_list));
494 newp->provider_name = arg;
496 /* lookup and cache the actual provider now */
497 newp->provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP,
499 AUTHN_PROVIDER_VERSION);
501 if (newp->provider == NULL) {
502 /* by the time they use it, the provider should be loaded and
503 registered with us. */
504 return apr_psprintf(cmd->pool,
505 "Unknown Authn provider: %s",
506 newp->provider_name);
509 if (!newp->provider->get_realm_hash) {
510 /* if it doesn't provide the appropriate function, reject it */
511 return apr_psprintf(cmd->pool,
512 "The '%s' Authn provider doesn't support "
513 "Digest Authentication", newp->provider_name);
516 /* Add it to the list now. */
517 if (!conf->providers) {
518 conf->providers = newp;
521 authn_provider_list *last = conf->providers;
532 static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
534 digest_config_rec *conf = (digest_config_rec *) config;
536 if (!strcasecmp(op, "none")) {
537 apr_array_clear(conf->qop_list);
538 *(const char **)apr_array_push(conf->qop_list) = "none";
542 if (!strcasecmp(op, "auth-int")) {
543 return "AuthDigestQop auth-int is not implemented";
545 else if (ap_casecmpstr(op, "auth")) {
546 return apr_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
549 *(const char **)apr_array_push(conf->qop_list) = op;
554 static const char *set_nonce_lifetime(cmd_parms *cmd, void *config,
560 lifetime = strtol(t, &endptr, 10);
561 if (endptr < (t+strlen(t)) && !apr_isspace(*endptr)) {
562 return apr_pstrcat(cmd->pool,
563 "Invalid time in AuthDigestNonceLifetime: ",
567 ((digest_config_rec *) config)->nonce_lifetime = apr_time_from_sec(lifetime);
571 static const char *set_nonce_format(cmd_parms *cmd, void *config,
574 return "AuthDigestNonceFormat is not implemented";
577 static const char *set_nc_check(cmd_parms *cmd, void *config, int flag)
579 #if !APR_HAS_SHARED_MEMORY
581 return "AuthDigestNcCheck: ERROR: nonce-count checking "
582 "is not supported on platforms without shared-memory "
587 ((digest_config_rec *) config)->check_nc = flag;
591 static const char *set_algorithm(cmd_parms *cmd, void *config, const char *alg)
593 if (!strcasecmp(alg, "MD5-sess")) {
594 return "AuthDigestAlgorithm: ERROR: algorithm `MD5-sess' "
595 "is not implemented";
597 else if (ap_casecmpstr(alg, "MD5")) {
598 return apr_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
601 ((digest_config_rec *) config)->algorithm = alg;
605 static const char *set_uri_list(cmd_parms *cmd, void *config, const char *uri)
607 digest_config_rec *c = (digest_config_rec *) config;
609 c->uri_list[strlen(c->uri_list)-1] = '\0';
610 c->uri_list = apr_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
613 c->uri_list = apr_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
618 static const char *set_shmem_size(cmd_parms *cmd, void *config,
619 const char *size_str)
624 size = strtol(size_str, &endptr, 10);
625 while (apr_isspace(*endptr)) endptr++;
626 if (*endptr == '\0' || *endptr == 'b' || *endptr == 'B') {
629 else if (*endptr == 'k' || *endptr == 'K') {
632 else if (*endptr == 'm' || *endptr == 'M') {
636 return apr_pstrcat(cmd->pool, "Invalid size in AuthDigestShmemSize: ",
640 min = sizeof(*client_list) + sizeof(client_entry*) + sizeof(client_entry);
642 return apr_psprintf(cmd->pool, "size in AuthDigestShmemSize too small: "
643 "%ld < %ld", size, min);
647 num_buckets = (size - sizeof(*client_list)) /
648 (sizeof(client_entry*) + HASH_DEPTH * sizeof(client_entry));
649 if (num_buckets == 0) {
652 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, APLOGNO(01763)
653 "Set shmem-size: %" APR_SIZE_T_FMT ", num-buckets: %ld",
654 shmem_size, num_buckets);
659 static const command_rec digest_cmds[] =
661 AP_INIT_TAKE1("AuthName", set_realm, NULL, OR_AUTHCFG,
662 "The authentication realm (e.g. \"Members Only\")"),
663 AP_INIT_ITERATE("AuthDigestProvider", add_authn_provider, NULL, OR_AUTHCFG,
664 "specify the auth providers for a directory or location"),
665 AP_INIT_ITERATE("AuthDigestQop", set_qop, NULL, OR_AUTHCFG,
666 "A list of quality-of-protection options"),
667 AP_INIT_TAKE1("AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG,
668 "Maximum lifetime of the server nonce (seconds)"),
669 AP_INIT_TAKE1("AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG,
670 "The format to use when generating the server nonce"),
671 AP_INIT_FLAG("AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG,
672 "Whether or not to check the nonce-count sent by the client"),
673 AP_INIT_TAKE1("AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG,
674 "The algorithm used for the hash calculation"),
675 AP_INIT_ITERATE("AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG,
676 "A list of URI's which belong to the same protection space as the current URI"),
677 AP_INIT_TAKE1("AuthDigestShmemSize", set_shmem_size, NULL, RSRC_CONF,
678 "The amount of shared memory to allocate for keeping track of clients"),
686 * Each client is assigned a number, which is transferred in the opaque
687 * field of the WWW-Authenticate and Authorization headers. The number
688 * is just a simple counter which is incremented for each new client.
689 * Clients can't forge this number because it is hashed up into the
690 * server nonce, and that is checked.
692 * The clients are kept in a simple hash table, which consists of an
693 * array of client_entry's, each with a linked list of entries hanging
694 * off it. The client's number modulo the size of the array gives the
697 * The clients are garbage collected whenever a new client is allocated
698 * but there is not enough space left in the shared memory segment. A
699 * simple semi-LRU is used for this: whenever a client entry is accessed
700 * it is moved to the beginning of the linked list in its bucket (this
701 * also makes for faster lookups for current clients). The garbage
702 * collecter then just removes the oldest entry (i.e. the one at the
703 * end of the list) in each bucket.
705 * The main advantages of the above scheme are that it's easy to implement
706 * and it keeps the hash table evenly balanced (i.e. same number of entries
707 * in each bucket). The major disadvantage is that you may be throwing
708 * entries out which are in active use. This is not tragic, as these
709 * clients will just be sent a new client id (opaque field) and nonce
710 * with a stale=true (i.e. it will just look like the nonce expired,
711 * thereby forcing an extra round trip). If the shared memory segment
712 * has enough headroom over the current client set size then this should
713 * not occur too often.
715 * To help tune the size of the shared memory segment (and see if the
716 * above algorithm is really sufficient) a set of counters is kept
717 * indicating the number of clients held, the number of garbage collected
718 * clients, and the number of erroneously purged clients. These are printed
719 * out at each garbage collection run. Note that access to the counters is
720 * not synchronized because they are just indicaters, and whether they are
721 * off by a few doesn't matter; and for the same reason no attempt is made
722 * to guarantee the num_renewed is correct in the face of clients spoofing
727 * Get the client given its client number (the key). Returns the entry,
728 * or NULL if it's not found.
730 * Access to the list itself is synchronized via locks. However, access
731 * to the entry returned by get_client() is NOT synchronized. This means
732 * that there are potentially problems if a client uses multiple,
733 * simultaneous connections to access url's within the same protection
734 * space. However, these problems are not new: when using multiple
735 * connections you have no guarantee of the order the requests are
736 * processed anyway, so you have problems with the nonce-count and
737 * one-time nonces anyway.
739 static client_entry *get_client(unsigned long key, const request_rec *r)
742 client_entry *entry, *prev = NULL;
745 if (!key || !client_shm) return NULL;
747 bucket = key % client_list->tbl_len;
748 entry = client_list->table[bucket];
750 apr_global_mutex_lock(client_lock);
752 while (entry && key != entry->key) {
757 if (entry && prev) { /* move entry to front of list */
758 prev->next = entry->next;
759 entry->next = client_list->table[bucket];
760 client_list->table[bucket] = entry;
763 apr_global_mutex_unlock(client_lock);
766 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01764)
767 "get_client(): client %lu found", key);
770 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01765)
771 "get_client(): client %lu not found", key);
778 /* A simple garbage-collecter to remove unused clients. It removes the
779 * last entry in each bucket and updates the counters. Returns the
780 * number of removed entries.
784 client_entry *entry, *prev;
785 unsigned long num_removed = 0, idx;
787 /* garbage collect all last entries */
789 for (idx = 0; idx < client_list->tbl_len; idx++) {
790 entry = client_list->table[idx];
792 while (entry->next) { /* find last entry */
797 prev->next = NULL; /* cut list */
800 client_list->table[idx] = NULL;
802 if (entry) { /* remove entry */
803 apr_rmm_free(client_rmm, apr_rmm_offset_get(client_rmm, entry));
808 /* update counters and log */
810 client_list->num_entries -= num_removed;
811 client_list->num_removed += num_removed;
818 * Add a new client to the list. Returns the entry if successful, NULL
819 * otherwise. This triggers the garbage collection if memory is low.
821 static client_entry *add_client(unsigned long key, client_entry *info,
828 if (!key || !client_shm) {
832 bucket = key % client_list->tbl_len;
834 apr_global_mutex_lock(client_lock);
836 /* try to allocate a new entry */
838 entry = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(client_entry)));
840 long num_removed = gc();
841 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01766)
842 "gc'd %ld client entries. Total new clients: "
843 "%ld; Total removed clients: %ld; Total renewed clients: "
845 client_list->num_created - client_list->num_renewed,
846 client_list->num_removed, client_list->num_renewed);
847 entry = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(client_entry)));
849 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01767)
850 "unable to allocate new auth_digest client");
851 apr_global_mutex_unlock(client_lock);
852 return NULL; /* give up */
856 /* now add the entry */
858 memcpy(entry, info, sizeof(client_entry));
860 entry->next = client_list->table[bucket];
861 client_list->table[bucket] = entry;
862 client_list->num_created++;
863 client_list->num_entries++;
865 apr_global_mutex_unlock(client_lock);
867 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01768)
868 "allocated new client %lu", key);
875 * Authorization header parser code
878 /* Parse the Authorization header, if it exists */
879 static int get_digest_rec(request_rec *r, digest_header_rec *resp)
881 const char *auth_line;
886 auth_line = apr_table_get(r->headers_in,
887 (PROXYREQ_PROXY == r->proxyreq)
888 ? "Proxy-Authorization"
891 resp->auth_hdr_sts = NO_HEADER;
895 resp->scheme = ap_getword_white(r->pool, &auth_line);
896 if (ap_casecmpstr(resp->scheme, "Digest")) {
897 resp->auth_hdr_sts = NOT_DIGEST;
901 l = strlen(auth_line);
903 key = apr_palloc(r->pool, l+1);
904 value = apr_palloc(r->pool, l+1);
906 while (auth_line[0] != '\0') {
910 while (apr_isspace(auth_line[0])) {
914 while (auth_line[0] != '=' && auth_line[0] != ','
915 && auth_line[0] != '\0' && !apr_isspace(auth_line[0])) {
916 key[vk++] = *auth_line++;
919 while (apr_isspace(auth_line[0])) {
925 if (auth_line[0] == '=') {
927 while (apr_isspace(auth_line[0])) {
932 if (auth_line[0] == '\"') { /* quoted string */
934 while (auth_line[0] != '\"' && auth_line[0] != '\0') {
935 if (auth_line[0] == '\\' && auth_line[1] != '\0') {
936 auth_line++; /* escaped char */
938 value[vv++] = *auth_line++;
940 if (auth_line[0] != '\0') {
945 while (auth_line[0] != ',' && auth_line[0] != '\0'
946 && !apr_isspace(auth_line[0])) {
947 value[vv++] = *auth_line++;
953 while (auth_line[0] != ',' && auth_line[0] != '\0') {
956 if (auth_line[0] != '\0') {
960 if (!ap_casecmpstr(key, "username"))
961 resp->username = apr_pstrdup(r->pool, value);
962 else if (!ap_casecmpstr(key, "realm"))
963 resp->realm = apr_pstrdup(r->pool, value);
964 else if (!ap_casecmpstr(key, "nonce"))
965 resp->nonce = apr_pstrdup(r->pool, value);
966 else if (!ap_casecmpstr(key, "uri"))
967 resp->uri = apr_pstrdup(r->pool, value);
968 else if (!ap_casecmpstr(key, "response"))
969 resp->digest = apr_pstrdup(r->pool, value);
970 else if (!ap_casecmpstr(key, "algorithm"))
971 resp->algorithm = apr_pstrdup(r->pool, value);
972 else if (!ap_casecmpstr(key, "cnonce"))
973 resp->cnonce = apr_pstrdup(r->pool, value);
974 else if (!ap_casecmpstr(key, "opaque"))
975 resp->opaque = apr_pstrdup(r->pool, value);
976 else if (!ap_casecmpstr(key, "qop"))
977 resp->message_qop = apr_pstrdup(r->pool, value);
978 else if (!ap_casecmpstr(key, "nc"))
979 resp->nonce_count = apr_pstrdup(r->pool, value);
982 if (!resp->username || !resp->realm || !resp->nonce || !resp->uri
984 || (resp->message_qop && (!resp->cnonce || !resp->nonce_count))) {
985 resp->auth_hdr_sts = INVALID;
990 resp->opaque_num = (unsigned long) strtol(resp->opaque, NULL, 16);
993 resp->auth_hdr_sts = VALID;
998 /* Because the browser may preemptively send auth info, incrementing the
999 * nonce-count when it does, and because the client does not get notified
1000 * if the URI didn't need authentication after all, we need to be sure to
1001 * update the nonce-count each time we receive an Authorization header no
1002 * matter what the final outcome of the request. Furthermore this is a
1003 * convenient place to get the request-uri (before any subrequests etc
1004 * are initiated) and to initialize the request_config.
1006 * Note that this must be called after mod_proxy had its go so that
1007 * r->proxyreq is set correctly.
1009 static int parse_hdr_and_update_nc(request_rec *r)
1011 digest_header_rec *resp;
1014 if (!ap_is_initial_req(r)) {
1018 resp = apr_pcalloc(r->pool, sizeof(digest_header_rec));
1019 resp->raw_request_uri = r->unparsed_uri;
1020 resp->psd_request_uri = &r->parsed_uri;
1021 resp->needed_auth = 0;
1022 resp->method = r->method;
1023 ap_set_module_config(r->request_config, &auth_digest_module, resp);
1025 res = get_digest_rec(r, resp);
1026 resp->client = get_client(resp->opaque_num, r);
1027 if (res == OK && resp->client) {
1028 resp->client->nonce_count++;
1036 * Nonce generation code
1039 /* The hash part of the nonce is a SHA-1 hash of the time, realm, server host
1040 * and port, opaque, and our secret.
1042 static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
1043 const server_rec *server,
1044 const digest_config_rec *conf)
1046 unsigned char sha1[APR_SHA1_DIGESTSIZE];
1049 memcpy(&ctx, &conf->nonce_ctx, sizeof(ctx));
1051 apr_sha1_update_binary(&ctx, (const unsigned char *) server->server_hostname,
1052 strlen(server->server_hostname));
1053 apr_sha1_update_binary(&ctx, (const unsigned char *) &server->port,
1054 sizeof(server->port));
1056 apr_sha1_update_binary(&ctx, (const unsigned char *) timestr, strlen(timestr));
1058 apr_sha1_update_binary(&ctx, (const unsigned char *) opaque,
1061 apr_sha1_final(sha1, &ctx);
1063 ap_bin2hex(sha1, APR_SHA1_DIGESTSIZE, hash);
1067 /* The nonce has the format b64(time)+hash .
1069 static const char *gen_nonce(apr_pool_t *p, apr_time_t now, const char *opaque,
1070 const server_rec *server,
1071 const digest_config_rec *conf)
1073 char *nonce = apr_palloc(p, NONCE_LEN+1);
1076 if (conf->nonce_lifetime != 0) {
1079 else if (otn_counter) {
1080 /* this counter is not synch'd, because it doesn't really matter
1081 * if it counts exactly.
1083 t.time = (*otn_counter)++;
1086 /* XXX: WHAT IS THIS CONSTANT? */
1089 apr_base64_encode_binary(nonce, t.arr, sizeof(t.arr));
1090 gen_nonce_hash(nonce+NONCE_TIME_LEN, nonce, opaque, server, conf);
1097 * Opaque and hash-table management
1101 * Generate a new client entry, add it to the list, and return the
1102 * entry. Returns NULL if failed.
1104 static client_entry *gen_client(const request_rec *r)
1107 client_entry new_entry = { 0, NULL, 0, "" }, *entry;
1113 apr_global_mutex_lock(opaque_lock);
1114 op = (*opaque_cntr)++;
1115 apr_global_mutex_unlock(opaque_lock);
1117 if (!(entry = add_client(op, &new_entry, r->server))) {
1118 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01769)
1119 "failed to allocate client entry - ignoring client");
1128 * Authorization challenge generation code (for WWW-Authenticate)
1131 static const char *ltox(apr_pool_t *p, unsigned long num)
1134 return apr_psprintf(p, "%lx", num);
1141 static void note_digest_auth_failure(request_rec *r,
1142 const digest_config_rec *conf,
1143 digest_header_rec *resp, int stale)
1145 const char *qop, *opaque, *opaque_param, *domain, *nonce;
1148 if (apr_is_empty_array(conf->qop_list)) {
1149 qop = ", qop=\"auth\"";
1151 else if (!ap_casecmpstr(*(const char **)(conf->qop_list->elts), "none")) {
1155 qop = apr_pstrcat(r->pool, ", qop=\"",
1156 apr_array_pstrcat(r->pool, conf->qop_list, ','),
1163 if (resp->opaque == NULL) {
1165 if ((conf->check_nc || conf->nonce_lifetime == 0)
1166 && (resp->client = gen_client(r)) != NULL) {
1167 opaque = ltox(r->pool, resp->client->key);
1170 opaque = ""; /* opaque not needed */
1173 else if (resp->client == NULL) {
1174 /* client info was gc'd */
1175 resp->client = gen_client(r);
1176 if (resp->client != NULL) {
1177 opaque = ltox(r->pool, resp->client->key);
1179 client_list->num_renewed++;
1182 opaque = ""; /* ??? */
1186 opaque = resp->opaque;
1187 /* we're generating a new nonce, so reset the nonce-count */
1188 resp->client->nonce_count = 0;
1192 opaque_param = apr_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
1195 opaque_param = NULL;
1200 nonce = gen_nonce(r->pool, r->request_time, opaque, r->server, conf);
1201 if (resp->client && conf->nonce_lifetime == 0) {
1202 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1205 /* setup domain attribute. We want to send this attribute wherever
1206 * possible so that the client won't send the Authorization header
1207 * unnecessarily (it's usually > 200 bytes!).
1211 /* don't send domain
1212 * - for proxy requests
1213 * - if it's not specified
1215 if (r->proxyreq || !conf->uri_list) {
1219 domain = conf->uri_list;
1222 apr_table_mergen(r->err_headers_out,
1223 (PROXYREQ_PROXY == r->proxyreq)
1224 ? "Proxy-Authenticate" : "WWW-Authenticate",
1225 apr_psprintf(r->pool, "Digest realm=\"%s\", "
1226 "nonce=\"%s\", algorithm=%s%s%s%s%s",
1227 ap_auth_name(r), nonce, conf->algorithm,
1228 opaque_param ? opaque_param : "",
1229 domain ? domain : "",
1230 stale ? ", stale=true" : "", qop));
1234 static int hook_note_digest_auth_failure(request_rec *r, const char *auth_type)
1236 request_rec *mainreq;
1237 digest_header_rec *resp;
1238 digest_config_rec *conf;
1240 if (ap_casecmpstr(auth_type, "Digest"))
1243 /* get the client response and mark */
1246 while (mainreq->main != NULL) {
1247 mainreq = mainreq->main;
1249 while (mainreq->prev != NULL) {
1250 mainreq = mainreq->prev;
1252 resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1253 &auth_digest_module);
1254 resp->needed_auth = 1;
1259 conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1260 &auth_digest_module);
1262 note_digest_auth_failure(r, conf, resp, 0);
1269 * Authorization header verification code
1272 static authn_status get_hash(request_rec *r, const char *user,
1273 digest_config_rec *conf)
1275 authn_status auth_result;
1277 authn_provider_list *current_provider;
1279 current_provider = conf->providers;
1281 const authn_provider *provider;
1283 /* For now, if a provider isn't set, we'll be nice and use the file
1286 if (!current_provider) {
1287 provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP,
1288 AUTHN_DEFAULT_PROVIDER,
1289 AUTHN_PROVIDER_VERSION);
1291 if (!provider || !provider->get_realm_hash) {
1292 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01770)
1293 "No Authn provider configured");
1294 auth_result = AUTH_GENERAL_ERROR;
1297 apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, AUTHN_DEFAULT_PROVIDER);
1300 provider = current_provider->provider;
1301 apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, current_provider->provider_name);
1305 /* We expect the password to be md5 hash of user:realm:password */
1306 auth_result = provider->get_realm_hash(r, user, conf->realm,
1309 apr_table_unset(r->notes, AUTHN_PROVIDER_NAME_NOTE);
1311 /* Something occured. Stop checking. */
1312 if (auth_result != AUTH_USER_NOT_FOUND) {
1316 /* If we're not really configured for providers, stop now. */
1317 if (!conf->providers) {
1321 current_provider = current_provider->next;
1322 } while (current_provider);
1324 if (auth_result == AUTH_USER_FOUND) {
1325 conf->ha1 = password;
1331 static int check_nc(const request_rec *r, const digest_header_rec *resp,
1332 const digest_config_rec *conf)
1335 const char *snc = resp->nonce_count;
1338 if (conf->check_nc && !client_shm) {
1339 /* Shouldn't happen, but just in case... */
1340 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01771)
1341 "cannot check nonce count without shared memory");
1345 if (!conf->check_nc || !client_shm) {
1349 if (!apr_is_empty_array(conf->qop_list) &&
1350 !ap_casecmpstr(*(const char **)(conf->qop_list->elts), "none")) {
1351 /* qop is none, client must not send a nonce count */
1353 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01772)
1354 "invalid nc %s received - no nonce count allowed when qop=none",
1358 /* qop is none, cannot check nonce count */
1362 nc = strtol(snc, &endptr, 16);
1363 if (endptr < (snc+strlen(snc)) && !apr_isspace(*endptr)) {
1364 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01773)
1365 "invalid nc %s received - not a number", snc);
1369 if (!resp->client) {
1373 if (nc != resp->client->nonce_count) {
1374 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01774)
1375 "Warning, possible replay attack: nonce-count "
1376 "check failed: %lu != %lu", nc,
1377 resp->client->nonce_count);
1384 static int check_nonce(request_rec *r, digest_header_rec *resp,
1385 const digest_config_rec *conf)
1388 time_rec nonce_time;
1389 char tmp, hash[NONCE_HASH_LEN+1];
1391 if (strlen(resp->nonce) != NONCE_LEN) {
1392 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01775)
1393 "invalid nonce %s received - length is not %d",
1394 resp->nonce, NONCE_LEN);
1395 note_digest_auth_failure(r, conf, resp, 1);
1396 return HTTP_UNAUTHORIZED;
1399 tmp = resp->nonce[NONCE_TIME_LEN];
1400 resp->nonce[NONCE_TIME_LEN] = '\0';
1401 apr_base64_decode_binary(nonce_time.arr, resp->nonce);
1402 gen_nonce_hash(hash, resp->nonce, resp->opaque, r->server, conf);
1403 resp->nonce[NONCE_TIME_LEN] = tmp;
1404 resp->nonce_time = nonce_time.time;
1406 if (strcmp(hash, resp->nonce+NONCE_TIME_LEN)) {
1407 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01776)
1408 "invalid nonce %s received - hash is not %s",
1410 note_digest_auth_failure(r, conf, resp, 1);
1411 return HTTP_UNAUTHORIZED;
1414 dt = r->request_time - nonce_time.time;
1415 if (conf->nonce_lifetime > 0 && dt < 0) {
1416 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01777)
1417 "invalid nonce %s received - user attempted "
1418 "time travel", resp->nonce);
1419 note_digest_auth_failure(r, conf, resp, 1);
1420 return HTTP_UNAUTHORIZED;
1423 if (conf->nonce_lifetime > 0) {
1424 if (dt > conf->nonce_lifetime) {
1425 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0,r, APLOGNO(01778)
1426 "user %s: nonce expired (%.2f seconds old "
1427 "- max lifetime %.2f) - sending new nonce",
1428 r->user, (double)apr_time_sec(dt),
1429 (double)apr_time_sec(conf->nonce_lifetime));
1430 note_digest_auth_failure(r, conf, resp, 1);
1431 return HTTP_UNAUTHORIZED;
1434 else if (conf->nonce_lifetime == 0 && resp->client) {
1435 if (memcmp(resp->client->last_nonce, resp->nonce, NONCE_LEN)) {
1436 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01779)
1437 "user %s: one-time-nonce mismatch - sending "
1438 "new nonce", r->user);
1439 note_digest_auth_failure(r, conf, resp, 1);
1440 return HTTP_UNAUTHORIZED;
1443 /* else (lifetime < 0) => never expires */
1448 /* The actual MD5 code... whee */
1451 static const char *old_digest(const request_rec *r,
1452 const digest_header_rec *resp, const char *ha1)
1456 ha2 = ap_md5(r->pool, (unsigned char *)apr_pstrcat(r->pool, resp->method, ":",
1458 return ap_md5(r->pool,
1459 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1464 static const char *new_digest(const request_rec *r,
1465 digest_header_rec *resp,
1466 const digest_config_rec *conf)
1468 const char *ha1, *ha2, *a2;
1472 a2 = apr_pstrcat(r->pool, resp->method, ":", resp->uri, NULL);
1473 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1475 return ap_md5(r->pool,
1476 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1477 ":", resp->nonce_count, ":",
1479 resp->message_qop, ":", ha2,
1484 static void copy_uri_components(apr_uri_t *dst,
1485 apr_uri_t *src, request_rec *r) {
1486 if (src->scheme && src->scheme[0] != '\0') {
1487 dst->scheme = src->scheme;
1490 dst->scheme = (char *) "http";
1493 if (src->hostname && src->hostname[0] != '\0') {
1494 dst->hostname = apr_pstrdup(r->pool, src->hostname);
1495 ap_unescape_url(dst->hostname);
1498 dst->hostname = (char *) ap_get_server_name(r);
1501 if (src->port_str && src->port_str[0] != '\0') {
1502 dst->port = src->port;
1505 dst->port = ap_get_server_port(r);
1508 if (src->path && src->path[0] != '\0') {
1509 dst->path = apr_pstrdup(r->pool, src->path);
1510 ap_unescape_url(dst->path);
1513 dst->path = src->path;
1516 if (src->query && src->query[0] != '\0') {
1517 dst->query = apr_pstrdup(r->pool, src->query);
1518 ap_unescape_url(dst->query);
1521 dst->query = src->query;
1524 dst->hostinfo = src->hostinfo;
1527 /* These functions return 0 if client is OK, and proper error status
1528 * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
1529 * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
1530 * couldn't figure out how to tell if the client is authorized or not.
1532 * If they return DECLINED, and all other modules also decline, that's
1533 * treated by the server core as a configuration error, logged and
1537 /* Determine user ID, and check if the attributes are correct, if it
1538 * really is that user, if the nonce is correct, etc.
1541 static int authenticate_digest_user(request_rec *r)
1543 digest_config_rec *conf;
1544 digest_header_rec *resp;
1545 request_rec *mainreq;
1548 authn_status return_code;
1550 /* do we require Digest auth for this URI? */
1552 if (!(t = ap_auth_type(r)) || ap_casecmpstr(t, "Digest")) {
1556 if (!ap_auth_name(r)) {
1557 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01780)
1558 "need AuthName: %s", r->uri);
1559 return HTTP_INTERNAL_SERVER_ERROR;
1563 /* get the client response and mark */
1566 while (mainreq->main != NULL) {
1567 mainreq = mainreq->main;
1569 while (mainreq->prev != NULL) {
1570 mainreq = mainreq->prev;
1572 resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1573 &auth_digest_module);
1574 resp->needed_auth = 1;
1579 conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1580 &auth_digest_module);
1583 /* check for existence and syntax of Auth header */
1585 if (resp->auth_hdr_sts != VALID) {
1586 if (resp->auth_hdr_sts == NOT_DIGEST) {
1587 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01781)
1588 "client used wrong authentication scheme `%s': %s",
1589 resp->scheme, r->uri);
1591 else if (resp->auth_hdr_sts == INVALID) {
1592 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01782)
1593 "missing user, realm, nonce, uri, digest, "
1594 "cnonce, or nonce_count in authorization header: %s",
1597 /* else (resp->auth_hdr_sts == NO_HEADER) */
1598 note_digest_auth_failure(r, conf, resp, 0);
1599 return HTTP_UNAUTHORIZED;
1602 r->user = (char *) resp->username;
1603 r->ap_auth_type = (char *) "Digest";
1605 /* check the auth attributes */
1607 if (strcmp(resp->uri, resp->raw_request_uri)) {
1608 /* Hmm, the simple match didn't work (probably a proxy modified the
1609 * request-uri), so lets do a more sophisticated match
1611 apr_uri_t r_uri, d_uri;
1613 copy_uri_components(&r_uri, resp->psd_request_uri, r);
1614 if (apr_uri_parse(r->pool, resp->uri, &d_uri) != APR_SUCCESS) {
1615 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01783)
1616 "invalid uri <%s> in Authorization header",
1618 return HTTP_BAD_REQUEST;
1621 if (d_uri.hostname) {
1622 ap_unescape_url(d_uri.hostname);
1625 ap_unescape_url(d_uri.path);
1629 ap_unescape_url(d_uri.query);
1632 if (r->method_number == M_CONNECT) {
1633 if (!r_uri.hostinfo || strcmp(resp->uri, r_uri.hostinfo)) {
1634 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01785)
1635 "uri mismatch - <%s> does not match "
1636 "request-uri <%s>", resp->uri, r_uri.hostinfo);
1637 return HTTP_BAD_REQUEST;
1641 /* check hostname matches, if present */
1642 (d_uri.hostname && d_uri.hostname[0] != '\0'
1643 && strcasecmp(d_uri.hostname, r_uri.hostname))
1644 /* check port matches, if present */
1645 || (d_uri.port_str && d_uri.port != r_uri.port)
1646 /* check that server-port is default port if no port present */
1647 || (d_uri.hostname && d_uri.hostname[0] != '\0'
1648 && !d_uri.port_str && r_uri.port != ap_default_port(r))
1649 /* check that path matches */
1650 || (d_uri.path != r_uri.path
1651 /* either exact match */
1652 && (!d_uri.path || !r_uri.path
1653 || strcmp(d_uri.path, r_uri.path))
1654 /* or '*' matches empty path in scheme://host */
1655 && !(d_uri.path && !r_uri.path && resp->psd_request_uri->hostname
1656 && d_uri.path[0] == '*' && d_uri.path[1] == '\0'))
1657 /* check that query matches */
1658 || (d_uri.query != r_uri.query
1659 && (!d_uri.query || !r_uri.query
1660 || strcmp(d_uri.query, r_uri.query)))
1662 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01786)
1663 "uri mismatch - <%s> does not match "
1664 "request-uri <%s>", resp->uri, resp->raw_request_uri);
1665 return HTTP_BAD_REQUEST;
1669 if (resp->opaque && resp->opaque_num == 0) {
1670 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01787)
1671 "received invalid opaque - got `%s'",
1673 note_digest_auth_failure(r, conf, resp, 0);
1674 return HTTP_UNAUTHORIZED;
1678 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02533)
1679 "realm mismatch - got `%s' but no realm specified",
1681 note_digest_auth_failure(r, conf, resp, 0);
1682 return HTTP_UNAUTHORIZED;
1685 if (!resp->realm || strcmp(resp->realm, conf->realm)) {
1686 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01788)
1687 "realm mismatch - got `%s' but expected `%s'",
1688 resp->realm, conf->realm);
1689 note_digest_auth_failure(r, conf, resp, 0);
1690 return HTTP_UNAUTHORIZED;
1693 if (resp->algorithm != NULL
1694 && ap_casecmpstr(resp->algorithm, "MD5")) {
1695 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01789)
1696 "unknown algorithm `%s' received: %s",
1697 resp->algorithm, r->uri);
1698 note_digest_auth_failure(r, conf, resp, 0);
1699 return HTTP_UNAUTHORIZED;
1702 return_code = get_hash(r, r->user, conf);
1704 if (return_code == AUTH_USER_NOT_FOUND) {
1705 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01790)
1706 "user `%s' in realm `%s' not found: %s",
1707 r->user, conf->realm, r->uri);
1708 note_digest_auth_failure(r, conf, resp, 0);
1709 return HTTP_UNAUTHORIZED;
1711 else if (return_code == AUTH_USER_FOUND) {
1712 /* we have a password, so continue */
1714 else if (return_code == AUTH_DENIED) {
1715 /* authentication denied in the provider before attempting a match */
1716 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01791)
1717 "user `%s' in realm `%s' denied by provider: %s",
1718 r->user, conf->realm, r->uri);
1719 note_digest_auth_failure(r, conf, resp, 0);
1720 return HTTP_UNAUTHORIZED;
1722 else if (return_code == AUTH_HANDLED) {
1726 /* AUTH_GENERAL_ERROR (or worse)
1727 * We'll assume that the module has already said what its error
1730 return HTTP_INTERNAL_SERVER_ERROR;
1733 if (resp->message_qop == NULL) {
1734 /* old (rfc-2069) style digest */
1735 if (strcmp(resp->digest, old_digest(r, resp, conf->ha1))) {
1736 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01792)
1737 "user %s: password mismatch: %s", r->user,
1739 note_digest_auth_failure(r, conf, resp, 0);
1740 return HTTP_UNAUTHORIZED;
1744 const char *exp_digest;
1746 const char **tmp = (const char **)(conf->qop_list->elts);
1747 for (idx = 0; idx < conf->qop_list->nelts; idx++) {
1748 if (!ap_casecmpstr(*tmp, resp->message_qop)) {
1756 && !(apr_is_empty_array(conf->qop_list)
1757 && !ap_casecmpstr(resp->message_qop, "auth"))) {
1758 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01793)
1759 "invalid qop `%s' received: %s",
1760 resp->message_qop, r->uri);
1761 note_digest_auth_failure(r, conf, resp, 0);
1762 return HTTP_UNAUTHORIZED;
1765 exp_digest = new_digest(r, resp, conf);
1767 /* we failed to allocate a client struct */
1768 return HTTP_INTERNAL_SERVER_ERROR;
1770 if (strcmp(resp->digest, exp_digest)) {
1771 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01794)
1772 "user %s: password mismatch: %s", r->user,
1774 note_digest_auth_failure(r, conf, resp, 0);
1775 return HTTP_UNAUTHORIZED;
1779 if (check_nc(r, resp, conf) != OK) {
1780 note_digest_auth_failure(r, conf, resp, 0);
1781 return HTTP_UNAUTHORIZED;
1784 /* Note: this check is done last so that a "stale=true" can be
1785 generated if the nonce is old */
1786 if ((res = check_nonce(r, resp, conf))) {
1794 * Authorization-Info header code
1797 static int add_auth_info(request_rec *r)
1799 const digest_config_rec *conf =
1800 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1801 &auth_digest_module);
1802 digest_header_rec *resp =
1803 (digest_header_rec *) ap_get_module_config(r->request_config,
1804 &auth_digest_module);
1805 const char *ai = NULL, *nextnonce = "";
1807 if (resp == NULL || !resp->needed_auth || conf == NULL) {
1811 /* 2069-style entity-digest is not supported (it's too hard, and
1812 * there are no clients which support 2069 but not 2617). */
1816 if (conf->nonce_lifetime > 0) {
1817 /* send nextnonce if current nonce will expire in less than 30 secs */
1818 if ((r->request_time - resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
1819 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"",
1820 gen_nonce(r->pool, r->request_time,
1821 resp->opaque, r->server, conf),
1824 resp->client->nonce_count = 0;
1827 else if (conf->nonce_lifetime == 0 && resp->client) {
1828 const char *nonce = gen_nonce(r->pool, 0, resp->opaque, r->server,
1830 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
1831 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1833 /* else nonce never expires, hence no nextnonce */
1836 /* do rfc-2069 digest
1838 if (!apr_is_empty_array(conf->qop_list) &&
1839 !ap_casecmpstr(*(const char **)(conf->qop_list->elts), "none")
1840 && resp->message_qop == NULL) {
1841 /* use only RFC-2069 format */
1845 const char *resp_dig, *ha1, *a2, *ha2;
1847 /* calculate rspauth attribute
1851 a2 = apr_pstrcat(r->pool, ":", resp->uri, NULL);
1852 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1854 resp_dig = ap_md5(r->pool,
1855 (unsigned char *)apr_pstrcat(r->pool, ha1, ":",
1857 resp->nonce_count, ":",
1860 resp->message_qop : "",
1863 /* assemble Authentication-Info header
1865 ai = apr_pstrcat(r->pool,
1866 "rspauth=\"", resp_dig, "\"",
1868 resp->cnonce ? ", cnonce=\"" : "",
1870 ? ap_escape_quotes(r->pool, resp->cnonce)
1872 resp->cnonce ? "\"" : "",
1873 resp->nonce_count ? ", nc=" : "",
1874 resp->nonce_count ? resp->nonce_count : "",
1875 resp->message_qop ? ", qop=" : "",
1876 resp->message_qop ? resp->message_qop : "",
1881 apr_table_mergen(r->headers_out,
1882 (PROXYREQ_PROXY == r->proxyreq)
1883 ? "Proxy-Authentication-Info"
1884 : "Authentication-Info",
1891 static void register_hooks(apr_pool_t *p)
1893 static const char * const cfgPost[]={ "http_core.c", NULL };
1894 static const char * const parsePre[]={ "mod_proxy.c", NULL };
1896 ap_hook_pre_config(pre_init, NULL, NULL, APR_HOOK_MIDDLE);
1897 ap_hook_post_config(initialize_module, NULL, cfgPost, APR_HOOK_MIDDLE);
1898 ap_hook_child_init(initialize_child, NULL, NULL, APR_HOOK_MIDDLE);
1899 ap_hook_post_read_request(parse_hdr_and_update_nc, parsePre, NULL, APR_HOOK_MIDDLE);
1900 ap_hook_check_authn(authenticate_digest_user, NULL, NULL, APR_HOOK_MIDDLE,
1901 AP_AUTH_INTERNAL_PER_CONF);
1903 ap_hook_fixups(add_auth_info, NULL, NULL, APR_HOOK_MIDDLE);
1904 ap_hook_note_auth_failure(hook_note_digest_auth_failure, NULL, NULL,
1909 AP_DECLARE_MODULE(auth_digest) =
1911 STANDARD20_MODULE_STUFF,
1912 create_digest_dir_config, /* dir config creater */
1913 NULL, /* dir merger --- default is to override */
1914 NULL, /* server config */
1915 NULL, /* merge server config */
1916 digest_cmds, /* command table */
1917 register_hooks /* register hooks */