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

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors