1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * mod_auth_digest: MD5 digest authentication
20 * Originally by Alexei Kosut <akosut@nueva.pvt.k12.ca.us>
21 * Updated to RFC-2617 by Ronald Tschalär <ronald@innovation.ch>
22 * based on mod_auth, by Rob McCool and Robert S. Thau
24 * This module an updated version of modules/standard/mod_digest.c
25 * It is still fairly new and problems may turn up - submit problem
26 * reports to the Apache bug-database, or send them directly to me
27 * at ronald@innovation.ch.
29 * Requires either /dev/random (or equivalent) or the truerand library,
30 * available for instance from
31 * ftp://research.att.com/dist/mab/librand.shar
34 * - qop=auth-int (when streams and trailer support available)
35 * - nonce-format configurability
36 * - Proxy-Authorization-Info header is set by this module, but is
37 * currently ignored by mod_proxy (needs patch to mod_proxy)
38 * - generating the secret takes a while (~ 8 seconds) if using the
40 * - The source of the secret should be run-time directive (with server
41 * scope: RSRC_CONF). However, that could be tricky when trying to
42 * choose truerand vs. file...
43 * - shared-mem not completely tested yet. Seems to work ok for me,
44 * but... (definitely won't work on Windoze)
45 * - Sharing a realm among multiple servers has following problems:
46 * o Server name and port can't be included in nonce-hash
47 * (we need two nonce formats, which must be configured explicitly)
48 * o Nonce-count check can't be for equal, or then nonce-count checking
49 * must be disabled. What we could do is the following:
50 * (expected < received) ? set expected = received : issue error
51 * The only problem is that it allows replay attacks when somebody
52 * captures a packet sent to one server and sends it to another
53 * one. Should we add "AuthDigestNcCheck Strict"?
54 * - expired nonces give amaya fits.
58 #include "apr_base64.h"
61 #include "apr_errno.h"
62 #include "apr_global_mutex.h"
63 #include "apr_strings.h"
65 #define APR_WANT_STRFUNC
68 #include "ap_config.h"
70 #include "http_config.h"
71 #include "http_core.h"
72 #include "http_request.h"
74 #include "http_protocol.h"
79 #include "ap_provider.h"
83 /* Disable shmem until pools/init gets sorted out
84 * remove following two lines when fixed
86 #undef APR_HAS_SHARED_MEMORY
87 #define APR_HAS_SHARED_MEMORY 0
89 /* struct to hold the configuration info */
91 typedef struct digest_config_struct
{
93 authn_provider_list
*providers
;
96 apr_sha1_ctx_t nonce_ctx
;
97 apr_time_t nonce_lifetime
;
98 const char *nonce_format
;
100 const char *algorithm
;
106 #define DFLT_ALGORITHM "MD5"
108 #define DFLT_NONCE_LIFE apr_time_from_sec(300)
109 #define NEXTNONCE_DELTA apr_time_from_sec(30)
112 #define NONCE_TIME_LEN (((sizeof(apr_time_t)+2)/3)*4)
113 #define NONCE_HASH_LEN (2*APR_SHA1_DIGESTSIZE)
114 #define NONCE_LEN (int )(NONCE_TIME_LEN + NONCE_HASH_LEN)
116 #define SECRET_LEN 20
119 /* client list definitions */
121 typedef struct hash_entry
{
122 unsigned long key
; /* the key for this entry */
123 struct hash_entry
*next
; /* next entry in the bucket */
124 unsigned long nonce_count
; /* for nonce-count checking */
125 char ha1
[2*APR_MD5_DIGESTSIZE
+1]; /* for algorithm=MD5-sess */
126 char last_nonce
[NONCE_LEN
+1]; /* for one-time nonce's */
129 static struct hash_table
{
130 client_entry
**table
;
131 unsigned long tbl_len
;
132 unsigned long num_entries
;
133 unsigned long num_created
;
134 unsigned long num_removed
;
135 unsigned long num_renewed
;
139 /* struct to hold a parsed Authorization header */
141 enum hdr_sts
{ NO_HEADER
, NOT_DIGEST
, INVALID
, VALID
};
143 typedef struct digest_header_struct
{
146 const char *username
;
151 const char *algorithm
;
154 unsigned long opaque_num
;
155 const char *message_qop
;
156 const char *nonce_count
;
157 /* the following fields are not (directly) from the header */
158 apr_time_t nonce_time
;
159 enum hdr_sts auth_hdr_sts
;
160 const char *raw_request_uri
;
161 apr_uri_t
*psd_request_uri
;
163 client_entry
*client
;
167 /* (mostly) nonce stuff */
169 typedef union time_union
{
171 unsigned char arr
[sizeof(apr_time_t
)];
174 static unsigned char secret
[SECRET_LEN
];
176 /* client-list, opaque, and one-time-nonce stuff */
178 static apr_shm_t
*client_shm
= NULL
;
179 static apr_rmm_t
*client_rmm
= NULL
;
180 static unsigned long *opaque_cntr
;
181 static apr_time_t
*otn_counter
; /* one-time-nonce counter */
182 static apr_global_mutex_t
*client_lock
= NULL
;
183 static apr_global_mutex_t
*opaque_lock
= NULL
;
184 static char client_lock_name
[L_tmpnam
];
185 static char opaque_lock_name
[L_tmpnam
];
187 #define DEF_SHMEM_SIZE 1000L /* ~ 12 entries */
188 #define DEF_NUM_BUCKETS 15L
191 static long shmem_size
= DEF_SHMEM_SIZE
;
192 static long num_buckets
= DEF_NUM_BUCKETS
;
195 module AP_MODULE_DECLARE_DATA auth_digest_module
;
198 * initialization code
201 static apr_status_t
cleanup_tables(void *not_used
)
203 ap_log_error(APLOG_MARK
, APLOG_STARTUP
, 0, NULL
,
204 "Digest: cleaning up shared memory");
208 apr_shm_destroy(client_shm
);
213 apr_global_mutex_destroy(client_lock
);
218 apr_global_mutex_destroy(opaque_lock
);
225 static apr_status_t
initialize_secret(server_rec
*s
)
229 ap_log_error(APLOG_MARK
, APLOG_NOTICE
, 0, s
,
230 "Digest: generating secret for digest authentication ...");
233 status
= apr_generate_random_bytes(secret
, sizeof(secret
));
235 #error APR random number support is missing; you probably need to install the truerand library.
238 if (status
!= APR_SUCCESS
) {
240 ap_log_error(APLOG_MARK
, APLOG_CRIT
, status
, s
,
241 "Digest: error generating secret: %s",
242 apr_strerror(status
, buf
, sizeof(buf
)));
246 ap_log_error(APLOG_MARK
, APLOG_NOTICE
, 0, s
, "Digest: done");
251 static void log_error_and_cleanup(char *msg
, apr_status_t sts
, server_rec
*s
)
253 ap_log_error(APLOG_MARK
, APLOG_ERR
, sts
, s
,
254 "Digest: %s - all nonce-count checking, one-time nonces, and "
255 "MD5-sess algorithm disabled", msg
);
257 cleanup_tables(NULL
);
260 #if APR_HAS_SHARED_MEMORY
262 static void initialize_tables(server_rec
*s
, apr_pool_t
*ctx
)
267 /* set up client list */
269 sts
= apr_shm_create(&client_shm
, shmem_size
, tmpnam(NULL
), ctx
);
270 if (sts
!= APR_SUCCESS
) {
271 log_error_and_cleanup("failed to create shared memory segments", sts
, s
);
275 client_list
= apr_rmm_malloc(client_rmm
, sizeof(*client_list
) +
276 sizeof(client_entry
*)*num_buckets
);
278 log_error_and_cleanup("failed to allocate shared memory", -1, s
);
281 client_list
->table
= (client_entry
**) (client_list
+ 1);
282 for (idx
= 0; idx
< num_buckets
; idx
++) {
283 client_list
->table
[idx
] = NULL
;
285 client_list
->tbl_len
= num_buckets
;
286 client_list
->num_entries
= 0;
288 tmpnam(client_lock_name
);
289 /* FIXME: get the client_lock_name from a directive so we're portable
290 * to non-process-inheriting operating systems, like Win32. */
291 sts
= apr_global_mutex_create(&client_lock
, client_lock_name
,
292 APR_LOCK_DEFAULT
, ctx
);
293 if (sts
!= APR_SUCCESS
) {
294 log_error_and_cleanup("failed to create lock (client_lock)", sts
, s
);
301 opaque_cntr
= apr_rmm_malloc(client_rmm
, sizeof(*opaque_cntr
));
302 if (opaque_cntr
== NULL
) {
303 log_error_and_cleanup("failed to allocate shared memory", -1, s
);
308 tmpnam(opaque_lock_name
);
309 /* FIXME: get the opaque_lock_name from a directive so we're portable
310 * to non-process-inheriting operating systems, like Win32. */
311 sts
= apr_global_mutex_create(&opaque_lock
, opaque_lock_name
,
312 APR_LOCK_DEFAULT
, ctx
);
313 if (sts
!= APR_SUCCESS
) {
314 log_error_and_cleanup("failed to create lock (opaque_lock)", sts
, s
);
319 /* setup one-time-nonce counter */
321 otn_counter
= apr_rmm_malloc(client_rmm
, sizeof(*otn_counter
));
322 if (otn_counter
== NULL
) {
323 log_error_and_cleanup("failed to allocate shared memory", -1, s
);
334 #endif /* APR_HAS_SHARED_MEMORY */
337 static int initialize_module(apr_pool_t
*p
, apr_pool_t
*plog
,
338 apr_pool_t
*ptemp
, server_rec
*s
)
341 const char *userdata_key
= "auth_digest_init";
343 /* initialize_module() will be called twice, and if it's a DSO
344 * then all static data from the first call will be lost. Only
345 * set up our static data on the second call. */
346 apr_pool_userdata_get(&data
, userdata_key
, s
->process
->pool
);
348 apr_pool_userdata_set((const void *)1, userdata_key
,
349 apr_pool_cleanup_null
, s
->process
->pool
);
352 if (initialize_secret(s
) != APR_SUCCESS
) {
356 #if APR_HAS_SHARED_MEMORY
357 /* Note: this stuff is currently fixed for the lifetime of the server,
358 * i.e. even across restarts. This means that A) any shmem-size
359 * configuration changes are ignored, and B) certain optimizations,
360 * such as only allocating the smallest necessary entry for each
361 * client, can't be done. However, the alternative is a nightmare:
362 * we can't call apr_shm_destroy on a graceful restart because there
363 * will be children using the tables, and we also don't know when the
364 * last child dies. Therefore we can never clean up the old stuff,
365 * creating a creeping memory leak.
367 initialize_tables(s
, p
);
368 apr_pool_cleanup_register(p
, NULL
, cleanup_tables
, apr_pool_cleanup_null
);
369 #endif /* APR_HAS_SHARED_MEMORY */
373 static void initialize_child(apr_pool_t
*p
, server_rec
*s
)
381 /* FIXME: get the client_lock_name from a directive so we're portable
382 * to non-process-inheriting operating systems, like Win32. */
383 sts
= apr_global_mutex_child_init(&client_lock
, client_lock_name
, p
);
384 if (sts
!= APR_SUCCESS
) {
385 log_error_and_cleanup("failed to create lock (client_lock)", sts
, s
);
388 /* FIXME: get the opaque_lock_name from a directive so we're portable
389 * to non-process-inheriting operating systems, like Win32. */
390 sts
= apr_global_mutex_child_init(&opaque_lock
, opaque_lock_name
, p
);
391 if (sts
!= APR_SUCCESS
) {
392 log_error_and_cleanup("failed to create lock (opaque_lock)", sts
, s
);
401 static void *create_digest_dir_config(apr_pool_t
*p
, char *dir
)
403 digest_config_rec
*conf
;
409 conf
= (digest_config_rec
*) apr_pcalloc(p
, sizeof(digest_config_rec
));
411 conf
->qop_list
= apr_palloc(p
, sizeof(char*));
412 conf
->qop_list
[0] = NULL
;
413 conf
->nonce_lifetime
= DFLT_NONCE_LIFE
;
414 conf
->dir_name
= apr_pstrdup(p
, dir
);
415 conf
->algorithm
= DFLT_ALGORITHM
;
421 static const char *set_realm(cmd_parms
*cmd
, void *config
, const char *realm
)
423 digest_config_rec
*conf
= (digest_config_rec
*) config
;
425 /* The core already handles the realm, but it's just too convenient to
426 * grab it ourselves too and cache some setups. However, we need to
427 * let the core get at it too, which is why we decline at the end -
428 * this relies on the fact that http_core is last in the list.
432 /* we precompute the part of the nonce hash that is constant (well,
433 * the host:port would be too, but that varies for .htaccess files
434 * and directives outside a virtual host section)
436 apr_sha1_init(&conf
->nonce_ctx
);
437 apr_sha1_update_binary(&conf
->nonce_ctx
, secret
, sizeof(secret
));
438 apr_sha1_update_binary(&conf
->nonce_ctx
, (const unsigned char *) realm
,
444 static const char *add_authn_provider(cmd_parms
*cmd
, void *config
,
447 digest_config_rec
*conf
= (digest_config_rec
*)config
;
448 authn_provider_list
*newp
;
450 newp
= apr_pcalloc(cmd
->pool
, sizeof(authn_provider_list
));
451 newp
->provider_name
= apr_pstrdup(cmd
->pool
, arg
);
453 /* lookup and cache the actual provider now */
454 newp
->provider
= ap_lookup_provider(AUTHN_PROVIDER_GROUP
,
456 AUTHN_PROVIDER_VERSION
);
458 if (newp
->provider
== NULL
) {
459 /* by the time they use it, the provider should be loaded and
460 registered with us. */
461 return apr_psprintf(cmd
->pool
,
462 "Unknown Authn provider: %s",
463 newp
->provider_name
);
466 if (!newp
->provider
->get_realm_hash
) {
467 /* if it doesn't provide the appropriate function, reject it */
468 return apr_psprintf(cmd
->pool
,
469 "The '%s' Authn provider doesn't support "
470 "Digest Authentication", newp
->provider_name
);
473 /* Add it to the list now. */
474 if (!conf
->providers
) {
475 conf
->providers
= newp
;
478 authn_provider_list
*last
= conf
->providers
;
489 static const char *set_qop(cmd_parms
*cmd
, void *config
, const char *op
)
491 digest_config_rec
*conf
= (digest_config_rec
*) config
;
495 if (!strcasecmp(op
, "none")) {
496 if (conf
->qop_list
[0] == NULL
) {
497 conf
->qop_list
= apr_palloc(cmd
->pool
, 2 * sizeof(char*));
498 conf
->qop_list
[1] = NULL
;
500 conf
->qop_list
[0] = "none";
504 if (!strcasecmp(op
, "auth-int")) {
505 ap_log_error(APLOG_MARK
, APLOG_WARNING
, 0, cmd
->server
,
506 "Digest: WARNING: qop `auth-int' currently only works "
507 "correctly for responses with no entity");
509 else if (strcasecmp(op
, "auth")) {
510 return apr_pstrcat(cmd
->pool
, "Unrecognized qop: ", op
, NULL
);
513 for (cnt
= 0; conf
->qop_list
[cnt
] != NULL
; cnt
++)
516 tmp
= apr_palloc(cmd
->pool
, (cnt
+ 2) * sizeof(char*));
517 memcpy(tmp
, conf
->qop_list
, cnt
*sizeof(char*));
518 tmp
[cnt
] = apr_pstrdup(cmd
->pool
, op
);
520 conf
->qop_list
= tmp
;
525 static const char *set_nonce_lifetime(cmd_parms
*cmd
, void *config
,
531 lifetime
= strtol(t
, &endptr
, 10);
532 if (endptr
< (t
+strlen(t
)) && !apr_isspace(*endptr
)) {
533 return apr_pstrcat(cmd
->pool
,
534 "Invalid time in AuthDigestNonceLifetime: ",
538 ((digest_config_rec
*) config
)->nonce_lifetime
= apr_time_from_sec(lifetime
);
542 static const char *set_nonce_format(cmd_parms
*cmd
, void *config
,
545 ((digest_config_rec
*) config
)->nonce_format
= fmt
;
546 return "AuthDigestNonceFormat is not implemented (yet)";
549 static const char *set_nc_check(cmd_parms
*cmd
, void *config
, int flag
)
551 if (flag
&& !client_shm
)
552 ap_log_error(APLOG_MARK
, APLOG_WARNING
, 0,
553 cmd
->server
, "Digest: WARNING: nonce-count checking "
554 "is not supported on platforms without shared-memory "
555 "support - disabling check");
557 ((digest_config_rec
*) config
)->check_nc
= flag
;
561 static const char *set_algorithm(cmd_parms
*cmd
, void *config
, const char *alg
)
563 if (!strcasecmp(alg
, "MD5-sess")) {
565 ap_log_error(APLOG_MARK
, APLOG_WARNING
, 0,
566 cmd
->server
, "Digest: WARNING: algorithm `MD5-sess' "
567 "is not supported on platforms without shared-memory "
568 "support - reverting to MD5");
572 else if (strcasecmp(alg
, "MD5")) {
573 return apr_pstrcat(cmd
->pool
, "Invalid algorithm in AuthDigestAlgorithm: ", alg
, NULL
);
576 ((digest_config_rec
*) config
)->algorithm
= alg
;
580 static const char *set_uri_list(cmd_parms
*cmd
, void *config
, const char *uri
)
582 digest_config_rec
*c
= (digest_config_rec
*) config
;
584 c
->uri_list
[strlen(c
->uri_list
)-1] = '\0';
585 c
->uri_list
= apr_pstrcat(cmd
->pool
, c
->uri_list
, " ", uri
, "\"", NULL
);
588 c
->uri_list
= apr_pstrcat(cmd
->pool
, ", domain=\"", uri
, "\"", NULL
);
593 static const char *set_shmem_size(cmd_parms
*cmd
, void *config
,
594 const char *size_str
)
599 size
= strtol(size_str
, &endptr
, 10);
600 while (apr_isspace(*endptr
)) endptr
++;
601 if (*endptr
== '\0' || *endptr
== 'b' || *endptr
== 'B') {
604 else if (*endptr
== 'k' || *endptr
== 'K') {
607 else if (*endptr
== 'm' || *endptr
== 'M') {
611 return apr_pstrcat(cmd
->pool
, "Invalid size in AuthDigestShmemSize: ",
615 min
= sizeof(*client_list
) + sizeof(client_entry
*) + sizeof(client_entry
);
617 return apr_psprintf(cmd
->pool
, "size in AuthDigestShmemSize too small: "
618 "%ld < %ld", size
, min
);
622 num_buckets
= (size
- sizeof(*client_list
)) /
623 (sizeof(client_entry
*) + HASH_DEPTH
* sizeof(client_entry
));
624 if (num_buckets
== 0) {
627 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, cmd
->server
,
628 "Digest: Set shmem-size: %ld, num-buckets: %ld", shmem_size
,
634 static const command_rec digest_cmds
[] =
636 AP_INIT_TAKE1("AuthName", set_realm
, NULL
, OR_AUTHCFG
,
637 "The authentication realm (e.g. \"Members Only\")"),
638 AP_INIT_ITERATE("AuthDigestProvider", add_authn_provider
, NULL
, OR_AUTHCFG
,
639 "specify the auth providers for a directory or location"),
640 AP_INIT_ITERATE("AuthDigestQop", set_qop
, NULL
, OR_AUTHCFG
,
641 "A list of quality-of-protection options"),
642 AP_INIT_TAKE1("AuthDigestNonceLifetime", set_nonce_lifetime
, NULL
, OR_AUTHCFG
,
643 "Maximum lifetime of the server nonce (seconds)"),
644 AP_INIT_TAKE1("AuthDigestNonceFormat", set_nonce_format
, NULL
, OR_AUTHCFG
,
645 "The format to use when generating the server nonce"),
646 AP_INIT_FLAG("AuthDigestNcCheck", set_nc_check
, NULL
, OR_AUTHCFG
,
647 "Whether or not to check the nonce-count sent by the client"),
648 AP_INIT_TAKE1("AuthDigestAlgorithm", set_algorithm
, NULL
, OR_AUTHCFG
,
649 "The algorithm used for the hash calculation"),
650 AP_INIT_ITERATE("AuthDigestDomain", set_uri_list
, NULL
, OR_AUTHCFG
,
651 "A list of URI's which belong to the same protection space as the current URI"),
652 AP_INIT_TAKE1("AuthDigestShmemSize", set_shmem_size
, NULL
, RSRC_CONF
,
653 "The amount of shared memory to allocate for keeping track of clients"),
661 * Each client is assigned a number, which is transferred in the opaque
662 * field of the WWW-Authenticate and Authorization headers. The number
663 * is just a simple counter which is incremented for each new client.
664 * Clients can't forge this number because it is hashed up into the
665 * server nonce, and that is checked.
667 * The clients are kept in a simple hash table, which consists of an
668 * array of client_entry's, each with a linked list of entries hanging
669 * off it. The client's number modulo the size of the array gives the
672 * The clients are garbage collected whenever a new client is allocated
673 * but there is not enough space left in the shared memory segment. A
674 * simple semi-LRU is used for this: whenever a client entry is accessed
675 * it is moved to the beginning of the linked list in its bucket (this
676 * also makes for faster lookups for current clients). The garbage
677 * collecter then just removes the oldest entry (i.e. the one at the
678 * end of the list) in each bucket.
680 * The main advantages of the above scheme are that it's easy to implement
681 * and it keeps the hash table evenly balanced (i.e. same number of entries
682 * in each bucket). The major disadvantage is that you may be throwing
683 * entries out which are in active use. This is not tragic, as these
684 * clients will just be sent a new client id (opaque field) and nonce
685 * with a stale=true (i.e. it will just look like the nonce expired,
686 * thereby forcing an extra round trip). If the shared memory segment
687 * has enough headroom over the current client set size then this should
688 * not occur too often.
690 * To help tune the size of the shared memory segment (and see if the
691 * above algorithm is really sufficient) a set of counters is kept
692 * indicating the number of clients held, the number of garbage collected
693 * clients, and the number of erroneously purged clients. These are printed
694 * out at each garbage collection run. Note that access to the counters is
695 * not synchronized because they are just indicaters, and whether they are
696 * off by a few doesn't matter; and for the same reason no attempt is made
697 * to guarantee the num_renewed is correct in the face of clients spoofing
702 * Get the client given its client number (the key). Returns the entry,
703 * or NULL if it's not found.
705 * Access to the list itself is synchronized via locks. However, access
706 * to the entry returned by get_client() is NOT synchronized. This means
707 * that there are potentially problems if a client uses multiple,
708 * simultaneous connections to access url's within the same protection
709 * space. However, these problems are not new: when using multiple
710 * connections you have no guarantee of the order the requests are
711 * processed anyway, so you have problems with the nonce-count and
712 * one-time nonces anyway.
714 static client_entry
*get_client(unsigned long key
, const request_rec
*r
)
717 client_entry
*entry
, *prev
= NULL
;
720 if (!key
|| !client_shm
) return NULL
;
722 bucket
= key
% client_list
->tbl_len
;
723 entry
= client_list
->table
[bucket
];
725 apr_global_mutex_lock(client_lock
);
727 while (entry
&& key
!= entry
->key
) {
732 if (entry
&& prev
) { /* move entry to front of list */
733 prev
->next
= entry
->next
;
734 entry
->next
= client_list
->table
[bucket
];
735 client_list
->table
[bucket
] = entry
;
738 apr_global_mutex_unlock(client_lock
);
741 ap_log_rerror(APLOG_MARK
, APLOG_DEBUG
, 0, r
,
742 "get_client(): client %lu found", key
);
745 ap_log_rerror(APLOG_MARK
, APLOG_DEBUG
, 0, r
,
746 "get_client(): client %lu not found", key
);
753 /* A simple garbage-collecter to remove unused clients. It removes the
754 * last entry in each bucket and updates the counters. Returns the
755 * number of removed entries.
759 client_entry
*entry
, *prev
;
760 unsigned long num_removed
= 0, idx
;
762 /* garbage collect all last entries */
764 for (idx
= 0; idx
< client_list
->tbl_len
; idx
++) {
765 entry
= client_list
->table
[idx
];
767 while (entry
->next
) { /* find last entry */
772 prev
->next
= NULL
; /* cut list */
775 client_list
->table
[idx
] = NULL
;
777 if (entry
) { /* remove entry */
778 apr_rmm_free(client_rmm
, (apr_rmm_off_t
)entry
);
783 /* update counters and log */
785 client_list
->num_entries
-= num_removed
;
786 client_list
->num_removed
+= num_removed
;
793 * Add a new client to the list. Returns the entry if successful, NULL
794 * otherwise. This triggers the garbage collection if memory is low.
796 static client_entry
*add_client(unsigned long key
, client_entry
*info
,
803 if (!key
|| !client_shm
) {
807 bucket
= key
% client_list
->tbl_len
;
808 entry
= client_list
->table
[bucket
];
810 apr_global_mutex_lock(client_lock
);
812 /* try to allocate a new entry */
814 entry
= (client_entry
*)apr_rmm_malloc(client_rmm
, sizeof(client_entry
));
816 long num_removed
= gc();
817 ap_log_error(APLOG_MARK
, APLOG_INFO
, 0, s
,
818 "Digest: gc'd %ld client entries. Total new clients: "
819 "%ld; Total removed clients: %ld; Total renewed clients: "
821 client_list
->num_created
- client_list
->num_renewed
,
822 client_list
->num_removed
, client_list
->num_renewed
);
823 entry
= (client_entry
*)apr_rmm_malloc(client_rmm
, sizeof(client_entry
));
825 return NULL
; /* give up */
829 /* now add the entry */
831 memcpy(entry
, info
, sizeof(client_entry
));
833 entry
->next
= client_list
->table
[bucket
];
834 client_list
->table
[bucket
] = entry
;
835 client_list
->num_created
++;
836 client_list
->num_entries
++;
838 apr_global_mutex_unlock(client_lock
);
840 ap_log_error(APLOG_MARK
, APLOG_DEBUG
, 0, s
,
841 "allocated new client %lu", key
);
848 * Authorization header parser code
851 /* Parse the Authorization header, if it exists */
852 static int get_digest_rec(request_rec
*r
, digest_header_rec
*resp
)
854 const char *auth_line
;
859 auth_line
= apr_table_get(r
->headers_in
,
860 (PROXYREQ_PROXY
== r
->proxyreq
)
861 ? "Proxy-Authorization"
864 resp
->auth_hdr_sts
= NO_HEADER
;
868 resp
->scheme
= ap_getword_white(r
->pool
, &auth_line
);
869 if (strcasecmp(resp
->scheme
, "Digest")) {
870 resp
->auth_hdr_sts
= NOT_DIGEST
;
874 l
= strlen(auth_line
);
876 key
= apr_palloc(r
->pool
, l
+1);
877 value
= apr_palloc(r
->pool
, l
+1);
879 while (auth_line
[0] != '\0') {
883 while (apr_isspace(auth_line
[0])) {
887 while (auth_line
[0] != '=' && auth_line
[0] != ','
888 && auth_line
[0] != '\0' && !apr_isspace(auth_line
[0])) {
889 key
[vk
++] = *auth_line
++;
892 while (apr_isspace(auth_line
[0])) {
898 if (auth_line
[0] == '=') {
900 while (apr_isspace(auth_line
[0])) {
905 if (auth_line
[0] == '\"') { /* quoted string */
907 while (auth_line
[0] != '\"' && auth_line
[0] != '\0') {
908 if (auth_line
[0] == '\\' && auth_line
[1] != '\0') {
909 auth_line
++; /* escaped char */
911 value
[vv
++] = *auth_line
++;
913 if (auth_line
[0] != '\0') {
918 while (auth_line
[0] != ',' && auth_line
[0] != '\0'
919 && !apr_isspace(auth_line
[0])) {
920 value
[vv
++] = *auth_line
++;
926 while (auth_line
[0] != ',' && auth_line
[0] != '\0') {
929 if (auth_line
[0] != '\0') {
933 if (!strcasecmp(key
, "username"))
934 resp
->username
= apr_pstrdup(r
->pool
, value
);
935 else if (!strcasecmp(key
, "realm"))
936 resp
->realm
= apr_pstrdup(r
->pool
, value
);
937 else if (!strcasecmp(key
, "nonce"))
938 resp
->nonce
= apr_pstrdup(r
->pool
, value
);
939 else if (!strcasecmp(key
, "uri"))
940 resp
->uri
= apr_pstrdup(r
->pool
, value
);
941 else if (!strcasecmp(key
, "response"))
942 resp
->digest
= apr_pstrdup(r
->pool
, value
);
943 else if (!strcasecmp(key
, "algorithm"))
944 resp
->algorithm
= apr_pstrdup(r
->pool
, value
);
945 else if (!strcasecmp(key
, "cnonce"))
946 resp
->cnonce
= apr_pstrdup(r
->pool
, value
);
947 else if (!strcasecmp(key
, "opaque"))
948 resp
->opaque
= apr_pstrdup(r
->pool
, value
);
949 else if (!strcasecmp(key
, "qop"))
950 resp
->message_qop
= apr_pstrdup(r
->pool
, value
);
951 else if (!strcasecmp(key
, "nc"))
952 resp
->nonce_count
= apr_pstrdup(r
->pool
, value
);
955 if (!resp
->username
|| !resp
->realm
|| !resp
->nonce
|| !resp
->uri
957 || (resp
->message_qop
&& (!resp
->cnonce
|| !resp
->nonce_count
))) {
958 resp
->auth_hdr_sts
= INVALID
;
963 resp
->opaque_num
= (unsigned long) strtol(resp
->opaque
, NULL
, 16);
966 resp
->auth_hdr_sts
= VALID
;
971 /* Because the browser may preemptively send auth info, incrementing the
972 * nonce-count when it does, and because the client does not get notified
973 * if the URI didn't need authentication after all, we need to be sure to
974 * update the nonce-count each time we receive an Authorization header no
975 * matter what the final outcome of the request. Furthermore this is a
976 * convenient place to get the request-uri (before any subrequests etc
977 * are initiated) and to initialize the request_config.
979 * Note that this must be called after mod_proxy had its go so that
980 * r->proxyreq is set correctly.
982 static int parse_hdr_and_update_nc(request_rec
*r
)
984 digest_header_rec
*resp
;
987 if (!ap_is_initial_req(r
)) {
991 resp
= apr_pcalloc(r
->pool
, sizeof(digest_header_rec
));
992 resp
->raw_request_uri
= r
->unparsed_uri
;
993 resp
->psd_request_uri
= &r
->parsed_uri
;
994 resp
->needed_auth
= 0;
995 resp
->method
= r
->method
;
996 ap_set_module_config(r
->request_config
, &auth_digest_module
, resp
);
998 res
= get_digest_rec(r
, resp
);
999 resp
->client
= get_client(resp
->opaque_num
, r
);
1000 if (res
== OK
&& resp
->client
) {
1001 resp
->client
->nonce_count
++;
1009 * Nonce generation code
1012 /* The hash part of the nonce is a SHA-1 hash of the time, realm, server host
1013 * and port, opaque, and our secret.
1015 static void gen_nonce_hash(char *hash
, const char *timestr
, const char *opaque
,
1016 const server_rec
*server
,
1017 const digest_config_rec
*conf
)
1019 const char *hex
= "0123456789abcdef";
1020 unsigned char sha1
[APR_SHA1_DIGESTSIZE
];
1024 memcpy(&ctx
, &conf
->nonce_ctx
, sizeof(ctx
));
1026 apr_sha1_update_binary(&ctx, (const unsigned char *) server->server_hostname,
1027 strlen(server->server_hostname));
1028 apr_sha1_update_binary(&ctx, (const unsigned char *) &server->port,
1029 sizeof(server->port));
1031 apr_sha1_update_binary(&ctx
, (const unsigned char *) timestr
, strlen(timestr
));
1033 apr_sha1_update_binary(&ctx
, (const unsigned char *) opaque
,
1036 apr_sha1_final(sha1
, &ctx
);
1038 for (idx
=0; idx
<APR_SHA1_DIGESTSIZE
; idx
++) {
1039 *hash
++ = hex
[sha1
[idx
] >> 4];
1040 *hash
++ = hex
[sha1
[idx
] & 0xF];
1047 /* The nonce has the format b64(time)+hash .
1049 static const char *gen_nonce(apr_pool_t
*p
, apr_time_t now
, const char *opaque
,
1050 const server_rec
*server
,
1051 const digest_config_rec
*conf
)
1053 char *nonce
= apr_palloc(p
, NONCE_LEN
+1);
1057 if (conf
->nonce_lifetime
!= 0) {
1060 else if (otn_counter
) {
1061 /* this counter is not synch'd, because it doesn't really matter
1062 * if it counts exactly.
1064 t
.time
= (*otn_counter
)++;
1067 /* XXX: WHAT IS THIS CONSTANT? */
1070 len
= apr_base64_encode_binary(nonce
, t
.arr
, sizeof(t
.arr
));
1071 gen_nonce_hash(nonce
+NONCE_TIME_LEN
, nonce
, opaque
, server
, conf
);
1078 * Opaque and hash-table management
1082 * Generate a new client entry, add it to the list, and return the
1083 * entry. Returns NULL if failed.
1085 static client_entry
*gen_client(const request_rec
*r
)
1088 client_entry new_entry
= { 0, NULL
, 0, "", "" }, *entry
;
1094 apr_global_mutex_lock(opaque_lock
);
1095 op
= (*opaque_cntr
)++;
1096 apr_global_mutex_lock(opaque_lock
);
1098 if (!(entry
= add_client(op
, &new_entry
, r
->server
))) {
1099 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1100 "Digest: failed to allocate client entry - ignoring "
1112 * If you want to use algorithm=MD5-sess you must write get_userpw_hash()
1113 * yourself (see below). The dummy provided here just uses the hash from
1114 * the auth-file, i.e. it is only useful for testing client implementations
1119 * get_userpw_hash() will be called each time a new session needs to be
1120 * generated and is expected to return the equivalent of
1122 * h_urp = ap_md5(r->pool,
1123 * apr_pstrcat(r->pool, username, ":", ap_auth_name(r), ":", passwd))
1125 * (unsigned char *) apr_pstrcat(r->pool, h_urp, ":", resp->nonce, ":",
1126 * resp->cnonce, NULL));
1128 * or put differently, it must return
1130 * MD5(MD5(username ":" realm ":" password) ":" nonce ":" cnonce)
1132 * If something goes wrong, the failure must be logged and NULL returned.
1134 * You must implement this yourself, which will probably consist of code
1135 * contacting the password server with the necessary information (typically
1136 * the username, realm, nonce, and cnonce) and receiving the hash from it.
1138 * TBD: This function should probably be in a seperate source file so that
1139 * people need not modify mod_auth_digest.c each time they install a new
1140 * version of apache.
1142 static const char *get_userpw_hash(const request_rec
*r
,
1143 const digest_header_rec
*resp
,
1144 const digest_config_rec
*conf
)
1146 return ap_md5(r
->pool
,
1147 (unsigned char *) apr_pstrcat(r
->pool
, conf
->ha1
, ":", resp
->nonce
,
1148 ":", resp
->cnonce
, NULL
));
1152 /* Retrieve current session H(A1). If there is none and "generate" is
1153 * true then a new session for MD5-sess is generated and stored in the
1154 * client struct; if generate is false, or a new session could not be
1155 * generated then NULL is returned (in case of failure to generate the
1156 * failure reason will have been logged already).
1158 static const char *get_session_HA1(const request_rec
*r
,
1159 digest_header_rec
*resp
,
1160 const digest_config_rec
*conf
,
1163 const char *ha1
= NULL
;
1165 /* return the current sessions if there is one */
1166 if (resp
->opaque
&& resp
->client
&& resp
->client
->ha1
[0]) {
1167 return resp
->client
->ha1
;
1169 else if (!generate
) {
1173 /* generate a new session */
1174 if (!resp
->client
) {
1175 resp
->client
= gen_client(r
);
1178 ha1
= get_userpw_hash(r
, resp
, conf
);
1180 memcpy(resp
->client
->ha1
, ha1
, sizeof(resp
->client
->ha1
));
1188 static void clear_session(const digest_header_rec
*resp
)
1191 resp
->client
->ha1
[0] = '\0';
1196 * Authorization challenge generation code (for WWW-Authenticate)
1199 static const char *ltox(apr_pool_t
*p
, unsigned long num
)
1202 return apr_psprintf(p
, "%lx", num
);
1209 static void note_digest_auth_failure(request_rec
*r
,
1210 const digest_config_rec
*conf
,
1211 digest_header_rec
*resp
, int stale
)
1213 const char *qop
, *opaque
, *opaque_param
, *domain
, *nonce
;
1218 if (conf
->qop_list
[0] == NULL
) {
1219 qop
= ", qop=\"auth\"";
1221 else if (!strcasecmp(conf
->qop_list
[0], "none")) {
1225 qop
= apr_pstrcat(r
->pool
, ", qop=\"", conf
->qop_list
[0], NULL
);
1226 for (cnt
= 1; conf
->qop_list
[cnt
] != NULL
; cnt
++) {
1227 qop
= apr_pstrcat(r
->pool
, qop
, ",", conf
->qop_list
[cnt
], NULL
);
1229 qop
= apr_pstrcat(r
->pool
, qop
, "\"", NULL
);
1234 if (resp
->opaque
== NULL
) {
1236 if ((conf
->check_nc
|| conf
->nonce_lifetime
== 0
1237 || !strcasecmp(conf
->algorithm
, "MD5-sess"))
1238 && (resp
->client
= gen_client(r
)) != NULL
) {
1239 opaque
= ltox(r
->pool
, resp
->client
->key
);
1242 opaque
= ""; /* opaque not needed */
1245 else if (resp
->client
== NULL
) {
1246 /* client info was gc'd */
1247 resp
->client
= gen_client(r
);
1248 if (resp
->client
!= NULL
) {
1249 opaque
= ltox(r
->pool
, resp
->client
->key
);
1251 client_list
->num_renewed
++;
1254 opaque
= ""; /* ??? */
1258 opaque
= resp
->opaque
;
1259 /* we're generating a new nonce, so reset the nonce-count */
1260 resp
->client
->nonce_count
= 0;
1264 opaque_param
= apr_pstrcat(r
->pool
, ", opaque=\"", opaque
, "\"", NULL
);
1267 opaque_param
= NULL
;
1272 nonce
= gen_nonce(r
->pool
, r
->request_time
, opaque
, r
->server
, conf
);
1273 if (resp
->client
&& conf
->nonce_lifetime
== 0) {
1274 memcpy(resp
->client
->last_nonce
, nonce
, NONCE_LEN
+1);
1277 /* Setup MD5-sess stuff. Note that we just clear out the session
1278 * info here, since we can't generate a new session until the request
1279 * from the client comes in with the cnonce.
1282 if (!strcasecmp(conf
->algorithm
, "MD5-sess")) {
1283 clear_session(resp
);
1286 /* setup domain attribute. We want to send this attribute wherever
1287 * possible so that the client won't send the Authorization header
1288 * unneccessarily (it's usually > 200 bytes!).
1292 /* don't send domain
1293 * - for proxy requests
1294 * - if it's no specified
1296 if (r
->proxyreq
|| !conf
->uri_list
) {
1300 domain
= conf
->uri_list
;
1303 apr_table_mergen(r
->err_headers_out
,
1304 (PROXYREQ_PROXY
== r
->proxyreq
)
1305 ? "Proxy-Authenticate" : "WWW-Authenticate",
1306 apr_psprintf(r
->pool
, "Digest realm=\"%s\", "
1307 "nonce=\"%s\", algorithm=%s%s%s%s%s",
1308 ap_auth_name(r
), nonce
, conf
->algorithm
,
1309 opaque_param
? opaque_param
: "",
1310 domain
? domain
: "",
1311 stale
? ", stale=true" : "", qop
));
1317 * Authorization header verification code
1320 static authn_status
get_hash(request_rec
*r
, const char *user
,
1321 digest_config_rec
*conf
)
1323 authn_status auth_result
;
1325 authn_provider_list
*current_provider
;
1327 current_provider
= conf
->providers
;
1329 const authn_provider
*provider
;
1331 /* For now, if a provider isn't set, we'll be nice and use the file
1334 if (!current_provider
) {
1335 provider
= ap_lookup_provider(AUTHN_PROVIDER_GROUP
,
1336 AUTHN_DEFAULT_PROVIDER
,
1337 AUTHN_PROVIDER_VERSION
);
1339 if (!provider
|| !provider
->get_realm_hash
) {
1340 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1341 "No Authn provider configured");
1342 auth_result
= AUTH_GENERAL_ERROR
;
1345 apr_table_setn(r
->notes
, AUTHN_PROVIDER_NAME_NOTE
, AUTHN_DEFAULT_PROVIDER
);
1348 provider
= current_provider
->provider
;
1349 apr_table_setn(r
->notes
, AUTHN_PROVIDER_NAME_NOTE
, current_provider
->provider_name
);
1353 /* We expect the password to be md5 hash of user:realm:password */
1354 auth_result
= provider
->get_realm_hash(r
, user
, conf
->realm
,
1357 apr_table_unset(r
->notes
, AUTHN_PROVIDER_NAME_NOTE
);
1359 /* Something occured. Stop checking. */
1360 if (auth_result
!= AUTH_USER_NOT_FOUND
) {
1364 /* If we're not really configured for providers, stop now. */
1365 if (!conf
->providers
) {
1369 current_provider
= current_provider
->next
;
1370 } while (current_provider
);
1372 if (auth_result
== AUTH_USER_FOUND
) {
1373 conf
->ha1
= password
;
1379 static int check_nc(const request_rec
*r
, const digest_header_rec
*resp
,
1380 const digest_config_rec
*conf
)
1383 const char *snc
= resp
->nonce_count
;
1386 if (!conf
->check_nc
|| !client_shm
) {
1390 nc
= strtol(snc
, &endptr
, 16);
1391 if (endptr
< (snc
+strlen(snc
)) && !apr_isspace(*endptr
)) {
1392 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1393 "Digest: invalid nc %s received - not a number", snc
);
1397 if (!resp
->client
) {
1401 if (nc
!= resp
->client
->nonce_count
) {
1402 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1403 "Digest: Warning, possible replay attack: nonce-count "
1404 "check failed: %lu != %lu", nc
,
1405 resp
->client
->nonce_count
);
1412 static int check_nonce(request_rec
*r
, digest_header_rec
*resp
,
1413 const digest_config_rec
*conf
)
1417 time_rec nonce_time
;
1418 char tmp
, hash
[NONCE_HASH_LEN
+1];
1420 if (strlen(resp
->nonce
) != NONCE_LEN
) {
1421 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1422 "Digest: invalid nonce %s received - length is not %d",
1423 resp
->nonce
, NONCE_LEN
);
1424 note_digest_auth_failure(r
, conf
, resp
, 1);
1425 return HTTP_UNAUTHORIZED
;
1428 tmp
= resp
->nonce
[NONCE_TIME_LEN
];
1429 resp
->nonce
[NONCE_TIME_LEN
] = '\0';
1430 len
= apr_base64_decode_binary(nonce_time
.arr
, resp
->nonce
);
1431 gen_nonce_hash(hash
, resp
->nonce
, resp
->opaque
, r
->server
, conf
);
1432 resp
->nonce
[NONCE_TIME_LEN
] = tmp
;
1433 resp
->nonce_time
= nonce_time
.time
;
1435 if (strcmp(hash
, resp
->nonce
+NONCE_TIME_LEN
)) {
1436 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1437 "Digest: invalid nonce %s received - hash is not %s",
1439 note_digest_auth_failure(r
, conf
, resp
, 1);
1440 return HTTP_UNAUTHORIZED
;
1443 dt
= r
->request_time
- nonce_time
.time
;
1444 if (conf
->nonce_lifetime
> 0 && dt
< 0) {
1445 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1446 "Digest: invalid nonce %s received - user attempted "
1447 "time travel", resp
->nonce
);
1448 note_digest_auth_failure(r
, conf
, resp
, 1);
1449 return HTTP_UNAUTHORIZED
;
1452 if (conf
->nonce_lifetime
> 0) {
1453 if (dt
> conf
->nonce_lifetime
) {
1454 ap_log_rerror(APLOG_MARK
, APLOG_INFO
, 0,r
,
1455 "Digest: user %s: nonce expired (%.2f seconds old "
1456 "- max lifetime %.2f) - sending new nonce",
1457 r
->user
, (double)apr_time_sec(dt
),
1458 (double)apr_time_sec(conf
->nonce_lifetime
));
1459 note_digest_auth_failure(r
, conf
, resp
, 1);
1460 return HTTP_UNAUTHORIZED
;
1463 else if (conf
->nonce_lifetime
== 0 && resp
->client
) {
1464 if (memcmp(resp
->client
->last_nonce
, resp
->nonce
, NONCE_LEN
)) {
1465 ap_log_rerror(APLOG_MARK
, APLOG_INFO
, 0, r
,
1466 "Digest: user %s: one-time-nonce mismatch - sending "
1467 "new nonce", r
->user
);
1468 note_digest_auth_failure(r
, conf
, resp
, 1);
1469 return HTTP_UNAUTHORIZED
;
1472 /* else (lifetime < 0) => never expires */
1477 /* The actual MD5 code... whee */
1480 static const char *old_digest(const request_rec
*r
,
1481 const digest_header_rec
*resp
, const char *ha1
)
1485 ha2
= ap_md5(r
->pool
, (unsigned char *)apr_pstrcat(r
->pool
, resp
->method
, ":",
1487 return ap_md5(r
->pool
,
1488 (unsigned char *)apr_pstrcat(r
->pool
, ha1
, ":", resp
->nonce
,
1493 static const char *new_digest(const request_rec
*r
,
1494 digest_header_rec
*resp
,
1495 const digest_config_rec
*conf
)
1497 const char *ha1
, *ha2
, *a2
;
1499 if (resp
->algorithm
&& !strcasecmp(resp
->algorithm
, "MD5-sess")) {
1500 ha1
= get_session_HA1(r
, resp
, conf
, 1);
1509 if (resp
->message_qop
&& !strcasecmp(resp
->message_qop
, "auth-int")) {
1510 a2
= apr_pstrcat(r
->pool
, resp
->method
, ":", resp
->uri
, ":",
1511 ap_md5(r
->pool
, (const unsigned char*) ""), NULL
);
1515 a2
= apr_pstrcat(r
->pool
, resp
->method
, ":", resp
->uri
, NULL
);
1517 ha2
= ap_md5(r
->pool
, (const unsigned char *)a2
);
1519 return ap_md5(r
->pool
,
1520 (unsigned char *)apr_pstrcat(r
->pool
, ha1
, ":", resp
->nonce
,
1521 ":", resp
->nonce_count
, ":",
1523 resp
->message_qop
, ":", ha2
,
1528 static void copy_uri_components(apr_uri_t
*dst
,
1529 apr_uri_t
*src
, request_rec
*r
) {
1530 if (src
->scheme
&& src
->scheme
[0] != '\0') {
1531 dst
->scheme
= src
->scheme
;
1534 dst
->scheme
= (char *) "http";
1537 if (src
->hostname
&& src
->hostname
[0] != '\0') {
1538 dst
->hostname
= apr_pstrdup(r
->pool
, src
->hostname
);
1539 ap_unescape_url(dst
->hostname
);
1542 dst
->hostname
= (char *) ap_get_server_name(r
);
1545 if (src
->port_str
&& src
->port_str
[0] != '\0') {
1546 dst
->port
= src
->port
;
1549 dst
->port
= ap_get_server_port(r
);
1552 if (src
->path
&& src
->path
[0] != '\0') {
1553 dst
->path
= apr_pstrdup(r
->pool
, src
->path
);
1554 ap_unescape_url(dst
->path
);
1557 dst
->path
= src
->path
;
1560 if (src
->query
&& src
->query
[0] != '\0') {
1561 dst
->query
= apr_pstrdup(r
->pool
, src
->query
);
1562 ap_unescape_url(dst
->query
);
1565 dst
->query
= src
->query
;
1568 dst
->hostinfo
= src
->hostinfo
;
1571 /* These functions return 0 if client is OK, and proper error status
1572 * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
1573 * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
1574 * couldn't figure out how to tell if the client is authorized or not.
1576 * If they return DECLINED, and all other modules also decline, that's
1577 * treated by the server core as a configuration error, logged and
1581 /* Determine user ID, and check if the attributes are correct, if it
1582 * really is that user, if the nonce is correct, etc.
1585 static int authenticate_digest_user(request_rec
*r
)
1587 digest_config_rec
*conf
;
1588 digest_header_rec
*resp
;
1589 request_rec
*mainreq
;
1592 authn_status return_code
;
1594 /* do we require Digest auth for this URI? */
1596 if (!(t
= ap_auth_type(r
)) || strcasecmp(t
, "Digest")) {
1600 if (!ap_auth_name(r
)) {
1601 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1602 "Digest: need AuthName: %s", r
->uri
);
1603 return HTTP_INTERNAL_SERVER_ERROR
;
1607 /* get the client response and mark */
1610 while (mainreq
->main
!= NULL
) {
1611 mainreq
= mainreq
->main
;
1613 while (mainreq
->prev
!= NULL
) {
1614 mainreq
= mainreq
->prev
;
1616 resp
= (digest_header_rec
*) ap_get_module_config(mainreq
->request_config
,
1617 &auth_digest_module
);
1618 resp
->needed_auth
= 1;
1623 conf
= (digest_config_rec
*) ap_get_module_config(r
->per_dir_config
,
1624 &auth_digest_module
);
1627 /* check for existence and syntax of Auth header */
1629 if (resp
->auth_hdr_sts
!= VALID
) {
1630 if (resp
->auth_hdr_sts
== NOT_DIGEST
) {
1631 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1632 "Digest: client used wrong authentication scheme "
1633 "`%s': %s", resp
->scheme
, r
->uri
);
1635 else if (resp
->auth_hdr_sts
== INVALID
) {
1636 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1637 "Digest: missing user, realm, nonce, uri, digest, "
1638 "cnonce, or nonce_count in authorization header: %s",
1641 /* else (resp->auth_hdr_sts == NO_HEADER) */
1642 note_digest_auth_failure(r
, conf
, resp
, 0);
1643 return HTTP_UNAUTHORIZED
;
1646 r
->user
= (char *) resp
->username
;
1647 r
->ap_auth_type
= (char *) "Digest";
1649 /* check the auth attributes */
1651 if (strcmp(resp
->uri
, resp
->raw_request_uri
)) {
1652 /* Hmm, the simple match didn't work (probably a proxy modified the
1653 * request-uri), so lets do a more sophisticated match
1655 apr_uri_t r_uri
, d_uri
;
1657 copy_uri_components(&r_uri
, resp
->psd_request_uri
, r
);
1658 if (apr_uri_parse(r
->pool
, resp
->uri
, &d_uri
) != APR_SUCCESS
) {
1659 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1660 "Digest: invalid uri <%s> in Authorization header",
1662 return HTTP_BAD_REQUEST
;
1665 if (d_uri
.hostname
) {
1666 ap_unescape_url(d_uri
.hostname
);
1669 ap_unescape_url(d_uri
.path
);
1673 ap_unescape_url(d_uri
.query
);
1675 else if (r_uri
.query
) {
1676 /* MSIE compatibility hack. MSIE has some RFC issues - doesn't
1677 * include the query string in the uri Authorization component
1678 * or when computing the response component. the second part
1679 * works out ok, since we can hash the header and get the same
1680 * result. however, the uri from the request line won't match
1681 * the uri Authorization component since the header lacks the
1682 * query string, leaving us incompatable with a (broken) MSIE.
1684 * the workaround is to fake a query string match if in the proper
1685 * environment - BrowserMatch MSIE, for example. the cool thing
1686 * is that if MSIE ever fixes itself the simple match ought to
1687 * work and this code won't be reached anyway, even if the
1688 * environment is set.
1691 if (apr_table_get(r
->subprocess_env
,
1692 "AuthDigestEnableQueryStringHack")) {
1694 ap_log_rerror(APLOG_MARK
, APLOG_INFO
, 0, r
, "Digest: "
1695 "applying AuthDigestEnableQueryStringHack "
1696 "to uri <%s>", resp
->raw_request_uri
);
1698 d_uri
.query
= r_uri
.query
;
1702 if (r
->method_number
== M_CONNECT
) {
1703 if (!r_uri
.hostinfo
|| strcmp(resp
->uri
, r_uri
.hostinfo
)) {
1704 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1705 "Digest: uri mismatch - <%s> does not match "
1706 "request-uri <%s>", resp
->uri
, r_uri
.hostinfo
);
1707 return HTTP_BAD_REQUEST
;
1711 /* check hostname matches, if present */
1712 (d_uri
.hostname
&& d_uri
.hostname
[0] != '\0'
1713 && strcasecmp(d_uri
.hostname
, r_uri
.hostname
))
1714 /* check port matches, if present */
1715 || (d_uri
.port_str
&& d_uri
.port
!= r_uri
.port
)
1716 /* check that server-port is default port if no port present */
1717 || (d_uri
.hostname
&& d_uri
.hostname
[0] != '\0'
1718 && !d_uri
.port_str
&& r_uri
.port
!= ap_default_port(r
))
1719 /* check that path matches */
1720 || (d_uri
.path
!= r_uri
.path
1721 /* either exact match */
1722 && (!d_uri
.path
|| !r_uri
.path
1723 || strcmp(d_uri
.path
, r_uri
.path
))
1724 /* or '*' matches empty path in scheme://host */
1725 && !(d_uri
.path
&& !r_uri
.path
&& resp
->psd_request_uri
->hostname
1726 && d_uri
.path
[0] == '*' && d_uri
.path
[1] == '\0'))
1727 /* check that query matches */
1728 || (d_uri
.query
!= r_uri
.query
1729 && (!d_uri
.query
|| !r_uri
.query
1730 || strcmp(d_uri
.query
, r_uri
.query
)))
1732 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1733 "Digest: uri mismatch - <%s> does not match "
1734 "request-uri <%s>", resp
->uri
, resp
->raw_request_uri
);
1735 return HTTP_BAD_REQUEST
;
1739 if (resp
->opaque
&& resp
->opaque_num
== 0) {
1740 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1741 "Digest: received invalid opaque - got `%s'",
1743 note_digest_auth_failure(r
, conf
, resp
, 0);
1744 return HTTP_UNAUTHORIZED
;
1747 if (strcmp(resp
->realm
, conf
->realm
)) {
1748 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1749 "Digest: realm mismatch - got `%s' but expected `%s'",
1750 resp
->realm
, conf
->realm
);
1751 note_digest_auth_failure(r
, conf
, resp
, 0);
1752 return HTTP_UNAUTHORIZED
;
1755 if (resp
->algorithm
!= NULL
1756 && strcasecmp(resp
->algorithm
, "MD5")
1757 && strcasecmp(resp
->algorithm
, "MD5-sess")) {
1758 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1759 "Digest: unknown algorithm `%s' received: %s",
1760 resp
->algorithm
, r
->uri
);
1761 note_digest_auth_failure(r
, conf
, resp
, 0);
1762 return HTTP_UNAUTHORIZED
;
1765 return_code
= get_hash(r
, r
->user
, conf
);
1767 if (return_code
== AUTH_USER_NOT_FOUND
) {
1768 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1769 "Digest: user `%s' in realm `%s' not found: %s",
1770 r
->user
, conf
->realm
, r
->uri
);
1771 note_digest_auth_failure(r
, conf
, resp
, 0);
1772 return HTTP_UNAUTHORIZED
;
1774 else if (return_code
== AUTH_USER_FOUND
) {
1775 /* we have a password, so continue */
1777 else if (return_code
== AUTH_DENIED
) {
1778 /* authentication denied in the provider before attempting a match */
1779 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1780 "Digest: user `%s' in realm `%s' denied by provider: %s",
1781 r
->user
, conf
->realm
, r
->uri
);
1782 note_digest_auth_failure(r
, conf
, resp
, 0);
1783 return HTTP_UNAUTHORIZED
;
1786 /* AUTH_GENERAL_ERROR (or worse)
1787 * We'll assume that the module has already said what its error
1790 return HTTP_INTERNAL_SERVER_ERROR
;
1793 if (resp
->message_qop
== NULL
) {
1794 /* old (rfc-2069) style digest */
1795 if (strcmp(resp
->digest
, old_digest(r
, resp
, conf
->ha1
))) {
1796 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1797 "Digest: user %s: password mismatch: %s", r
->user
,
1799 note_digest_auth_failure(r
, conf
, resp
, 0);
1800 return HTTP_UNAUTHORIZED
;
1804 const char *exp_digest
;
1806 for (idx
= 0; conf
->qop_list
[idx
] != NULL
; idx
++) {
1807 if (!strcasecmp(conf
->qop_list
[idx
], resp
->message_qop
)) {
1814 && !(conf
->qop_list
[0] == NULL
1815 && !strcasecmp(resp
->message_qop
, "auth"))) {
1816 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1817 "Digest: invalid qop `%s' received: %s",
1818 resp
->message_qop
, r
->uri
);
1819 note_digest_auth_failure(r
, conf
, resp
, 0);
1820 return HTTP_UNAUTHORIZED
;
1823 exp_digest
= new_digest(r
, resp
, conf
);
1825 /* we failed to allocate a client struct */
1826 return HTTP_INTERNAL_SERVER_ERROR
;
1828 if (strcmp(resp
->digest
, exp_digest
)) {
1829 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1830 "Digest: user %s: password mismatch: %s", r
->user
,
1832 note_digest_auth_failure(r
, conf
, resp
, 0);
1833 return HTTP_UNAUTHORIZED
;
1837 if (check_nc(r
, resp
, conf
) != OK
) {
1838 note_digest_auth_failure(r
, conf
, resp
, 0);
1839 return HTTP_UNAUTHORIZED
;
1842 /* Note: this check is done last so that a "stale=true" can be
1843 generated if the nonce is old */
1844 if ((res
= check_nonce(r
, resp
, conf
))) {
1852 * Authorization-Info header code
1855 static int add_auth_info(request_rec
*r
)
1857 const digest_config_rec
*conf
=
1858 (digest_config_rec
*) ap_get_module_config(r
->per_dir_config
,
1859 &auth_digest_module
);
1860 digest_header_rec
*resp
=
1861 (digest_header_rec
*) ap_get_module_config(r
->request_config
,
1862 &auth_digest_module
);
1863 const char *ai
= NULL
, *nextnonce
= "";
1865 if (resp
== NULL
|| !resp
->needed_auth
|| conf
== NULL
) {
1869 /* 2069-style entity-digest is not supported (it's too hard, and
1870 * there are no clients which support 2069 but not 2617). */
1874 if (conf
->nonce_lifetime
> 0) {
1875 /* send nextnonce if current nonce will expire in less than 30 secs */
1876 if ((r
->request_time
- resp
->nonce_time
) > (conf
->nonce_lifetime
-NEXTNONCE_DELTA
)) {
1877 nextnonce
= apr_pstrcat(r
->pool
, ", nextnonce=\"",
1878 gen_nonce(r
->pool
, r
->request_time
,
1879 resp
->opaque
, r
->server
, conf
),
1882 resp
->client
->nonce_count
= 0;
1885 else if (conf
->nonce_lifetime
== 0 && resp
->client
) {
1886 const char *nonce
= gen_nonce(r
->pool
, 0, resp
->opaque
, r
->server
,
1888 nextnonce
= apr_pstrcat(r
->pool
, ", nextnonce=\"", nonce
, "\"", NULL
);
1889 memcpy(resp
->client
->last_nonce
, nonce
, NONCE_LEN
+1);
1891 /* else nonce never expires, hence no nextnonce */
1894 /* do rfc-2069 digest
1896 if (conf
->qop_list
[0] && !strcasecmp(conf
->qop_list
[0], "none")
1897 && resp
->message_qop
== NULL
) {
1898 /* use only RFC-2069 format */
1902 const char *resp_dig
, *ha1
, *a2
, *ha2
;
1904 /* calculate rspauth attribute
1906 if (resp
->algorithm
&& !strcasecmp(resp
->algorithm
, "MD5-sess")) {
1907 ha1
= get_session_HA1(r
, resp
, conf
, 0);
1909 ap_log_rerror(APLOG_MARK
, APLOG_ERR
, 0, r
,
1910 "Digest: internal error: couldn't find session "
1911 "info for user %s", resp
->username
);
1919 if (resp
->message_qop
&& !strcasecmp(resp
->message_qop
, "auth-int")) {
1920 a2
= apr_pstrcat(r
->pool
, ":", resp
->uri
, ":",
1921 ap_md5(r
->pool
,(const unsigned char *) ""), NULL
);
1925 a2
= apr_pstrcat(r
->pool
, ":", resp
->uri
, NULL
);
1927 ha2
= ap_md5(r
->pool
, (const unsigned char *)a2
);
1929 resp_dig
= ap_md5(r
->pool
,
1930 (unsigned char *)apr_pstrcat(r
->pool
, ha1
, ":",
1932 resp
->nonce_count
, ":",
1935 resp
->message_qop
: "",
1938 /* assemble Authentication-Info header
1940 ai
= apr_pstrcat(r
->pool
,
1941 "rspauth=\"", resp_dig
, "\"",
1943 resp
->cnonce
? ", cnonce=\"" : "",
1945 ? ap_escape_quotes(r
->pool
, resp
->cnonce
)
1947 resp
->cnonce
? "\"" : "",
1948 resp
->nonce_count
? ", nc=" : "",
1949 resp
->nonce_count
? resp
->nonce_count
: "",
1950 resp
->message_qop
? ", qop=" : "",
1951 resp
->message_qop
? resp
->message_qop
: "",
1956 apr_table_mergen(r
->headers_out
,
1957 (PROXYREQ_PROXY
== r
->proxyreq
)
1958 ? "Proxy-Authentication-Info"
1959 : "Authentication-Info",
1966 static void register_hooks(apr_pool_t
*p
)
1968 static const char * const cfgPost
[]={ "http_core.c", NULL
};
1969 static const char * const parsePre
[]={ "mod_proxy.c", NULL
};
1971 ap_hook_post_config(initialize_module
, NULL
, cfgPost
, APR_HOOK_MIDDLE
);
1972 ap_hook_child_init(initialize_child
, NULL
, NULL
, APR_HOOK_MIDDLE
);
1973 ap_hook_post_read_request(parse_hdr_and_update_nc
, parsePre
, NULL
, APR_HOOK_MIDDLE
);
1974 ap_hook_check_authn(authenticate_digest_user
, NULL
, NULL
, APR_HOOK_MIDDLE
,
1975 AP_AUTH_INTERNAL_PER_CONF
);
1977 ap_hook_fixups(add_auth_info
, NULL
, NULL
, APR_HOOK_MIDDLE
);
1980 module AP_MODULE_DECLARE_DATA auth_digest_module
=
1982 STANDARD20_MODULE_STUFF
,
1983 create_digest_dir_config
, /* dir config creater */
1984 NULL
, /* dir merger --- default is to override */
1985 NULL
, /* server config */
1986 NULL
, /* merge server config */
1987 digest_cmds
, /* command table */
1988 register_hooks
/* register hooks */