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