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;
88 apr_array_header_t *qop_list;
89 apr_sha1_ctx_t nonce_ctx;
90 apr_time_t nonce_lifetime;
92 const char *algorithm;
98 #define DFLT_ALGORITHM "MD5"
100 #define DFLT_NONCE_LIFE apr_time_from_sec(300)
101 #define NEXTNONCE_DELTA apr_time_from_sec(30)
104 #define NONCE_TIME_LEN (((sizeof(apr_time_t)+2)/3)*4)
105 #define NONCE_HASH_LEN (2*APR_SHA1_DIGESTSIZE)
106 #define NONCE_LEN (int )(NONCE_TIME_LEN + NONCE_HASH_LEN)
108 #define SECRET_LEN 20
109 #define RETAINED_DATA_ID "mod_auth_digest"
112 /* client list definitions */
114 typedef struct hash_entry {
115 unsigned long key; /* the key for this entry */
116 struct hash_entry *next; /* next entry in the bucket */
117 unsigned long nonce_count; /* for nonce-count checking */
118 char last_nonce[NONCE_LEN+1]; /* for one-time nonce's */
121 static struct hash_table {
122 client_entry **table;
123 unsigned long tbl_len;
124 unsigned long num_entries;
125 unsigned long num_created;
126 unsigned long num_removed;
127 unsigned long num_renewed;
131 /* struct to hold a parsed Authorization header */
133 enum hdr_sts { NO_HEADER, NOT_DIGEST, INVALID, VALID };
135 typedef struct digest_header_struct {
138 const char *username;
143 const char *algorithm;
146 unsigned long opaque_num;
147 const char *message_qop;
148 const char *nonce_count;
149 /* the following fields are not (directly) from the header */
150 const char *raw_request_uri;
151 apr_uri_t *psd_request_uri;
152 apr_time_t nonce_time;
153 enum hdr_sts auth_hdr_sts;
155 client_entry *client;
159 /* (mostly) nonce stuff */
161 typedef union time_union {
163 unsigned char arr[sizeof(apr_time_t)];
166 static unsigned char *secret;
168 /* client-list, opaque, and one-time-nonce stuff */
170 static apr_shm_t *client_shm = NULL;
171 static apr_rmm_t *client_rmm = NULL;
172 static unsigned long *opaque_cntr;
173 static apr_time_t *otn_counter; /* one-time-nonce counter */
174 static apr_global_mutex_t *client_lock = NULL;
175 static apr_global_mutex_t *opaque_lock = NULL;
176 static const char *client_mutex_type = "authdigest-client";
177 static const char *opaque_mutex_type = "authdigest-opaque";
178 static const char *client_shm_filename;
180 #define DEF_SHMEM_SIZE 1000L /* ~ 12 entries */
181 #define DEF_NUM_BUCKETS 15L
184 static apr_size_t shmem_size = DEF_SHMEM_SIZE;
185 static unsigned long num_buckets = DEF_NUM_BUCKETS;
188 module AP_MODULE_DECLARE_DATA auth_digest_module;
191 * initialization code
194 static apr_status_t cleanup_tables(void *not_used)
196 ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, APLOGNO(01756)
197 "cleaning up shared memory");
200 apr_rmm_destroy(client_rmm);
205 apr_shm_destroy(client_shm);
210 apr_global_mutex_destroy(client_lock);
215 apr_global_mutex_destroy(opaque_lock);
224 static void log_error_and_cleanup(char *msg, apr_status_t sts, server_rec *s)
226 ap_log_error(APLOG_MARK, APLOG_ERR, sts, s, APLOGNO(01760)
227 "%s - all nonce-count checking and one-time nonces "
230 cleanup_tables(NULL);
233 #if APR_HAS_SHARED_MEMORY
235 static int initialize_tables(server_rec *s, apr_pool_t *ctx)
240 /* set up client list */
242 /* Create the shared memory segment */
245 * Create a unique filename using our pid. This information is
246 * stashed in the global variable so the children inherit it.
248 client_shm_filename = ap_runtime_dir_relative(ctx, "authdigest_shm");
249 client_shm_filename = ap_append_pid(ctx, client_shm_filename, ".");
251 /* Use anonymous shm by default, fall back on name-based. */
252 sts = apr_shm_create(&client_shm, shmem_size, NULL, ctx);
253 if (APR_STATUS_IS_ENOTIMPL(sts)) {
254 /* For a name-based segment, remove it first in case of a
255 * previous unclean shutdown. */
256 apr_shm_remove(client_shm_filename, ctx);
258 /* Now create that segment */
259 sts = apr_shm_create(&client_shm, shmem_size,
260 client_shm_filename, ctx);
263 if (APR_SUCCESS != sts) {
264 ap_log_error(APLOG_MARK, APLOG_ERR, sts, s, APLOGNO(01762)
265 "Failed to create shared memory segment on file %s",
266 client_shm_filename);
267 log_error_and_cleanup("failed to initialize shm", sts, s);
268 return HTTP_INTERNAL_SERVER_ERROR;
271 sts = apr_rmm_init(&client_rmm,
272 NULL, /* no lock, we'll do the locking ourselves */
273 apr_shm_baseaddr_get(client_shm),
275 if (sts != APR_SUCCESS) {
276 log_error_and_cleanup("failed to initialize rmm", sts, s);
280 client_list = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(*client_list) +
281 sizeof(client_entry*)*num_buckets));
283 log_error_and_cleanup("failed to allocate shared memory", -1, s);
286 client_list->table = (client_entry**) (client_list + 1);
287 for (idx = 0; idx < num_buckets; idx++) {
288 client_list->table[idx] = NULL;
290 client_list->tbl_len = num_buckets;
291 client_list->num_entries = 0;
293 sts = ap_global_mutex_create(&client_lock, NULL, client_mutex_type, NULL,
295 if (sts != APR_SUCCESS) {
296 log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
303 opaque_cntr = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(*opaque_cntr)));
304 if (opaque_cntr == NULL) {
305 log_error_and_cleanup("failed to allocate shared memory", -1, s);
310 sts = ap_global_mutex_create(&opaque_lock, NULL, opaque_mutex_type, NULL,
312 if (sts != APR_SUCCESS) {
313 log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
318 /* setup one-time-nonce counter */
320 otn_counter = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(*otn_counter)));
321 if (otn_counter == NULL) {
322 log_error_and_cleanup("failed to allocate shared memory", -1, s);
333 #endif /* APR_HAS_SHARED_MEMORY */
335 static int pre_init(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
340 rv = ap_mutex_register(pconf, client_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
341 if (rv != APR_SUCCESS)
343 rv = ap_mutex_register(pconf, opaque_mutex_type, NULL, APR_LOCK_DEFAULT, 0);
344 if (rv != APR_SUCCESS)
347 retained = ap_retained_data_get(RETAINED_DATA_ID);
348 if (retained == NULL) {
349 retained = ap_retained_data_create(RETAINED_DATA_ID, SECRET_LEN);
350 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, APLOGNO(01757)
351 "generating secret for digest authentication");
353 rv = apr_generate_random_bytes(retained, SECRET_LEN);
355 #error APR random number support is missing
357 if (rv != APR_SUCCESS) {
358 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(01758)
359 "error generating secret");
367 static int initialize_module(apr_pool_t *p, apr_pool_t *plog,
368 apr_pool_t *ptemp, server_rec *s)
370 /* initialize_module() will be called twice, and if it's a DSO
371 * then all static data from the first call will be lost. Only
372 * set up our static data on the second call. */
373 if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG)
376 #if APR_HAS_SHARED_MEMORY
377 /* Note: this stuff is currently fixed for the lifetime of the server,
378 * i.e. even across restarts. This means that A) any shmem-size
379 * configuration changes are ignored, and B) certain optimizations,
380 * such as only allocating the smallest necessary entry for each
381 * client, can't be done. However, the alternative is a nightmare:
382 * we can't call apr_shm_destroy on a graceful restart because there
383 * will be children using the tables, and we also don't know when the
384 * last child dies. Therefore we can never clean up the old stuff,
385 * creating a creeping memory leak.
387 if (initialize_tables(s, p) != OK) {
390 /* Call cleanup_tables on exit or restart */
391 apr_pool_cleanup_register(p, NULL, cleanup_tables, apr_pool_cleanup_null);
392 #endif /* APR_HAS_SHARED_MEMORY */
396 static void initialize_child(apr_pool_t *p, server_rec *s)
404 /* Get access to rmm in child */
405 sts = apr_rmm_attach(&client_rmm,
407 apr_shm_baseaddr_get(client_shm),
409 if (sts != APR_SUCCESS) {
410 log_error_and_cleanup("failed to attach to rmm", sts, s);
414 sts = apr_global_mutex_child_init(&client_lock,
415 apr_global_mutex_lockfile(client_lock),
417 if (sts != APR_SUCCESS) {
418 log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
421 sts = apr_global_mutex_child_init(&opaque_lock,
422 apr_global_mutex_lockfile(opaque_lock),
424 if (sts != APR_SUCCESS) {
425 log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
434 static void *create_digest_dir_config(apr_pool_t *p, char *dir)
436 digest_config_rec *conf;
442 conf = (digest_config_rec *) apr_pcalloc(p, sizeof(digest_config_rec));
444 conf->qop_list = apr_array_make(p, 2, sizeof(char *));
445 conf->nonce_lifetime = DFLT_NONCE_LIFE;
446 conf->dir_name = apr_pstrdup(p, dir);
447 conf->algorithm = DFLT_ALGORITHM;
455 * The realm is no longer precomputed because it may be an expression, which
456 * makes this hooking of AuthName quite weird.
458 static const char *set_realm(cmd_parms *cmd, void *config, const char *realm)
460 digest_config_rec *conf = (digest_config_rec *) config;
464 /* check that we got random numbers */
465 for (i = 0; i < SECRET_LEN; i++) {
469 ap_assert(i < SECRET_LEN);
472 /* we precompute the part of the nonce hash that is constant (well,
473 * the host:port would be too, but that varies for .htaccess files
474 * and directives outside a virtual host section)
476 apr_sha1_init(&conf->nonce_ctx);
477 apr_sha1_update_binary(&conf->nonce_ctx, secret, SECRET_LEN);
483 static const char *add_authn_provider(cmd_parms *cmd, void *config,
486 digest_config_rec *conf = (digest_config_rec*)config;
487 authn_provider_list *newp;
489 newp = apr_pcalloc(cmd->pool, sizeof(authn_provider_list));
490 newp->provider_name = arg;
492 /* lookup and cache the actual provider now */
493 newp->provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP,
495 AUTHN_PROVIDER_VERSION);
497 if (newp->provider == NULL) {
498 /* by the time they use it, the provider should be loaded and
499 registered with us. */
500 return apr_psprintf(cmd->pool,
501 "Unknown Authn provider: %s",
502 newp->provider_name);
505 if (!newp->provider->get_realm_hash) {
506 /* if it doesn't provide the appropriate function, reject it */
507 return apr_psprintf(cmd->pool,
508 "The '%s' Authn provider doesn't support "
509 "Digest Authentication", newp->provider_name);
512 /* Add it to the list now. */
513 if (!conf->providers) {
514 conf->providers = newp;
517 authn_provider_list *last = conf->providers;
528 static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
530 digest_config_rec *conf = (digest_config_rec *) config;
532 if (!strcasecmp(op, "none")) {
533 apr_array_clear(conf->qop_list);
534 *(const char **)apr_array_push(conf->qop_list) = "none";
538 if (!strcasecmp(op, "auth-int")) {
539 return "AuthDigestQop auth-int is not implemented";
541 else if (ap_casecmpstr(op, "auth")) {
542 return apr_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
545 *(const char **)apr_array_push(conf->qop_list) = op;
550 static const char *set_nonce_lifetime(cmd_parms *cmd, void *config,
556 lifetime = strtol(t, &endptr, 10);
557 if (endptr < (t+strlen(t)) && !apr_isspace(*endptr)) {
558 return apr_pstrcat(cmd->pool,
559 "Invalid time in AuthDigestNonceLifetime: ",
563 ((digest_config_rec *) config)->nonce_lifetime = apr_time_from_sec(lifetime);
567 static const char *set_nonce_format(cmd_parms *cmd, void *config,
570 return "AuthDigestNonceFormat is not implemented";
573 static const char *set_nc_check(cmd_parms *cmd, void *config, int flag)
575 #if !APR_HAS_SHARED_MEMORY
577 return "AuthDigestNcCheck: ERROR: nonce-count checking "
578 "is not supported on platforms without shared-memory "
583 ((digest_config_rec *) config)->check_nc = flag;
587 static const char *set_algorithm(cmd_parms *cmd, void *config, const char *alg)
589 if (!strcasecmp(alg, "MD5-sess")) {
590 return "AuthDigestAlgorithm: ERROR: algorithm `MD5-sess' "
591 "is not implemented";
593 else if (ap_casecmpstr(alg, "MD5")) {
594 return apr_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
597 ((digest_config_rec *) config)->algorithm = alg;
601 static const char *set_uri_list(cmd_parms *cmd, void *config, const char *uri)
603 digest_config_rec *c = (digest_config_rec *) config;
605 c->uri_list[strlen(c->uri_list)-1] = '\0';
606 c->uri_list = apr_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
609 c->uri_list = apr_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
614 static const char *set_shmem_size(cmd_parms *cmd, void *config,
615 const char *size_str)
620 size = strtol(size_str, &endptr, 10);
621 while (apr_isspace(*endptr)) endptr++;
622 if (*endptr == '\0' || *endptr == 'b' || *endptr == 'B') {
625 else if (*endptr == 'k' || *endptr == 'K') {
628 else if (*endptr == 'm' || *endptr == 'M') {
632 return apr_pstrcat(cmd->pool, "Invalid size in AuthDigestShmemSize: ",
636 min = sizeof(*client_list) + sizeof(client_entry*) + sizeof(client_entry);
638 return apr_psprintf(cmd->pool, "size in AuthDigestShmemSize too small: "
639 "%ld < %ld", size, min);
643 num_buckets = (size - sizeof(*client_list)) /
644 (sizeof(client_entry*) + HASH_DEPTH * sizeof(client_entry));
645 if (num_buckets == 0) {
648 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, APLOGNO(01763)
649 "Set shmem-size: %" APR_SIZE_T_FMT ", num-buckets: %ld",
650 shmem_size, num_buckets);
655 static const command_rec digest_cmds[] =
657 AP_INIT_TAKE1("AuthName", set_realm, NULL, OR_AUTHCFG,
658 "The authentication realm (e.g. \"Members Only\")"),
659 AP_INIT_ITERATE("AuthDigestProvider", add_authn_provider, NULL, OR_AUTHCFG,
660 "specify the auth providers for a directory or location"),
661 AP_INIT_ITERATE("AuthDigestQop", set_qop, NULL, OR_AUTHCFG,
662 "A list of quality-of-protection options"),
663 AP_INIT_TAKE1("AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG,
664 "Maximum lifetime of the server nonce (seconds)"),
665 AP_INIT_TAKE1("AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG,
666 "The format to use when generating the server nonce"),
667 AP_INIT_FLAG("AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG,
668 "Whether or not to check the nonce-count sent by the client"),
669 AP_INIT_TAKE1("AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG,
670 "The algorithm used for the hash calculation"),
671 AP_INIT_ITERATE("AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG,
672 "A list of URI's which belong to the same protection space as the current URI"),
673 AP_INIT_TAKE1("AuthDigestShmemSize", set_shmem_size, NULL, RSRC_CONF,
674 "The amount of shared memory to allocate for keeping track of clients"),
682 * Each client is assigned a number, which is transferred in the opaque
683 * field of the WWW-Authenticate and Authorization headers. The number
684 * is just a simple counter which is incremented for each new client.
685 * Clients can't forge this number because it is hashed up into the
686 * server nonce, and that is checked.
688 * The clients are kept in a simple hash table, which consists of an
689 * array of client_entry's, each with a linked list of entries hanging
690 * off it. The client's number modulo the size of the array gives the
693 * The clients are garbage collected whenever a new client is allocated
694 * but there is not enough space left in the shared memory segment. A
695 * simple semi-LRU is used for this: whenever a client entry is accessed
696 * it is moved to the beginning of the linked list in its bucket (this
697 * also makes for faster lookups for current clients). The garbage
698 * collecter then just removes the oldest entry (i.e. the one at the
699 * end of the list) in each bucket.
701 * The main advantages of the above scheme are that it's easy to implement
702 * and it keeps the hash table evenly balanced (i.e. same number of entries
703 * in each bucket). The major disadvantage is that you may be throwing
704 * entries out which are in active use. This is not tragic, as these
705 * clients will just be sent a new client id (opaque field) and nonce
706 * with a stale=true (i.e. it will just look like the nonce expired,
707 * thereby forcing an extra round trip). If the shared memory segment
708 * has enough headroom over the current client set size then this should
709 * not occur too often.
711 * To help tune the size of the shared memory segment (and see if the
712 * above algorithm is really sufficient) a set of counters is kept
713 * indicating the number of clients held, the number of garbage collected
714 * clients, and the number of erroneously purged clients. These are printed
715 * out at each garbage collection run. Note that access to the counters is
716 * not synchronized because they are just indicaters, and whether they are
717 * off by a few doesn't matter; and for the same reason no attempt is made
718 * to guarantee the num_renewed is correct in the face of clients spoofing
723 * Get the client given its client number (the key). Returns the entry,
724 * or NULL if it's not found.
726 * Access to the list itself is synchronized via locks. However, access
727 * to the entry returned by get_client() is NOT synchronized. This means
728 * that there are potentially problems if a client uses multiple,
729 * simultaneous connections to access url's within the same protection
730 * space. However, these problems are not new: when using multiple
731 * connections you have no guarantee of the order the requests are
732 * processed anyway, so you have problems with the nonce-count and
733 * one-time nonces anyway.
735 static client_entry *get_client(unsigned long key, const request_rec *r)
738 client_entry *entry, *prev = NULL;
741 if (!key || !client_shm) return NULL;
743 bucket = key % client_list->tbl_len;
744 entry = client_list->table[bucket];
746 apr_global_mutex_lock(client_lock);
748 while (entry && key != entry->key) {
753 if (entry && prev) { /* move entry to front of list */
754 prev->next = entry->next;
755 entry->next = client_list->table[bucket];
756 client_list->table[bucket] = entry;
759 apr_global_mutex_unlock(client_lock);
762 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01764)
763 "get_client(): client %lu found", key);
766 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01765)
767 "get_client(): client %lu not found", key);
774 /* A simple garbage-collecter to remove unused clients. It removes the
775 * last entry in each bucket and updates the counters. Returns the
776 * number of removed entries.
780 client_entry *entry, *prev;
781 unsigned long num_removed = 0, idx;
783 /* garbage collect all last entries */
785 for (idx = 0; idx < client_list->tbl_len; idx++) {
786 entry = client_list->table[idx];
788 while (entry->next) { /* find last entry */
793 prev->next = NULL; /* cut list */
796 client_list->table[idx] = NULL;
798 if (entry) { /* remove entry */
799 apr_rmm_free(client_rmm, apr_rmm_offset_get(client_rmm, entry));
804 /* update counters and log */
806 client_list->num_entries -= num_removed;
807 client_list->num_removed += num_removed;
814 * Add a new client to the list. Returns the entry if successful, NULL
815 * otherwise. This triggers the garbage collection if memory is low.
817 static client_entry *add_client(unsigned long key, client_entry *info,
824 if (!key || !client_shm) {
828 bucket = key % client_list->tbl_len;
830 apr_global_mutex_lock(client_lock);
832 /* try to allocate a new entry */
834 entry = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(client_entry)));
836 long num_removed = gc();
837 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(01766)
838 "gc'd %ld client entries. Total new clients: "
839 "%ld; Total removed clients: %ld; Total renewed clients: "
841 client_list->num_created - client_list->num_renewed,
842 client_list->num_removed, client_list->num_renewed);
843 entry = apr_rmm_addr_get(client_rmm, apr_rmm_malloc(client_rmm, sizeof(client_entry)));
845 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01767)
846 "unable to allocate new auth_digest client");
847 apr_global_mutex_unlock(client_lock);
848 return NULL; /* give up */
852 /* now add the entry */
854 memcpy(entry, info, sizeof(client_entry));
856 entry->next = client_list->table[bucket];
857 client_list->table[bucket] = entry;
858 client_list->num_created++;
859 client_list->num_entries++;
861 apr_global_mutex_unlock(client_lock);
863 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01768)
864 "allocated new client %lu", key);
871 * Authorization header parser code
874 /* Parse the Authorization header, if it exists */
875 static int get_digest_rec(request_rec *r, digest_header_rec *resp)
877 const char *auth_line;
882 auth_line = apr_table_get(r->headers_in,
883 (PROXYREQ_PROXY == r->proxyreq)
884 ? "Proxy-Authorization"
887 resp->auth_hdr_sts = NO_HEADER;
891 resp->scheme = ap_getword_white(r->pool, &auth_line);
892 if (ap_casecmpstr(resp->scheme, "Digest")) {
893 resp->auth_hdr_sts = NOT_DIGEST;
897 l = strlen(auth_line);
899 key = apr_palloc(r->pool, l+1);
900 value = apr_palloc(r->pool, l+1);
902 while (auth_line[0] != '\0') {
906 while (apr_isspace(auth_line[0])) {
910 while (auth_line[0] != '=' && auth_line[0] != ','
911 && auth_line[0] != '\0' && !apr_isspace(auth_line[0])) {
912 key[vk++] = *auth_line++;
915 while (apr_isspace(auth_line[0])) {
921 if (auth_line[0] == '=') {
923 while (apr_isspace(auth_line[0])) {
928 if (auth_line[0] == '\"') { /* quoted string */
930 while (auth_line[0] != '\"' && auth_line[0] != '\0') {
931 if (auth_line[0] == '\\' && auth_line[1] != '\0') {
932 auth_line++; /* escaped char */
934 value[vv++] = *auth_line++;
936 if (auth_line[0] != '\0') {
941 while (auth_line[0] != ',' && auth_line[0] != '\0'
942 && !apr_isspace(auth_line[0])) {
943 value[vv++] = *auth_line++;
949 while (auth_line[0] != ',' && auth_line[0] != '\0') {
952 if (auth_line[0] != '\0') {
956 if (!ap_casecmpstr(key, "username"))
957 resp->username = apr_pstrdup(r->pool, value);
958 else if (!ap_casecmpstr(key, "realm"))
959 resp->realm = apr_pstrdup(r->pool, value);
960 else if (!ap_casecmpstr(key, "nonce"))
961 resp->nonce = apr_pstrdup(r->pool, value);
962 else if (!ap_casecmpstr(key, "uri"))
963 resp->uri = apr_pstrdup(r->pool, value);
964 else if (!ap_casecmpstr(key, "response"))
965 resp->digest = apr_pstrdup(r->pool, value);
966 else if (!ap_casecmpstr(key, "algorithm"))
967 resp->algorithm = apr_pstrdup(r->pool, value);
968 else if (!ap_casecmpstr(key, "cnonce"))
969 resp->cnonce = apr_pstrdup(r->pool, value);
970 else if (!ap_casecmpstr(key, "opaque"))
971 resp->opaque = apr_pstrdup(r->pool, value);
972 else if (!ap_casecmpstr(key, "qop"))
973 resp->message_qop = apr_pstrdup(r->pool, value);
974 else if (!ap_casecmpstr(key, "nc"))
975 resp->nonce_count = apr_pstrdup(r->pool, value);
978 if (!resp->username || !resp->realm || !resp->nonce || !resp->uri
980 || (resp->message_qop && (!resp->cnonce || !resp->nonce_count))) {
981 resp->auth_hdr_sts = INVALID;
986 resp->opaque_num = (unsigned long) strtol(resp->opaque, NULL, 16);
989 resp->auth_hdr_sts = VALID;
994 /* Because the browser may preemptively send auth info, incrementing the
995 * nonce-count when it does, and because the client does not get notified
996 * if the URI didn't need authentication after all, we need to be sure to
997 * update the nonce-count each time we receive an Authorization header no
998 * matter what the final outcome of the request. Furthermore this is a
999 * convenient place to get the request-uri (before any subrequests etc
1000 * are initiated) and to initialize the request_config.
1002 * Note that this must be called after mod_proxy had its go so that
1003 * r->proxyreq is set correctly.
1005 static int parse_hdr_and_update_nc(request_rec *r)
1007 digest_header_rec *resp;
1010 if (!ap_is_initial_req(r)) {
1014 resp = apr_pcalloc(r->pool, sizeof(digest_header_rec));
1015 resp->raw_request_uri = r->unparsed_uri;
1016 resp->psd_request_uri = &r->parsed_uri;
1017 resp->needed_auth = 0;
1018 resp->method = r->method;
1019 ap_set_module_config(r->request_config, &auth_digest_module, resp);
1021 res = get_digest_rec(r, resp);
1022 resp->client = get_client(resp->opaque_num, r);
1023 if (res == OK && resp->client) {
1024 resp->client->nonce_count++;
1032 * Nonce generation code
1035 /* The hash part of the nonce is a SHA-1 hash of the time, realm, server host
1036 * and port, opaque, and our secret.
1038 static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
1039 const server_rec *server,
1040 const digest_config_rec *conf,
1043 unsigned char sha1[APR_SHA1_DIGESTSIZE];
1046 memcpy(&ctx, &conf->nonce_ctx, sizeof(ctx));
1048 apr_sha1_update_binary(&ctx, (const unsigned char *) server->server_hostname,
1049 strlen(server->server_hostname));
1050 apr_sha1_update_binary(&ctx, (const unsigned char *) &server->port,
1051 sizeof(server->port));
1054 apr_sha1_update_binary(&ctx, (const unsigned char *) realm, strlen(realm));
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,
1074 char *nonce = apr_palloc(p, NONCE_LEN+1);
1077 if (conf->nonce_lifetime != 0) {
1080 else if (otn_counter) {
1081 /* this counter is not synch'd, because it doesn't really matter
1082 * if it counts exactly.
1084 t.time = (*otn_counter)++;
1087 /* XXX: WHAT IS THIS CONSTANT? */
1090 apr_base64_encode_binary(nonce, t.arr, sizeof(t.arr));
1091 gen_nonce_hash(nonce+NONCE_TIME_LEN, nonce, opaque, server, conf, realm);
1098 * Opaque and hash-table management
1102 * Generate a new client entry, add it to the list, and return the
1103 * entry. Returns NULL if failed.
1105 static client_entry *gen_client(const request_rec *r)
1108 client_entry new_entry = { 0, NULL, 0, "" }, *entry;
1114 apr_global_mutex_lock(opaque_lock);
1115 op = (*opaque_cntr)++;
1116 apr_global_mutex_unlock(opaque_lock);
1118 if (!(entry = add_client(op, &new_entry, r->server))) {
1119 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01769)
1120 "failed to allocate client entry - ignoring client");
1129 * Authorization challenge generation code (for WWW-Authenticate)
1132 static const char *ltox(apr_pool_t *p, unsigned long num)
1135 return apr_psprintf(p, "%lx", num);
1142 static void note_digest_auth_failure(request_rec *r,
1143 const digest_config_rec *conf,
1144 digest_header_rec *resp, int stale)
1146 const char *qop, *opaque, *opaque_param, *domain, *nonce;
1149 if (apr_is_empty_array(conf->qop_list)) {
1150 qop = ", qop=\"auth\"";
1152 else if (!ap_casecmpstr(*(const char **)(conf->qop_list->elts), "none")) {
1156 qop = apr_pstrcat(r->pool, ", qop=\"",
1157 apr_array_pstrcat(r->pool, conf->qop_list, ','),
1164 if (resp->opaque == NULL) {
1166 if ((conf->check_nc || conf->nonce_lifetime == 0)
1167 && (resp->client = gen_client(r)) != NULL) {
1168 opaque = ltox(r->pool, resp->client->key);
1171 opaque = ""; /* opaque not needed */
1174 else if (resp->client == NULL) {
1175 /* client info was gc'd */
1176 resp->client = gen_client(r);
1177 if (resp->client != NULL) {
1178 opaque = ltox(r->pool, resp->client->key);
1180 client_list->num_renewed++;
1183 opaque = ""; /* ??? */
1187 opaque = resp->opaque;
1188 /* we're generating a new nonce, so reset the nonce-count */
1189 resp->client->nonce_count = 0;
1193 opaque_param = apr_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
1196 opaque_param = NULL;
1201 nonce = gen_nonce(r->pool, r->request_time, opaque, r->server, conf, ap_auth_name(r));
1202 if (resp->client && conf->nonce_lifetime == 0) {
1203 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1206 /* setup domain attribute. We want to send this attribute wherever
1207 * possible so that the client won't send the Authorization header
1208 * unnecessarily (it's usually > 200 bytes!).
1212 /* don't send domain
1213 * - for proxy requests
1214 * - if it's not specified
1216 if (r->proxyreq || !conf->uri_list) {
1220 domain = conf->uri_list;
1223 apr_table_mergen(r->err_headers_out,
1224 (PROXYREQ_PROXY == r->proxyreq)
1225 ? "Proxy-Authenticate" : "WWW-Authenticate",
1226 apr_psprintf(r->pool, "Digest realm=\"%s\", "
1227 "nonce=\"%s\", algorithm=%s%s%s%s%s",
1228 ap_auth_name(r), nonce, conf->algorithm,
1229 opaque_param ? opaque_param : "",
1230 domain ? domain : "",
1231 stale ? ", stale=true" : "", qop));
1235 static int hook_note_digest_auth_failure(request_rec *r, const char *auth_type)
1237 request_rec *mainreq;
1238 digest_header_rec *resp;
1239 digest_config_rec *conf;
1241 if (ap_casecmpstr(auth_type, "Digest"))
1244 /* get the client response and mark */
1247 while (mainreq->main != NULL) {
1248 mainreq = mainreq->main;
1250 while (mainreq->prev != NULL) {
1251 mainreq = mainreq->prev;
1253 resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1254 &auth_digest_module);
1255 resp->needed_auth = 1;
1260 conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1261 &auth_digest_module);
1263 note_digest_auth_failure(r, conf, resp, 0);
1270 * Authorization header verification code
1273 static authn_status get_hash(request_rec *r, const char *user,
1274 digest_config_rec *conf)
1276 authn_status auth_result;
1278 authn_provider_list *current_provider;
1280 current_provider = conf->providers;
1282 const authn_provider *provider;
1284 /* For now, if a provider isn't set, we'll be nice and use the file
1287 if (!current_provider) {
1288 provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP,
1289 AUTHN_DEFAULT_PROVIDER,
1290 AUTHN_PROVIDER_VERSION);
1292 if (!provider || !provider->get_realm_hash) {
1293 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01770)
1294 "No Authn provider configured");
1295 auth_result = AUTH_GENERAL_ERROR;
1298 apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, AUTHN_DEFAULT_PROVIDER);
1301 provider = current_provider->provider;
1302 apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, current_provider->provider_name);
1306 /* We expect the password to be md5 hash of user:realm:password */
1307 auth_result = provider->get_realm_hash(r, user, ap_auth_name(r),
1310 apr_table_unset(r->notes, AUTHN_PROVIDER_NAME_NOTE);
1312 /* Something occured. Stop checking. */
1313 if (auth_result != AUTH_USER_NOT_FOUND) {
1317 /* If we're not really configured for providers, stop now. */
1318 if (!conf->providers) {
1322 current_provider = current_provider->next;
1323 } while (current_provider);
1325 if (auth_result == AUTH_USER_FOUND) {
1326 conf->ha1 = password;
1332 static int check_nc(const request_rec *r, const digest_header_rec *resp,
1333 const digest_config_rec *conf)
1336 const char *snc = resp->nonce_count;
1339 if (conf->check_nc && !client_shm) {
1340 /* Shouldn't happen, but just in case... */
1341 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01771)
1342 "cannot check nonce count without shared memory");
1346 if (!conf->check_nc || !client_shm) {
1350 if (!apr_is_empty_array(conf->qop_list) &&
1351 !ap_casecmpstr(*(const char **)(conf->qop_list->elts), "none")) {
1352 /* qop is none, client must not send a nonce count */
1354 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01772)
1355 "invalid nc %s received - no nonce count allowed when qop=none",
1359 /* qop is none, cannot check nonce count */
1363 nc = strtol(snc, &endptr, 16);
1364 if (endptr < (snc+strlen(snc)) && !apr_isspace(*endptr)) {
1365 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01773)
1366 "invalid nc %s received - not a number", snc);
1370 if (!resp->client) {
1374 if (nc != resp->client->nonce_count) {
1375 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01774)
1376 "Warning, possible replay attack: nonce-count "
1377 "check failed: %lu != %lu", nc,
1378 resp->client->nonce_count);
1385 static int check_nonce(request_rec *r, digest_header_rec *resp,
1386 const digest_config_rec *conf)
1389 time_rec nonce_time;
1390 char tmp, hash[NONCE_HASH_LEN+1];
1392 if (strlen(resp->nonce) != NONCE_LEN) {
1393 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01775)
1394 "invalid nonce %s received - length is not %d",
1395 resp->nonce, NONCE_LEN);
1396 note_digest_auth_failure(r, conf, resp, 1);
1397 return HTTP_UNAUTHORIZED;
1400 tmp = resp->nonce[NONCE_TIME_LEN];
1401 resp->nonce[NONCE_TIME_LEN] = '\0';
1402 apr_base64_decode_binary(nonce_time.arr, resp->nonce);
1403 gen_nonce_hash(hash, resp->nonce, resp->opaque, r->server, conf, ap_auth_name(r));
1404 resp->nonce[NONCE_TIME_LEN] = tmp;
1405 resp->nonce_time = nonce_time.time;
1407 if (strcmp(hash, resp->nonce+NONCE_TIME_LEN)) {
1408 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01776)
1409 "invalid nonce %s received - hash is not %s",
1411 note_digest_auth_failure(r, conf, resp, 1);
1412 return HTTP_UNAUTHORIZED;
1415 dt = r->request_time - nonce_time.time;
1416 if (conf->nonce_lifetime > 0 && dt < 0) {
1417 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01777)
1418 "invalid nonce %s received - user attempted "
1419 "time travel", resp->nonce);
1420 note_digest_auth_failure(r, conf, resp, 1);
1421 return HTTP_UNAUTHORIZED;
1424 if (conf->nonce_lifetime > 0) {
1425 if (dt > conf->nonce_lifetime) {
1426 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0,r, APLOGNO(01778)
1427 "user %s: nonce expired (%.2f seconds old "
1428 "- max lifetime %.2f) - sending new nonce",
1429 r->user, (double)apr_time_sec(dt),
1430 (double)apr_time_sec(conf->nonce_lifetime));
1431 note_digest_auth_failure(r, conf, resp, 1);
1432 return HTTP_UNAUTHORIZED;
1435 else if (conf->nonce_lifetime == 0 && resp->client) {
1436 if (memcmp(resp->client->last_nonce, resp->nonce, NONCE_LEN)) {
1437 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01779)
1438 "user %s: one-time-nonce mismatch - sending "
1439 "new nonce", r->user);
1440 note_digest_auth_failure(r, conf, resp, 1);
1441 return HTTP_UNAUTHORIZED;
1444 /* else (lifetime < 0) => never expires */
1449 /* The actual MD5 code... whee */
1452 static const char *old_digest(const request_rec *r,
1453 const digest_header_rec *resp, const char *ha1)
1457 ha2 = ap_md5(r->pool, (unsigned char *)apr_pstrcat(r->pool, resp->method, ":",
1459 return ap_md5(r->pool,
1460 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1465 static const char *new_digest(const request_rec *r,
1466 digest_header_rec *resp,
1467 const digest_config_rec *conf)
1469 const char *ha1, *ha2, *a2;
1473 a2 = apr_pstrcat(r->pool, resp->method, ":", resp->uri, NULL);
1474 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1476 return ap_md5(r->pool,
1477 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1478 ":", resp->nonce_count, ":",
1480 resp->message_qop, ":", ha2,
1485 static void copy_uri_components(apr_uri_t *dst,
1486 apr_uri_t *src, request_rec *r) {
1487 if (src->scheme && src->scheme[0] != '\0') {
1488 dst->scheme = src->scheme;
1491 dst->scheme = (char *) "http";
1494 if (src->hostname && src->hostname[0] != '\0') {
1495 dst->hostname = apr_pstrdup(r->pool, src->hostname);
1496 ap_unescape_url(dst->hostname);
1499 dst->hostname = (char *) ap_get_server_name(r);
1502 if (src->port_str && src->port_str[0] != '\0') {
1503 dst->port = src->port;
1506 dst->port = ap_get_server_port(r);
1509 if (src->path && src->path[0] != '\0') {
1510 dst->path = apr_pstrdup(r->pool, src->path);
1511 ap_unescape_url(dst->path);
1514 dst->path = src->path;
1517 if (src->query && src->query[0] != '\0') {
1518 dst->query = apr_pstrdup(r->pool, src->query);
1519 ap_unescape_url(dst->query);
1522 dst->query = src->query;
1525 dst->hostinfo = src->hostinfo;
1528 /* These functions return 0 if client is OK, and proper error status
1529 * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
1530 * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
1531 * couldn't figure out how to tell if the client is authorized or not.
1533 * If they return DECLINED, and all other modules also decline, that's
1534 * treated by the server core as a configuration error, logged and
1538 /* Determine user ID, and check if the attributes are correct, if it
1539 * really is that user, if the nonce is correct, etc.
1542 static int authenticate_digest_user(request_rec *r)
1544 digest_config_rec *conf;
1545 digest_header_rec *resp;
1546 request_rec *mainreq;
1549 authn_status return_code;
1552 /* do we require Digest auth for this URI? */
1554 if (!(t = ap_auth_type(r)) || ap_casecmpstr(t, "Digest")) {
1558 if (!ap_auth_name(r)) {
1559 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01780)
1560 "need AuthName: %s", r->uri);
1561 return HTTP_INTERNAL_SERVER_ERROR;
1565 /* get the client response and mark */
1568 while (mainreq->main != NULL) {
1569 mainreq = mainreq->main;
1571 while (mainreq->prev != NULL) {
1572 mainreq = mainreq->prev;
1574 resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1575 &auth_digest_module);
1576 resp->needed_auth = 1;
1578 realm = ap_auth_name(r);
1582 conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1583 &auth_digest_module);
1586 /* check for existence and syntax of Auth header */
1588 if (resp->auth_hdr_sts != VALID) {
1589 if (resp->auth_hdr_sts == NOT_DIGEST) {
1590 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01781)
1591 "client used wrong authentication scheme `%s': %s",
1592 resp->scheme, r->uri);
1594 else if (resp->auth_hdr_sts == INVALID) {
1595 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01782)
1596 "missing user, realm, nonce, uri, digest, "
1597 "cnonce, or nonce_count in authorization header: %s",
1600 /* else (resp->auth_hdr_sts == NO_HEADER) */
1601 note_digest_auth_failure(r, conf, resp, 0);
1602 return HTTP_UNAUTHORIZED;
1605 r->user = (char *) resp->username;
1606 r->ap_auth_type = (char *) "Digest";
1608 /* check the auth attributes */
1610 if (strcmp(resp->uri, resp->raw_request_uri)) {
1611 /* Hmm, the simple match didn't work (probably a proxy modified the
1612 * request-uri), so lets do a more sophisticated match
1614 apr_uri_t r_uri, d_uri;
1616 copy_uri_components(&r_uri, resp->psd_request_uri, r);
1617 if (apr_uri_parse(r->pool, resp->uri, &d_uri) != APR_SUCCESS) {
1618 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01783)
1619 "invalid uri <%s> in Authorization header",
1621 return HTTP_BAD_REQUEST;
1624 if (d_uri.hostname) {
1625 ap_unescape_url(d_uri.hostname);
1628 ap_unescape_url(d_uri.path);
1632 ap_unescape_url(d_uri.query);
1635 if (r->method_number == M_CONNECT) {
1636 if (!r_uri.hostinfo || strcmp(resp->uri, r_uri.hostinfo)) {
1637 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01785)
1638 "uri mismatch - <%s> does not match "
1639 "request-uri <%s>", resp->uri, r_uri.hostinfo);
1640 return HTTP_BAD_REQUEST;
1644 /* check hostname matches, if present */
1645 (d_uri.hostname && d_uri.hostname[0] != '\0'
1646 && strcasecmp(d_uri.hostname, r_uri.hostname))
1647 /* check port matches, if present */
1648 || (d_uri.port_str && d_uri.port != r_uri.port)
1649 /* check that server-port is default port if no port present */
1650 || (d_uri.hostname && d_uri.hostname[0] != '\0'
1651 && !d_uri.port_str && r_uri.port != ap_default_port(r))
1652 /* check that path matches */
1653 || (d_uri.path != r_uri.path
1654 /* either exact match */
1655 && (!d_uri.path || !r_uri.path
1656 || strcmp(d_uri.path, r_uri.path))
1657 /* or '*' matches empty path in scheme://host */
1658 && !(d_uri.path && !r_uri.path && resp->psd_request_uri->hostname
1659 && d_uri.path[0] == '*' && d_uri.path[1] == '\0'))
1660 /* check that query matches */
1661 || (d_uri.query != r_uri.query
1662 && (!d_uri.query || !r_uri.query
1663 || strcmp(d_uri.query, r_uri.query)))
1665 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01786)
1666 "uri mismatch - <%s> does not match "
1667 "request-uri <%s>", resp->uri, resp->raw_request_uri);
1668 return HTTP_BAD_REQUEST;
1672 if (resp->opaque && resp->opaque_num == 0) {
1673 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01787)
1674 "received invalid opaque - got `%s'",
1676 note_digest_auth_failure(r, conf, resp, 0);
1677 return HTTP_UNAUTHORIZED;
1683 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02533)
1684 "realm mismatch - got `%s' but no realm specified",
1686 note_digest_auth_failure(r, conf, resp, 0);
1687 return HTTP_UNAUTHORIZED;
1690 if (!resp->realm || strcmp(resp->realm, realm)) {
1691 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01788)
1692 "realm mismatch - got `%s' but expected `%s'",
1693 resp->realm, realm);
1694 note_digest_auth_failure(r, conf, resp, 0);
1695 return HTTP_UNAUTHORIZED;
1698 if (resp->algorithm != NULL
1699 && ap_casecmpstr(resp->algorithm, "MD5")) {
1700 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01789)
1701 "unknown algorithm `%s' received: %s",
1702 resp->algorithm, r->uri);
1703 note_digest_auth_failure(r, conf, resp, 0);
1704 return HTTP_UNAUTHORIZED;
1707 return_code = get_hash(r, r->user, conf);
1709 if (return_code == AUTH_USER_NOT_FOUND) {
1710 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01790)
1711 "user `%s' in realm `%s' not found: %s",
1712 r->user, realm, r->uri);
1713 note_digest_auth_failure(r, conf, resp, 0);
1714 return HTTP_UNAUTHORIZED;
1716 else if (return_code == AUTH_USER_FOUND) {
1717 /* we have a password, so continue */
1719 else if (return_code == AUTH_DENIED) {
1720 /* authentication denied in the provider before attempting a match */
1721 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01791)
1722 "user `%s' in realm `%s' denied by provider: %s",
1723 r->user, realm, r->uri);
1724 note_digest_auth_failure(r, conf, resp, 0);
1725 return HTTP_UNAUTHORIZED;
1727 else if (return_code == AUTH_HANDLED) {
1731 /* AUTH_GENERAL_ERROR (or worse)
1732 * We'll assume that the module has already said what its error
1735 return HTTP_INTERNAL_SERVER_ERROR;
1738 if (resp->message_qop == NULL) {
1739 /* old (rfc-2069) style digest */
1740 if (strcmp(resp->digest, old_digest(r, resp, conf->ha1))) {
1741 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01792)
1742 "user %s: password mismatch: %s", r->user,
1744 note_digest_auth_failure(r, conf, resp, 0);
1745 return HTTP_UNAUTHORIZED;
1749 const char *exp_digest;
1751 const char **tmp = (const char **)(conf->qop_list->elts);
1752 for (idx = 0; idx < conf->qop_list->nelts; idx++) {
1753 if (!ap_casecmpstr(*tmp, resp->message_qop)) {
1761 && !(apr_is_empty_array(conf->qop_list)
1762 && !ap_casecmpstr(resp->message_qop, "auth"))) {
1763 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01793)
1764 "invalid qop `%s' received: %s",
1765 resp->message_qop, r->uri);
1766 note_digest_auth_failure(r, conf, resp, 0);
1767 return HTTP_UNAUTHORIZED;
1770 exp_digest = new_digest(r, resp, conf);
1772 /* we failed to allocate a client struct */
1773 return HTTP_INTERNAL_SERVER_ERROR;
1775 if (strcmp(resp->digest, exp_digest)) {
1776 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01794)
1777 "user %s: password mismatch: %s", r->user,
1779 note_digest_auth_failure(r, conf, resp, 0);
1780 return HTTP_UNAUTHORIZED;
1784 if (check_nc(r, resp, conf) != OK) {
1785 note_digest_auth_failure(r, conf, resp, 0);
1786 return HTTP_UNAUTHORIZED;
1789 /* Note: this check is done last so that a "stale=true" can be
1790 generated if the nonce is old */
1791 if ((res = check_nonce(r, resp, conf))) {
1799 * Authorization-Info header code
1802 static int add_auth_info(request_rec *r)
1804 const digest_config_rec *conf =
1805 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1806 &auth_digest_module);
1807 digest_header_rec *resp =
1808 (digest_header_rec *) ap_get_module_config(r->request_config,
1809 &auth_digest_module);
1810 const char *ai = NULL, *nextnonce = "";
1812 if (resp == NULL || !resp->needed_auth || conf == NULL) {
1816 /* 2069-style entity-digest is not supported (it's too hard, and
1817 * there are no clients which support 2069 but not 2617). */
1821 if (conf->nonce_lifetime > 0) {
1822 /* send nextnonce if current nonce will expire in less than 30 secs */
1823 if ((r->request_time - resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
1824 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"",
1825 gen_nonce(r->pool, r->request_time,
1826 resp->opaque, r->server, conf, ap_auth_name(r)),
1829 resp->client->nonce_count = 0;
1832 else if (conf->nonce_lifetime == 0 && resp->client) {
1833 const char *nonce = gen_nonce(r->pool, 0, resp->opaque, r->server,
1834 conf, ap_auth_name(r));
1835 nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
1836 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1838 /* else nonce never expires, hence no nextnonce */
1841 /* do rfc-2069 digest
1843 if (!apr_is_empty_array(conf->qop_list) &&
1844 !ap_casecmpstr(*(const char **)(conf->qop_list->elts), "none")
1845 && resp->message_qop == NULL) {
1846 /* use only RFC-2069 format */
1850 const char *resp_dig, *ha1, *a2, *ha2;
1852 /* calculate rspauth attribute
1856 a2 = apr_pstrcat(r->pool, ":", resp->uri, NULL);
1857 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1859 resp_dig = ap_md5(r->pool,
1860 (unsigned char *)apr_pstrcat(r->pool, ha1, ":",
1862 resp->nonce_count, ":",
1865 resp->message_qop : "",
1868 /* assemble Authentication-Info header
1870 ai = apr_pstrcat(r->pool,
1871 "rspauth=\"", resp_dig, "\"",
1873 resp->cnonce ? ", cnonce=\"" : "",
1875 ? ap_escape_quotes(r->pool, resp->cnonce)
1877 resp->cnonce ? "\"" : "",
1878 resp->nonce_count ? ", nc=" : "",
1879 resp->nonce_count ? resp->nonce_count : "",
1880 resp->message_qop ? ", qop=" : "",
1881 resp->message_qop ? resp->message_qop : "",
1886 apr_table_mergen(r->headers_out,
1887 (PROXYREQ_PROXY == r->proxyreq)
1888 ? "Proxy-Authentication-Info"
1889 : "Authentication-Info",
1896 static void register_hooks(apr_pool_t *p)
1898 static const char * const cfgPost[]={ "http_core.c", NULL };
1899 static const char * const parsePre[]={ "mod_proxy.c", NULL };
1901 ap_hook_pre_config(pre_init, NULL, NULL, APR_HOOK_MIDDLE);
1902 ap_hook_post_config(initialize_module, NULL, cfgPost, APR_HOOK_MIDDLE);
1903 ap_hook_child_init(initialize_child, NULL, NULL, APR_HOOK_MIDDLE);
1904 ap_hook_post_read_request(parse_hdr_and_update_nc, parsePre, NULL, APR_HOOK_MIDDLE);
1905 ap_hook_check_authn(authenticate_digest_user, NULL, NULL, APR_HOOK_MIDDLE,
1906 AP_AUTH_INTERNAL_PER_CONF);
1908 ap_hook_fixups(add_auth_info, NULL, NULL, APR_HOOK_MIDDLE);
1909 ap_hook_note_auth_failure(hook_note_digest_auth_failure, NULL, NULL,
1914 AP_DECLARE_MODULE(auth_digest) =
1916 STANDARD20_MODULE_STUFF,
1917 create_digest_dir_config, /* dir config creater */
1918 NULL, /* dir merger --- default is to override */
1919 NULL, /* server config */
1920 NULL, /* merge server config */
1921 digest_cmds, /* command table */
1922 register_hooks /* register hooks */