1 /* ====================================================================
2 * The Apache Software License, Version 1.1
3 *
4 * Copyright (c) 2000-2003 The Apache Software Foundation. All rights
5 * reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 *
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
17 * distribution.
18 *
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
25 *
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
30 *
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
34 *
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46 * SUCH DAMAGE.
47 * ====================================================================
48 *
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
53 *
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
57 */
58
59 /*
60 * mod_auth_digest: MD5 digest authentication
61 *
62 * Originally by Alexei Kosut <akosut@nueva.pvt.k12.ca.us>
63 * Updated to RFC-2617 by Ronald Tschal�r <ronald@innovation.ch>
64 * based on mod_auth, by Rob McCool and Robert S. Thau
65 *
66 * This module an updated version of modules/standard/mod_digest.c
67 * However, it has not been extensively tested yet, and is therefore
68 * currently marked experimental. Send problem reports to me
69 * (ronald@innovation.ch)
70 *
71 * Requires either /dev/random (or equivalent) or the truerand library,
72 * available for instance from
73 * ftp://research.att.com/dist/mab/librand.shar
74 *
75 * Open Issues:
76 * - qop=auth-int (when streams and trailer support available)
77 * - nonce-format configurability
78 * - Proxy-Authorization-Info header is set by this module, but is
79 * currently ignored by mod_proxy (needs patch to mod_proxy)
80 * - generating the secret takes a while (~ 8 seconds) if using the
81 * truerand library
82 * - The source of the secret should be run-time directive (with server
83 * scope: RSRC_CONF). However, that could be tricky when trying to
84 * choose truerand vs. file...
85 * - shared-mem not completely tested yet. Seems to work ok for me,
86 * but... (definitely won't work on Windoze)
87 * - Sharing a realm among multiple servers has following problems:
88 * o Server name and port can't be included in nonce-hash
89 * (we need two nonce formats, which must be configured explicitly)
90 * o Nonce-count check can't be for equal, or then nonce-count checking
91 * must be disabled. What we could do is the following:
92 * (expected < received) ? set expected = received : issue error
93 * The only problem is that it allows replay attacks when somebody
94 * captures a packet sent to one server and sends it to another
95 * one. Should we add "AuthDigestNcCheck Strict"?
96 */
97
98 #include "httpd.h"
99 #include "http_config.h"
100 #include "http_conf_globals.h"
101 #include "http_core.h"
102 #include "http_request.h"
103 #include "http_log.h"
104 #include "http_main.h"
105 #include "http_protocol.h"
106 #include "ap_config.h"
107 #include "ap_ctype.h"
108 #include "util_uri.h"
109 #include "util_md5.h"
110 #include "ap_sha1.h"
111
112 __RCSID("$MirOS: src/usr.sbin/httpd/src/modules/experimental/mod_auth_digest.c,v 1.7 2010/09/21 21:24:41 tg Exp $");
113
114 /* struct to hold the configuration info */
115
116 typedef struct digest_config_struct {
117 const char *dir_name;
118 const char *pwfile;
119 const char *grpfile;
120 const char *realm;
121 const char **qop_list;
122 AP_SHA1_CTX nonce_ctx;
123 long nonce_lifetime;
124 const char *nonce_format;
125 int check_nc;
126 const char *algorithm;
127 char *uri_list;
128 const char *ha1;
129 } digest_config_rec;
130
131
132 #define DFLT_ALGORITHM "MD5"
133
134 #define DFLT_NONCE_LIFE 300L
135 #define NEXTNONCE_DELTA 30
136
137
138 #define NONCE_TIME_LEN (((sizeof(time_t)+2)/3)*4)
139 #define NONCE_HASH_LEN (2*SHA_DIGESTSIZE)
140 #define NONCE_LEN (NONCE_TIME_LEN + NONCE_HASH_LEN)
141
142 #define SECRET_LEN 20
143
144
145 /* client list definitions */
146
147 typedef struct hash_entry {
148 unsigned long key; /* the key for this entry */
149 struct hash_entry *next; /* next entry in the bucket */
150 unsigned long nonce_count; /* for nonce-count checking */
151 char ha1[2*MD5_DIGESTSIZE+1]; /* for algorithm=MD5-sess */
152 char last_nonce[NONCE_LEN+1]; /* for one-time nonce's */
153 } client_entry;
154
155 static struct hash_table {
156 client_entry **table;
157 unsigned long tbl_len;
158 unsigned long num_entries;
159 unsigned long num_created;
160 unsigned long num_removed;
161 unsigned long num_renewed;
162 } *client_list;
163
164
165 /* struct to hold a parsed Authorization header */
166
167 enum hdr_sts { NO_HEADER, NOT_DIGEST, INVALID, VALID };
168
169 typedef struct digest_header_struct {
170 const char *scheme;
171 const char *realm;
172 const char *username;
173 char *nonce;
174 const char *uri;
175 const char *digest;
176 const char *algorithm;
177 const char *cnonce;
178 const char *opaque;
179 unsigned long opaque_num;
180 const char *message_qop;
181 const char *nonce_count;
182 /* the following fields are not (directly) from the header */
183 time_t nonce_time;
184 enum hdr_sts auth_hdr_sts;
185 const char *raw_request_uri;
186 uri_components *psd_request_uri;
187 int needed_auth;
188 client_entry *client;
189 } digest_header_rec;
190
191
192 /* (mostly) nonce stuff */
193
194 typedef union time_union {
195 time_t time;
196 unsigned char arr[sizeof(time_t)];
197 } time_rec;
198
199
200 static unsigned char secret[SECRET_LEN];
201 static int call_cnt = 0;
202
203
204 static void *client_mm = NULL;
205
206 module MODULE_VAR_EXPORT digest_auth_module;
207
208 /*
209 * initialization code
210 */
211
initialize_secret(server_rec * s)212 static void initialize_secret(server_rec *s)
213 {
214 arc4random_buf(secret, sizeof(secret));
215 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
216 "Digest: generated secret for digest authentication");
217 }
218
initialize_module(server_rec * s,pool * p)219 static void initialize_module(server_rec *s, pool *p)
220 {
221 /* keep from doing the init more than once at startup, and delay
222 * the init until the second round
223 */
224 if (++call_cnt < 2)
225 return;
226
227 /* only initialize the secret on startup, not on restarts */
228 if (call_cnt == 2)
229 initialize_secret(s);
230 }
231
232
233 /*
234 * configuration code
235 */
236
create_digest_dir_config(pool * p,char * dir)237 static void *create_digest_dir_config(pool *p, char *dir)
238 {
239 digest_config_rec *conf;
240
241 if (dir == NULL) return NULL;
242
243 conf = (digest_config_rec *) ap_pcalloc(p, sizeof(digest_config_rec));
244 if (conf) {
245 conf->qop_list = ap_palloc(p, sizeof(char*));
246 conf->qop_list[0] = NULL;
247 conf->nonce_lifetime = DFLT_NONCE_LIFE;
248 conf->dir_name = ap_pstrdup(p, dir);
249 conf->algorithm = DFLT_ALGORITHM;
250 }
251
252 return conf;
253 }
254
set_realm(cmd_parms * cmd,void * config,const char * realm)255 static const char *set_realm(cmd_parms *cmd, void *config, const char *realm)
256 {
257 digest_config_rec *conf = (digest_config_rec *) config;
258
259 /* The core already handles the realm, but it's just too convenient to
260 * grab it ourselves too and cache some setups. However, we need to
261 * let the core get at it too, which is why we decline at the end -
262 * this relies on the fact that http_core is last in the list.
263 */
264 conf->realm = realm;
265
266 /* we precompute the part of the nonce hash that is constant (well,
267 * the host:port would be too, but that varies for .htaccess files
268 * and directives outside a virtual host section)
269 */
270 ap_SHA1Init(&conf->nonce_ctx);
271 ap_SHA1Update_binary(&conf->nonce_ctx, secret, sizeof(secret));
272 ap_SHA1Update_binary(&conf->nonce_ctx, (const unsigned char *) realm,
273 strlen(realm));
274
275 return DECLINE_CMD;
276 }
277
set_digest_file(cmd_parms * cmd,void * config,const char * file)278 static const char *set_digest_file(cmd_parms *cmd, void *config,
279 const char *file)
280 {
281 ((digest_config_rec *) config)->pwfile = file;
282 ap_server_strip_chroot((char *)(((digest_config_rec *) config)->pwfile), 1);
283 return NULL;
284 }
285
set_group_file(cmd_parms * cmd,void * config,const char * file)286 static const char *set_group_file(cmd_parms *cmd, void *config,
287 const char *file)
288 {
289 ((digest_config_rec *) config)->grpfile = file;
290 ap_server_strip_chroot((char *)(((digest_config_rec *) config)->grpfile), 1);
291 return NULL;
292 }
293
set_qop(cmd_parms * cmd,void * config,const char * op)294 static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
295 {
296 digest_config_rec *conf = (digest_config_rec *) config;
297 char **tmp;
298 int cnt;
299
300 if (!strcasecmp(op, "none")) {
301 if (conf->qop_list[0] == NULL) {
302 conf->qop_list = ap_palloc(cmd->pool, 2 * sizeof(char*));
303 conf->qop_list[1] = NULL;
304 }
305 conf->qop_list[0] = "none";
306 return NULL;
307 }
308
309 if (!strcasecmp(op, "auth-int"))
310 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, cmd->server,
311 "Digest: WARNING: qop `auth-int' currently only works "
312 "correctly for responses with no entity");
313 else if (strcasecmp(op, "auth"))
314 return ap_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
315
316 for (cnt=0; conf->qop_list[cnt] != NULL; cnt++)
317 ;
318 tmp = ap_palloc(cmd->pool, (cnt+2)*sizeof(char*));
319 memcpy(tmp, conf->qop_list, cnt*sizeof(char*));
320 tmp[cnt] = ap_pstrdup(cmd->pool, op);
321 tmp[cnt+1] = NULL;
322 conf->qop_list = (const char **)tmp;
323
324 return NULL;
325 }
326
set_nonce_lifetime(cmd_parms * cmd,void * config,const char * t)327 static const char *set_nonce_lifetime(cmd_parms *cmd, void *config,
328 const char *t)
329 {
330 char *endptr;
331 long lifetime;
332
333 lifetime = ap_strtol(t, &endptr, 10);
334 if (endptr < (t+strlen(t)) && !ap_isspace(*endptr))
335 return ap_pstrcat(cmd->pool, "Invalid time in AuthDigestNonceLifetime: ", t, NULL);
336
337 ((digest_config_rec *) config)->nonce_lifetime = lifetime;
338 return NULL;
339 }
340
set_nonce_format(cmd_parms * cmd,void * config,const char * fmt)341 static const char *set_nonce_format(cmd_parms *cmd, void *config,
342 const char *fmt)
343 {
344 ((digest_config_rec *) config)->nonce_format = fmt;
345 return "AuthDigestNonceFormat is not implemented (yet)";
346 }
347
set_nc_check(cmd_parms * cmd,void * config,int flag)348 static const char *set_nc_check(cmd_parms *cmd, void *config, int flag)
349 {
350 ((digest_config_rec *) config)->check_nc = flag;
351 return NULL;
352 }
353
set_algorithm(cmd_parms * cmd,void * config,const char * alg)354 static const char *set_algorithm(cmd_parms *cmd, void *config, const char *alg)
355 {
356 if (!strcasecmp(alg, "MD5-sess"))
357 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, cmd->server,
358 "Digest: WARNING: algorithm `MD5-sess' is currently not "
359 "correctly implemented");
360 else if (strcasecmp(alg, "MD5"))
361 return ap_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
362
363 ((digest_config_rec *) config)->algorithm = alg;
364 return NULL;
365 }
366
set_uri_list(cmd_parms * cmd,void * config,const char * uri)367 static const char *set_uri_list(cmd_parms *cmd, void *config, const char *uri)
368 {
369 digest_config_rec *c = (digest_config_rec *) config;
370 if (c->uri_list) {
371 c->uri_list[strlen(c->uri_list)-1] = '\0';
372 c->uri_list = ap_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
373 }
374 else
375 c->uri_list = ap_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
376 return NULL;
377 }
378
379 static const command_rec digest_cmds[] =
380 {
381 {"AuthName", set_realm, NULL, OR_AUTHCFG, TAKE1,
382 "The authentication realm (e.g. \"Members Only\")"},
383 {"AuthDigestFile", set_digest_file, NULL, OR_AUTHCFG, TAKE1,
384 "The name of the file containing the usernames and password hashes"},
385 {"AuthDigestGroupFile", set_group_file, NULL, OR_AUTHCFG, TAKE1,
386 "The name of the file containing the group names and members"},
387 {"AuthDigestQop", set_qop, NULL, OR_AUTHCFG, ITERATE,
388 "A list of quality-of-protection options"},
389 {"AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG, TAKE1,
390 "Maximum lifetime of the server nonce (seconds)"},
391 {"AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG, TAKE1,
392 "The format to use when generating the server nonce"},
393 {"AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG, FLAG,
394 "Whether or not to check the nonce-count sent by the client"},
395 {"AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG, TAKE1,
396 "The algorithm used for the hash calculation"},
397 {"AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG, ITERATE,
398 "A list of URI's which belong to the same protection space as the current URI"},
399 {NULL, NULL, NULL, 0, 0, NULL}
400 };
401
get_client(unsigned long key,const request_rec * r)402 static client_entry *get_client(unsigned long key, const request_rec *r)
403 {
404 return NULL;
405 }
406
407 /*
408 * Authorization header parser code
409 */
410
411 /* Parse the Authorization header, if it exists */
get_digest_rec(request_rec * r,digest_header_rec * resp)412 static int get_digest_rec(request_rec *r, digest_header_rec *resp)
413 {
414 const char *auth_line;
415 size_t l;
416 int vk = 0, vv = 0;
417 char *key, *value;
418
419 auth_line = ap_table_get(r->headers_in,
420 r->proxyreq == STD_PROXY ? "Proxy-Authorization"
421 : "Authorization");
422 if (!auth_line) {
423 resp->auth_hdr_sts = NO_HEADER;
424 return !OK;
425 }
426
427 resp->scheme = ap_getword_white(r->pool, &auth_line);
428 if (strcasecmp(resp->scheme, "Digest")) {
429 resp->auth_hdr_sts = NOT_DIGEST;
430 return !OK;
431 }
432
433 l = strlen(auth_line);
434
435 key = ap_palloc(r->pool, l+1);
436 value = ap_palloc(r->pool, l+1);
437
438 while (auth_line[0] != '\0') {
439
440 /* find key */
441
442 while (ap_isspace(auth_line[0])) auth_line++;
443 vk = 0;
444 while (auth_line[0] != '=' && auth_line[0] != ','
445 && auth_line[0] != '\0' && !ap_isspace(auth_line[0]))
446 key[vk++] = *auth_line++;
447 key[vk] = '\0';
448 while (ap_isspace(auth_line[0])) auth_line++;
449
450 /* find value */
451
452 if (auth_line[0] == '=') {
453 auth_line++;
454 while (ap_isspace(auth_line[0])) auth_line++;
455
456 vv = 0;
457 if (auth_line[0] == '\"') { /* quoted string */
458 auth_line++;
459 while (auth_line[0] != '\"' && auth_line[0] != '\0') {
460 if (auth_line[0] == '\\' && auth_line[1] != '\0')
461 auth_line++; /* escaped char */
462 value[vv++] = *auth_line++;
463 }
464 if (auth_line[0] != '\0') auth_line++;
465 }
466 else { /* token */
467 while (auth_line[0] != ',' && auth_line[0] != '\0'
468 && !ap_isspace(auth_line[0]))
469 value[vv++] = *auth_line++;
470 }
471 value[vv] = '\0';
472 }
473
474 while (auth_line[0] != ',' && auth_line[0] != '\0') auth_line++;
475 if (auth_line[0] != '\0') auth_line++;
476
477 if (!strcasecmp(key, "username"))
478 resp->username = ap_pstrdup(r->pool, value);
479 else if (!strcasecmp(key, "realm"))
480 resp->realm = ap_pstrdup(r->pool, value);
481 else if (!strcasecmp(key, "nonce"))
482 resp->nonce = ap_pstrdup(r->pool, value);
483 else if (!strcasecmp(key, "uri"))
484 resp->uri = ap_pstrdup(r->pool, value);
485 else if (!strcasecmp(key, "response"))
486 resp->digest = ap_pstrdup(r->pool, value);
487 else if (!strcasecmp(key, "algorithm"))
488 resp->algorithm = ap_pstrdup(r->pool, value);
489 else if (!strcasecmp(key, "cnonce"))
490 resp->cnonce = ap_pstrdup(r->pool, value);
491 else if (!strcasecmp(key, "opaque"))
492 resp->opaque = ap_pstrdup(r->pool, value);
493 else if (!strcasecmp(key, "qop"))
494 resp->message_qop = ap_pstrdup(r->pool, value);
495 else if (!strcasecmp(key, "nc"))
496 resp->nonce_count = ap_pstrdup(r->pool, value);
497 }
498
499 if (!resp->username || !resp->realm || !resp->nonce || !resp->uri
500 || !resp->digest
501 || (resp->message_qop && (!resp->cnonce || !resp->nonce_count))) {
502 resp->auth_hdr_sts = INVALID;
503 return !OK;
504 }
505
506 if (resp->opaque)
507 resp->opaque_num = (unsigned long) ap_strtol(resp->opaque, NULL, 16);
508
509 resp->auth_hdr_sts = VALID;
510 return OK;
511 }
512
513
514 /* Because the browser may preemptively send auth info, incrementing the
515 * nonce-count when it does, and because the client does not get notified
516 * if the URI didn't need authentication after all, we need to be sure to
517 * update the nonce-count each time we receive an Authorization header no
518 * matter what the final outcome of the request. Furthermore this is a
519 * convenient place to get the request-uri (before any subrequests etc
520 * are initiated) and to initialize the request_config.
521 *
522 * Note that this must be called after mod_proxy had its go so that
523 * r->proxyreq is set correctly.
524 */
update_nonce_count(request_rec * r)525 static int update_nonce_count(request_rec *r)
526 {
527 digest_header_rec *resp;
528 int res;
529
530 if (!ap_is_initial_req(r))
531 return DECLINED;
532
533 resp = ap_pcalloc(r->pool, sizeof(digest_header_rec));
534 resp->raw_request_uri = r->unparsed_uri;
535 resp->psd_request_uri = &r->parsed_uri;
536 resp->needed_auth = 0;
537 ap_set_module_config(r->request_config, &digest_auth_module, resp);
538
539 res = get_digest_rec(r, resp);
540 resp->client = get_client(resp->opaque_num, r);
541 if (res == OK && resp->client)
542 resp->client->nonce_count++;
543
544 return DECLINED;
545 }
546
547
548 /*
549 * Nonce generation code
550 */
551
552 /* The hash part of the nonce is a SHA-1 hash of the time, realm, server host
553 * and port, opaque, and our secret.
554 */
gen_nonce_hash(char * hash,const char * timestr,const char * opaque,const server_rec * server,const digest_config_rec * conf)555 static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
556 const server_rec *server,
557 const digest_config_rec *conf)
558 {
559 const char *hex = "0123456789abcdef";
560 unsigned char sha1[SHA_DIGESTSIZE];
561 AP_SHA1_CTX ctx;
562 int idx;
563
564 memcpy(&ctx, &conf->nonce_ctx, sizeof(ctx));
565 /*
566 ap_SHA1Update_binary(&ctx, (const unsigned char *) server->server_hostname,
567 strlen(server->server_hostname));
568 ap_SHA1Update_binary(&ctx, (const unsigned char *) &server->port,
569 sizeof(server->port));
570 */
571 ap_SHA1Update_binary(&ctx, (const unsigned char *) timestr, strlen(timestr));
572 if (opaque)
573 ap_SHA1Update_binary(&ctx, (const unsigned char *) opaque,
574 strlen(opaque));
575 ap_SHA1Final(sha1, &ctx);
576
577 for (idx=0; idx<SHA_DIGESTSIZE; idx++) {
578 *hash++ = hex[sha1[idx] >> 4];
579 *hash++ = hex[sha1[idx] & 0xF];
580 }
581
582 *hash++ = '\0';
583 }
584
585
586 /* The nonce has the format b64(time)+hash .
587 */
gen_nonce(pool * p,time_t now,const char * opaque,const server_rec * server,const digest_config_rec * conf)588 static const char *gen_nonce(pool *p, time_t now, const char *opaque,
589 const server_rec *server,
590 const digest_config_rec *conf)
591 {
592 char *nonce = ap_palloc(p, NONCE_LEN+1);
593 time_rec t;
594
595 if (conf->nonce_lifetime != 0)
596 t.time = now;
597 else
598 t.time = 42;
599 ap_base64encode_binary(nonce, t.arr, sizeof(t.arr));
600 gen_nonce_hash(nonce+NONCE_TIME_LEN, nonce, opaque, server, conf);
601
602 return nonce;
603 }
604
605
606 /*
607 * Opaque and hash-table management
608 */
609
gen_client(const request_rec * r)610 static client_entry *gen_client(const request_rec *r) { return NULL; }
611
612
613
614 /*
615 * MD5-sess code.
616 *
617 * If you want to use algorithm=MD5-sess you must write get_userpw_hash()
618 * yourself (see below). The dummy provided here just uses the hash from
619 * the auth-file, i.e. it is only useful for testing client implementations
620 * of MD5-sess .
621 */
622
623 /*
624 * get_userpw_hash() will be called each time a new session needs to be
625 * generated and is expected to return the equivalent of
626 *
627 * h_urp = ap_md5(r->pool,
628 * ap_pstrcat(r->pool, username, ":", ap_auth_name(r), ":", passwd))
629 * ap_md5(r->pool,
630 * (unsigned char *) ap_pstrcat(r->pool, h_urp, ":", resp->nonce, ":",
631 * resp->cnonce, NULL));
632 *
633 * or put differently, it must return
634 *
635 * MD5(MD5(username ":" realm ":" password) ":" nonce ":" cnonce)
636 *
637 * If something goes wrong, the failure must be logged and NULL returned.
638 *
639 * You must implement this yourself, which will probably consist of code
640 * contacting the password server with the necessary information (typically
641 * the username, realm, nonce, and cnonce) and receiving the hash from it.
642 *
643 * TBD: This function should probably be in a seperate source file so that
644 * people need not modify mod_auth_digest.c each time they install a new
645 * version of apache.
646 */
get_userpw_hash(const request_rec * r,const digest_header_rec * resp,const digest_config_rec * conf)647 static const char *get_userpw_hash(const request_rec *r,
648 const digest_header_rec *resp,
649 const digest_config_rec *conf)
650 {
651 return ap_md5(r->pool,
652 (unsigned char *) ap_pstrcat(r->pool, conf->ha1, ":", resp->nonce,
653 ":", resp->cnonce, NULL));
654 }
655
656
657 /* Retrieve current session H(A1). If there is none and "generate" is
658 * true then a new session for MD5-sess is generated and stored in the
659 * client struct; if generate is false, or a new session could not be
660 * generated then NULL is returned (in case of failure to generate the
661 * failure reason will have been logged already).
662 */
get_session_HA1(const request_rec * r,digest_header_rec * resp,const digest_config_rec * conf,int generate)663 static const char *get_session_HA1(const request_rec *r,
664 digest_header_rec *resp,
665 const digest_config_rec *conf,
666 int generate)
667 {
668 const char *ha1 = NULL;
669
670 /* return the current sessions if there is one */
671 if (resp->opaque && resp->client && resp->client->ha1[0])
672 return resp->client->ha1;
673 else if (!generate)
674 return NULL;
675
676 /* generate a new session */
677 if (!resp->client)
678 resp->client = gen_client(r);
679 if (resp->client) {
680 ha1 = get_userpw_hash(r, resp, conf);
681 if (ha1)
682 memcpy(resp->client->ha1, ha1, sizeof(resp->client->ha1));
683 }
684
685 return ha1;
686 }
687
688
clear_session(const digest_header_rec * resp)689 static void clear_session(const digest_header_rec *resp)
690 {
691 if (resp->client)
692 resp->client->ha1[0] = '\0';
693 }
694
695 /*
696 * Authorization challenge generation code (for WWW-Authenticate)
697 */
698
ltox(pool * p,unsigned long num)699 static const char *ltox(pool *p, unsigned long num)
700 {
701 if (num != 0)
702 return ap_psprintf(p, "%lx", num);
703 else
704 return "";
705 }
706
note_digest_auth_failure(request_rec * r,const digest_config_rec * conf,digest_header_rec * resp,int stale)707 static void note_digest_auth_failure(request_rec *r,
708 const digest_config_rec *conf,
709 digest_header_rec *resp, int stale)
710 {
711 const char *qop, *opaque, *opaque_param, *domain, *nonce;
712 int cnt;
713
714
715 /* Setup qop */
716
717 if (conf->qop_list[0] == NULL)
718 qop = ", qop=\"auth\"";
719 else if (!strcasecmp(conf->qop_list[0], "none"))
720 qop = "";
721 else {
722 qop = ap_pstrcat(r->pool, ", qop=\"", conf->qop_list[0], NULL);
723 for (cnt=1; conf->qop_list[cnt] != NULL; cnt++)
724 qop = ap_pstrcat(r->pool, qop, ",", conf->qop_list[cnt], NULL);
725 qop = ap_pstrcat(r->pool, qop, "\"", NULL);
726 }
727
728 /* Setup opaque */
729
730 if (resp->opaque == NULL) {
731 /* new client */
732 if ((conf->check_nc || conf->nonce_lifetime == 0
733 || !strcasecmp(conf->algorithm, "MD5-sess"))
734 && (resp->client = gen_client(r)) != NULL)
735 opaque = ltox(r->pool, resp->client->key);
736 else
737 opaque = ""; /* opaque not needed */
738 }
739 else if (resp->client == NULL) {
740 /* client info was gc'd */
741 resp->client = gen_client(r);
742 if (resp->client != NULL) {
743 opaque = ltox(r->pool, resp->client->key);
744 stale = 1;
745 client_list->num_renewed++;
746 }
747 else
748 opaque = ""; /* ??? */
749 }
750 else {
751 opaque = resp->opaque;
752 /* we're generating a new nonce, so reset the nonce-count */
753 resp->client->nonce_count = 0;
754 }
755
756 if (opaque[0])
757 opaque_param = ap_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
758 else
759 opaque_param = NULL;
760
761 /* Setup nonce */
762
763 nonce = gen_nonce(r->pool, r->request_time, opaque, r->server, conf);
764 if (resp->client && conf->nonce_lifetime == 0)
765 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
766
767 /* Setup MD5-sess stuff. Note that we just clear out the session
768 * info here, since we can't generate a new session until the request
769 * from the client comes in with the cnonce.
770 */
771
772 if (!strcasecmp(conf->algorithm, "MD5-sess"))
773 clear_session(resp);
774
775 /* setup domain attribute. We want to send this attribute wherever
776 * possible so that the client won't send the Authorization header
777 * unneccessarily (it's usually > 200 bytes!).
778 */
779
780 /* don't send domain
781 * - for proxy requests
782 * - if it's no specified
783 */
784 if (r->proxyreq || !conf->uri_list) {
785 domain = NULL;
786 }
787 else {
788 domain = conf->uri_list;
789 }
790
791 ap_table_mergen(r->err_headers_out,
792 r->proxyreq == STD_PROXY ? "Proxy-Authenticate"
793 : "WWW-Authenticate",
794 ap_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%s\", "
795 "algorithm=%s%s%s%s%s",
796 ap_auth_name(r), nonce, conf->algorithm,
797 opaque_param ? opaque_param : "",
798 domain ? domain : "",
799 stale ? ", stale=true" : "", qop));
800 }
801
802
803 /*
804 * Authorization header verification code
805 */
806
get_hash(request_rec * r,const char * user,const char * realm,const char * auth_pwfile)807 static const char *get_hash(request_rec *r, const char *user,
808 const char *realm, const char *auth_pwfile)
809 {
810 configfile_t *f;
811 char l[MAX_STRING_LEN];
812 const char *rpw;
813 char *w, *x;
814
815 if (!(f = ap_pcfg_openfile(r->pool, auth_pwfile))) {
816 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
817 "Digest: Could not open password file: %s", auth_pwfile);
818 return NULL;
819 }
820 while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
821 if ((l[0] == '#') || (!l[0]))
822 continue;
823 rpw = l;
824 w = ap_getword(r->pool, &rpw, ':');
825 x = ap_getword(r->pool, &rpw, ':');
826
827 if (x && w && !strcmp(user, w) && !strcmp(realm, x)) {
828 ap_cfg_closefile(f);
829 return ap_pstrdup(r->pool, rpw);
830 }
831 }
832 ap_cfg_closefile(f);
833 return NULL;
834 }
835
check_nc(const request_rec * r,const digest_header_rec * resp,const digest_config_rec * conf)836 static int check_nc(const request_rec *r, const digest_header_rec *resp,
837 const digest_config_rec *conf)
838 {
839 unsigned long nc;
840 const char *snc = resp->nonce_count;
841 char *endptr;
842
843 if (!conf->check_nc || !client_mm)
844 return OK;
845
846 nc = ap_strtol(snc, &endptr, 16);
847 if (endptr < (snc+strlen(snc)) && !ap_isspace(*endptr)) {
848 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
849 "Digest: invalid nc %s received - not a number", snc);
850 return !OK;
851 }
852
853 if (!resp->client)
854 return !OK;
855
856 if (nc != resp->client->nonce_count) {
857 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
858 "Digest: Warning, possible replay attack: nonce-count "
859 "check failed: %lu != %lu", nc,
860 resp->client->nonce_count);
861 return !OK;
862 }
863
864 return OK;
865 }
866
check_nonce(request_rec * r,digest_header_rec * resp,const digest_config_rec * conf)867 static int check_nonce(request_rec *r, digest_header_rec *resp,
868 const digest_config_rec *conf)
869 {
870 double dt;
871 time_rec nonce_time;
872 char tmp, hash[NONCE_HASH_LEN+1];
873
874 if (strlen(resp->nonce) != NONCE_LEN) {
875 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
876 "Digest: invalid nonce %s received - length is not %zu",
877 resp->nonce, NONCE_LEN);
878 note_digest_auth_failure(r, conf, resp, 1);
879 return AUTH_REQUIRED;
880 }
881
882 tmp = resp->nonce[NONCE_TIME_LEN];
883 resp->nonce[NONCE_TIME_LEN] = '\0';
884 ap_base64decode_binary(nonce_time.arr, resp->nonce);
885 gen_nonce_hash(hash, resp->nonce, resp->opaque, r->server, conf);
886 resp->nonce[NONCE_TIME_LEN] = tmp;
887 resp->nonce_time = nonce_time.time;
888
889 if (strcmp(hash, resp->nonce+NONCE_TIME_LEN)) {
890 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
891 "Digest: invalid nonce %s received - hash is not %s",
892 resp->nonce, hash);
893 note_digest_auth_failure(r, conf, resp, 1);
894 return AUTH_REQUIRED;
895 }
896
897 dt = difftime(r->request_time, nonce_time.time);
898 if (conf->nonce_lifetime > 0 && dt < 0) {
899 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
900 "Digest: invalid nonce %s received - user attempted "
901 "time travel", resp->nonce);
902 note_digest_auth_failure(r, conf, resp, 1);
903 return AUTH_REQUIRED;
904 }
905
906 if (conf->nonce_lifetime > 0) {
907 if (dt > conf->nonce_lifetime) {
908 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, r,
909 "Digest: user %s: nonce expired - sending new nonce",
910 r->connection->user);
911 note_digest_auth_failure(r, conf, resp, 1);
912 return AUTH_REQUIRED;
913 }
914 }
915 else if (conf->nonce_lifetime == 0 && resp->client) {
916 if (memcmp(resp->client->last_nonce, resp->nonce, NONCE_LEN)) {
917 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, r,
918 "Digest: user %s: one-time-nonce mismatch - sending "
919 "new nonce", r->connection->user);
920 note_digest_auth_failure(r, conf, resp, 1);
921 return AUTH_REQUIRED;
922 }
923 }
924 /* else (lifetime < 0) => never expires */
925
926 return OK;
927 }
928
929 /* The actual MD5 code... whee */
930
931 /* RFC-2069 */
old_digest(const request_rec * r,const digest_header_rec * resp,const char * ha1)932 static const char *old_digest(const request_rec *r,
933 const digest_header_rec *resp, const char *ha1)
934 {
935 const char *ha2;
936
937 ha2 = ap_md5(r->pool, (unsigned char *)ap_pstrcat(r->pool, r->method, ":",
938 resp->uri, NULL));
939 return ap_md5(r->pool,
940 (unsigned char *)ap_pstrcat(r->pool, ha1, ":", resp->nonce,
941 ":", ha2, NULL));
942 }
943
944 /* RFC-2617 */
new_digest(const request_rec * r,digest_header_rec * resp,const digest_config_rec * conf)945 static const char *new_digest(const request_rec *r,
946 digest_header_rec *resp,
947 const digest_config_rec *conf)
948 {
949 const char *ha1, *ha2, *a2;
950
951 if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
952 ha1 = get_session_HA1(r, resp, conf, 1);
953 if (!ha1)
954 return NULL;
955 }
956 else
957 ha1 = conf->ha1;
958
959 if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int"))
960 a2 = ap_pstrcat(r->pool, r->method, ":", resp->uri, ":",
961 ap_md5(r->pool, (const unsigned char*) ""), NULL); /* TBD */
962 else
963 a2 = ap_pstrcat(r->pool, r->method, ":", resp->uri, NULL);
964 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
965
966 return ap_md5(r->pool,
967 (unsigned char *)ap_pstrcat(r->pool, ha1, ":", resp->nonce,
968 ":", resp->nonce_count, ":",
969 resp->cnonce, ":",
970 resp->message_qop, ":", ha2,
971 NULL));
972 }
973
974
copy_uri_components(uri_components * dst,uri_components * src,request_rec * r)975 static void copy_uri_components(uri_components *dst, uri_components *src,
976 request_rec *r)
977 {
978 if (src->scheme && src->scheme[0] != '\0')
979 dst->scheme = src->scheme;
980 else
981 dst->scheme = (char *) "http";
982
983 if (src->hostname && src->hostname[0] != '\0') {
984 dst->hostname = ap_pstrdup(r->pool, src->hostname);
985 ap_unescape_url(dst->hostname);
986 }
987 else
988 dst->hostname = (char *) ap_get_server_name(r);
989
990 if (src->port_str && src->port_str[0] != '\0')
991 dst->port = src->port;
992 else
993 dst->port = ap_get_server_port(r);
994
995 if (src->path && src->path[0] != '\0') {
996 dst->path = ap_pstrdup(r->pool, src->path);
997 ap_unescape_url(dst->path);
998 }
999 else
1000 dst->path = src->path;
1001
1002 if (src->query && src->query[0] != '\0') {
1003 dst->query = ap_pstrdup(r->pool, src->query);
1004 ap_unescape_url(dst->query);
1005 }
1006 else
1007 dst->query = src->query;
1008 }
1009
1010 /* This handles non-FQDN's. If h1 is empty, the comparison succeeds. Else
1011 * if h1 is a FQDN (i.e. contains a '.') then normal strcasecmp() is done.
1012 * Else only the first part of h2 (up to the first '.') is compared.
1013 */
compare_hostnames(const char * h1,const char * h2)1014 static int compare_hostnames(const char *h1, const char *h2)
1015 {
1016 const char *dot;
1017
1018 /* if no hostname given, then ok */
1019 if (!h1 || h1[0] == '\0')
1020 return 1;
1021
1022 /* handle FQDN's in h1 */
1023 dot = strchr(h1, '.');
1024 if (dot != NULL)
1025 return !strcasecmp(h1, h2);
1026
1027 /* handle non-FQDN's in h1 */
1028 dot = strchr(h2, '.');
1029 if (dot == NULL)
1030 return !strcasecmp(h1, h2);
1031 else
1032 return (strlen(h1) == (size_t) (dot - h2)) && !strncasecmp(h1, h2, dot-h2);
1033 }
1034
1035 /* These functions return 0 if client is OK, and proper error status
1036 * if not... either AUTH_REQUIRED, if we made a check, and it failed, or
1037 * SERVER_ERROR, if things are so totally confused that we couldn't
1038 * figure out how to tell if the client is authorized or not.
1039 *
1040 * If they return DECLINED, and all other modules also decline, that's
1041 * treated by the server core as a configuration error, logged and
1042 * reported as such.
1043 */
1044
1045 /* Determine user ID, and check if the attributes are correct, if it
1046 * really is that user, if the nonce is correct, etc.
1047 */
1048
authenticate_digest_user(request_rec * r)1049 static int authenticate_digest_user(request_rec *r)
1050 {
1051 digest_config_rec *conf;
1052 digest_header_rec *resp;
1053 request_rec *mainreq;
1054 conn_rec *conn = r->connection;
1055 const char *t;
1056 int res;
1057
1058
1059 /* do we require Digest auth for this URI? */
1060
1061 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest"))
1062 return DECLINED;
1063
1064 if (!ap_auth_name(r)) {
1065 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1066 "Digest: need AuthName: %s", r->uri);
1067 return SERVER_ERROR;
1068 }
1069
1070
1071 /* get the client response and mark */
1072
1073 mainreq = r;
1074 while (mainreq->main != NULL) mainreq = mainreq->main;
1075 while (mainreq->prev != NULL) mainreq = mainreq->prev;
1076 resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
1077 &digest_auth_module);
1078 resp->needed_auth = 1;
1079
1080
1081 /* get our conf */
1082
1083 conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1084 &digest_auth_module);
1085
1086
1087 /* check for existence and syntax of Auth header */
1088
1089 if (resp->auth_hdr_sts != VALID) {
1090 if (resp->auth_hdr_sts == NOT_DIGEST)
1091 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1092 "Digest: client used wrong authentication scheme "
1093 "`%s': %s", resp->scheme, r->uri);
1094 else if (resp->auth_hdr_sts == INVALID)
1095 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1096 "Digest: missing user, realm, nonce, uri, digest, "
1097 "cnonce, or nonce_count in authorization header: %s",
1098 r->uri);
1099 /* else (resp->auth_hdr_sts == NO_HEADER) */
1100 note_digest_auth_failure(r, conf, resp, 0);
1101 return AUTH_REQUIRED;
1102 }
1103
1104 r->connection->user = (char *) resp->username;
1105 r->connection->ap_auth_type = (char *) "Digest";
1106
1107
1108 /* check the auth attributes */
1109
1110 if (strcmp(resp->uri, resp->raw_request_uri)) {
1111 /* Hmm, the simple match didn't work (probably a proxy modified the
1112 * request-uri), so lets do a more sophisticated match
1113 */
1114 uri_components r_uri, d_uri;
1115
1116 copy_uri_components(&r_uri, resp->psd_request_uri, r);
1117 if (ap_parse_uri_components(r->pool, resp->uri, &d_uri) != HTTP_OK) {
1118 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1119 "Digest: invalid uri <%s> in Authorization header",
1120 resp->uri);
1121 return BAD_REQUEST;
1122 }
1123
1124 if (d_uri.hostname)
1125 ap_unescape_url(d_uri.hostname);
1126 if (d_uri.path)
1127 ap_unescape_url(d_uri.path);
1128 if (d_uri.query)
1129 ap_unescape_url(d_uri.query);
1130
1131 if (r->method_number == M_CONNECT) {
1132 if (strcmp(resp->uri, r_uri.hostinfo)) {
1133 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1134 "Digest: uri mismatch - <%s> does not match "
1135 "request-uri <%s>", resp->uri, r_uri.hostinfo);
1136 return BAD_REQUEST;
1137 }
1138 }
1139 else if (
1140 /* check hostname matches, if present */
1141 !compare_hostnames(d_uri.hostname, r_uri.hostname)
1142 /* check port matches, if present */
1143 || (d_uri.port_str && d_uri.port != r_uri.port)
1144 /* check that server-port is default port if no port present */
1145 || (d_uri.hostname && d_uri.hostname[0] != '\0'
1146 && !d_uri.port_str && r_uri.port != ap_default_port(r))
1147 /* check that path matches */
1148 || (d_uri.path != r_uri.path
1149 /* either exact match */
1150 && (!d_uri.path || !r_uri.path
1151 || strcmp(d_uri.path, r_uri.path))
1152 /* or '*' matches empty path in scheme://host */
1153 && !(d_uri.path && !r_uri.path && resp->psd_request_uri->hostname
1154 && d_uri.path[0] == '*' && d_uri.path[1] == '\0'))
1155 ) {
1156 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1157 "Digest: uri mismatch - <%s> does not match "
1158 "request-uri <%s>", resp->uri, resp->raw_request_uri);
1159 return BAD_REQUEST;
1160 }
1161 }
1162
1163 if (resp->opaque && resp->opaque_num == 0) {
1164 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1165 "Digest: received invalid opaque - got `%s'",
1166 resp->opaque);
1167 note_digest_auth_failure(r, conf, resp, 0);
1168 return AUTH_REQUIRED;
1169 }
1170
1171 if (strcmp(resp->realm, conf->realm)) {
1172 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1173 "Digest: realm mismatch - got `%s' but expected `%s'",
1174 resp->realm, conf->realm);
1175 note_digest_auth_failure(r, conf, resp, 0);
1176 return AUTH_REQUIRED;
1177 }
1178
1179 if (resp->algorithm != NULL
1180 && strcasecmp(resp->algorithm, "MD5")
1181 && strcasecmp(resp->algorithm, "MD5-sess")) {
1182 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1183 "Digest: unknown algorithm `%s' received: %s",
1184 resp->algorithm, r->uri);
1185 note_digest_auth_failure(r, conf, resp, 0);
1186 return AUTH_REQUIRED;
1187 }
1188
1189 if (!conf->pwfile)
1190 return DECLINED;
1191
1192 if (!(conf->ha1 = get_hash(r, conn->user, conf->realm, conf->pwfile))) {
1193 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1194 "Digest: user `%s' in realm `%s' not found: %s",
1195 conn->user, conf->realm, r->uri);
1196 note_digest_auth_failure(r, conf, resp, 0);
1197 return AUTH_REQUIRED;
1198 }
1199
1200 if (resp->message_qop == NULL) {
1201 /* old (rfc-2069) style digest */
1202 if (strcmp(resp->digest, old_digest(r, resp, conf->ha1))) {
1203 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1204 "Digest: user %s: password mismatch: %s", conn->user,
1205 r->uri);
1206 note_digest_auth_failure(r, conf, resp, 0);
1207 return AUTH_REQUIRED;
1208 }
1209 }
1210 else {
1211 const char *exp_digest;
1212 int match = 0, idx;
1213 for (idx=0; conf->qop_list[idx] != NULL; idx++) {
1214 if (!strcasecmp(conf->qop_list[idx], resp->message_qop)) {
1215 match = 1;
1216 break;
1217 }
1218 }
1219
1220 if (!match
1221 && !(conf->qop_list[0] == NULL
1222 && !strcasecmp(resp->message_qop, "auth"))) {
1223 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1224 "Digest: invalid qop `%s' received: %s",
1225 resp->message_qop, r->uri);
1226 note_digest_auth_failure(r, conf, resp, 0);
1227 return AUTH_REQUIRED;
1228 }
1229
1230 if (check_nc(r, resp, conf) != OK) {
1231 note_digest_auth_failure(r, conf, resp, 0);
1232 return AUTH_REQUIRED;
1233 }
1234
1235 exp_digest = new_digest(r, resp, conf);
1236 if (!exp_digest) {
1237 /* we failed to allocate a client struct */
1238 return SERVER_ERROR;
1239 }
1240 if (strcmp(resp->digest, exp_digest)) {
1241 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1242 "Digest: user %s: password mismatch: %s", conn->user,
1243 r->uri);
1244 note_digest_auth_failure(r, conf, resp, 0);
1245 return AUTH_REQUIRED;
1246 }
1247 }
1248
1249 /* Note: this check is done last so that a "stale=true" can be
1250 generated if the nonce is old */
1251 if ((res = check_nonce(r, resp, conf)))
1252 return res;
1253
1254 return OK;
1255 }
1256
1257
1258 /*
1259 * Checking ID
1260 */
1261
groups_for_user(request_rec * r,const char * user,const char * grpfile)1262 static table *groups_for_user(request_rec *r, const char *user,
1263 const char *grpfile)
1264 {
1265 configfile_t *f;
1266 table *grps = ap_make_table(r->pool, 15);
1267 pool *sp;
1268 char l[MAX_STRING_LEN];
1269 const char *group_name, *ll, *w;
1270
1271 if (!(f = ap_pcfg_openfile(r->pool, grpfile))) {
1272 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
1273 "Digest: Could not open group file: %s", grpfile);
1274 return NULL;
1275 }
1276
1277 sp = ap_make_sub_pool(r->pool);
1278
1279 while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
1280 if ((l[0] == '#') || (!l[0]))
1281 continue;
1282 ll = l;
1283 ap_clear_pool(sp);
1284
1285 group_name = ap_getword(sp, &ll, ':');
1286
1287 while (ll[0]) {
1288 w = ap_getword_conf(sp, &ll);
1289 if (!strcmp(w, user)) {
1290 ap_table_setn(grps, ap_pstrdup(r->pool, group_name), "in");
1291 break;
1292 }
1293 }
1294 }
1295
1296 ap_cfg_closefile(f);
1297 ap_destroy_pool(sp);
1298 return grps;
1299 }
1300
1301
digest_check_auth(request_rec * r)1302 static int digest_check_auth(request_rec *r)
1303 {
1304 const digest_config_rec *conf =
1305 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1306 &digest_auth_module);
1307 const char *user = r->connection->user;
1308 int m = r->method_number;
1309 int method_restricted = 0;
1310 register int x;
1311 const char *t, *w;
1312 table *grpstatus;
1313 const array_header *reqs_arr;
1314 require_line *reqs;
1315
1316 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest"))
1317 return DECLINED;
1318
1319 reqs_arr = ap_requires(r);
1320 /* If there is no "requires" directive, then any user will do.
1321 */
1322 if (!reqs_arr)
1323 return OK;
1324 reqs = (require_line *) reqs_arr->elts;
1325
1326 if (conf->grpfile)
1327 grpstatus = groups_for_user(r, user, conf->grpfile);
1328 else
1329 grpstatus = NULL;
1330
1331 for (x = 0; x < reqs_arr->nelts; x++) {
1332
1333 if (!(reqs[x].method_mask & (1 << m)))
1334 continue;
1335
1336 method_restricted = 1;
1337
1338 t = reqs[x].requirement;
1339 w = ap_getword_white(r->pool, &t);
1340 if (!strcasecmp(w, "valid-user"))
1341 return OK;
1342 else if (!strcasecmp(w, "user")) {
1343 while (t[0]) {
1344 w = ap_getword_conf(r->pool, &t);
1345 if (!strcmp(user, w))
1346 return OK;
1347 }
1348 }
1349 else if (!strcasecmp(w, "group")) {
1350 if (!grpstatus)
1351 return DECLINED;
1352
1353 while (t[0]) {
1354 w = ap_getword_conf(r->pool, &t);
1355 if (ap_table_get(grpstatus, w))
1356 return OK;
1357 }
1358 }
1359 else {
1360 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1361 "Digest: access to %s failed, reason: unknown require "
1362 "directive \"%s\"", r->uri, reqs[x].requirement);
1363 return DECLINED;
1364 }
1365 }
1366
1367 if (!method_restricted)
1368 return OK;
1369
1370 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1371 "Digest: access to %s failed, reason: user %s not allowed access",
1372 r->uri, user);
1373
1374 note_digest_auth_failure(r, conf,
1375 (digest_header_rec *) ap_get_module_config(r->request_config,
1376 &digest_auth_module),
1377 0);
1378 return AUTH_REQUIRED;
1379 }
1380
1381
1382 /*
1383 * Authorization-Info header code
1384 */
1385
add_auth_info(request_rec * r)1386 static int add_auth_info(request_rec *r)
1387 {
1388 const digest_config_rec *conf =
1389 (digest_config_rec *) ap_get_module_config(r->per_dir_config,
1390 &digest_auth_module);
1391 digest_header_rec *resp =
1392 (digest_header_rec *) ap_get_module_config(r->request_config,
1393 &digest_auth_module);
1394 const char *ai = NULL, *digest = NULL, *nextnonce = "";
1395
1396 if (resp == NULL || !resp->needed_auth || conf == NULL)
1397 return OK;
1398
1399
1400 /* rfc-2069 digest
1401 */
1402 if (resp->message_qop == NULL) {
1403 /* old client, so calc rfc-2069 digest */
1404
1405 }
1406
1407
1408 /* setup nextnonce
1409 */
1410 if (conf->nonce_lifetime > 0) {
1411 /* send nextnonce if current nonce will expire in less than 30 secs */
1412 if (difftime(r->request_time, resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
1413 nextnonce = ap_pstrcat(r->pool, ", nextnonce=\"",
1414 gen_nonce(r->pool, r->request_time,
1415 resp->opaque, r->server, conf),
1416 "\"", NULL);
1417 if (resp->client)
1418 resp->client->nonce_count = 0;
1419 }
1420 }
1421 else if (conf->nonce_lifetime == 0 && resp->client) {
1422 const char *nonce = gen_nonce(r->pool, 0, resp->opaque, r->server,
1423 conf);
1424 nextnonce = ap_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
1425 memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
1426 }
1427 /* else nonce never expires, hence no nextnonce */
1428
1429
1430 /* do rfc-2069 digest
1431 */
1432 if (conf->qop_list[0] && !strcasecmp(conf->qop_list[0], "none")
1433 && resp->message_qop == NULL) {
1434 /* use only RFC-2069 format */
1435 if (digest)
1436 ai = ap_pstrcat(r->pool, "digest=\"", digest, "\"", nextnonce,NULL);
1437 else
1438 ai = nextnonce;
1439 }
1440 else {
1441 const char *resp_dig, *ha1, *a2, *ha2;
1442
1443 /* calculate rspauth attribute
1444 */
1445 if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
1446 ha1 = get_session_HA1(r, resp, conf, 0);
1447 if (!ha1) {
1448 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r,
1449 "Digest: internal error: couldn't find session "
1450 "info for user %s", resp->username);
1451 return !OK;
1452 }
1453 }
1454 else
1455 ha1 = conf->ha1;
1456
1457 if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int"))
1458 a2 = ap_pstrcat(r->pool, ":", resp->uri, ":",
1459 ap_md5(r->pool, (const unsigned char *) ""), NULL); /* TBD */
1460 else
1461 a2 = ap_pstrcat(r->pool, ":", resp->uri, NULL);
1462 ha2 = ap_md5(r->pool, (const unsigned char *)a2);
1463
1464 resp_dig = ap_md5(r->pool,
1465 (unsigned char *)ap_pstrcat(r->pool, ha1, ":",
1466 resp->nonce, ":",
1467 resp->nonce_count, ":",
1468 resp->cnonce, ":",
1469 resp->message_qop ?
1470 resp->message_qop : "",
1471 ":", ha2, NULL));
1472
1473 /* assemble Authentication-Info header
1474 */
1475 ai = ap_pstrcat(r->pool,
1476 "rspauth=\"", resp_dig, "\"",
1477 nextnonce,
1478 resp->cnonce ? ", cnonce=\"" : "",
1479 resp->cnonce ? ap_escape_quotes(r->pool, resp->cnonce) :
1480 "",
1481 resp->cnonce ? "\"" : "",
1482 resp->nonce_count ? ", nc=" : "",
1483 resp->nonce_count ? resp->nonce_count : "",
1484 resp->message_qop ? ", qop=" : "",
1485 resp->message_qop ? resp->message_qop : "",
1486 digest ? "digest=\"" : "",
1487 digest ? digest : "",
1488 digest ? "\"" : "",
1489 NULL);
1490 }
1491
1492 if (ai && ai[0])
1493 ap_table_mergen(r->headers_out,
1494 r->proxyreq == STD_PROXY ? "Proxy-Authentication-Info"
1495 : "Authentication-Info",
1496 ai);
1497 return OK;
1498 }
1499
1500
1501 module MODULE_VAR_EXPORT digest_auth_module =
1502 {
1503 STANDARD_MODULE_STUFF,
1504 initialize_module, /* initializer */
1505 create_digest_dir_config, /* dir config creater */
1506 NULL, /* dir merger --- default is to override */
1507 NULL, /* server config */
1508 NULL, /* merge server config */
1509 digest_cmds, /* command table */
1510 NULL, /* handlers */
1511 NULL, /* filename translation */
1512 authenticate_digest_user, /* check_user_id */
1513 digest_check_auth, /* check auth */
1514 NULL, /* check access */
1515 NULL, /* type_checker */
1516 add_auth_info, /* fixups */
1517 NULL, /* logger */
1518 NULL, /* header parser */
1519 NULL, /* child_init */
1520 NULL, /* child_exit */
1521 update_nonce_count /* post read-request */
1522 };
1523