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