]> git.ipfire.org Git - thirdparty/squid.git/blob - src/auth/digest/auth_digest.cc
Renamed squid.h to squid-old.h and config.h to squid.h
[thirdparty/squid.git] / src / auth / digest / auth_digest.cc
1 /*
2 * $Id$
3 *
4 * DEBUG: section 29 Authenticator
5 * AUTHOR: Robert Collins
6 *
7 * SQUID Internet Object Cache http://squid.nlanr.net/Squid/
8 * ----------------------------------------------------------
9 *
10 * Squid is the result of efforts by numerous individuals from the
11 * Internet community. Development is led by Duane Wessels of the
12 * National Laboratory for Applied Network Research and funded by the
13 * National Science Foundation. Squid is Copyrighted (C) 1998 by
14 * the Regents of the University of California. Please see the
15 * COPYRIGHT file for full details. Squid incorporates software
16 * developed and/or copyrighted by other sources. Please see the
17 * CREDITS file for full details.
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
32 *
33 */
34
35 /* The functions in this file handle authentication.
36 * They DO NOT perform access control or auditing.
37 * See acl.c for access control and client_side.c for auditing */
38
39
40 #include "squid-old.h"
41 #include "rfc2617.h"
42 #include "auth/digest/auth_digest.h"
43 #include "auth/digest/Scheme.h"
44 #include "auth/digest/User.h"
45 #include "auth/digest/UserRequest.h"
46 #include "auth/Gadgets.h"
47 #include "auth/State.h"
48 #include "base64.h"
49 #include "base/StringArea.h"
50 #include "event.h"
51 #include "mgr/Registration.h"
52 #include "Store.h"
53 #include "HttpRequest.h"
54 #include "HttpReply.h"
55 #include "wordlist.h"
56 #include "SquidTime.h"
57
58 /* Digest Scheme */
59
60 static AUTHSSTATS authenticateDigestStats;
61
62 helper *digestauthenticators = NULL;
63
64 static hash_table *digest_nonce_cache;
65
66 static int authdigest_initialised = 0;
67 static MemAllocator *digest_nonce_pool = NULL;
68
69 enum http_digest_attr_type {
70 DIGEST_USERNAME,
71 DIGEST_REALM,
72 DIGEST_QOP,
73 DIGEST_ALGORITHM,
74 DIGEST_URI,
75 DIGEST_NONCE,
76 DIGEST_NC,
77 DIGEST_CNONCE,
78 DIGEST_RESPONSE,
79 DIGEST_ENUM_END
80 };
81
82 static const HttpHeaderFieldAttrs DigestAttrs[DIGEST_ENUM_END] = {
83 {"username", (http_hdr_type)DIGEST_USERNAME},
84 {"realm", (http_hdr_type)DIGEST_REALM},
85 {"qop", (http_hdr_type)DIGEST_QOP},
86 {"algorithm", (http_hdr_type)DIGEST_ALGORITHM},
87 {"uri", (http_hdr_type)DIGEST_URI},
88 {"nonce", (http_hdr_type)DIGEST_NONCE},
89 {"nc", (http_hdr_type)DIGEST_NC},
90 {"cnonce", (http_hdr_type)DIGEST_CNONCE},
91 {"response", (http_hdr_type)DIGEST_RESPONSE},
92 };
93
94 static HttpHeaderFieldInfo *DigestFieldsInfo = NULL;
95
96 /*
97 *
98 * Nonce Functions
99 *
100 */
101
102 static void authenticateDigestNonceCacheCleanup(void *data);
103 static digest_nonce_h *authenticateDigestNonceFindNonce(const char *nonceb64);
104 static digest_nonce_h *authenticateDigestNonceNew(void);
105 static void authenticateDigestNonceDelete(digest_nonce_h * nonce);
106 static void authenticateDigestNonceSetup(void);
107 static int authDigestNonceIsStale(digest_nonce_h * nonce);
108 static void authDigestNonceEncode(digest_nonce_h * nonce);
109 static void authDigestNonceLink(digest_nonce_h * nonce);
110 #if NOT_USED
111 static int authDigestNonceLinks(digest_nonce_h * nonce);
112 #endif
113 static void authDigestNonceUserUnlink(digest_nonce_h * nonce);
114
115 static void
116 authDigestNonceEncode(digest_nonce_h * nonce)
117 {
118 if (!nonce)
119 return;
120
121 if (nonce->key)
122 xfree(nonce->key);
123
124 nonce->key = xstrdup(base64_encode_bin((char *) &(nonce->noncedata), sizeof(digest_nonce_data)));
125 }
126
127 static digest_nonce_h *
128 authenticateDigestNonceNew(void)
129 {
130 digest_nonce_h *newnonce = static_cast < digest_nonce_h * >(digest_nonce_pool->alloc());
131 digest_nonce_h *temp;
132
133 /* NONCE CREATION - NOTES AND REASONING. RBC 20010108
134 * === EXCERPT FROM RFC 2617 ===
135 * The contents of the nonce are implementation dependent. The quality
136 * of the implementation depends on a good choice. A nonce might, for
137 * example, be constructed as the base 64 encoding of
138 *
139 * time-stamp H(time-stamp ":" ETag ":" private-key)
140 *
141 * where time-stamp is a server-generated time or other non-repeating
142 * value, ETag is the value of the HTTP ETag header associated with
143 * the requested entity, and private-key is data known only to the
144 * server. With a nonce of this form a server would recalculate the
145 * hash portion after receiving the client authentication header and
146 * reject the request if it did not match the nonce from that header
147 * or if the time-stamp value is not recent enough. In this way the
148 * server can limit the time of the nonce's validity. The inclusion of
149 * the ETag prevents a replay request for an updated version of the
150 * resource. (Note: including the IP address of the client in the
151 * nonce would appear to offer the server the ability to limit the
152 * reuse of the nonce to the same client that originally got it.
153 * However, that would break proxy farms, where requests from a single
154 * user often go through different proxies in the farm. Also, IP
155 * address spoofing is not that hard.)
156 * ====
157 *
158 * Now for my reasoning:
159 * We will not accept a unrecognised nonce->we have all recognisable
160 * nonces stored. If we send out unique base64 encodings we guarantee
161 * that a given nonce applies to only one user (barring attacks or
162 * really bad timing with expiry and creation). Using a random
163 * component in the nonce allows us to loop to find a unique nonce.
164 * We use H(nonce_data) so the nonce is meaningless to the reciever.
165 * So our nonce looks like base64(H(timestamp,pointertohash,randomdata))
166 * And even if our randomness is not very random (probably due to
167 * bad coding on my part) we don't really care - the timestamp and
168 * memory pointer also guarantee local uniqueness in the input to the hash
169 * function.
170 */
171
172 /* create a new nonce */
173 newnonce->nc = 0;
174 newnonce->flags.valid = 1;
175 newnonce->noncedata.self = newnonce;
176 newnonce->noncedata.creationtime = current_time.tv_sec;
177 newnonce->noncedata.randomdata = squid_random();
178
179 authDigestNonceEncode(newnonce);
180 /*
181 * loop until we get a unique nonce. The nonce creation must
182 * have a random factor
183 */
184
185 while ((temp = authenticateDigestNonceFindNonce((char const *) (newnonce->key)))) {
186 /* create a new nonce */
187 newnonce->noncedata.randomdata = squid_random();
188 authDigestNonceEncode(newnonce);
189 }
190
191 hash_join(digest_nonce_cache, newnonce);
192 /* the cache's link */
193 authDigestNonceLink(newnonce);
194 newnonce->flags.incache = 1;
195 debugs(29, 5, "authenticateDigestNonceNew: created nonce " << newnonce << " at " << newnonce->noncedata.creationtime);
196 return newnonce;
197 }
198
199 static void
200 authenticateDigestNonceDelete(digest_nonce_h * nonce)
201 {
202 if (nonce) {
203 assert(nonce->references == 0);
204 #if UNREACHABLECODE
205
206 if (nonce->flags.incache)
207 hash_remove_link(digest_nonce_cache, nonce);
208
209 #endif
210
211 assert(nonce->flags.incache == 0);
212
213 safe_free(nonce->key);
214
215 digest_nonce_pool->freeOne(nonce);
216 }
217 }
218
219 static void
220 authenticateDigestNonceSetup(void)
221 {
222 if (!digest_nonce_pool)
223 digest_nonce_pool = memPoolCreate("Digest Scheme nonce's", sizeof(digest_nonce_h));
224
225 if (!digest_nonce_cache) {
226 digest_nonce_cache = hash_create((HASHCMP *) strcmp, 7921, hash_string);
227 assert(digest_nonce_cache);
228 eventAdd("Digest none cache maintenance", authenticateDigestNonceCacheCleanup, NULL, static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest"))->nonceGCInterval, 1);
229 }
230 }
231
232 void
233 authenticateDigestNonceShutdown(void)
234 {
235 /*
236 * We empty the cache of any nonces left in there.
237 */
238 digest_nonce_h *nonce;
239
240 if (digest_nonce_cache) {
241 debugs(29, 2, "authenticateDigestNonceShutdown: Shutting down nonce cache ");
242 hash_first(digest_nonce_cache);
243
244 while ((nonce = ((digest_nonce_h *) hash_next(digest_nonce_cache)))) {
245 assert(nonce->flags.incache);
246 authDigestNoncePurge(nonce);
247 }
248 }
249
250 #if DEBUGSHUTDOWN
251 if (digest_nonce_pool) {
252 delete digest_nonce_pool;
253 digest_nonce_pool = NULL;
254 }
255
256 #endif
257 debugs(29, 2, "authenticateDigestNonceShutdown: Nonce cache shutdown");
258 }
259
260 static void
261 authenticateDigestNonceCacheCleanup(void *data)
262 {
263 /*
264 * We walk the hash by nonceb64 as that is the unique key we
265 * use. For big hash tables we could consider stepping through
266 * the cache, 100/200 entries at a time. Lets see how it flies
267 * first.
268 */
269 digest_nonce_h *nonce;
270 debugs(29, 3, "authenticateDigestNonceCacheCleanup: Cleaning the nonce cache now");
271 debugs(29, 3, "authenticateDigestNonceCacheCleanup: Current time: " << current_time.tv_sec);
272 hash_first(digest_nonce_cache);
273
274 while ((nonce = ((digest_nonce_h *) hash_next(digest_nonce_cache)))) {
275 debugs(29, 3, "authenticateDigestNonceCacheCleanup: nonce entry : " << nonce << " '" << (char *) nonce->key << "'");
276 debugs(29, 4, "authenticateDigestNonceCacheCleanup: Creation time: " << nonce->noncedata.creationtime);
277
278 if (authDigestNonceIsStale(nonce)) {
279 debugs(29, 4, "authenticateDigestNonceCacheCleanup: Removing nonce " << (char *) nonce->key << " from cache due to timeout.");
280 assert(nonce->flags.incache);
281 /* invalidate nonce so future requests fail */
282 nonce->flags.valid = 0;
283 /* if it is tied to a auth_user, remove the tie */
284 authDigestNonceUserUnlink(nonce);
285 authDigestNoncePurge(nonce);
286 }
287 }
288
289 debugs(29, 3, "authenticateDigestNonceCacheCleanup: Finished cleaning the nonce cache.");
290
291 if (static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest"))->active())
292 eventAdd("Digest none cache maintenance", authenticateDigestNonceCacheCleanup, NULL, static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest"))->nonceGCInterval, 1);
293 }
294
295 static void
296 authDigestNonceLink(digest_nonce_h * nonce)
297 {
298 assert(nonce != NULL);
299 nonce->references++;
300 debugs(29, 9, "authDigestNonceLink: nonce '" << nonce << "' now at '" << nonce->references << "'.");
301 }
302
303 #if NOT_USED
304 static int
305 authDigestNonceLinks(digest_nonce_h * nonce)
306 {
307 if (!nonce)
308 return -1;
309
310 return nonce->references;
311 }
312
313 #endif
314
315 void
316 authDigestNonceUnlink(digest_nonce_h * nonce)
317 {
318 assert(nonce != NULL);
319
320 if (nonce->references > 0) {
321 nonce->references--;
322 } else {
323 debugs(29, 1, "authDigestNonceUnlink; Attempt to lower nonce " << nonce << " refcount below 0!");
324 }
325
326 debugs(29, 9, "authDigestNonceUnlink: nonce '" << nonce << "' now at '" << nonce->references << "'.");
327
328 if (nonce->references == 0)
329 authenticateDigestNonceDelete(nonce);
330 }
331
332 const char *
333 authenticateDigestNonceNonceb64(const digest_nonce_h * nonce)
334 {
335 if (!nonce)
336 return NULL;
337
338 return (char const *) nonce->key;
339 }
340
341 static digest_nonce_h *
342 authenticateDigestNonceFindNonce(const char *nonceb64)
343 {
344 digest_nonce_h *nonce = NULL;
345
346 if (nonceb64 == NULL)
347 return NULL;
348
349 debugs(29, 9, "authDigestNonceFindNonce:looking for nonceb64 '" << nonceb64 << "' in the nonce cache.");
350
351 nonce = static_cast < digest_nonce_h * >(hash_lookup(digest_nonce_cache, nonceb64));
352
353 if ((nonce == NULL) || (strcmp(authenticateDigestNonceNonceb64(nonce), nonceb64)))
354 return NULL;
355
356 debugs(29, 9, "authDigestNonceFindNonce: Found nonce '" << nonce << "'");
357
358 return nonce;
359 }
360
361 int
362 authDigestNonceIsValid(digest_nonce_h * nonce, char nc[9])
363 {
364 unsigned long intnc;
365 /* do we have a nonce ? */
366
367 if (!nonce)
368 return 0;
369
370 intnc = strtol(nc, NULL, 16);
371
372 /* has it already been invalidated ? */
373 if (!nonce->flags.valid) {
374 debugs(29, 4, "authDigestNonceIsValid: Nonce already invalidated");
375 return 0;
376 }
377
378 /* is the nonce-count ok ? */
379 if (!static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest"))->CheckNonceCount) {
380 nonce->nc++;
381 return -1; /* forced OK by configuration */
382 }
383
384 if ((static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest"))->NonceStrictness && intnc != nonce->nc + 1) ||
385 intnc < nonce->nc + 1) {
386 debugs(29, 4, "authDigestNonceIsValid: Nonce count doesn't match");
387 nonce->flags.valid = 0;
388 return 0;
389 }
390
391 /* seems ok */
392 /* increment the nonce count - we've already checked that intnc is a
393 * valid representation for us, so we don't need the test here.
394 */
395 nonce->nc = intnc;
396
397 return -1;
398 }
399
400 static int
401 authDigestNonceIsStale(digest_nonce_h * nonce)
402 {
403 /* do we have a nonce ? */
404
405 if (!nonce)
406 return -1;
407
408 /* has it's max duration expired? */
409 if (nonce->noncedata.creationtime + static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest"))->noncemaxduration < current_time.tv_sec) {
410 debugs(29, 4, "authDigestNonceIsStale: Nonce is too old. " <<
411 nonce->noncedata.creationtime << " " <<
412 static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest"))->noncemaxduration << " " <<
413 current_time.tv_sec);
414
415 nonce->flags.valid = 0;
416 return -1;
417 }
418
419 if (nonce->nc > 99999998) {
420 debugs(29, 4, "authDigestNonceIsStale: Nonce count overflow");
421 nonce->flags.valid = 0;
422 return -1;
423 }
424
425 if (nonce->nc > static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest"))->noncemaxuses) {
426 debugs(29, 4, "authDigestNoncelastRequest: Nonce count over user limit");
427 nonce->flags.valid = 0;
428 return -1;
429 }
430
431 /* seems ok */
432 return 0;
433 }
434
435 /**
436 * \retval 0 the digest is not stale yet
437 * \retval -1 the digest will be stale on the next request
438 */
439 int
440 authDigestNonceLastRequest(digest_nonce_h * nonce)
441 {
442 if (!nonce)
443 return -1;
444
445 if (nonce->nc == 99999997) {
446 debugs(29, 4, "authDigestNoncelastRequest: Nonce count about to overflow");
447 return -1;
448 }
449
450 if (nonce->nc >= static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest"))->noncemaxuses - 1) {
451 debugs(29, 4, "authDigestNoncelastRequest: Nonce count about to hit user limit");
452 return -1;
453 }
454
455 /* and other tests are possible. */
456 return 0;
457 }
458
459 void
460 authDigestNoncePurge(digest_nonce_h * nonce)
461 {
462 if (!nonce)
463 return;
464
465 if (!nonce->flags.incache)
466 return;
467
468 hash_remove_link(digest_nonce_cache, nonce);
469
470 nonce->flags.incache = 0;
471
472 /* the cache's link */
473 authDigestNonceUnlink(nonce);
474 }
475
476 /* USER related functions */
477 static Auth::User::Pointer
478 authDigestUserFindUsername(const char *username)
479 {
480 AuthUserHashPointer *usernamehash;
481 debugs(29, 9, HERE << "Looking for user '" << username << "'");
482
483 if (username && (usernamehash = static_cast < AuthUserHashPointer * >(hash_lookup(proxy_auth_username_cache, username)))) {
484 while ((usernamehash->user()->auth_type != Auth::AUTH_DIGEST) && (usernamehash->next))
485 usernamehash = static_cast<AuthUserHashPointer *>(usernamehash->next);
486
487 if (usernamehash->user()->auth_type == Auth::AUTH_DIGEST) {
488 return usernamehash->user();
489 }
490 }
491
492 return NULL;
493 }
494
495 void
496 Auth::Digest::Config::rotateHelpers()
497 {
498 /* schedule closure of existing helpers */
499 if (digestauthenticators) {
500 helperShutdown(digestauthenticators);
501 }
502
503 /* NP: dynamic helper restart will ensure they start up again as needed. */
504 }
505
506 void
507 Auth::Digest::Config::dump(StoreEntry * entry, const char *name, Auth::Config * scheme)
508 {
509 wordlist *list = authenticateProgram;
510 debugs(29, 9, "authDigestCfgDump: Dumping configuration");
511 storeAppendPrintf(entry, "%s %s", name, "digest");
512
513 while (list != NULL) {
514 storeAppendPrintf(entry, " %s", list->key);
515 list = list->next;
516 }
517
518 storeAppendPrintf(entry, "\n%s %s realm %s\n%s %s children %d startup=%d idle=%d concurrency=%d\n%s %s nonce_max_count %d\n%s %s nonce_max_duration %d seconds\n%s %s nonce_garbage_interval %d seconds\n",
519 name, "digest", digestAuthRealm,
520 name, "digest", authenticateChildren.n_max, authenticateChildren.n_startup, authenticateChildren.n_idle, authenticateChildren.concurrency,
521 name, "digest", noncemaxuses,
522 name, "digest", (int) noncemaxduration,
523 name, "digest", (int) nonceGCInterval);
524 }
525
526 bool
527 Auth::Digest::Config::active() const
528 {
529 return authdigest_initialised == 1;
530 }
531
532 bool
533 Auth::Digest::Config::configured() const
534 {
535 if ((authenticateProgram != NULL) &&
536 (authenticateChildren.n_max != 0) &&
537 (digestAuthRealm != NULL) && (noncemaxduration > -1))
538 return true;
539
540 return false;
541 }
542
543 /* add the [www-|Proxy-]authenticate header on a 407 or 401 reply */
544 void
545 Auth::Digest::Config::fixHeader(Auth::UserRequest::Pointer auth_user_request, HttpReply *rep, http_hdr_type hdrType, HttpRequest * request)
546 {
547 if (!authenticateProgram)
548 return;
549
550 int stale = 0;
551
552 if (auth_user_request != NULL) {
553 Auth::Digest::UserRequest *digest_request = dynamic_cast<Auth::Digest::UserRequest*>(auth_user_request.getRaw());
554 assert (digest_request != NULL);
555
556 stale = !digest_request->flags.invalid_password;
557 }
558
559 /* on a 407 or 401 we always use a new nonce */
560 digest_nonce_h *nonce = authenticateDigestNonceNew();
561
562 debugs(29, 9, HERE << "Sending type:" << hdrType <<
563 " header: 'Digest realm=\"" << digestAuthRealm << "\", nonce=\"" <<
564 authenticateDigestNonceNonceb64(nonce) << "\", qop=\"" << QOP_AUTH <<
565 "\", stale=" << (stale ? "true" : "false"));
566
567 /* in the future, for WWW auth we may want to support the domain entry */
568 httpHeaderPutStrf(&rep->header, hdrType, "Digest realm=\"%s\", nonce=\"%s\", qop=\"%s\", stale=%s", digestAuthRealm, authenticateDigestNonceNonceb64(nonce), QOP_AUTH, stale ? "true" : "false");
569 }
570
571 /* Initialize helpers and the like for this auth scheme. Called AFTER parsing the
572 * config file */
573 void
574 Auth::Digest::Config::init(Auth::Config * scheme)
575 {
576 if (authenticateProgram) {
577 DigestFieldsInfo = httpHeaderBuildFieldsInfo(DigestAttrs, DIGEST_ENUM_END);
578 authenticateDigestNonceSetup();
579 authdigest_initialised = 1;
580
581 if (digestauthenticators == NULL)
582 digestauthenticators = new helper("digestauthenticator");
583
584 digestauthenticators->cmdline = authenticateProgram;
585
586 digestauthenticators->childs.updateLimits(authenticateChildren);
587
588 digestauthenticators->ipc_type = IPC_STREAM;
589
590 helperOpenServers(digestauthenticators);
591 }
592 }
593
594 void
595 Auth::Digest::Config::registerWithCacheManager(void)
596 {
597 Mgr::RegisterAction("digestauthenticator",
598 "Digest User Authenticator Stats",
599 authenticateDigestStats, 0, 1);
600 }
601
602 /* free any allocated configuration details */
603 void
604 Auth::Digest::Config::done()
605 {
606 authdigest_initialised = 0;
607
608 if (digestauthenticators)
609 helperShutdown(digestauthenticators);
610
611 if (DigestFieldsInfo) {
612 httpHeaderDestroyFieldsInfo(DigestFieldsInfo, DIGEST_ENUM_END);
613 DigestFieldsInfo = NULL;
614 }
615
616 if (!shutting_down)
617 return;
618
619 delete digestauthenticators;
620 digestauthenticators = NULL;
621
622 if (authenticateProgram)
623 wordlistDestroy(&authenticateProgram);
624
625 safe_free(digestAuthRealm);
626 }
627
628 Auth::Digest::Config::Config() :
629 digestAuthRealm(NULL),
630 nonceGCInterval(5*60),
631 noncemaxduration(30*60),
632 noncemaxuses(50),
633 NonceStrictness(0),
634 CheckNonceCount(1),
635 PostWorkaround(0),
636 utf8(0)
637 {}
638
639 void
640 Auth::Digest::Config::parse(Auth::Config * scheme, int n_configured, char *param_str)
641 {
642 if (strcasecmp(param_str, "program") == 0) {
643 if (authenticateProgram)
644 wordlistDestroy(&authenticateProgram);
645
646 parse_wordlist(&authenticateProgram);
647
648 requirePathnameExists("auth_param digest program", authenticateProgram->key);
649 } else if (strcasecmp(param_str, "children") == 0) {
650 authenticateChildren.parseConfig();
651 } else if (strcasecmp(param_str, "realm") == 0) {
652 parse_eol(&digestAuthRealm);
653 } else if (strcasecmp(param_str, "nonce_garbage_interval") == 0) {
654 parse_time_t(&nonceGCInterval);
655 } else if (strcasecmp(param_str, "nonce_max_duration") == 0) {
656 parse_time_t(&noncemaxduration);
657 } else if (strcasecmp(param_str, "nonce_max_count") == 0) {
658 parse_int((int *) &noncemaxuses);
659 } else if (strcasecmp(param_str, "nonce_strictness") == 0) {
660 parse_onoff(&NonceStrictness);
661 } else if (strcasecmp(param_str, "check_nonce_count") == 0) {
662 parse_onoff(&CheckNonceCount);
663 } else if (strcasecmp(param_str, "post_workaround") == 0) {
664 parse_onoff(&PostWorkaround);
665 } else if (strcasecmp(param_str, "utf8") == 0) {
666 parse_onoff(&utf8);
667 } else {
668 debugs(29, 0, "unrecognised digest auth scheme parameter '" << param_str << "'");
669 }
670 }
671
672 const char *
673 Auth::Digest::Config::type() const
674 {
675 return Auth::Digest::Scheme::GetInstance()->type();
676 }
677
678
679 static void
680 authenticateDigestStats(StoreEntry * sentry)
681 {
682 helperStats(sentry, digestauthenticators, "Digest Authenticator Statistics");
683 }
684
685 /* NonceUserUnlink: remove the reference to auth_user and unlink the node from the list */
686
687 static void
688 authDigestNonceUserUnlink(digest_nonce_h * nonce)
689 {
690 Auth::Digest::User *digest_user;
691 dlink_node *link, *tmplink;
692
693 if (!nonce)
694 return;
695
696 if (!nonce->user)
697 return;
698
699 digest_user = nonce->user;
700
701 /* unlink from the user list. Yes we're crossing structures but this is the only
702 * time this code is needed
703 */
704 link = digest_user->nonces.head;
705
706 while (link) {
707 tmplink = link;
708 link = link->next;
709
710 if (tmplink->data == nonce) {
711 dlinkDelete(tmplink, &digest_user->nonces);
712 authDigestNonceUnlink(static_cast < digest_nonce_h * >(tmplink->data));
713 dlinkNodeDelete(tmplink);
714 link = NULL;
715 }
716 }
717
718 /* this reference to user was not locked because freeeing the user frees
719 * the nonce too.
720 */
721 nonce->user = NULL;
722 }
723
724 /* authDigestUserLinkNonce: add a nonce to a given user's struct */
725 static void
726 authDigestUserLinkNonce(Auth::Digest::User * user, digest_nonce_h * nonce)
727 {
728 dlink_node *node;
729
730 if (!user || !nonce)
731 return;
732
733 Auth::Digest::User *digest_user = user;
734
735 node = digest_user->nonces.head;
736
737 while (node && (node->data != nonce))
738 node = node->next;
739
740 if (node)
741 return;
742
743 node = dlinkNodeNew();
744
745 dlinkAddTail(nonce, node, &digest_user->nonces);
746
747 authDigestNonceLink(nonce);
748
749 /* ping this nonce to this auth user */
750 assert((nonce->user == NULL) || (nonce->user == user));
751
752 /* we don't lock this reference because removing the user removes the
753 * hash too. Of course if that changes we're stuffed so read the code huh?
754 */
755 nonce->user = user;
756 }
757
758 /* setup the necessary info to log the username */
759 static Auth::UserRequest::Pointer
760 authDigestLogUsername(char *username, Auth::UserRequest::Pointer auth_user_request)
761 {
762 assert(auth_user_request != NULL);
763
764 /* log the username */
765 debugs(29, 9, "authDigestLogUsername: Creating new user for logging '" << username << "'");
766 Auth::User::Pointer digest_user = new Auth::Digest::User(static_cast<Auth::Digest::Config*>(Auth::Config::Find("digest")));
767 /* save the credentials */
768 digest_user->username(username);
769 /* set the auth_user type */
770 digest_user->auth_type = Auth::AUTH_BROKEN;
771 /* link the request to the user */
772 auth_user_request->user(digest_user);
773 return auth_user_request;
774 }
775
776 /*
777 * Decode a Digest [Proxy-]Auth string, placing the results in the passed
778 * Auth_user structure.
779 */
780 Auth::UserRequest::Pointer
781 Auth::Digest::Config::decode(char const *proxy_auth)
782 {
783 const char *item;
784 const char *p;
785 const char *pos = NULL;
786 char *username = NULL;
787 digest_nonce_h *nonce;
788 int ilen;
789
790 debugs(29, 9, "authenticateDigestDecodeAuth: beginning");
791
792 Auth::Digest::UserRequest *digest_request = new Auth::Digest::UserRequest();
793
794 /* trim DIGEST from string */
795
796 while (xisgraph(*proxy_auth))
797 proxy_auth++;
798
799 /* Trim leading whitespace before decoding */
800 while (xisspace(*proxy_auth))
801 proxy_auth++;
802
803 String temp(proxy_auth);
804
805 while (strListGetItem(&temp, ',', &item, &ilen, &pos)) {
806 /* isolate directive name & value */
807 size_t nlen;
808 size_t vlen;
809 if ((p = (const char *)memchr(item, '=', ilen)) && (p - item < ilen)) {
810 nlen = p++ - item;
811 vlen = ilen - (p - item);
812 } else {
813 nlen = ilen;
814 vlen = 0;
815 }
816
817 StringArea keyName(item, nlen-1);
818 String value;
819
820 if (vlen > 0) {
821 // see RFC 2617 section 3.2.1 and 3.2.2 for details on the BNF
822
823 if (keyName == StringArea("domain",6) || keyName == StringArea("uri",3)) {
824 // domain is Special. Not a quoted-string, must not be de-quoted. But is wrapped in '"'
825 // BUG 3077: uri= can also be sent to us in a mangled (invalid!) form like domain
826 if (*p == '"' && *(p + vlen -1) == '"') {
827 value.limitInit(p+1, vlen-2);
828 }
829 } else if (keyName == StringArea("qop",3)) {
830 // qop is more special.
831 // On request this must not be quoted-string de-quoted. But is several values wrapped in '"'
832 // On response this is a single un-quoted token.
833 if (*p == '"' && *(p + vlen -1) == '"') {
834 value.limitInit(p+1, vlen-2);
835 } else {
836 value.limitInit(p, vlen);
837 }
838 } else if (*p == '"') {
839 if (!httpHeaderParseQuotedString(p, vlen, &value)) {
840 debugs(29, 9, HERE << "Failed to parse attribute '" << item << "' in '" << temp << "'");
841 continue;
842 }
843 } else {
844 value.limitInit(p, vlen);
845 }
846 } else {
847 debugs(29, 9, HERE << "Failed to parse attribute '" << item << "' in '" << temp << "'");
848 continue;
849 }
850
851 /* find type */
852 http_digest_attr_type type = (http_digest_attr_type)httpHeaderIdByName(item, nlen, DigestFieldsInfo, DIGEST_ENUM_END);
853
854 switch (type) {
855 case DIGEST_USERNAME:
856 safe_free(username);
857 username = xstrndup(value.rawBuf(), value.size() + 1);
858 debugs(29, 9, HERE << "Found Username '" << username << "'");
859 break;
860
861 case DIGEST_REALM:
862 safe_free(digest_request->realm);
863 digest_request->realm = xstrndup(value.rawBuf(), value.size() + 1);
864 debugs(29, 9, HERE << "Found realm '" << digest_request->realm << "'");
865 break;
866
867 case DIGEST_QOP:
868 safe_free(digest_request->qop);
869 digest_request->qop = xstrndup(value.rawBuf(), value.size() + 1);
870 debugs(29, 9, HERE << "Found qop '" << digest_request->qop << "'");
871 break;
872
873 case DIGEST_ALGORITHM:
874 safe_free(digest_request->algorithm);
875 digest_request->algorithm = xstrndup(value.rawBuf(), value.size() + 1);
876 debugs(29, 9, HERE << "Found algorithm '" << digest_request->algorithm << "'");
877 break;
878
879 case DIGEST_URI:
880 safe_free(digest_request->uri);
881 digest_request->uri = xstrndup(value.rawBuf(), value.size() + 1);
882 debugs(29, 9, HERE << "Found uri '" << digest_request->uri << "'");
883 break;
884
885 case DIGEST_NONCE:
886 safe_free(digest_request->nonceb64);
887 digest_request->nonceb64 = xstrndup(value.rawBuf(), value.size() + 1);
888 debugs(29, 9, HERE << "Found nonce '" << digest_request->nonceb64 << "'");
889 break;
890
891 case DIGEST_NC:
892 if (value.size() != 8) {
893 debugs(29, 9, HERE << "Invalid nc '" << value << "' in '" << temp << "'");
894 }
895 xstrncpy(digest_request->nc, value.rawBuf(), value.size() + 1);
896 debugs(29, 9, HERE << "Found noncecount '" << digest_request->nc << "'");
897 break;
898
899 case DIGEST_CNONCE:
900 safe_free(digest_request->cnonce);
901 digest_request->cnonce = xstrndup(value.rawBuf(), value.size() + 1);
902 debugs(29, 9, HERE << "Found cnonce '" << digest_request->cnonce << "'");
903 break;
904
905 case DIGEST_RESPONSE:
906 safe_free(digest_request->response);
907 digest_request->response = xstrndup(value.rawBuf(), value.size() + 1);
908 debugs(29, 9, HERE << "Found response '" << digest_request->response << "'");
909 break;
910
911 default:
912 debugs(29, 3, HERE << "Unknown attribute '" << item << "' in '" << temp << "'");
913 break;
914 }
915 }
916
917 temp.clean();
918
919
920 /* now we validate the data given to us */
921
922 /*
923 * TODO: on invalid parameters we should return 400, not 407.
924 * Find some clean way of doing this. perhaps return a valid
925 * struct, and set the direction to clientwards combined with
926 * a change to the clientwards handling code (ie let the
927 * clientwards call set the error type (but limited to known
928 * correct values - 400/401/407
929 */
930
931 /* 2069 requirements */
932
933 /* do we have a username ? */
934 if (!username || username[0] == '\0') {
935 debugs(29, 2, HERE << "Empty or not present username");
936 return authDigestLogUsername(username, digest_request);
937 }
938
939 /* Sanity check of the username.
940 * " can not be allowed in usernames until * the digest helper protocol
941 * have been redone
942 */
943 if (strchr(username, '"')) {
944 debugs(29, 2, HERE << "Unacceptable username '" << username << "'");
945 return authDigestLogUsername(username, digest_request);
946 }
947
948 /* do we have a realm ? */
949 if (!digest_request->realm || digest_request->realm[0] == '\0') {
950 debugs(29, 2, HERE << "Empty or not present realm");
951 return authDigestLogUsername(username, digest_request);
952 }
953
954 /* and a nonce? */
955 if (!digest_request->nonceb64 || digest_request->nonceb64[0] == '\0') {
956 debugs(29, 2, HERE << "Empty or not present nonce");
957 return authDigestLogUsername(username, digest_request);
958 }
959
960 /* we can't check the URI just yet. We'll check it in the
961 * authenticate phase, but needs to be given */
962 if (!digest_request->uri || digest_request->uri[0] == '\0') {
963 debugs(29, 2, HERE << "Missing URI field");
964 return authDigestLogUsername(username, digest_request);
965 }
966
967 /* is the response the correct length? */
968 if (!digest_request->response || strlen(digest_request->response) != 32) {
969 debugs(29, 2, HERE << "Response length invalid");
970 return authDigestLogUsername(username, digest_request);
971 }
972
973 /* check the algorithm is present and supported */
974 if (!digest_request->algorithm)
975 digest_request->algorithm = xstrndup("MD5", 4);
976 else if (strcmp(digest_request->algorithm, "MD5")
977 && strcmp(digest_request->algorithm, "MD5-sess")) {
978 debugs(29, 2, HERE << "invalid algorithm specified!");
979 return authDigestLogUsername(username, digest_request);
980 }
981
982 /* 2617 requirements, indicated by qop */
983 if (digest_request->qop) {
984
985 /* check the qop is what we expected. */
986 if (strcmp(digest_request->qop, QOP_AUTH) != 0) {
987 /* we received a qop option we didn't send */
988 debugs(29, 2, HERE << "Invalid qop option received");
989 return authDigestLogUsername(username, digest_request);
990 }
991
992 /* check cnonce */
993 if (!digest_request->cnonce || digest_request->cnonce[0] == '\0') {
994 debugs(29, 2, HERE << "Missing cnonce field");
995 return authDigestLogUsername(username, digest_request);
996 }
997
998 /* check nc */
999 if (strlen(digest_request->nc) != 8 || strspn(digest_request->nc, "0123456789abcdefABCDEF") != 8) {
1000 debugs(29, 2, HERE << "invalid nonce count");
1001 return authDigestLogUsername(username, digest_request);
1002 }
1003 } else {
1004 /* cnonce and nc both require qop */
1005 if (digest_request->cnonce || digest_request->nc) {
1006 debugs(29, 2, HERE << "missing qop!");
1007 return authDigestLogUsername(username, digest_request);
1008 }
1009 }
1010
1011 /** below nonce state dependent **/
1012
1013 /* now the nonce */
1014 nonce = authenticateDigestNonceFindNonce(digest_request->nonceb64);
1015 if (!nonce) {
1016 /* we couldn't find a matching nonce! */
1017 debugs(29, 2, HERE << "Unexpected or invalid nonce received");
1018 if (digest_request->user() != NULL)
1019 digest_request->user()->credentials(Auth::Failed);
1020 return authDigestLogUsername(username, digest_request);
1021 }
1022
1023 digest_request->nonce = nonce;
1024 authDigestNonceLink(nonce);
1025
1026 /* check that we're not being hacked / the username hasn't changed */
1027 if (nonce->user && strcmp(username, nonce->user->username())) {
1028 debugs(29, 2, HERE << "Username for the nonce does not equal the username for the request");
1029 return authDigestLogUsername(username, digest_request);
1030 }
1031
1032 /* the method we'll check at the authenticate step as well */
1033
1034
1035 /* we don't send or parse opaques. Ok so we're flexable ... */
1036
1037 /* find the user */
1038 Auth::Digest::User *digest_user;
1039
1040 Auth::User::Pointer auth_user;
1041
1042 if ((auth_user = authDigestUserFindUsername(username)) == NULL) {
1043 /* the user doesn't exist in the username cache yet */
1044 debugs(29, 9, HERE << "Creating new digest user '" << username << "'");
1045 digest_user = new Auth::Digest::User(this);
1046 /* auth_user is a parent */
1047 auth_user = digest_user;
1048 /* save the username */
1049 digest_user->username(username);
1050 /* set the user type */
1051 digest_user->auth_type = Auth::AUTH_DIGEST;
1052 /* this auth_user struct is the one to get added to the
1053 * username cache */
1054 /* store user in hash's */
1055 digest_user->addToNameCache();
1056
1057 /*
1058 * Add the digest to the user so we can tell if a hacking
1059 * or spoofing attack is taking place. We do this by assuming
1060 * the user agent won't change user name without warning.
1061 */
1062 authDigestUserLinkNonce(digest_user, nonce);
1063 } else {
1064 debugs(29, 9, HERE << "Found user '" << username << "' in the user cache as '" << auth_user << "'");
1065 digest_user = static_cast<Auth::Digest::User *>(auth_user.getRaw());
1066 xfree(username);
1067 }
1068
1069 /*link the request and the user */
1070 assert(digest_request != NULL);
1071
1072 digest_request->user(digest_user);
1073 debugs(29, 9, HERE << "username = '" << digest_user->username() << "'\nrealm = '" <<
1074 digest_request->realm << "'\nqop = '" << digest_request->qop <<
1075 "'\nalgorithm = '" << digest_request->algorithm << "'\nuri = '" <<
1076 digest_request->uri << "'\nnonce = '" << digest_request->nonceb64 <<
1077 "'\nnc = '" << digest_request->nc << "'\ncnonce = '" <<
1078 digest_request->cnonce << "'\nresponse = '" <<
1079 digest_request->response << "'\ndigestnonce = '" << nonce << "'");
1080
1081 return digest_request;
1082 }