bottleneck testcase based on rubbos
[bottlenecks.git] / rubbos / app / httpd-2.0.64 / modules / aaa / mod_auth_digest.c
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /*
18  * mod_auth_digest: MD5 digest authentication
19  *
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
23  *
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.
28  *
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
32  *
33  * Open Issues:
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
39  *     truerand library
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.  
55  */
56
57 #include "apr_sha1.h"
58 #include "apr_base64.h"
59 #include "apr_lib.h"
60 #include "apr_time.h"
61 #include "apr_errno.h"
62 #include "apr_global_mutex.h"
63 #include "apr_strings.h"
64
65 #define APR_WANT_STRFUNC
66 #include "apr_want.h"
67
68 #include "ap_config.h"
69 #include "httpd.h"
70 #include "http_config.h"
71 #include "http_core.h"
72 #include "http_request.h"
73 #include "http_log.h"
74 #include "http_protocol.h"
75 #include "apr_uri.h"
76 #include "util_md5.h"
77 #include "apr_shm.h"
78 #include "apr_rmm.h"
79
80 /* Disable shmem until pools/init gets sorted out 
81  * remove following two lines when fixed 
82  */
83 #undef APR_HAS_SHARED_MEMORY
84 #define APR_HAS_SHARED_MEMORY 0
85
86 /* struct to hold the configuration info */
87
88 typedef struct digest_config_struct {
89     const char  *dir_name;
90     const char  *pwfile;
91     const char  *grpfile;
92     const char  *realm;
93     char **qop_list;
94     apr_sha1_ctx_t  nonce_ctx;
95     apr_time_t    nonce_lifetime;
96     const char  *nonce_format;
97     int          check_nc;
98     const char  *algorithm;
99     char        *uri_list;
100     const char  *ha1;
101 } digest_config_rec;
102
103
104 #define DFLT_ALGORITHM  "MD5"
105
106 #define DFLT_NONCE_LIFE apr_time_from_sec(300)
107 #define NEXTNONCE_DELTA apr_time_from_sec(30)
108
109
110 #define NONCE_TIME_LEN  (((sizeof(apr_time_t)+2)/3)*4)
111 #define NONCE_HASH_LEN  (2*APR_SHA1_DIGESTSIZE)
112 #define NONCE_LEN       (int )(NONCE_TIME_LEN + NONCE_HASH_LEN)
113
114 #define SECRET_LEN      20
115
116
117 /* client list definitions */
118
119 typedef struct hash_entry {
120     unsigned long      key;                     /* the key for this entry    */
121     struct hash_entry *next;                    /* next entry in the bucket  */
122     unsigned long      nonce_count;             /* for nonce-count checking  */
123     char               ha1[2*MD5_DIGESTSIZE+1]; /* for algorithm=MD5-sess    */
124     char               last_nonce[NONCE_LEN+1]; /* for one-time nonce's      */
125 } client_entry;
126
127 static struct hash_table {
128     client_entry  **table;
129     unsigned long   tbl_len;
130     unsigned long   num_entries;
131     unsigned long   num_created;
132     unsigned long   num_removed;
133     unsigned long   num_renewed;
134 } *client_list;
135
136
137 /* struct to hold a parsed Authorization header */
138
139 enum hdr_sts { NO_HEADER, NOT_DIGEST, INVALID, VALID };
140
141 typedef struct digest_header_struct {
142     const char           *scheme;
143     const char           *realm;
144     const char           *username;
145           char           *nonce;
146     const char           *uri;
147     const char           *method;
148     const char           *digest;
149     const char           *algorithm;
150     const char           *cnonce;
151     const char           *opaque;
152     unsigned long         opaque_num;
153     const char           *message_qop;
154     const char           *nonce_count;
155     /* the following fields are not (directly) from the header */
156     apr_time_t            nonce_time;
157     enum hdr_sts          auth_hdr_sts;
158     const char           *raw_request_uri;
159     apr_uri_t            *psd_request_uri;
160     int                   needed_auth;
161     client_entry         *client;
162 } digest_header_rec;
163
164
165 /* (mostly) nonce stuff */
166
167 typedef union time_union {
168     apr_time_t    time;
169     unsigned char arr[sizeof(apr_time_t)];
170 } time_rec;
171
172 static unsigned char secret[SECRET_LEN];
173
174 /* client-list, opaque, and one-time-nonce stuff */
175
176 static apr_shm_t      *client_shm =  NULL;
177 static apr_rmm_t      *client_rmm = NULL;
178 static unsigned long  *opaque_cntr;
179 static apr_time_t     *otn_counter;     /* one-time-nonce counter */
180 static apr_global_mutex_t *client_lock = NULL;
181 static apr_global_mutex_t *opaque_lock = NULL;
182 static char           client_lock_name[L_tmpnam];
183 static char           opaque_lock_name[L_tmpnam];
184
185 #define DEF_SHMEM_SIZE  1000L           /* ~ 12 entries */
186 #define DEF_NUM_BUCKETS 15L
187 #define HASH_DEPTH      5
188
189 static long shmem_size  = DEF_SHMEM_SIZE;
190 static long num_buckets = DEF_NUM_BUCKETS;
191
192
193 module AP_MODULE_DECLARE_DATA auth_digest_module;
194
195 /*
196  * initialization code
197  */
198
199 static apr_status_t cleanup_tables(void *not_used)
200 {
201     ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
202                   "Digest: cleaning up shared memory");
203     fflush(stderr);
204
205     if (client_shm) {
206         apr_shm_destroy(client_shm);
207         client_shm = NULL;
208     }
209
210     if (client_lock) {
211         apr_global_mutex_destroy(client_lock);
212         client_lock = NULL;
213     }
214
215     if (opaque_lock) {
216         apr_global_mutex_destroy(opaque_lock);
217         opaque_lock = NULL;
218     }
219
220     return APR_SUCCESS;
221 }
222
223 static apr_status_t initialize_secret(server_rec *s)
224 {
225     apr_status_t status;
226
227     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s,
228                  "Digest: generating secret for digest authentication ...");
229
230 #if APR_HAS_RANDOM
231     status = apr_generate_random_bytes(secret, sizeof(secret));
232 #else
233 #error APR random number support is missing; you probably need to install the truerand library.
234 #endif
235
236     if (status != APR_SUCCESS) {
237         char buf[120];
238         ap_log_error(APLOG_MARK, APLOG_CRIT, status, s,
239                      "Digest: error generating secret: %s", 
240                      apr_strerror(status, buf, sizeof(buf)));
241         return status;
242     }
243
244     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, "Digest: done");
245
246     return APR_SUCCESS;
247 }
248
249 static void log_error_and_cleanup(char *msg, apr_status_t sts, server_rec *s)
250 {
251     ap_log_error(APLOG_MARK, APLOG_ERR, sts, s,
252                  "Digest: %s - all nonce-count checking, one-time nonces, and "
253                  "MD5-sess algorithm disabled", msg);
254
255     cleanup_tables(NULL);
256 }
257
258 #if APR_HAS_SHARED_MEMORY
259
260 static void initialize_tables(server_rec *s, apr_pool_t *ctx)
261 {
262     unsigned long idx;
263     apr_status_t   sts;
264
265     /* set up client list */
266
267     sts = apr_shm_create(&client_shm, shmem_size, tmpnam(NULL), ctx);
268     if (sts != APR_SUCCESS) {
269         log_error_and_cleanup("failed to create shared memory segments", sts, s);
270         return;
271     }
272
273     client_list = apr_rmm_malloc(client_rmm, sizeof(*client_list) +
274                                             sizeof(client_entry*)*num_buckets);
275     if (!client_list) {
276         log_error_and_cleanup("failed to allocate shared memory", -1, s);
277         return;
278     }
279     client_list->table = (client_entry**) (client_list + 1);
280     for (idx = 0; idx < num_buckets; idx++) {
281         client_list->table[idx] = NULL;
282     }
283     client_list->tbl_len     = num_buckets;
284     client_list->num_entries = 0;
285
286     tmpnam(client_lock_name);
287     /* FIXME: get the client_lock_name from a directive so we're portable
288      * to non-process-inheriting operating systems, like Win32. */
289     sts = apr_global_mutex_create(&client_lock, client_lock_name,
290                                   APR_LOCK_DEFAULT, ctx);
291     if (sts != APR_SUCCESS) {
292         log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
293         return;
294     }
295
296
297     /* setup opaque */
298
299     opaque_cntr = apr_rmm_malloc(client_rmm, sizeof(*opaque_cntr));
300     if (opaque_cntr == NULL) {
301         log_error_and_cleanup("failed to allocate shared memory", -1, s);
302         return;
303     }
304     *opaque_cntr = 1UL;
305
306     tmpnam(opaque_lock_name);
307     /* FIXME: get the opaque_lock_name from a directive so we're portable
308      * to non-process-inheriting operating systems, like Win32. */
309     sts = apr_global_mutex_create(&opaque_lock, opaque_lock_name,
310                                   APR_LOCK_DEFAULT, ctx);
311     if (sts != APR_SUCCESS) {
312         log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
313         return;
314     }
315
316
317     /* setup one-time-nonce counter */
318
319     otn_counter = apr_rmm_malloc(client_rmm, sizeof(*otn_counter));
320     if (otn_counter == NULL) {
321         log_error_and_cleanup("failed to allocate shared memory", -1, s);
322         return;
323     }
324     *otn_counter = 0;
325     /* no lock here */
326
327
328     /* success */
329     return;
330 }
331
332 #endif /* APR_HAS_SHARED_MEMORY */
333
334
335 static int initialize_module(apr_pool_t *p, apr_pool_t *plog,
336                              apr_pool_t *ptemp, server_rec *s)
337 {
338     void *data;
339     const char *userdata_key = "auth_digest_init";
340
341     /* initialize_module() will be called twice, and if it's a DSO
342      * then all static data from the first call will be lost. Only
343      * set up our static data on the second call. */
344     apr_pool_userdata_get(&data, userdata_key, s->process->pool);
345     if (!data) {
346         apr_pool_userdata_set((const void *)1, userdata_key,
347                                apr_pool_cleanup_null, s->process->pool);
348         return OK;
349     }
350     if (initialize_secret(s) != APR_SUCCESS) {
351         return !OK;
352     }
353
354 #if APR_HAS_SHARED_MEMORY
355     /* Note: this stuff is currently fixed for the lifetime of the server,
356      * i.e. even across restarts. This means that A) any shmem-size
357      * configuration changes are ignored, and B) certain optimizations,
358      * such as only allocating the smallest necessary entry for each
359      * client, can't be done. However, the alternative is a nightmare:
360      * we can't call apr_shm_destroy on a graceful restart because there
361      * will be children using the tables, and we also don't know when the
362      * last child dies. Therefore we can never clean up the old stuff,
363      * creating a creeping memory leak.
364      */
365     initialize_tables(s, p);
366     apr_pool_cleanup_register(p, NULL, cleanup_tables, apr_pool_cleanup_null);
367 #endif  /* APR_HAS_SHARED_MEMORY */
368     return OK;
369 }
370
371 static void initialize_child(apr_pool_t *p, server_rec *s)
372 {
373     apr_status_t sts;
374
375     if (!client_shm) {
376         return;
377     }
378
379     /* FIXME: get the client_lock_name from a directive so we're portable
380      * to non-process-inheriting operating systems, like Win32. */
381     sts = apr_global_mutex_child_init(&client_lock, client_lock_name, p);
382     if (sts != APR_SUCCESS) {
383         log_error_and_cleanup("failed to create lock (client_lock)", sts, s);
384         return;
385     }
386     /* FIXME: get the opaque_lock_name from a directive so we're portable
387      * to non-process-inheriting operating systems, like Win32. */
388     sts = apr_global_mutex_child_init(&opaque_lock, opaque_lock_name, p);
389     if (sts != APR_SUCCESS) {
390         log_error_and_cleanup("failed to create lock (opaque_lock)", sts, s);
391         return;
392     }
393 }
394
395 /*
396  * configuration code
397  */
398
399 static void *create_digest_dir_config(apr_pool_t *p, char *dir)
400 {
401     digest_config_rec *conf;
402
403     if (dir == NULL) {
404         return NULL;
405     }
406
407     conf = (digest_config_rec *) apr_pcalloc(p, sizeof(digest_config_rec));
408     if (conf) {
409         conf->qop_list       = apr_palloc(p, sizeof(char*));
410         conf->qop_list[0]    = NULL;
411         conf->nonce_lifetime = DFLT_NONCE_LIFE;
412         conf->dir_name       = apr_pstrdup(p, dir);
413         conf->algorithm      = DFLT_ALGORITHM;
414     }
415
416     return conf;
417 }
418
419 static const char *set_realm(cmd_parms *cmd, void *config, const char *realm)
420 {
421     digest_config_rec *conf = (digest_config_rec *) config;
422
423     /* The core already handles the realm, but it's just too convenient to
424      * grab it ourselves too and cache some setups. However, we need to
425      * let the core get at it too, which is why we decline at the end -
426      * this relies on the fact that http_core is last in the list.
427      */
428     conf->realm = realm;
429
430     /* we precompute the part of the nonce hash that is constant (well,
431      * the host:port would be too, but that varies for .htaccess files
432      * and directives outside a virtual host section)
433      */
434     apr_sha1_init(&conf->nonce_ctx);
435     apr_sha1_update_binary(&conf->nonce_ctx, secret, sizeof(secret));
436     apr_sha1_update_binary(&conf->nonce_ctx, (const unsigned char *) realm,
437                            strlen(realm));
438
439     return DECLINE_CMD;
440 }
441
442 static const char *set_digest_file(cmd_parms *cmd, void *config,
443                                    const char *file)
444 {
445     ((digest_config_rec *) config)->pwfile = file;
446     return NULL;
447 }
448
449 static const char *set_group_file(cmd_parms *cmd, void *config,
450                                   const char *file)
451 {
452     ((digest_config_rec *) config)->grpfile = file;
453     return NULL;
454 }
455
456 static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
457 {
458     digest_config_rec *conf = (digest_config_rec *) config;
459     char **tmp;
460     int cnt;
461
462     if (!strcasecmp(op, "none")) {
463         if (conf->qop_list[0] == NULL) {
464             conf->qop_list = apr_palloc(cmd->pool, 2 * sizeof(char*));
465             conf->qop_list[1] = NULL;
466         }
467         conf->qop_list[0] = "none";
468         return NULL;
469     }
470
471     if (!strcasecmp(op, "auth-int")) {
472         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
473                      "Digest: WARNING: qop `auth-int' currently only works "
474                      "correctly for responses with no entity");
475     }
476     else if (strcasecmp(op, "auth")) {
477         return apr_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
478     }
479
480     for (cnt = 0; conf->qop_list[cnt] != NULL; cnt++)
481         ;
482
483     tmp = apr_palloc(cmd->pool, (cnt + 2) * sizeof(char*));
484     memcpy(tmp, conf->qop_list, cnt*sizeof(char*));
485     tmp[cnt]   = apr_pstrdup(cmd->pool, op);
486     tmp[cnt+1] = NULL;
487     conf->qop_list = tmp;
488
489     return NULL;
490 }
491
492 static const char *set_nonce_lifetime(cmd_parms *cmd, void *config,
493                                       const char *t)
494 {
495     char *endptr;
496     long  lifetime;
497
498     lifetime = strtol(t, &endptr, 10); 
499     if (endptr < (t+strlen(t)) && !apr_isspace(*endptr)) {
500         return apr_pstrcat(cmd->pool,
501                            "Invalid time in AuthDigestNonceLifetime: ",
502                            t, NULL);
503     }
504
505     ((digest_config_rec *) config)->nonce_lifetime = apr_time_from_sec(lifetime);
506     return NULL;
507 }
508
509 static const char *set_nonce_format(cmd_parms *cmd, void *config,
510                                     const char *fmt)
511 {
512     ((digest_config_rec *) config)->nonce_format = fmt;
513     return "AuthDigestNonceFormat is not implemented (yet)";
514 }
515
516 static const char *set_nc_check(cmd_parms *cmd, void *config, int flag)
517 {
518     if (flag && !client_shm)
519         ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
520                      cmd->server, "Digest: WARNING: nonce-count checking "
521                      "is not supported on platforms without shared-memory "
522                      "support - disabling check");
523
524     ((digest_config_rec *) config)->check_nc = flag;
525     return NULL;
526 }
527
528 static const char *set_algorithm(cmd_parms *cmd, void *config, const char *alg)
529 {
530     if (!strcasecmp(alg, "MD5-sess")) {
531         if (!client_shm) {
532             ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
533                          cmd->server, "Digest: WARNING: algorithm `MD5-sess' "
534                          "is not supported on platforms without shared-memory "
535                          "support - reverting to MD5");
536             alg = "MD5";
537         }
538     }
539     else if (strcasecmp(alg, "MD5")) {
540         return apr_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
541     }
542
543     ((digest_config_rec *) config)->algorithm = alg;
544     return NULL;
545 }
546
547 static const char *set_uri_list(cmd_parms *cmd, void *config, const char *uri)
548 {
549     digest_config_rec *c = (digest_config_rec *) config;
550     if (c->uri_list) {
551         c->uri_list[strlen(c->uri_list)-1] = '\0';
552         c->uri_list = apr_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
553     }
554     else {
555         c->uri_list = apr_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
556     }
557     return NULL;
558 }
559
560 static const char *set_shmem_size(cmd_parms *cmd, void *config,
561                                   const char *size_str)
562 {
563     char *endptr;
564     long  size, min;
565
566     size = strtol(size_str, &endptr, 10); 
567     while (apr_isspace(*endptr)) endptr++;
568     if (*endptr == '\0' || *endptr == 'b' || *endptr == 'B') {
569         ;
570     }
571     else if (*endptr == 'k' || *endptr == 'K') {
572         size *= 1024;
573     }
574     else if (*endptr == 'm' || *endptr == 'M') {
575         size *= 1048576;
576     }
577     else {
578         return apr_pstrcat(cmd->pool, "Invalid size in AuthDigestShmemSize: ",
579                           size_str, NULL);
580     }
581
582     min = sizeof(*client_list) + sizeof(client_entry*) + sizeof(client_entry);
583     if (size < min) {
584         return apr_psprintf(cmd->pool, "size in AuthDigestShmemSize too small: "
585                            "%ld < %ld", size, min);
586     }
587
588     shmem_size  = size;
589     num_buckets = (size - sizeof(*client_list)) /
590                   (sizeof(client_entry*) + HASH_DEPTH * sizeof(client_entry));
591     if (num_buckets == 0) {
592         num_buckets = 1;
593     }
594     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
595                  "Digest: Set shmem-size: %ld, num-buckets: %ld", shmem_size,
596                  num_buckets);
597
598     return NULL;
599 }
600
601 static const command_rec digest_cmds[] =
602 {
603     AP_INIT_TAKE1("AuthName", set_realm, NULL, OR_AUTHCFG, 
604      "The authentication realm (e.g. \"Members Only\")"),
605     AP_INIT_TAKE1("AuthDigestFile", set_digest_file, NULL, OR_AUTHCFG, 
606      "The name of the file containing the usernames and password hashes"),
607     AP_INIT_TAKE1("AuthDigestGroupFile", set_group_file, NULL, OR_AUTHCFG, 
608      "The name of the file containing the group names and members"),
609     AP_INIT_ITERATE("AuthDigestQop", set_qop, NULL, OR_AUTHCFG, 
610      "A list of quality-of-protection options"),
611     AP_INIT_TAKE1("AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG, 
612      "Maximum lifetime of the server nonce (seconds)"),
613     AP_INIT_TAKE1("AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG, 
614      "The format to use when generating the server nonce"),
615     AP_INIT_FLAG("AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG, 
616      "Whether or not to check the nonce-count sent by the client"),
617     AP_INIT_TAKE1("AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG, 
618      "The algorithm used for the hash calculation"),
619     AP_INIT_ITERATE("AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG, 
620      "A list of URI's which belong to the same protection space as the current URI"),
621     AP_INIT_TAKE1("AuthDigestShmemSize", set_shmem_size, NULL, RSRC_CONF, 
622      "The amount of shared memory to allocate for keeping track of clients"),
623     {NULL}
624 };
625
626
627 /*
628  * client list code
629  *
630  * Each client is assigned a number, which is transfered in the opaque
631  * field of the WWW-Authenticate and Authorization headers. The number
632  * is just a simple counter which is incremented for each new client.
633  * Clients can't forge this number because it is hashed up into the
634  * server nonce, and that is checked.
635  *
636  * The clients are kept in a simple hash table, which consists of an
637  * array of client_entry's, each with a linked list of entries hanging
638  * off it. The client's number modulo the size of the array gives the
639  * bucket number.
640  *
641  * The clients are garbage collected whenever a new client is allocated
642  * but there is not enough space left in the shared memory segment. A
643  * simple semi-LRU is used for this: whenever a client entry is accessed
644  * it is moved to the beginning of the linked list in its bucket (this
645  * also makes for faster lookups for current clients). The garbage
646  * collecter then just removes the oldest entry (i.e. the one at the
647  * end of the list) in each bucket.
648  *
649  * The main advantages of the above scheme are that it's easy to implement
650  * and it keeps the hash table evenly balanced (i.e. same number of entries
651  * in each bucket). The major disadvantage is that you may be throwing
652  * entries out which are in active use. This is not tragic, as these
653  * clients will just be sent a new client id (opaque field) and nonce
654  * with a stale=true (i.e. it will just look like the nonce expired,
655  * thereby forcing an extra round trip). If the shared memory segment
656  * has enough headroom over the current client set size then this should
657  * not occur too often.
658  *
659  * To help tune the size of the shared memory segment (and see if the
660  * above algorithm is really sufficient) a set of counters is kept
661  * indicating the number of clients held, the number of garbage collected
662  * clients, and the number of erroneously purged clients. These are printed
663  * out at each garbage collection run. Note that access to the counters is
664  * not synchronized because they are just indicaters, and whether they are
665  * off by a few doesn't matter; and for the same reason no attempt is made
666  * to guarantee the num_renewed is correct in the face of clients spoofing
667  * the opaque field.
668  */
669
670 /*
671  * Get the client given its client number (the key). Returns the entry,
672  * or NULL if it's not found.
673  *
674  * Access to the list itself is synchronized via locks. However, access
675  * to the entry returned by get_client() is NOT synchronized. This means
676  * that there are potentially problems if a client uses multiple,
677  * simultaneous connections to access url's within the same protection
678  * space. However, these problems are not new: when using multiple
679  * connections you have no guarantee of the order the requests are
680  * processed anyway, so you have problems with the nonce-count and
681  * one-time nonces anyway.
682  */
683 static client_entry *get_client(unsigned long key, const request_rec *r)
684 {
685     int bucket;
686     client_entry *entry, *prev = NULL;
687
688
689     if (!key || !client_shm)  return NULL;
690
691     bucket = key % client_list->tbl_len;
692     entry  = client_list->table[bucket];
693
694     apr_global_mutex_lock(client_lock);
695
696     while (entry && key != entry->key) {
697         prev  = entry;
698         entry = entry->next;
699     }
700
701     if (entry && prev) {                /* move entry to front of list */
702         prev->next  = entry->next;
703         entry->next = client_list->table[bucket];
704         client_list->table[bucket] = entry;
705     }
706
707     apr_global_mutex_unlock(client_lock);
708
709     if (entry) {
710         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
711                       "get_client(): client %lu found", key);
712     }
713     else {
714         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
715                       "get_client(): client %lu not found", key);
716     }
717
718     return entry;
719 }
720
721
722 /* A simple garbage-collecter to remove unused clients. It removes the
723  * last entry in each bucket and updates the counters. Returns the
724  * number of removed entries.
725  */
726 static long gc(void)
727 {
728     client_entry *entry, *prev;
729     unsigned long num_removed = 0, idx;
730
731     /* garbage collect all last entries */
732
733     for (idx = 0; idx < client_list->tbl_len; idx++) {
734         entry = client_list->table[idx];
735         prev  = NULL;
736         while (entry->next) {   /* find last entry */
737             prev  = entry;
738             entry = entry->next;
739         }
740         if (prev) {
741             prev->next = NULL;   /* cut list */
742         }
743         else {
744             client_list->table[idx] = NULL;
745         }
746         if (entry) {                    /* remove entry */
747             apr_rmm_free(client_rmm, (apr_rmm_off_t)entry);
748             num_removed++;
749         }
750     }
751
752     /* update counters and log */
753
754     client_list->num_entries -= num_removed;
755     client_list->num_removed += num_removed;
756
757     return num_removed;
758 }
759
760
761 /*
762  * Add a new client to the list. Returns the entry if successful, NULL
763  * otherwise. This triggers the garbage collection if memory is low.
764  */
765 static client_entry *add_client(unsigned long key, client_entry *info,
766                                 server_rec *s)
767 {
768     int bucket;
769     client_entry *entry;
770
771
772     if (!key || !client_shm) {
773         return NULL;
774     }
775
776     bucket = key % client_list->tbl_len;
777     entry  = client_list->table[bucket];
778
779     apr_global_mutex_lock(client_lock);
780
781     /* try to allocate a new entry */
782
783     entry = (client_entry *)apr_rmm_malloc(client_rmm, sizeof(client_entry));
784     if (!entry) {
785         long num_removed = gc();
786         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
787                      "Digest: gc'd %ld client entries. Total new clients: "
788                      "%ld; Total removed clients: %ld; Total renewed clients: "
789                      "%ld", num_removed,
790                      client_list->num_created - client_list->num_renewed,
791                      client_list->num_removed, client_list->num_renewed);
792         entry = (client_entry *)apr_rmm_malloc(client_rmm, sizeof(client_entry));
793         if (!entry) {
794             return NULL;       /* give up */
795         }
796     }
797
798     /* now add the entry */
799
800     memcpy(entry, info, sizeof(client_entry));
801     entry->key  = key;
802     entry->next = client_list->table[bucket];
803     client_list->table[bucket] = entry;
804     client_list->num_created++;
805     client_list->num_entries++;
806
807     apr_global_mutex_unlock(client_lock);
808
809     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
810                  "allocated new client %lu", key);
811
812     return entry;
813 }
814
815
816 /*
817  * Authorization header parser code
818  */
819
820 /* Parse the Authorization header, if it exists */
821 static int get_digest_rec(request_rec *r, digest_header_rec *resp)
822 {
823     const char *auth_line;
824     apr_size_t l;
825     int vk = 0, vv = 0;
826     char *key, *value;
827
828     auth_line = apr_table_get(r->headers_in,
829                              (PROXYREQ_PROXY == r->proxyreq)
830                                  ? "Proxy-Authorization"
831                                  : "Authorization");
832     if (!auth_line) {
833         resp->auth_hdr_sts = NO_HEADER;
834         return !OK;
835     }
836
837     resp->scheme = ap_getword_white(r->pool, &auth_line);
838     if (strcasecmp(resp->scheme, "Digest")) {
839         resp->auth_hdr_sts = NOT_DIGEST;
840         return !OK;
841     }
842
843     l = strlen(auth_line);
844
845     key   = apr_palloc(r->pool, l+1);
846     value = apr_palloc(r->pool, l+1);
847
848     while (auth_line[0] != '\0') {
849
850         /* find key */
851
852         while (apr_isspace(auth_line[0])) {
853             auth_line++;
854         }
855         vk = 0;
856         while (auth_line[0] != '=' && auth_line[0] != ','
857                && auth_line[0] != '\0' && !apr_isspace(auth_line[0])) {
858             key[vk++] = *auth_line++;
859         }
860         key[vk] = '\0';
861         while (apr_isspace(auth_line[0])) {
862             auth_line++;
863         }
864
865         /* find value */
866
867         if (auth_line[0] == '=') {
868             auth_line++;
869             while (apr_isspace(auth_line[0])) {
870                 auth_line++;
871             }
872
873             vv = 0;
874             if (auth_line[0] == '\"') {         /* quoted string */
875                 auth_line++;
876                 while (auth_line[0] != '\"' && auth_line[0] != '\0') {
877                     if (auth_line[0] == '\\' && auth_line[1] != '\0') {
878                         auth_line++;            /* escaped char */
879                     }
880                     value[vv++] = *auth_line++;
881                 }
882                 if (auth_line[0] != '\0') {
883                     auth_line++;
884                 }
885             }
886             else {                               /* token */
887                 while (auth_line[0] != ',' && auth_line[0] != '\0'
888                        && !apr_isspace(auth_line[0])) {
889                     value[vv++] = *auth_line++;
890                 }
891             }
892             value[vv] = '\0';
893         }
894
895         while (auth_line[0] != ',' && auth_line[0] != '\0') {
896             auth_line++;
897         }
898         if (auth_line[0] != '\0') {
899             auth_line++;
900         }
901
902         if (!strcasecmp(key, "username"))
903             resp->username = apr_pstrdup(r->pool, value);
904         else if (!strcasecmp(key, "realm"))
905             resp->realm = apr_pstrdup(r->pool, value);
906         else if (!strcasecmp(key, "nonce"))
907             resp->nonce = apr_pstrdup(r->pool, value);
908         else if (!strcasecmp(key, "uri"))
909             resp->uri = apr_pstrdup(r->pool, value);
910         else if (!strcasecmp(key, "response"))
911             resp->digest = apr_pstrdup(r->pool, value);
912         else if (!strcasecmp(key, "algorithm"))
913             resp->algorithm = apr_pstrdup(r->pool, value);
914         else if (!strcasecmp(key, "cnonce"))
915             resp->cnonce = apr_pstrdup(r->pool, value);
916         else if (!strcasecmp(key, "opaque"))
917             resp->opaque = apr_pstrdup(r->pool, value);
918         else if (!strcasecmp(key, "qop"))
919             resp->message_qop = apr_pstrdup(r->pool, value);
920         else if (!strcasecmp(key, "nc"))
921             resp->nonce_count = apr_pstrdup(r->pool, value);
922     }
923
924     if (!resp->username || !resp->realm || !resp->nonce || !resp->uri
925         || !resp->digest
926         || (resp->message_qop && (!resp->cnonce || !resp->nonce_count))) {
927         resp->auth_hdr_sts = INVALID;
928         return !OK;
929     }
930
931     if (resp->opaque) {
932         resp->opaque_num = (unsigned long) strtol(resp->opaque, NULL, 16);
933     }
934
935     resp->auth_hdr_sts = VALID;
936     return OK;
937 }
938
939
940 /* Because the browser may preemptively send auth info, incrementing the
941  * nonce-count when it does, and because the client does not get notified
942  * if the URI didn't need authentication after all, we need to be sure to
943  * update the nonce-count each time we receive an Authorization header no
944  * matter what the final outcome of the request. Furthermore this is a
945  * convenient place to get the request-uri (before any subrequests etc
946  * are initiated) and to initialize the request_config.
947  *
948  * Note that this must be called after mod_proxy had its go so that
949  * r->proxyreq is set correctly.
950  */
951 static int parse_hdr_and_update_nc(request_rec *r)
952 {
953     digest_header_rec *resp;
954     int res;
955
956     if (!ap_is_initial_req(r)) {
957         return DECLINED;
958     }
959
960     resp = apr_pcalloc(r->pool, sizeof(digest_header_rec));
961     resp->raw_request_uri = r->unparsed_uri;
962     resp->psd_request_uri = &r->parsed_uri;
963     resp->needed_auth = 0;
964     resp->method = r->method;
965     ap_set_module_config(r->request_config, &auth_digest_module, resp);
966
967     res = get_digest_rec(r, resp);
968     resp->client = get_client(resp->opaque_num, r);
969     if (res == OK && resp->client) {
970         resp->client->nonce_count++;
971     }
972
973     return DECLINED;
974 }
975
976
977 /*
978  * Nonce generation code
979  */
980
981 /* The hash part of the nonce is a SHA-1 hash of the time, realm, server host
982  * and port, opaque, and our secret.
983  */
984 static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
985                            const server_rec *server,
986                            const digest_config_rec *conf)
987 {
988     const char *hex = "0123456789abcdef";
989     unsigned char sha1[APR_SHA1_DIGESTSIZE];
990     apr_sha1_ctx_t ctx;
991     int idx;
992
993     memcpy(&ctx, &conf->nonce_ctx, sizeof(ctx));
994     /*
995     apr_sha1_update_binary(&ctx, (const unsigned char *) server->server_hostname,
996                          strlen(server->server_hostname));
997     apr_sha1_update_binary(&ctx, (const unsigned char *) &server->port,
998                          sizeof(server->port));
999      */
1000     apr_sha1_update_binary(&ctx, (const unsigned char *) timestr, strlen(timestr));
1001     if (opaque) {
1002         apr_sha1_update_binary(&ctx, (const unsigned char *) opaque,
1003                              strlen(opaque));
1004     }
1005     apr_sha1_final(sha1, &ctx);
1006
1007     for (idx=0; idx<APR_SHA1_DIGESTSIZE; idx++) {
1008         *hash++ = hex[sha1[idx] >> 4];
1009         *hash++ = hex[sha1[idx] & 0xF];
1010     }
1011
1012     *hash++ = '\0';
1013 }
1014
1015
1016 /* The nonce has the format b64(time)+hash .
1017  */
1018 static const char *gen_nonce(apr_pool_t *p, apr_time_t now, const char *opaque,
1019                              const server_rec *server,
1020                              const digest_config_rec *conf)
1021 {
1022     char *nonce = apr_palloc(p, NONCE_LEN+1);
1023     int len;
1024     time_rec t;
1025
1026     if (conf->nonce_lifetime != 0) {
1027         t.time = now;
1028     }
1029     else if (otn_counter) {
1030         /* this counter is not synch'd, because it doesn't really matter
1031          * if it counts exactly.
1032          */
1033         t.time = (*otn_counter)++;
1034     }
1035     else {
1036         /* XXX: WHAT IS THIS CONSTANT? */
1037         t.time = 42;
1038     }
1039     len = apr_base64_encode_binary(nonce, t.arr, sizeof(t.arr));
1040     gen_nonce_hash(nonce+NONCE_TIME_LEN, nonce, opaque, server, conf);
1041
1042     return nonce;
1043 }
1044
1045
1046 /*
1047  * Opaque and hash-table management
1048  */
1049
1050 /*
1051  * Generate a new client entry, add it to the list, and return the
1052  * entry. Returns NULL if failed.
1053  */
1054 static client_entry *gen_client(const request_rec *r)
1055 {
1056     unsigned long op;
1057     client_entry new_entry = { 0, NULL, 0, "", "" }, *entry;
1058
1059     if (!opaque_cntr) {
1060         return NULL;
1061     }
1062
1063     apr_global_mutex_lock(opaque_lock);
1064     op = (*opaque_cntr)++;
1065     apr_global_mutex_lock(opaque_lock);
1066
1067     if (!(entry = add_client(op, &new_entry, r->server))) {
1068         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1069                       "Digest: failed to allocate client entry - ignoring "
1070                       "client");
1071         return NULL;
1072     }
1073
1074     return entry;
1075 }
1076
1077
1078 /*
1079  * MD5-sess code.
1080  *
1081  * If you want to use algorithm=MD5-sess you must write get_userpw_hash()
1082  * yourself (see below). The dummy provided here just uses the hash from
1083  * the auth-file, i.e. it is only useful for testing client implementations
1084  * of MD5-sess .
1085  */
1086
1087 /*
1088  * get_userpw_hash() will be called each time a new session needs to be
1089  * generated and is expected to return the equivalent of
1090  *
1091  * h_urp = ap_md5(r->pool,
1092  *         apr_pstrcat(r->pool, username, ":", ap_auth_name(r), ":", passwd))
1093  * ap_md5(r->pool,
1094  *         (unsigned char *) apr_pstrcat(r->pool, h_urp, ":", resp->nonce, ":",
1095  *                                      resp->cnonce, NULL));
1096  *
1097  * or put differently, it must return
1098  *
1099  *   MD5(MD5(username ":" realm ":" password) ":" nonce ":" cnonce)
1100  *
1101  * If something goes wrong, the failure must be logged and NULL returned.
1102  *
1103  * You must implement this yourself, which will probably consist of code
1104  * contacting the password server with the necessary information (typically
1105  * the username, realm, nonce, and cnonce) and receiving the hash from it.
1106  *
1107  * TBD: This function should probably be in a seperate source file so that
1108  * people need not modify mod_auth_digest.c each time they install a new
1109  * version of apache.
1110  */
1111 static const char *get_userpw_hash(const request_rec *r,
1112                                    const digest_header_rec *resp,
1113                                    const digest_config_rec *conf)
1114 {
1115     return ap_md5(r->pool,
1116              (unsigned char *) apr_pstrcat(r->pool, conf->ha1, ":", resp->nonce,
1117                                            ":", resp->cnonce, NULL));
1118 }
1119
1120
1121 /* Retrieve current session H(A1). If there is none and "generate" is
1122  * true then a new session for MD5-sess is generated and stored in the
1123  * client struct; if generate is false, or a new session could not be
1124  * generated then NULL is returned (in case of failure to generate the
1125  * failure reason will have been logged already).
1126  */
1127 static const char *get_session_HA1(const request_rec *r,
1128                                    digest_header_rec *resp,
1129                                    const digest_config_rec *conf,
1130                                    int generate)
1131 {
1132     const char *ha1 = NULL;
1133
1134     /* return the current sessions if there is one */
1135     if (resp->opaque && resp->client && resp->client->ha1[0]) {
1136         return resp->client->ha1;
1137     }
1138     else if (!generate) {
1139         return NULL;
1140     }
1141
1142     /* generate a new session */
1143     if (!resp->client) {
1144         resp->client = gen_client(r);
1145     }
1146     if (resp->client) {
1147         ha1 = get_userpw_hash(r, resp, conf);
1148         if (ha1) {
1149             memcpy(resp->client->ha1, ha1, sizeof(resp->client->ha1));
1150         }
1151     }
1152
1153     return ha1;
1154 }
1155
1156
1157 static void clear_session(const digest_header_rec *resp)
1158 {
1159     if (resp->client) {
1160         resp->client->ha1[0] = '\0';
1161     }
1162 }
1163
1164 /*
1165  * Authorization challenge generation code (for WWW-Authenticate)
1166  */
1167
1168 static const char *ltox(apr_pool_t *p, unsigned long num)
1169 {
1170     if (num != 0) {
1171         return apr_psprintf(p, "%lx", num);
1172     }
1173     else {
1174         return "";
1175     }
1176 }
1177
1178 static void note_digest_auth_failure(request_rec *r,
1179                                      const digest_config_rec *conf,
1180                                      digest_header_rec *resp, int stale)
1181 {
1182     const char   *qop, *opaque, *opaque_param, *domain, *nonce;
1183     int           cnt;
1184
1185     /* Setup qop */
1186
1187     if (conf->qop_list[0] == NULL) {
1188         qop = ", qop=\"auth\"";
1189     }
1190     else if (!strcasecmp(conf->qop_list[0], "none")) {
1191         qop = "";
1192     }
1193     else {
1194         qop = apr_pstrcat(r->pool, ", qop=\"", conf->qop_list[0], NULL);
1195         for (cnt = 1; conf->qop_list[cnt] != NULL; cnt++) {
1196             qop = apr_pstrcat(r->pool, qop, ",", conf->qop_list[cnt], NULL);
1197         }
1198         qop = apr_pstrcat(r->pool, qop, "\"", NULL);
1199     }
1200
1201     /* Setup opaque */
1202
1203     if (resp->opaque == NULL) {
1204         /* new client */
1205         if ((conf->check_nc || conf->nonce_lifetime == 0
1206              || !strcasecmp(conf->algorithm, "MD5-sess"))
1207             && (resp->client = gen_client(r)) != NULL) {
1208             opaque = ltox(r->pool, resp->client->key);
1209         }
1210         else {
1211             opaque = "";                /* opaque not needed */
1212         }
1213     }
1214     else if (resp->client == NULL) {
1215         /* client info was gc'd */
1216         resp->client = gen_client(r);
1217         if (resp->client != NULL) {
1218             opaque = ltox(r->pool, resp->client->key);
1219             stale = 1;
1220             client_list->num_renewed++;
1221         }
1222         else {
1223             opaque = "";                /* ??? */
1224         }
1225     }
1226     else {
1227         opaque = resp->opaque;
1228         /* we're generating a new nonce, so reset the nonce-count */
1229         resp->client->nonce_count = 0;
1230     }
1231
1232     if (opaque[0]) {
1233         opaque_param = apr_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
1234     }
1235     else {
1236         opaque_param = NULL;
1237     }
1238
1239     /* Setup nonce */
1240
1241     nonce = gen_nonce(r->pool, r->request_time, opaque, r->server, conf);
1242     if (resp->client && conf->nonce_lifetime == 0) {
1243         memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1244     }
1245
1246     /* Setup MD5-sess stuff. Note that we just clear out the session
1247      * info here, since we can't generate a new session until the request
1248      * from the client comes in with the cnonce.
1249      */
1250
1251     if (!strcasecmp(conf->algorithm, "MD5-sess")) {
1252         clear_session(resp);
1253     }
1254
1255     /* setup domain attribute. We want to send this attribute wherever
1256      * possible so that the client won't send the Authorization header
1257      * unneccessarily (it's usually > 200 bytes!).
1258      */
1259
1260     /* don't send domain
1261      * - for proxy requests
1262      * - if it's no specified
1263      */
1264     if (r->proxyreq || !conf->uri_list) {
1265         domain = NULL;  
1266     }
1267     else {
1268         domain = conf->uri_list;
1269     }
1270
1271     apr_table_mergen(r->err_headers_out,
1272                      (PROXYREQ_PROXY == r->proxyreq)
1273                          ? "Proxy-Authenticate" : "WWW-Authenticate",
1274                      apr_psprintf(r->pool, "Digest realm=\"%s\", "
1275                                   "nonce=\"%s\", algorithm=%s%s%s%s%s",
1276                                   ap_auth_name(r), nonce, conf->algorithm,
1277                                   opaque_param ? opaque_param : "",
1278                                   domain ? domain : "",
1279                                   stale ? ", stale=true" : "", qop));
1280
1281 }
1282
1283
1284 /*
1285  * Authorization header verification code
1286  */
1287
1288 static const char *get_hash(request_rec *r, const char *user,
1289                             const char *realm, const char *auth_pwfile)
1290 {
1291     ap_configfile_t *f;
1292     char l[MAX_STRING_LEN];
1293     const char *rpw;
1294     char *w, *x;
1295     apr_status_t sts;
1296
1297     if ((sts = ap_pcfg_openfile(&f, r->pool, auth_pwfile)) != APR_SUCCESS) {
1298         ap_log_rerror(APLOG_MARK, APLOG_ERR, sts, r,
1299                       "Digest: Could not open password file: %s", auth_pwfile);
1300         return NULL;
1301     }
1302     while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
1303         if ((l[0] == '#') || (!l[0])) {
1304             continue;
1305         }
1306         rpw = l;
1307         w = ap_getword(r->pool, &rpw, ':');
1308         x = ap_getword(r->pool, &rpw, ':');
1309
1310         if (x && w && !strcmp(user, w) && !strcmp(realm, x)) {
1311             ap_cfg_closefile(f);
1312             return apr_pstrdup(r->pool, rpw);
1313         }
1314     }
1315     ap_cfg_closefile(f);
1316     return NULL;
1317 }
1318
1319 static int check_nc(const request_rec *r, const digest_header_rec *resp,
1320                     const digest_config_rec *conf)
1321 {
1322     unsigned long nc;
1323     const char *snc = resp->nonce_count;
1324     char *endptr;
1325
1326     if (!conf->check_nc || !client_shm) {
1327         return OK;
1328     }
1329
1330     nc = strtol(snc, &endptr, 16);
1331     if (endptr < (snc+strlen(snc)) && !apr_isspace(*endptr)) {
1332         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1333                       "Digest: invalid nc %s received - not a number", snc);
1334         return !OK;
1335     }
1336
1337     if (!resp->client) {
1338         return !OK;
1339     }
1340
1341     if (nc != resp->client->nonce_count) {
1342         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1343                       "Digest: Warning, possible replay attack: nonce-count "
1344                       "check failed: %lu != %lu", nc,
1345                       resp->client->nonce_count);
1346         return !OK;
1347     }
1348
1349     return OK;
1350 }
1351
1352 static int check_nonce(request_rec *r, digest_header_rec *resp,
1353                        const digest_config_rec *conf)
1354 {
1355     apr_time_t dt;
1356     int len;
1357     time_rec nonce_time;
1358     char tmp, hash[NONCE_HASH_LEN+1];
1359
1360     if (strlen(resp->nonce) != NONCE_LEN) {
1361         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1362                       "Digest: invalid nonce %s received - length is not %d",
1363                       resp->nonce, NONCE_LEN);
1364         note_digest_auth_failure(r, conf, resp, 1);
1365         return HTTP_UNAUTHORIZED;
1366     }
1367
1368     tmp = resp->nonce[NONCE_TIME_LEN];
1369     resp->nonce[NONCE_TIME_LEN] = '\0';
1370     len = apr_base64_decode_binary(nonce_time.arr, resp->nonce);
1371     gen_nonce_hash(hash, resp->nonce, resp->opaque, r->server, conf);
1372     resp->nonce[NONCE_TIME_LEN] = tmp;
1373     resp->nonce_time = nonce_time.time;
1374
1375     if (strcmp(hash, resp->nonce+NONCE_TIME_LEN)) {
1376         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1377                       "Digest: invalid nonce %s received - hash is not %s",
1378                       resp->nonce, hash);
1379         note_digest_auth_failure(r, conf, resp, 1);
1380         return HTTP_UNAUTHORIZED;
1381     }
1382
1383     dt = r->request_time - nonce_time.time;
1384     if (conf->nonce_lifetime > 0 && dt < 0) {
1385         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1386                       "Digest: invalid nonce %s received - user attempted "
1387                       "time travel", resp->nonce);
1388         note_digest_auth_failure(r, conf, resp, 1);
1389         return HTTP_UNAUTHORIZED;
1390     }
1391
1392     if (conf->nonce_lifetime > 0) {
1393         if (dt > conf->nonce_lifetime) {
1394             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0,r,
1395                           "Digest: user %s: nonce expired (%.2f seconds old "
1396                           "- max lifetime %.2f) - sending new nonce", 
1397                           r->user, (double)apr_time_sec(dt),
1398                           (double)apr_time_sec(conf->nonce_lifetime));
1399             note_digest_auth_failure(r, conf, resp, 1);
1400             return HTTP_UNAUTHORIZED;
1401         }
1402     }
1403     else if (conf->nonce_lifetime == 0 && resp->client) {
1404         if (memcmp(resp->client->last_nonce, resp->nonce, NONCE_LEN)) {
1405             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1406                           "Digest: user %s: one-time-nonce mismatch - sending "
1407                           "new nonce", r->user);
1408             note_digest_auth_failure(r, conf, resp, 1);
1409             return HTTP_UNAUTHORIZED;
1410         }
1411     }
1412     /* else (lifetime < 0) => never expires */
1413
1414     return OK;
1415 }
1416
1417 /* The actual MD5 code... whee */
1418
1419 /* RFC-2069 */
1420 static const char *old_digest(const request_rec *r,
1421                               const digest_header_rec *resp, const char *ha1)
1422 {
1423     const char *ha2;
1424
1425     ha2 = ap_md5(r->pool, (unsigned char *)apr_pstrcat(r->pool, resp->method, ":",
1426                                                        resp->uri, NULL));
1427     return ap_md5(r->pool,
1428                   (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1429                                               ":", ha2, NULL));
1430 }
1431
1432 /* RFC-2617 */
1433 static const char *new_digest(const request_rec *r,
1434                               digest_header_rec *resp,
1435                               const digest_config_rec *conf)
1436 {
1437     const char *ha1, *ha2, *a2;
1438
1439     if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
1440         ha1 = get_session_HA1(r, resp, conf, 1);
1441         if (!ha1) {
1442             return NULL;
1443         }
1444     }
1445     else {
1446         ha1 = conf->ha1;
1447     }
1448
1449     if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int")) {
1450         a2 = apr_pstrcat(r->pool, resp->method, ":", resp->uri, ":",
1451                          ap_md5(r->pool, (const unsigned char*) ""), NULL);
1452                          /* TBD */
1453     }
1454     else {
1455         a2 = apr_pstrcat(r->pool, resp->method, ":", resp->uri, NULL);
1456     }
1457     ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1458
1459     return ap_md5(r->pool,
1460                   (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
1461                                                ":", resp->nonce_count, ":",
1462                                                resp->cnonce, ":",
1463                                                resp->message_qop, ":", ha2,
1464                                                NULL));
1465 }
1466
1467
1468 static void copy_uri_components(apr_uri_t *dst, 
1469                                 apr_uri_t *src, request_rec *r) {
1470     if (src->scheme && src->scheme[0] != '\0') {
1471         dst->scheme = src->scheme;
1472     }
1473     else {
1474         dst->scheme = (char *) "http";
1475     }
1476
1477     if (src->hostname && src->hostname[0] != '\0') {
1478         dst->hostname = apr_pstrdup(r->pool, src->hostname);
1479         ap_unescape_url(dst->hostname);
1480     }
1481     else {
1482         dst->hostname = (char *) ap_get_server_name(r);
1483     }
1484
1485     if (src->port_str && src->port_str[0] != '\0') {
1486         dst->port = src->port;
1487     }
1488     else {
1489         dst->port = ap_get_server_port(r);
1490     }
1491
1492     if (src->path && src->path[0] != '\0') {
1493         dst->path = apr_pstrdup(r->pool, src->path);
1494         ap_unescape_url(dst->path);
1495     }
1496     else {
1497         dst->path = src->path;
1498     }
1499
1500     if (src->query && src->query[0] != '\0') {
1501         dst->query = apr_pstrdup(r->pool, src->query);
1502         ap_unescape_url(dst->query);
1503     }
1504     else {
1505         dst->query = src->query;
1506     }
1507
1508     dst->hostinfo = src->hostinfo;
1509 }
1510
1511 /* These functions return 0 if client is OK, and proper error status
1512  * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
1513  * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
1514  * couldn't figure out how to tell if the client is authorized or not.
1515  *
1516  * If they return DECLINED, and all other modules also decline, that's
1517  * treated by the server core as a configuration error, logged and
1518  * reported as such.
1519  */
1520
1521 /* Determine user ID, and check if the attributes are correct, if it
1522  * really is that user, if the nonce is correct, etc.
1523  */
1524
1525 static int authenticate_digest_user(request_rec *r)
1526 {
1527     digest_config_rec *conf;
1528     digest_header_rec *resp;
1529     request_rec       *mainreq;
1530     const char        *t;
1531     int                res;
1532
1533     /* do we require Digest auth for this URI? */
1534
1535     if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest")) {
1536         return DECLINED;
1537     }
1538
1539     if (!ap_auth_name(r)) {
1540         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1541                       "Digest: need AuthName: %s", r->uri);
1542         return HTTP_INTERNAL_SERVER_ERROR;
1543     }
1544
1545
1546     /* get the client response and mark */
1547
1548     mainreq = r;
1549     while (mainreq->main != NULL) {
1550         mainreq = mainreq->main;
1551     }
1552     while (mainreq->prev != NULL) {
1553         mainreq = mainreq->prev;
1554     }
1555     resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1556                                                       &auth_digest_module);
1557     resp->needed_auth = 1;
1558
1559
1560     /* get our conf */
1561
1562     conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1563                                                       &auth_digest_module);
1564
1565
1566     /* check for existence and syntax of Auth header */
1567
1568     if (resp->auth_hdr_sts != VALID) {
1569         if (resp->auth_hdr_sts == NOT_DIGEST) {
1570             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1571                           "Digest: client used wrong authentication scheme "
1572                           "`%s': %s", resp->scheme, r->uri);
1573         }
1574         else if (resp->auth_hdr_sts == INVALID) {
1575             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1576                           "Digest: missing user, realm, nonce, uri, digest, "
1577                           "cnonce, or nonce_count in authorization header: %s",
1578                           r->uri);
1579         }
1580         /* else (resp->auth_hdr_sts == NO_HEADER) */
1581         note_digest_auth_failure(r, conf, resp, 0);
1582         return HTTP_UNAUTHORIZED;
1583     }
1584
1585     r->user         = (char *) resp->username;
1586     r->ap_auth_type = (char *) "Digest";
1587
1588     /* check the auth attributes */
1589
1590     if (strcmp(resp->uri, resp->raw_request_uri)) {
1591         /* Hmm, the simple match didn't work (probably a proxy modified the
1592          * request-uri), so lets do a more sophisticated match
1593          */
1594         apr_uri_t r_uri, d_uri;
1595
1596         copy_uri_components(&r_uri, resp->psd_request_uri, r);
1597         if (apr_uri_parse(r->pool, resp->uri, &d_uri) != APR_SUCCESS) {
1598             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1599                           "Digest: invalid uri <%s> in Authorization header",
1600                           resp->uri);
1601             return HTTP_BAD_REQUEST;
1602         }
1603
1604         if (d_uri.hostname) {
1605             ap_unescape_url(d_uri.hostname);
1606         }
1607         if (d_uri.path) {
1608             ap_unescape_url(d_uri.path);
1609         }
1610         if (d_uri.query) {
1611             ap_unescape_url(d_uri.query);
1612         }
1613         else if (r_uri.query) {
1614             /* MSIE compatibility hack.  MSIE has some RFC issues - doesn't 
1615              * include the query string in the uri Authorization component
1616              * or when computing the response component.  the second part
1617              * works out ok, since we can hash the header and get the same
1618              * result.  however, the uri from the request line won't match
1619              * the uri Authorization component since the header lacks the 
1620              * query string, leaving us incompatable with a (broken) MSIE.
1621              * 
1622              * the workaround is to fake a query string match if in the proper
1623              * environment - BrowserMatch MSIE, for example.  the cool thing
1624              * is that if MSIE ever fixes itself the simple match ought to 
1625              * work and this code won't be reached anyway, even if the
1626              * environment is set.
1627              */
1628             
1629             if (apr_table_get(r->subprocess_env, 
1630                               "AuthDigestEnableQueryStringHack")) {
1631                 d_uri.query = r_uri.query;
1632             }
1633         }
1634
1635         if (r->method_number == M_CONNECT) {
1636             if (!r_uri.hostinfo || strcmp(resp->uri, r_uri.hostinfo)) {
1637                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1638                               "Digest: uri mismatch - <%s> does not match "
1639                               "request-uri <%s>", resp->uri, r_uri.hostinfo);
1640                 return HTTP_BAD_REQUEST;
1641             }
1642         }
1643         else if (
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)))
1664             ) {
1665             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1666                           "Digest: uri mismatch - <%s> does not match "
1667                           "request-uri <%s>", resp->uri, resp->raw_request_uri);
1668             return HTTP_BAD_REQUEST;
1669         }
1670     }
1671
1672     if (resp->opaque && resp->opaque_num == 0) {
1673         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1674                       "Digest: received invalid opaque - got `%s'",
1675                       resp->opaque);
1676         note_digest_auth_failure(r, conf, resp, 0);
1677         return HTTP_UNAUTHORIZED;
1678     }
1679
1680     if (strcmp(resp->realm, conf->realm)) {
1681         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1682                       "Digest: realm mismatch - got `%s' but expected `%s'",
1683                       resp->realm, conf->realm);
1684         note_digest_auth_failure(r, conf, resp, 0);
1685         return HTTP_UNAUTHORIZED;
1686     }
1687
1688     if (resp->algorithm != NULL
1689         && strcasecmp(resp->algorithm, "MD5")
1690         && strcasecmp(resp->algorithm, "MD5-sess")) {
1691         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1692                       "Digest: unknown algorithm `%s' received: %s",
1693                       resp->algorithm, r->uri);
1694         note_digest_auth_failure(r, conf, resp, 0);
1695         return HTTP_UNAUTHORIZED;
1696     }
1697
1698     if (!conf->pwfile) {
1699         return DECLINED;
1700     }
1701
1702     if (!(conf->ha1 = get_hash(r, r->user, conf->realm, conf->pwfile))) {
1703         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1704                       "Digest: user `%s' in realm `%s' not found: %s",
1705                       r->user, conf->realm, r->uri);
1706         note_digest_auth_failure(r, conf, resp, 0);
1707         return HTTP_UNAUTHORIZED;
1708     }
1709
1710     
1711     if (resp->message_qop == NULL) {
1712         /* old (rfc-2069) style digest */
1713         if (strcmp(resp->digest, old_digest(r, resp, conf->ha1))) {
1714             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1715                           "Digest: user %s: password mismatch: %s", r->user,
1716                           r->uri);
1717             note_digest_auth_failure(r, conf, resp, 0);
1718             return HTTP_UNAUTHORIZED;
1719         }
1720     }
1721     else {
1722         const char *exp_digest;
1723         int match = 0, idx;
1724         for (idx = 0; conf->qop_list[idx] != NULL; idx++) {
1725             if (!strcasecmp(conf->qop_list[idx], resp->message_qop)) {
1726                 match = 1;
1727                 break;
1728             }
1729         }
1730
1731         if (!match
1732             && !(conf->qop_list[0] == NULL
1733                  && !strcasecmp(resp->message_qop, "auth"))) {
1734             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1735                           "Digest: invalid qop `%s' received: %s",
1736                           resp->message_qop, r->uri);
1737             note_digest_auth_failure(r, conf, resp, 0);
1738             return HTTP_UNAUTHORIZED;
1739         }
1740
1741         exp_digest = new_digest(r, resp, conf);
1742         if (!exp_digest) {
1743             /* we failed to allocate a client struct */
1744             return HTTP_INTERNAL_SERVER_ERROR;
1745         }
1746         if (strcmp(resp->digest, exp_digest)) {
1747             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1748                           "Digest: user %s: password mismatch: %s", r->user,
1749                           r->uri);
1750             note_digest_auth_failure(r, conf, resp, 0);
1751             return HTTP_UNAUTHORIZED;
1752         }
1753     }
1754
1755     if (check_nc(r, resp, conf) != OK) {
1756         note_digest_auth_failure(r, conf, resp, 0);
1757         return HTTP_UNAUTHORIZED;
1758     }
1759
1760     /* Note: this check is done last so that a "stale=true" can be
1761        generated if the nonce is old */
1762     if ((res = check_nonce(r, resp, conf))) {
1763         return res;
1764     }
1765
1766     return OK;
1767 }
1768
1769
1770 /*
1771  * Checking ID
1772  */
1773
1774 static apr_table_t *groups_for_user(request_rec *r, const char *user,
1775                                     const char *grpfile)
1776 {
1777     ap_configfile_t *f;
1778     apr_table_t *grps = apr_table_make(r->pool, 15);
1779     apr_pool_t *sp;
1780     char l[MAX_STRING_LEN];
1781     const char *group_name, *ll, *w;
1782     apr_status_t sts;
1783
1784     if ((sts = ap_pcfg_openfile(&f, r->pool, grpfile)) != APR_SUCCESS) {
1785         ap_log_rerror(APLOG_MARK, APLOG_ERR, sts, r,
1786                       "Digest: Could not open group file: %s", grpfile);
1787         return NULL;
1788     }
1789
1790     if (apr_pool_create(&sp, r->pool) != APR_SUCCESS) {
1791         return NULL;
1792     }
1793
1794     while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
1795         if ((l[0] == '#') || (!l[0])) {
1796             continue;
1797         }
1798         ll = l;
1799         apr_pool_clear(sp);
1800
1801         group_name = ap_getword(sp, &ll, ':');
1802
1803         while (ll[0]) {
1804             w = ap_getword_conf(sp, &ll);
1805             if (!strcmp(w, user)) {
1806                 apr_table_setn(grps, apr_pstrdup(r->pool, group_name), "in");
1807                 break;
1808             }
1809         }
1810     }
1811
1812     ap_cfg_closefile(f);
1813     apr_pool_destroy(sp);
1814     return grps;
1815 }
1816
1817
1818 static int digest_check_auth(request_rec *r)
1819 {
1820     const digest_config_rec *conf =
1821                 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1822                                                            &auth_digest_module);
1823     const char *user = r->user;
1824     int m = r->method_number;
1825     int method_restricted = 0;
1826     register int x;
1827     const char *t, *w;
1828     apr_table_t *grpstatus;
1829     const apr_array_header_t *reqs_arr;
1830     require_line *reqs;
1831
1832     if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest")) {
1833         return DECLINED;
1834     }
1835
1836     reqs_arr = ap_requires(r);
1837     /* If there is no "requires" directive, then any user will do.
1838      */
1839     if (!reqs_arr) {
1840         return OK;
1841     }
1842     reqs = (require_line *) reqs_arr->elts;
1843
1844     if (conf->grpfile) {
1845         grpstatus = groups_for_user(r, user, conf->grpfile);
1846     }
1847     else {
1848         grpstatus = NULL;
1849     }
1850
1851     for (x = 0; x < reqs_arr->nelts; x++) {
1852
1853         if (!(reqs[x].method_mask & (AP_METHOD_BIT << m))) {
1854             continue;
1855         }
1856
1857         method_restricted = 1;
1858
1859         t = reqs[x].requirement;
1860         w = ap_getword_white(r->pool, &t);
1861         if (!strcasecmp(w, "valid-user")) {
1862             return OK;
1863         }
1864         else if (!strcasecmp(w, "user")) {
1865             while (t[0]) {
1866                 w = ap_getword_conf(r->pool, &t);
1867                 if (!strcmp(user, w)) {
1868                     return OK;
1869                 }
1870             }
1871         }
1872         else if (!strcasecmp(w, "group")) {
1873             if (!grpstatus) {
1874                 return DECLINED;
1875             }
1876
1877             while (t[0]) {
1878                 w = ap_getword_conf(r->pool, &t);
1879                 if (apr_table_get(grpstatus, w)) {
1880                     return OK;
1881                 }
1882             }
1883         }
1884         else {
1885             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1886                           "Digest: access to %s failed, reason: unknown "
1887                           "require directive \"%s\"",
1888                           r->uri, reqs[x].requirement);
1889             return DECLINED;
1890         }
1891     }
1892
1893     if (!method_restricted) {
1894         return OK;
1895     }
1896
1897     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1898                   "Digest: access to %s failed, reason: user %s not "
1899                   "allowed access", r->uri, user);
1900
1901     note_digest_auth_failure(r, conf,
1902         (digest_header_rec *) ap_get_module_config(r->request_config,
1903                                                    &auth_digest_module),
1904         0);
1905     return HTTP_UNAUTHORIZED;
1906 }
1907
1908
1909 /*
1910  * Authorization-Info header code
1911  */
1912
1913 #ifdef SEND_DIGEST
1914 static const char *hdr(const apr_table_t *tbl, const char *name)
1915 {
1916     const char *val = apr_table_get(tbl, name);
1917     if (val) {
1918         return val;
1919     }
1920     else {
1921         return "";
1922     }
1923 }
1924 #endif
1925
1926 static int add_auth_info(request_rec *r)
1927 {
1928     const digest_config_rec *conf =
1929                 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1930                                                            &auth_digest_module);
1931     digest_header_rec *resp =
1932                 (digest_header_rec *) ap_get_module_config(r->request_config,
1933                                                            &auth_digest_module);
1934     const char *ai = NULL, *digest = NULL, *nextnonce = "";
1935
1936     if (resp == NULL || !resp->needed_auth || conf == NULL) {
1937         return OK;
1938     }
1939
1940
1941     /* rfc-2069 digest
1942      */
1943     if (resp->message_qop == NULL) {
1944         /* old client, so calc rfc-2069 digest */
1945
1946 #ifdef SEND_DIGEST
1947         /* most of this totally bogus because the handlers don't set the
1948          * headers until the final handler phase (I wonder why this phase
1949          * is called fixup when there's almost nothing you can fix up...)
1950          *
1951          * Because it's basically impossible to get this right (e.g. the
1952          * Content-length is never set yet when we get here, and we can't
1953          * calc the entity hash) it's best to just leave this #def'd out.
1954          */
1955         char date[APR_RFC822_DATE_LEN];
1956         apr_rfc822_date(date, r->request_time);
1957         char *entity_info =
1958             ap_md5(r->pool,
1959                    (unsigned char *) apr_pstrcat(r->pool, resp->raw_request_uri,
1960                        ":",
1961                        r->content_type ? r->content_type : ap_default_type(r), ":",
1962                        hdr(r->headers_out, "Content-Length"), ":",
1963                        r->content_encoding ? r->content_encoding : "", ":",
1964                        hdr(r->headers_out, "Last-Modified"), ":",
1965                        r->no_cache && !apr_table_get(r->headers_out, "Expires") ?
1966                             date :
1967                             hdr(r->headers_out, "Expires"),
1968                        NULL));
1969         digest =
1970             ap_md5(r->pool,
1971                    (unsigned char *)apr_pstrcat(r->pool, conf->ha1, ":",
1972                                                resp->nonce, ":",
1973                                                r->method, ":",
1974                                                date, ":",
1975                                                entity_info, ":",
1976                                                ap_md5(r->pool, (unsigned char *) ""), /* H(entity) - TBD */
1977                                                NULL));
1978 #endif
1979     }
1980
1981
1982     /* setup nextnonce
1983      */
1984     if (conf->nonce_lifetime > 0) {
1985         /* send nextnonce if current nonce will expire in less than 30 secs */
1986         if ((r->request_time - resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
1987             nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"",
1988                                    gen_nonce(r->pool, r->request_time,
1989                                              resp->opaque, r->server, conf),
1990                                    "\"", NULL);
1991             if (resp->client)
1992                 resp->client->nonce_count = 0;
1993         }
1994     }
1995     else if (conf->nonce_lifetime == 0 && resp->client) {
1996         const char *nonce = gen_nonce(r->pool, 0, resp->opaque, r->server,
1997                                       conf);
1998         nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
1999         memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
2000     }
2001     /* else nonce never expires, hence no nextnonce */
2002
2003
2004     /* do rfc-2069 digest
2005      */
2006     if (conf->qop_list[0] && !strcasecmp(conf->qop_list[0], "none")
2007         && resp->message_qop == NULL) {
2008         /* use only RFC-2069 format */
2009         if (digest) {
2010             ai = apr_pstrcat(r->pool, "digest=\"", digest, "\"", nextnonce,NULL);
2011         }
2012         else {
2013             ai = nextnonce;
2014         }
2015     }
2016     else {
2017         const char *resp_dig, *ha1, *a2, *ha2;
2018
2019         /* calculate rspauth attribute
2020          */
2021         if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
2022             ha1 = get_session_HA1(r, resp, conf, 0);
2023             if (!ha1) {
2024                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2025                               "Digest: internal error: couldn't find session "
2026                               "info for user %s", resp->username);
2027                 return !OK;
2028             }
2029         }
2030         else {
2031             ha1 = conf->ha1;
2032         }
2033
2034         if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int")) {
2035             a2 = apr_pstrcat(r->pool, ":", resp->uri, ":",
2036                              ap_md5(r->pool,(const unsigned char *) ""), NULL);
2037                              /* TBD */
2038         }
2039         else {
2040             a2 = apr_pstrcat(r->pool, ":", resp->uri, NULL);
2041         }
2042         ha2 = ap_md5(r->pool, (const unsigned char *)a2);
2043
2044         resp_dig = ap_md5(r->pool,
2045                           (unsigned char *)apr_pstrcat(r->pool, ha1, ":",
2046                                                        resp->nonce, ":",
2047                                                        resp->nonce_count, ":",
2048                                                        resp->cnonce, ":",
2049                                                        resp->message_qop ?
2050                                                          resp->message_qop : "",
2051                                                        ":", ha2, NULL));
2052
2053         /* assemble Authentication-Info header
2054          */
2055         ai = apr_pstrcat(r->pool,
2056                          "rspauth=\"", resp_dig, "\"",
2057                          nextnonce,
2058                          resp->cnonce ? ", cnonce=\"" : "",
2059                          resp->cnonce
2060                            ? ap_escape_quotes(r->pool, resp->cnonce)
2061                            : "",
2062                          resp->cnonce ? "\"" : "",
2063                          resp->nonce_count ? ", nc=" : "",
2064                          resp->nonce_count ? resp->nonce_count : "",
2065                          resp->message_qop ? ", qop=" : "",
2066                          resp->message_qop ? resp->message_qop : "",
2067                          digest ? "digest=\"" : "",
2068                          digest ? digest : "",
2069                          digest ? "\"" : "",
2070                          NULL);
2071     }
2072
2073     if (ai && ai[0]) {
2074         apr_table_mergen(r->headers_out,
2075                          (PROXYREQ_PROXY == r->proxyreq)
2076                              ? "Proxy-Authentication-Info"
2077                              : "Authentication-Info",
2078                          ai);
2079     }
2080
2081     return OK;
2082 }
2083
2084
2085 static void register_hooks(apr_pool_t *p)
2086 {
2087     static const char * const cfgPost[]={ "http_core.c", NULL };
2088     static const char * const parsePre[]={ "mod_proxy.c", NULL };
2089
2090     ap_hook_post_config(initialize_module, NULL, cfgPost, APR_HOOK_MIDDLE);
2091     ap_hook_child_init(initialize_child, NULL, NULL, APR_HOOK_MIDDLE);
2092     ap_hook_post_read_request(parse_hdr_and_update_nc, parsePre, NULL, APR_HOOK_MIDDLE);
2093     ap_hook_check_user_id(authenticate_digest_user, NULL, NULL, APR_HOOK_MIDDLE);
2094     ap_hook_auth_checker(digest_check_auth, NULL, NULL, APR_HOOK_MIDDLE);
2095     ap_hook_fixups(add_auth_info, NULL, NULL, APR_HOOK_MIDDLE);
2096 }
2097
2098 module AP_MODULE_DECLARE_DATA auth_digest_module =
2099 {
2100     STANDARD20_MODULE_STUFF,
2101     create_digest_dir_config,   /* dir config creater */
2102     NULL,                       /* dir merger --- default is to override */
2103     NULL,                       /* server config */
2104     NULL,                       /* merge server config */
2105     digest_cmds,                /* command table */
2106     register_hooks              /* register hooks */
2107 };
2108