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