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 /* Now create that segment */
253 sts = apr_shm_create(&client_shm, shmem_size,
254 client_shm_filename, ctx);
255 if (APR_SUCCESS != sts) {
256 ap_log_error(APLOG_MARK, APLOG_ERR, sts, s, APLOGNO(01762)
257 "Failed to create shared memory segment on file %s",
258 client_shm_filename);
259 log_error_and_cleanup("failed to initialize shm", sts, s);
260 return HTTP_INTERNAL_SERVER_ERROR;
263 sts = apr_rmm_init(&client_rmm,
264 NULL, /* no lock, we'll do the locking ourselves */
265 apr_shm_baseaddr_get(client_shm),
267 if (sts != APR_SUCCESS) {
268 log_error_and_cleanup("failed to initialize rmm", sts, s);
272 client_list = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(*client_list) +
273 sizeof(client_entry*)*num_buckets));
275 log_error_and_cleanup("failed to allocate shared memory", -1, s);
278 client_list->table = (client_entry**) (client_list + 1);
279 for (idx = 0; idx < num_buckets; idx++) {
280 client_list->table[idx] = NULL;
282 client_list->tbl_len = num_buckets;
283 client_list->num_entries = 0;
285 sts = ap_global_mutex_create(&client_lock, NULL, client_mutex_type, NULL,
287 if (sts != APR_SUCCESS) {
288 log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
295 opaque_cntr = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(*opaque_cntr)));
296 if (opaque_cntr == NULL) {
297 log_error_and_cleanup("failed to allocate shared memory", -1, s);
302 sts = ap_global_mutex_create(&opaque_lock, NULL, opaque_mutex_type, NULL,
304 if (sts != APR_SUCCESS) {
305 log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
310 /* setup one-time-nonce counter */
312 otn_counter = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(*otn_counter)));
313 if (otn_counter == NULL) {
314 log_error_and_cleanup("failed to allocate shared memory", -1, s);
325 #endif /* APR_HAS_SHARED_MEMORY */
327 static int pre_init(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
332 rv = ap_mutex_register(pconf, client_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
333 if (rv != APR_SUCCESS)
335 rv = ap_mutex_register(pconf, opaque_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
336 if (rv != APR_SUCCESS)
339 retained = ap_retained_data_get(RETAINED_DATA_ID);
340 if (retained == NULL) {
341 retained = ap_retained_data_create(RETAINED_DATA_ID, SECRET_LEN);
342 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(01757)
343 "generating secret for digest authentication");
345 rv = apr_generate_random_bytes(retained, SECRET_LEN);
347 #error APR random number support is missing
349 if (rv != APR_SUCCESS) {
350 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(01758)
351 "error generating secret");
359 static int initialize_module(apr_pool_t *p, apr_pool_t *plog,
360 apr_pool_t *ptemp, server_rec *s)
362 /* initialize_module() will be called twice, and if it's a DSO
363 * then all static data from the first call will be lost. Only
364 * set up our static data on the second call. */
365 if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG)
368 #if APR_HAS_SHARED_MEMORY
369 /* Note: this stuff is currently fixed for the lifetime of the server,
370 * i.e. even across restarts. This means that A) any shmem-size
371 * configuration changes are ignored, and B) certain optimizations,
372 * such as only allocating the smallest necessary entry for each
373 * client, can't be done. However, the alternative is a nightmare:
374 * we can't call apr_shm_destroy on a graceful restart because there
375 * will be children using the tables, and we also don't know when the
376 * last child dies. Therefore we can never clean up the old stuff,
377 * creating a creeping memory leak.
379 if (initialize_tables(s, p) != OK) {
382 /* Call cleanup_tables on exit or restart */
383 apr_pool_cleanup_register(p, NULL, cleanup_tables, apr_pool_cleanup_null);
384 #endif /* APR_HAS_SHARED_MEMORY */
388 static void initialize_child(apr_pool_t *p, server_rec *s)
396 /* Get access to rmm in child */
397 sts = apr_rmm_attach(&client_rmm,
399 apr_shm_baseaddr_get(client_shm),
401 if (sts != APR_SUCCESS) {
402 log_error_and_cleanup("failed to attach to rmm", sts, s);
406 sts = apr_global_mutex_child_init(&client_lock,
407 apr_global_mutex_lockfile(client_lock),
409 if (sts != APR_SUCCESS) {
410 log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
413 sts = apr_global_mutex_child_init(&opaque_lock,
414 apr_global_mutex_lockfile(opaque_lock),
416 if (sts != APR_SUCCESS) {
417 log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
426 static void *create_digest_dir_config(apr_pool_t *p, char *dir)
428 digest_config_rec *conf;
434 conf = (digest_config_rec *) apr_pcalloc(p, sizeof(digest_config_rec));
436 conf->qop_list = apr_array_make(p, 2, sizeof(char *));
437 conf->nonce_lifetime = DFLT_NONCE_LIFE;
438 conf->dir_name = apr_pstrdup(p, dir);
439 conf->algorithm = DFLT_ALGORITHM;
445 static const char *set_realm(cmd_parms *cmd, void *config, const char *realm)
447 digest_config_rec *conf = (digest_config_rec *) config;
451 /* check that we got random numbers */
452 for (i = 0; i < SECRET_LEN; i++) {
456 ap_assert(i < SECRET_LEN);
459 /* The core already handles the realm, but it's just too convenient to
460 * grab it ourselves too and cache some setups. However, we need to
461 * let the core get at it too, which is why we decline at the end -
462 * this relies on the fact that http_core is last in the list.
466 /* we precompute the part of the nonce hash that is constant (well,
467 * the host:port would be too, but that varies for .htaccess files
468 * and directives outside a virtual host section)
470 apr_sha1_init(&conf->nonce_ctx);
471 apr_sha1_update_binary(&conf->nonce_ctx, secret, SECRET_LEN);
472 apr_sha1_update_binary(&conf->nonce_ctx, (const unsigned char *) realm,
478 static const char *add_authn_provider(cmd_parms *cmd, void *config,
481 digest_config_rec *conf = (digest_config_rec*)config;
482 authn_provider_list *newp;
484 newp = apr_pcalloc(cmd->pool, sizeof(authn_provider_list));
485 newp->provider_name = arg;
487 /* lookup and cache the actual provider now */
488 newp->provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP,
490 AUTHN_PROVIDER_VERSION);
492 if (newp->provider == NULL) {
493 /* by the time they use it, the provider should be loaded and
494 registered with us. */
495 return apr_psprintf(cmd->pool,
496 "Unknown Authn provider: %s",
497 newp->provider_name);
500 if (!newp->provider->get_realm_hash) {
501 /* if it doesn't provide the appropriate function, reject it */
502 return apr_psprintf(cmd->pool,
503 "The '%s' Authn provider doesn't support "
504 "Digest Authentication", newp->provider_name);
507 /* Add it to the list now. */
508 if (!conf->providers) {
509 conf->providers = newp;
512 authn_provider_list *last = conf->providers;
523 static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
525 digest_config_rec *conf = (digest_config_rec *) config;
527 if (!strcasecmp(op, "none")) {
528 apr_array_clear(conf->qop_list);
529 *(const char **)apr_array_push(conf->qop_list) = "none";
533 if (!strcasecmp(op, "auth-int")) {
534 return "AuthDigestQop auth-int is not implemented";
536 else if (strcasecmp(op, "auth")) {
537 return apr_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
540 *(const char **)apr_array_push(conf->qop_list) = op;
545 static const char *set_nonce_lifetime(cmd_parms *cmd, void *config,
551 lifetime = strtol(t, &endptr, 10);
552 if (endptr < (t+strlen(t)) && !apr_isspace(*endptr)) {
553 return apr_pstrcat(cmd->pool,
554 "Invalid time in AuthDigestNonceLifetime: ",
558 ((digest_config_rec *) config)->nonce_lifetime = apr_time_from_sec(lifetime);
562 static const char *set_nonce_format(cmd_parms *cmd, void *config,
565 return "AuthDigestNonceFormat is not implemented";
568 static const char *set_nc_check(cmd_parms *cmd, void *config, int flag)
570 #if !APR_HAS_SHARED_MEMORY
572 return "AuthDigestNcCheck: ERROR: nonce-count checking "
573 "is not supported on platforms without shared-memory "
578 ((digest_config_rec *) config)->check_nc = flag;
582 static const char *set_algorithm(cmd_parms *cmd, void *config, const char *alg)
584 if (!strcasecmp(alg, "MD5-sess")) {
585 return "AuthDigestAlgorithm: ERROR: algorithm `MD5-sess' "
586 "is not implemented";
588 else if (strcasecmp(alg, "MD5")) {
589 return apr_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
592 ((digest_config_rec *) config)->algorithm = alg;
596 static const char *set_uri_list(cmd_parms *cmd, void *config, const char *uri)
598 digest_config_rec *c = (digest_config_rec *) config;
600 c->uri_list[strlen(c->uri_list)-1] = '\0';
601 c->uri_list = apr_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
604 c->uri_list = apr_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
609 static const char *set_shmem_size(cmd_parms *cmd, void *config,
610 const char *size_str)
615 size = strtol(size_str, &endptr, 10);
616 while (apr_isspace(*endptr)) endptr++;
617 if (*endptr == '\0' || *endptr == 'b' || *endptr == 'B') {
620 else if (*endptr == 'k' || *endptr == 'K') {
623 else if (*endptr == 'm' || *endptr == 'M') {
627 return apr_pstrcat(cmd->pool, "Invalid size in AuthDigestShmemSize: ",
631 min = sizeof(*client_list) + sizeof(client_entry*) + sizeof(client_entry);
633 return apr_psprintf(cmd->pool, "size in AuthDigestShmemSize too small: "
634 "%ld < %ld", size, min);
638 num_buckets = (size - sizeof(*client_list)) /
639 (sizeof(client_entry*) + HASH_DEPTH * sizeof(client_entry));
640 if (num_buckets == 0) {
643 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, APLOGNO(01763)
644 "Set shmem-size: %" APR_SIZE_T_FMT ", num-buckets: %ld",
645 shmem_size, num_buckets);
650 static const command_rec digest_cmds[] =
652 AP_INIT_TAKE1("AuthName", set_realm, NULL, OR_AUTHCFG,
653 "The authentication realm (e.g. \"Members Only\")"),
654 AP_INIT_ITERATE("AuthDigestProvider", add_authn_provider, NULL, OR_AUTHCFG,
655 "specify the auth providers for a directory or location"),
656 AP_INIT_ITERATE("AuthDigestQop", set_qop, NULL, OR_AUTHCFG,
657 "A list of quality-of-protection options"),
658 AP_INIT_TAKE1("AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG,
659 "Maximum lifetime of the server nonce (seconds)"),
660 AP_INIT_TAKE1("AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG,
661 "The format to use when generating the server nonce"),
662 AP_INIT_FLAG("AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG,
663 "Whether or not to check the nonce-count sent by the client"),
664 AP_INIT_TAKE1("AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG,
665 "The algorithm used for the hash calculation"),
666 AP_INIT_ITERATE("AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG,
667 "A list of URI's which belong to the same protection space as the current URI"),
668 AP_INIT_TAKE1("AuthDigestShmemSize", set_shmem_size, NULL, RSRC_CONF,
669 "The amount of shared memory to allocate for keeping track of clients"),
677 * Each client is assigned a number, which is transferred in the opaque
678 * field of the WWW-Authenticate and Authorization headers. The number
679 * is just a simple counter which is incremented for each new client.
680 * Clients can't forge this number because it is hashed up into the
681 * server nonce, and that is checked.
683 * The clients are kept in a simple hash table, which consists of an
684 * array of client_entry's, each with a linked list of entries hanging
685 * off it. The client's number modulo the size of the array gives the
688 * The clients are garbage collected whenever a new client is allocated
689 * but there is not enough space left in the shared memory segment. A
690 * simple semi-LRU is used for this: whenever a client entry is accessed
691 * it is moved to the beginning of the linked list in its bucket (this
692 * also makes for faster lookups for current clients). The garbage
693 * collecter then just removes the oldest entry (i.e. the one at the
694 * end of the list) in each bucket.
696 * The main advantages of the above scheme are that it's easy to implement
697 * and it keeps the hash table evenly balanced (i.e. same number of entries
698 * in each bucket). The major disadvantage is that you may be throwing
699 * entries out which are in active use. This is not tragic, as these
700 * clients will just be sent a new client id (opaque field) and nonce
701 * with a stale=true (i.e. it will just look like the nonce expired,
702 * thereby forcing an extra round trip). If the shared memory segment
703 * has enough headroom over the current client set size then this should
704 * not occur too often.
706 * To help tune the size of the shared memory segment (and see if the
707 * above algorithm is really sufficient) a set of counters is kept
708 * indicating the number of clients held, the number of garbage collected
709 * clients, and the number of erroneously purged clients. These are printed
710 * out at each garbage collection run. Note that access to the counters is
711 * not synchronized because they are just indicaters, and whether they are
712 * off by a few doesn't matter; and for the same reason no attempt is made
713 * to guarantee the num_renewed is correct in the face of clients spoofing
718 * Get the client given its client number (the key). Returns the entry,
719 * or NULL if it's not found.
721 * Access to the list itself is synchronized via locks. However, access
722 * to the entry returned by get_client() is NOT synchronized. This means
723 * that there are potentially problems if a client uses multiple,
724 * simultaneous connections to access url's within the same protection
725 * space. However, these problems are not new: when using multiple
726 * connections you have no guarantee of the order the requests are
727 * processed anyway, so you have problems with the nonce-count and
728 * one-time nonces anyway.
730 static client_entry *get_client(unsigned long key, const request_rec *r)
733 client_entry *entry, *prev = NULL;
736 if (!key || !client_shm) return NULL;
738 bucket = key % client_list->tbl_len;
739 entry = client_list->table[bucket];
741 apr_global_mutex_lock(client_lock);
743 while (entry && key != entry->key) {
748 if (entry && prev) { /* move entry to front of list */
749 prev->next = entry->next;
750 entry->next = client_list->table[bucket];
751 client_list->table[bucket] = entry;
754 apr_global_mutex_unlock(client_lock);
757 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01764)
758 "get_client(): client %lu found", key);
761 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01765)
762 "get_client(): client %lu not found", key);
769 /* A simple garbage-collecter to remove unused clients. It removes the
770 * last entry in each bucket and updates the counters. Returns the
771 * number of removed entries.
775 client_entry *entry, *prev;
776 unsigned long num_removed = 0, idx;
778 /* garbage collect all last entries */
780 for (idx = 0; idx < client_list->tbl_len; idx++) {
781 entry = client_list->table[idx];
783 while (entry->next) { /* find last entry */
788 prev->next = NULL; /* cut list */
791 client_list->table[idx] = NULL;
793 if (entry) { /* remove entry */
794 apr_rmm_free(client_rmm, apr_rmm_offset_get(client_rmm, entry));
799 /* update counters and log */
801 client_list->num_entries -= num_removed;
802 client_list->num_removed += num_removed;
809 * Add a new client to the list. Returns the entry if successful, NULL
810 * otherwise. This triggers the garbage collection if memory is low.
812 static client_entry *add_client(unsigned long key, client_entry *info,
819 if (!key || !client_shm) {
823 bucket = key % client_list->tbl_len;
825 apr_global_mutex_lock(client_lock);
827 /* try to allocate a new entry */
829 entry = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(client_entry)));
831 long num_removed = gc();
832 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01766)
833 "gc'd %ld client entries. Total new clients: "
834 "%ld; Total removed clients: %ld; Total renewed clients: "
836 client_list->num_created - client_list->num_renewed,
837 client_list->num_removed, client_list->num_renewed);
838 entry = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(client_entry)));
840 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01767)
841 "unable to allocate new auth_digest client");
842 apr_global_mutex_unlock(client_lock);
843 return NULL; /* give up */
847 /* now add the entry */
849 memcpy(entry, info, sizeof(client_entry));
851 entry->next = client_list->table[bucket];
852 client_list->table[bucket] = entry;
853 client_list->num_created++;
854 client_list->num_entries++;
856 apr_global_mutex_unlock(client_lock);
858 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01768)
859 "allocated new client %lu", key);
866 * Authorization header parser code
869 /* Parse the Authorization header, if it exists */
870 static int get_digest_rec(request_rec *r, digest_header_rec *resp)
872 const char *auth_line;
877 auth_line = apr_table_get(r->headers_in,
878 (PROXYREQ_PROXY == r->proxyreq)
879 ? "Proxy-Authorization"
882 resp->auth_hdr_sts = NO_HEADER;
886 resp->scheme = ap_getword_white(r->pool, &auth_line);
887 if (strcasecmp(resp->scheme, "Digest")) {
888 resp->auth_hdr_sts = NOT_DIGEST;
892 l = strlen(auth_line);
894 key = apr_palloc(r->pool, l+1);
895 value = apr_palloc(r->pool, l+1);
897 while (auth_line[0] != '\0') {
901 while (apr_isspace(auth_line[0])) {
905 while (auth_line[0] != '=' && auth_line[0] != ','
906 && auth_line[0] != '\0' && !apr_isspace(auth_line[0])) {
907 key[vk++] = *auth_line++;
910 while (apr_isspace(auth_line[0])) {
916 if (auth_line[0] == '=') {
918 while (apr_isspace(auth_line[0])) {
923 if (auth_line[0] == '\"') { /* quoted string */
925 while (auth_line[0] != '\"' && auth_line[0] != '\0') {
926 if (auth_line[0] == '\\' && auth_line[1] != '\0') {
927 auth_line++; /* escaped char */
929 value[vv++] = *auth_line++;
931 if (auth_line[0] != '\0') {
936 while (auth_line[0] != ',' && auth_line[0] != '\0'
937 && !apr_isspace(auth_line[0])) {
938 value[vv++] = *auth_line++;
944 while (auth_line[0] != ',' && auth_line[0] != '\0') {
947 if (auth_line[0] != '\0') {
951 if (!strcasecmp(key, "username"))
952 resp->username = apr_pstrdup(r->pool, value);
953 else if (!strcasecmp(key, "realm"))
954 resp->realm = apr_pstrdup(r->pool, value);
955 else if (!strcasecmp(key, "nonce"))
956 resp->nonce = apr_pstrdup(r->pool, value);
957 else if (!strcasecmp(key, "uri"))
958 resp->uri = apr_pstrdup(r->pool, value);
959 else if (!strcasecmp(key, "response"))
960 resp->digest = apr_pstrdup(r->pool, value);
961 else if (!strcasecmp(key, "algorithm"))
962 resp->algorithm = apr_pstrdup(r->pool, value);
963 else if (!strcasecmp(key, "cnonce"))
964 resp->cnonce = apr_pstrdup(r->pool, value);
965 else if (!strcasecmp(key, "opaque"))
966 resp->opaque = apr_pstrdup(r->pool, value);
967 else if (!strcasecmp(key, "qop"))
968 resp->message_qop = apr_pstrdup(r->pool, value);
969 else if (!strcasecmp(key, "nc"))
970 resp->nonce_count = apr_pstrdup(r->pool, value);
973 if (!resp->username || !resp->realm || !resp->nonce || !resp->uri
975 || (resp->message_qop && (!resp->cnonce || !resp->nonce_count))) {
976 resp->auth_hdr_sts = INVALID;
981 resp->opaque_num = (unsigned long) strtol(resp->opaque, NULL, 16);
984 resp->auth_hdr_sts = VALID;
989 /* Because the browser may preemptively send auth info, incrementing the
990 * nonce-count when it does, and because the client does not get notified
991 * if the URI didn't need authentication after all, we need to be sure to
992 * update the nonce-count each time we receive an Authorization header no
993 * matter what the final outcome of the request. Furthermore this is a
994 * convenient place to get the request-uri (before any subrequests etc
995 * are initiated) and to initialize the request_config.
997 * Note that this must be called after mod_proxy had its go so that
998 * r->proxyreq is set correctly.
1000 static int parse_hdr_and_update_nc(request_rec *r)
1002 digest_header_rec *resp;
1005 if (!ap_is_initial_req(r)) {
1009 resp = apr_pcalloc(r->pool, sizeof(digest_header_rec));
1010 resp->raw_request_uri = r->unparsed_uri;
1011 resp->psd_request_uri = &r->parsed_uri;
1012 resp->needed_auth = 0;
1013 resp->method = r->method;
1014 ap_set_module_config(r->request_config, &auth_digest_module, resp);
1016 res = get_digest_rec(r, resp);
1017 resp->client = get_client(resp->opaque_num, r);
1018 if (res == OK && resp->client) {
1019 resp->client->nonce_count++;
1027 * Nonce generation code
1030 /* The hash part of the nonce is a SHA-1 hash of the time, realm, server host
1031 * and port, opaque, and our secret.
1033 static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
1034 const server_rec *server,
1035 const digest_config_rec *conf)
1037 unsigned char sha1[APR_SHA1_DIGESTSIZE];
1040 memcpy(&ctx, &conf->nonce_ctx, sizeof(ctx));
1042 apr_sha1_update_binary(&ctx, (const unsigned char *) server->server_hostname,
1043 strlen(server->server_hostname));
1044 apr_sha1_update_binary(&ctx, (const unsigned char *) &server->port,
1045 sizeof(server->port));
1047 apr_sha1_update_binary(&ctx, (const unsigned char *) timestr, strlen(timestr));
1049 apr_sha1_update_binary(&ctx, (const unsigned char *) opaque,
1052 apr_sha1_final(sha1, &ctx);
1054 ap_bin2hex(sha1, APR_SHA1_DIGESTSIZE, hash);
1058 /* The nonce has the format b64(time)+hash .
1060 static const char *gen_nonce(apr_pool_t *p, apr_time_t now, const char *opaque,
1061 const server_rec *server,
1062 const digest_config_rec *conf)
1064 char *nonce = apr_palloc(p, NONCE_LEN+1);
1067 if (conf->nonce_lifetime != 0) {
1070 else if (otn_counter) {
1071 /* this counter is not synch'd, because it doesn't really matter
1072 * if it counts exactly.
1074 t.time = (*otn_counter)++;
1077 /* XXX: WHAT IS THIS CONSTANT? */
1080 apr_base64_encode_binary(nonce, t.arr, sizeof(t.arr));
1081 gen_nonce_hash(nonce+NONCE_TIME_LEN, nonce, opaque, server, conf);
1088 * Opaque and hash-table management
1092 * Generate a new client entry, add it to the list, and return the
1093 * entry. Returns NULL if failed.
1095 static client_entry *gen_client(const request_rec *r)
1098 client_entry new_entry = { 0, NULL, 0, "" }, *entry;
1104 apr_global_mutex_lock(opaque_lock);
1105 op = (*opaque_cntr)++;
1106 apr_global_mutex_unlock(opaque_lock);
1108 if (!(entry = add_client(op, &new_entry, r->server))) {
1109 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01769)
1110 "failed to allocate client entry - ignoring client");
1119 * Authorization challenge generation code (for WWW-Authenticate)
1122 static const char *ltox(apr_pool_t *p, unsigned long num)
1125 return apr_psprintf(p, "%lx", num);
1132 static void note_digest_auth_failure(request_rec *r,
1133 const digest_config_rec *conf,
1134 digest_header_rec *resp, int stale)
1136 const char *qop, *opaque, *opaque_param, *domain, *nonce;
1139 if (apr_is_empty_array(conf->qop_list)) {
1140 qop = ", qop=\"auth\"";
1142 else if (!strcasecmp(*(const char **)(conf->qop_list->elts), "none")) {
1146 qop = apr_pstrcat(r->pool, ", qop=\"",
1147 apr_array_pstrcat(r->pool, conf->qop_list, ','),
1154 if (resp->opaque == NULL) {
1156 if ((conf->check_nc || conf->nonce_lifetime == 0)
1157 && (resp->client = gen_client(r)) != NULL) {
1158 opaque = ltox(r->pool, resp->client->key);
1161 opaque = ""; /* opaque not needed */
1164 else if (resp->client == NULL) {
1165 /* client info was gc'd */
1166 resp->client = gen_client(r);
1167 if (resp->client != NULL) {
1168 opaque = ltox(r->pool, resp->client->key);
1170 client_list->num_renewed++;
1173 opaque = ""; /* ??? */
1177 opaque = resp->opaque;
1178 /* we're generating a new nonce, so reset the nonce-count */
1179 resp->client->nonce_count = 0;
1183 opaque_param = apr_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
1186 opaque_param = NULL;
1191 nonce = gen_nonce(r->pool, r->request_time, opaque, r->server, conf);
1192 if (resp->client && conf->nonce_lifetime == 0) {
1193 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1196 /* setup domain attribute. We want to send this attribute wherever
1197 * possible so that the client won't send the Authorization header
1198 * unnecessarily (it's usually > 200 bytes!).
1202 /* don't send domain
1203 * - for proxy requests
1204 * - if it's not specified
1206 if (r->proxyreq || !conf->uri_list) {
1210 domain = conf->uri_list;
1213 apr_table_mergen(r->err_headers_out,
1214 (PROXYREQ_PROXY == r->proxyreq)
1215 ? "Proxy-Authenticate" : "WWW-Authenticate",
1216 apr_psprintf(r->pool, "Digest realm=\"%s\", "
1217 "nonce=\"%s\", algorithm=%s%s%s%s%s",
1218 ap_auth_name(r), nonce, conf->algorithm,
1219 opaque_param ? opaque_param : "",
1220 domain ? domain : "",
1221 stale ? ", stale=true" : "", qop));
1225 static int hook_note_digest_auth_failure(request_rec *r, const char *auth_type)
1227 request_rec *mainreq;
1228 digest_header_rec *resp;
1229 digest_config_rec *conf;
1231 if (strcasecmp(auth_type, "Digest"))
1234 /* get the client response and mark */
1237 while (mainreq->main != NULL) {
1238 mainreq = mainreq->main;
1240 while (mainreq->prev != NULL) {
1241 mainreq = mainreq->prev;
1243 resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1244 &auth_digest_module);
1245 resp->needed_auth = 1;
1250 conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1251 &auth_digest_module);
1253 note_digest_auth_failure(r, conf, resp, 0);
1260 * Authorization header verification code
1263 static authn_status get_hash(request_rec *r, const char *user,
1264 digest_config_rec *conf)
1266 authn_status auth_result;
1268 authn_provider_list *current_provider;
1270 current_provider = conf->providers;
1272 const authn_provider *provider;
1274 /* For now, if a provider isn't set, we'll be nice and use the file
1277 if (!current_provider) {
1278 provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP,
1279 AUTHN_DEFAULT_PROVIDER,
1280 AUTHN_PROVIDER_VERSION);
1282 if (!provider || !provider->get_realm_hash) {
1283 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01770)
1284 "No Authn provider configured");
1285 auth_result = AUTH_GENERAL_ERROR;
1288 apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, AUTHN_DEFAULT_PROVIDER);
1291 provider = current_provider->provider;
1292 apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, current_provider->provider_name);
1296 /* We expect the password to be md5 hash of user:realm:password */
1297 auth_result = provider->get_realm_hash(r, user, conf->realm,
1300 apr_table_unset(r->notes, AUTHN_PROVIDER_NAME_NOTE);
1302 /* Something occured. Stop checking. */
1303 if (auth_result != AUTH_USER_NOT_FOUND) {
1307 /* If we're not really configured for providers, stop now. */
1308 if (!conf->providers) {
1312 current_provider = current_provider->next;
1313 } while (current_provider);
1315 if (auth_result == AUTH_USER_FOUND) {
1316 conf->ha1 = password;
1322 static int check_nc(const request_rec *r, const digest_header_rec *resp,
1323 const digest_config_rec *conf)
1326 const char *snc = resp->nonce_count;
1329 if (conf->check_nc && !client_shm) {
1330 /* Shouldn't happen, but just in case... */
1331 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01771)
1332 "cannot check nonce count without shared memory");
1336 if (!conf->check_nc || !client_shm) {
1340 if (!apr_is_empty_array(conf->qop_list) &&
1341 !strcasecmp(*(const char **)(conf->qop_list->elts), "none")) {
1342 /* qop is none, client must not send a nonce count */
1344 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01772)
1345 "invalid nc %s received - no nonce count allowed when qop=none",
1349 /* qop is none, cannot check nonce count */
1353 nc = strtol(snc, &endptr, 16);
1354 if (endptr < (snc+strlen(snc)) && !apr_isspace(*endptr)) {
1355 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01773)
1356 "invalid nc %s received - not a number", snc);
1360 if (!resp->client) {
1364 if (nc != resp->client->nonce_count) {
1365 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01774)
1366 "Warning, possible replay attack: nonce-count "
1367 "check failed: %lu != %lu", nc,
1368 resp->client->nonce_count);
1375 static int check_nonce(request_rec *r, digest_header_rec *resp,
1376 const digest_config_rec *conf)
1379 time_rec nonce_time;
1380 char tmp, hash[NONCE_HASH_LEN+1];
1382 if (strlen(resp->nonce) != NONCE_LEN) {
1383 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01775)
1384 "invalid nonce %s received - length is not %d",
1385 resp->nonce, NONCE_LEN);
1386 note_digest_auth_failure(r, conf, resp, 1);
1387 return HTTP_UNAUTHORIZED;
1390 tmp = resp->nonce[NONCE_TIME_LEN];
1391 resp->nonce[NONCE_TIME_LEN] = '\0';
1392 apr_base64_decode_binary(nonce_time.arr, resp->nonce);
1393 gen_nonce_hash(hash, resp->nonce, resp->opaque, r->server, conf);
1394 resp->nonce[NONCE_TIME_LEN] = tmp;
1395 resp->nonce_time = nonce_time.time;
1397 if (strcmp(hash, resp->nonce+NONCE_TIME_LEN)) {
1398 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01776)
1399 "invalid nonce %s received - hash is not %s",
1401 note_digest_auth_failure(r, conf, resp, 1);
1402 return HTTP_UNAUTHORIZED;
1405 dt = r->request_time - nonce_time.time;
1406 if (conf->nonce_lifetime > 0 && dt < 0) {
1407 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01777)
1408 "invalid nonce %s received - user attempted "
1409 "time travel", resp->nonce);
1410 note_digest_auth_failure(r, conf, resp, 1);
1411 return HTTP_UNAUTHORIZED;
1414 if (conf->nonce_lifetime > 0) {
1415 if (dt > conf->nonce_lifetime) {
1416 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0,r, APLOGNO(01778)
1417 "user %s: nonce expired (%.2f seconds old "
1418 "- max lifetime %.2f) - sending new nonce",
1419 r->user, (double)apr_time_sec(dt),
1420 (double)apr_time_sec(conf->nonce_lifetime));
1421 note_digest_auth_failure(r, conf, resp, 1);
1422 return HTTP_UNAUTHORIZED;
1425 else if (conf->nonce_lifetime == 0 && resp->client) {
1426 if (memcmp(resp->client->last_nonce, resp->nonce, NONCE_LEN)) {
1427 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01779)
1428 "user %s: one-time-nonce mismatch - sending "
1429 "new nonce", r->user);
1430 note_digest_auth_failure(r, conf, resp, 1);
1431 return HTTP_UNAUTHORIZED;
1434 /* else (lifetime < 0) => never expires */
1439 /* The actual MD5 code... whee */
1442 static const char *old_digest(const request_rec *r,
1443 const digest_header_rec *resp, const char *ha1)
1447 ha2 = ap_md5(r->pool, (unsigned char *)apr_pstrcat(r->pool, resp->method, ":",
1449 return ap_md5(r->pool,
1450 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1455 static const char *new_digest(const request_rec *r,
1456 digest_header_rec *resp,
1457 const digest_config_rec *conf)
1459 const char *ha1, *ha2, *a2;
1463 a2 = apr_pstrcat(r->pool, resp->method, ":", resp->uri, NULL);
1464 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1466 return ap_md5(r->pool,
1467 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1468 ":", resp->nonce_count, ":",
1470 resp->message_qop, ":", ha2,
1475 static void copy_uri_components(apr_uri_t *dst,
1476 apr_uri_t *src, request_rec *r) {
1477 if (src->scheme && src->scheme[0] != '\0') {
1478 dst->scheme = src->scheme;
1481 dst->scheme = (char *) "http";
1484 if (src->hostname && src->hostname[0] != '\0') {
1485 dst->hostname = apr_pstrdup(r->pool, src->hostname);
1486 ap_unescape_url(dst->hostname);
1489 dst->hostname = (char *) ap_get_server_name(r);
1492 if (src->port_str && src->port_str[0] != '\0') {
1493 dst->port = src->port;
1496 dst->port = ap_get_server_port(r);
1499 if (src->path && src->path[0] != '\0') {
1500 dst->path = apr_pstrdup(r->pool, src->path);
1501 ap_unescape_url(dst->path);
1504 dst->path = src->path;
1507 if (src->query && src->query[0] != '\0') {
1508 dst->query = apr_pstrdup(r->pool, src->query);
1509 ap_unescape_url(dst->query);
1512 dst->query = src->query;
1515 dst->hostinfo = src->hostinfo;
1518 /* These functions return 0 if client is OK, and proper error status
1519 * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
1520 * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
1521 * couldn't figure out how to tell if the client is authorized or not.
1523 * If they return DECLINED, and all other modules also decline, that's
1524 * treated by the server core as a configuration error, logged and
1528 /* Determine user ID, and check if the attributes are correct, if it
1529 * really is that user, if the nonce is correct, etc.
1532 static int authenticate_digest_user(request_rec *r)
1534 digest_config_rec *conf;
1535 digest_header_rec *resp;
1536 request_rec *mainreq;
1539 authn_status return_code;
1541 /* do we require Digest auth for this URI? */
1543 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest")) {
1547 if (!ap_auth_name(r)) {
1548 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01780)
1549 "need AuthName: %s", r->uri);
1550 return HTTP_INTERNAL_SERVER_ERROR;
1554 /* get the client response and mark */
1557 while (mainreq->main != NULL) {
1558 mainreq = mainreq->main;
1560 while (mainreq->prev != NULL) {
1561 mainreq = mainreq->prev;
1563 resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1564 &auth_digest_module);
1565 resp->needed_auth = 1;
1570 conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1571 &auth_digest_module);
1574 /* check for existence and syntax of Auth header */
1576 if (resp->auth_hdr_sts != VALID) {
1577 if (resp->auth_hdr_sts == NOT_DIGEST) {
1578 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01781)
1579 "client used wrong authentication scheme `%s': %s",
1580 resp->scheme, r->uri);
1582 else if (resp->auth_hdr_sts == INVALID) {
1583 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01782)
1584 "missing user, realm, nonce, uri, digest, "
1585 "cnonce, or nonce_count in authorization header: %s",
1588 /* else (resp->auth_hdr_sts == NO_HEADER) */
1589 note_digest_auth_failure(r, conf, resp, 0);
1590 return HTTP_UNAUTHORIZED;
1593 r->user = (char *) resp->username;
1594 r->ap_auth_type = (char *) "Digest";
1596 /* check the auth attributes */
1598 if (strcmp(resp->uri, resp->raw_request_uri)) {
1599 /* Hmm, the simple match didn't work (probably a proxy modified the
1600 * request-uri), so lets do a more sophisticated match
1602 apr_uri_t r_uri, d_uri;
1604 copy_uri_components(&r_uri, resp->psd_request_uri, r);
1605 if (apr_uri_parse(r->pool, resp->uri, &d_uri) != APR_SUCCESS) {
1606 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01783)
1607 "invalid uri <%s> in Authorization header",
1609 return HTTP_BAD_REQUEST;
1612 if (d_uri.hostname) {
1613 ap_unescape_url(d_uri.hostname);
1616 ap_unescape_url(d_uri.path);
1620 ap_unescape_url(d_uri.query);
1622 else if (r_uri.query) {
1623 /* MSIE compatibility hack. MSIE has some RFC issues - doesn't
1624 * include the query string in the uri Authorization component
1625 * or when computing the response component. the second part
1626 * works out ok, since we can hash the header and get the same
1627 * result. however, the uri from the request line won't match
1628 * the uri Authorization component since the header lacks the
1629 * query string, leaving us incompatable with a (broken) MSIE.
1631 * the workaround is to fake a query string match if in the proper
1632 * environment - BrowserMatch MSIE, for example. the cool thing
1633 * is that if MSIE ever fixes itself the simple match ought to
1634 * work and this code won't be reached anyway, even if the
1635 * environment is set.
1638 if (apr_table_get(r->subprocess_env,
1639 "AuthDigestEnableQueryStringHack")) {
1641 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01784)
1642 "applying AuthDigestEnableQueryStringHack "
1643 "to uri <%s>", resp->raw_request_uri);
1645 d_uri.query = r_uri.query;
1649 if (r->method_number == M_CONNECT) {
1650 if (!r_uri.hostinfo || strcmp(resp->uri, r_uri.hostinfo)) {
1651 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01785)
1652 "uri mismatch - <%s> does not match "
1653 "request-uri <%s>", resp->uri, r_uri.hostinfo);
1654 return HTTP_BAD_REQUEST;
1658 /* check hostname matches, if present */
1659 (d_uri.hostname && d_uri.hostname[0] != '\0'
1660 && strcasecmp(d_uri.hostname, r_uri.hostname))
1661 /* check port matches, if present */
1662 || (d_uri.port_str && d_uri.port != r_uri.port)
1663 /* check that server-port is default port if no port present */
1664 || (d_uri.hostname && d_uri.hostname[0] != '\0'
1665 && !d_uri.port_str && r_uri.port != ap_default_port(r))
1666 /* check that path matches */
1667 || (d_uri.path != r_uri.path
1668 /* either exact match */
1669 && (!d_uri.path || !r_uri.path
1670 || strcmp(d_uri.path, r_uri.path))
1671 /* or '*' matches empty path in scheme://host */
1672 && !(d_uri.path && !r_uri.path && resp->psd_request_uri->hostname
1673 && d_uri.path[0] == '*' && d_uri.path[1] == '\0'))
1674 /* check that query matches */
1675 || (d_uri.query != r_uri.query
1676 && (!d_uri.query || !r_uri.query
1677 || strcmp(d_uri.query, r_uri.query)))
1679 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01786)
1680 "uri mismatch - <%s> does not match "
1681 "request-uri <%s>", resp->uri, resp->raw_request_uri);
1682 return HTTP_BAD_REQUEST;
1686 if (resp->opaque && resp->opaque_num == 0) {
1687 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01787)
1688 "received invalid opaque - got `%s'",
1690 note_digest_auth_failure(r, conf, resp, 0);
1691 return HTTP_UNAUTHORIZED;
1695 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02533)
1696 "realm mismatch - got `%s' but no realm specified",
1698 note_digest_auth_failure(r, conf, resp, 0);
1699 return HTTP_UNAUTHORIZED;
1702 if (!resp->realm || strcmp(resp->realm, conf->realm)) {
1703 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01788)
1704 "realm mismatch - got `%s' but expected `%s'",
1705 resp->realm, conf->realm);
1706 note_digest_auth_failure(r, conf, resp, 0);
1707 return HTTP_UNAUTHORIZED;
1710 if (resp->algorithm != NULL
1711 && strcasecmp(resp->algorithm, "MD5")) {
1712 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01789)
1713 "unknown algorithm `%s' received: %s",
1714 resp->algorithm, r->uri);
1715 note_digest_auth_failure(r, conf, resp, 0);
1716 return HTTP_UNAUTHORIZED;
1719 return_code = get_hash(r, r->user, conf);
1721 if (return_code == AUTH_USER_NOT_FOUND) {
1722 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01790)
1723 "user `%s' in realm `%s' not found: %s",
1724 r->user, conf->realm, r->uri);
1725 note_digest_auth_failure(r, conf, resp, 0);
1726 return HTTP_UNAUTHORIZED;
1728 else if (return_code == AUTH_USER_FOUND) {
1729 /* we have a password, so continue */
1731 else if (return_code == AUTH_DENIED) {
1732 /* authentication denied in the provider before attempting a match */
1733 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01791)
1734 "user `%s' in realm `%s' denied by provider: %s",
1735 r->user, conf->realm, r->uri);
1736 note_digest_auth_failure(r, conf, resp, 0);
1737 return HTTP_UNAUTHORIZED;
1739 else if (return_code == AUTH_HANDLED) {
1743 /* AUTH_GENERAL_ERROR (or worse)
1744 * We'll assume that the module has already said what its error
1747 return HTTP_INTERNAL_SERVER_ERROR;
1750 if (resp->message_qop == NULL) {
1751 /* old (rfc-2069) style digest */
1752 if (strcmp(resp->digest, old_digest(r, resp, conf->ha1))) {
1753 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01792)
1754 "user %s: password mismatch: %s", r->user,
1756 note_digest_auth_failure(r, conf, resp, 0);
1757 return HTTP_UNAUTHORIZED;
1761 const char *exp_digest;
1763 const char **tmp = (const char **)(conf->qop_list->elts);
1764 for (idx = 0; idx < conf->qop_list->nelts; idx++) {
1765 if (!strcasecmp(*tmp, resp->message_qop)) {
1773 && !(apr_is_empty_array(conf->qop_list)
1774 && !strcasecmp(resp->message_qop, "auth"))) {
1775 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01793)
1776 "invalid qop `%s' received: %s",
1777 resp->message_qop, r->uri);
1778 note_digest_auth_failure(r, conf, resp, 0);
1779 return HTTP_UNAUTHORIZED;
1782 exp_digest = new_digest(r, resp, conf);
1784 /* we failed to allocate a client struct */
1785 return HTTP_INTERNAL_SERVER_ERROR;
1787 if (strcmp(resp->digest, exp_digest)) {
1788 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01794)
1789 "user %s: password mismatch: %s", r->user,
1791 note_digest_auth_failure(r, conf, resp, 0);
1792 return HTTP_UNAUTHORIZED;
1796 if (check_nc(r, resp, conf) != OK) {
1797 note_digest_auth_failure(r, conf, resp, 0);
1798 return HTTP_UNAUTHORIZED;
1801 /* Note: this check is done last so that a "stale=true" can be
1802 generated if the nonce is old */
1803 if ((res = check_nonce(r, resp, conf))) {
1811 * Authorization-Info header code
1814 static int add_auth_info(request_rec *r)
1816 const digest_config_rec *conf =
1817 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1818 &auth_digest_module);
1819 digest_header_rec *resp =
1820 (digest_header_rec *) ap_get_module_config(r->request_config,
1821 &auth_digest_module);
1822 const char *ai = NULL, *nextnonce = "";
1824 if (resp == NULL || !resp->needed_auth || conf == NULL) {
1828 /* 2069-style entity-digest is not supported (it's too hard, and
1829 * there are no clients which support 2069 but not 2617). */
1833 if (conf->nonce_lifetime > 0) {
1834 /* send nextnonce if current nonce will expire in less than 30 secs */
1835 if ((r->request_time - resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
1836 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"",
1837 gen_nonce(r->pool, r->request_time,
1838 resp->opaque, r->server, conf),
1841 resp->client->nonce_count = 0;
1844 else if (conf->nonce_lifetime == 0 && resp->client) {
1845 const char *nonce = gen_nonce(r->pool, 0, resp->opaque, r->server,
1847 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
1848 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1850 /* else nonce never expires, hence no nextnonce */
1853 /* do rfc-2069 digest
1855 if (!apr_is_empty_array(conf->qop_list) &&
1856 !strcasecmp(*(const char **)(conf->qop_list->elts), "none")
1857 && resp->message_qop == NULL) {
1858 /* use only RFC-2069 format */
1862 const char *resp_dig, *ha1, *a2, *ha2;
1864 /* calculate rspauth attribute
1868 a2 = apr_pstrcat(r->pool, ":", resp->uri, NULL);
1869 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1871 resp_dig = ap_md5(r->pool,
1872 (unsigned char *)apr_pstrcat(r->pool, ha1, ":",
1874 resp->nonce_count, ":",
1877 resp->message_qop : "",
1880 /* assemble Authentication-Info header
1882 ai = apr_pstrcat(r->pool,
1883 "rspauth=\"", resp_dig, "\"",
1885 resp->cnonce ? ", cnonce=\"" : "",
1887 ? ap_escape_quotes(r->pool, resp->cnonce)
1889 resp->cnonce ? "\"" : "",
1890 resp->nonce_count ? ", nc=" : "",
1891 resp->nonce_count ? resp->nonce_count : "",
1892 resp->message_qop ? ", qop=" : "",
1893 resp->message_qop ? resp->message_qop : "",
1898 apr_table_mergen(r->headers_out,
1899 (PROXYREQ_PROXY == r->proxyreq)
1900 ? "Proxy-Authentication-Info"
1901 : "Authentication-Info",
1908 static void register_hooks(apr_pool_t *p)
1910 static const char * const cfgPost[]={ "http_core.c", NULL };
1911 static const char * const parsePre[]={ "mod_proxy.c", NULL };
1913 ap_hook_pre_config(pre_init, NULL, NULL, APR_HOOK_MIDDLE);
1914 ap_hook_post_config(initialize_module, NULL, cfgPost, APR_HOOK_MIDDLE);
1915 ap_hook_child_init(initialize_child, NULL, NULL, APR_HOOK_MIDDLE);
1916 ap_hook_post_read_request(parse_hdr_and_update_nc, parsePre, NULL, APR_HOOK_MIDDLE);
1917 ap_hook_check_authn(authenticate_digest_user, NULL, NULL, APR_HOOK_MIDDLE,
1918 AP_AUTH_INTERNAL_PER_CONF);
1920 ap_hook_fixups(add_auth_info, NULL, NULL, APR_HOOK_MIDDLE);
1921 ap_hook_note_auth_failure(hook_note_digest_auth_failure, NULL, NULL,
1926 AP_DECLARE_MODULE(auth_digest) =
1928 STANDARD20_MODULE_STUFF,
1929 create_digest_dir_config, /* dir config creater */
1930 NULL, /* dir merger --- default is to override */
1931 NULL, /* server config */
1932 NULL, /* merge server config */
1933 digest_cmds, /* command table */
1934 register_hooks /* register hooks */