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