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