Config.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2022 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"
16 #include "auth/CredentialsCache.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 "cache_cf.h"
26 #include "event.h"
27 #include "helper.h"
28 #include "HttpHeaderTools.h"
29 #include "HttpReply.h"
30 #include "HttpRequest.h"
31 #include "md5.h"
32 #include "mgr/Registration.h"
33 #include "rfc2617.h"
34 #include "sbuf/SBuf.h"
35 #include "sbuf/StringConvert.h"
36 #include "Store.h"
37 #include "StrList.h"
38 #include "wordlist.h"
39 
40 /* digest_nonce_h still uses explicit alloc()/freeOne() MemPool calls.
41  * XXX: convert to MEMPROXY_CLASS() API
42  */
43 #include "mem/Pool.h"
44 
45 #include <random>
46 
48 
50 
52 
53 static int authdigest_initialised = 0;
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 
92 static void authenticateDigestNonceCacheCleanup(void *data);
93 static digest_nonce_h *authenticateDigestNonceFindNonce(const char *noncehex);
94 static void authenticateDigestNonceDelete(digest_nonce_h * nonce);
95 static void authenticateDigestNonceSetup(void);
96 static void authDigestNonceEncode(digest_nonce_h * nonce);
97 static void authDigestNonceLink(digest_nonce_h * nonce);
98 static void authDigestNonceUserUnlink(digest_nonce_h * nonce);
99 
100 static void
101 authDigestNonceEncode(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 
119 digest_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  // NP: this will likely produce the same randomness sequences for each worker
162  // since they should all start within the 1-second resolution of seed value.
163  static std::mt19937 mt(static_cast<uint32_t>(getCurrentTime() & 0xFFFFFFFF));
164  static xuniform_int_distribution<uint32_t> newRandomData;
165 
166  /* create a new nonce */
167  newnonce->nc = 0;
168  newnonce->flags.valid = true;
169  newnonce->noncedata.creationtime = current_time.tv_sec;
170  newnonce->noncedata.randomdata = newRandomData(mt);
171 
172  authDigestNonceEncode(newnonce);
173 
174  // ensure temporal uniqueness by checking for existing nonce
175  while (authenticateDigestNonceFindNonce((char const *) (newnonce->key))) {
176  /* create a new nonce */
177  newnonce->noncedata.randomdata = newRandomData(mt);
178  authDigestNonceEncode(newnonce);
179  }
180 
181  hash_join(digest_nonce_cache, newnonce);
182  /* the cache's link */
183  authDigestNonceLink(newnonce);
184  newnonce->flags.incache = true;
185  debugs(29, 5, "created nonce " << newnonce << " at " << newnonce->noncedata.creationtime);
186  return newnonce;
187 }
188 
189 static void
190 authenticateDigestNonceDelete(digest_nonce_h * nonce)
191 {
192  if (nonce) {
193  assert(nonce->references == 0);
194  assert(!nonce->flags.incache);
195 
196  safe_free(nonce->key);
197 
198  digest_nonce_pool->freeOne(nonce);
199  }
200 }
201 
202 static void
204 {
205  if (!digest_nonce_pool)
206  digest_nonce_pool = memPoolCreate("Digest Scheme nonce's", sizeof(digest_nonce_h));
207 
208  if (!digest_nonce_cache) {
209  digest_nonce_cache = hash_create((HASHCMP *) strcmp, 7921, hash_string);
211  eventAdd("Digest nonce cache maintenance", authenticateDigestNonceCacheCleanup, NULL, static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->nonceGCInterval, 1);
212  }
213 }
214 
215 void
217 {
218  /*
219  * We empty the cache of any nonces left in there.
220  */
221  digest_nonce_h *nonce;
222 
223  if (digest_nonce_cache) {
224  debugs(29, 2, "Shutting down nonce cache");
226 
227  while ((nonce = ((digest_nonce_h *) hash_next(digest_nonce_cache)))) {
228  assert(nonce->flags.incache);
229  authDigestNoncePurge(nonce);
230  }
231  }
232 
233  debugs(29, 2, "Nonce cache shutdown");
234 }
235 
236 static void
238 {
239  /*
240  * We walk the hash by noncehex as that is the unique key we
241  * use. For big hash tables we could consider stepping through
242  * the cache, 100/200 entries at a time. Lets see how it flies
243  * first.
244  */
245  digest_nonce_h *nonce;
246  debugs(29, 3, "Cleaning the nonce cache now");
247  debugs(29, 3, "Current time: " << current_time.tv_sec);
249 
250  while ((nonce = ((digest_nonce_h *) hash_next(digest_nonce_cache)))) {
251  debugs(29, 3, "nonce entry : " << nonce << " '" << (char *) nonce->key << "'");
252  debugs(29, 4, "Creation time: " << nonce->noncedata.creationtime);
253 
254  if (authDigestNonceIsStale(nonce)) {
255  debugs(29, 4, "Removing nonce " << (char *) nonce->key << " from cache due to timeout.");
256  assert(nonce->flags.incache);
257  /* invalidate nonce so future requests fail */
258  nonce->flags.valid = false;
259  /* if it is tied to a auth_user, remove the tie */
261  authDigestNoncePurge(nonce);
262  }
263  }
264 
265  debugs(29, 3, "Finished cleaning the nonce cache.");
266 
267  if (static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->active())
268  eventAdd("Digest nonce cache maintenance", authenticateDigestNonceCacheCleanup, NULL, static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->nonceGCInterval, 1);
269 }
270 
271 static void
272 authDigestNonceLink(digest_nonce_h * nonce)
273 {
274  assert(nonce != NULL);
275  ++nonce->references;
276  assert(nonce->references != 0); // no overflows
277  debugs(29, 9, "nonce '" << nonce << "' now at '" << nonce->references << "'.");
278 }
279 
280 void
281 authDigestNonceUnlink(digest_nonce_h * nonce)
282 {
283  assert(nonce != NULL);
284 
285  if (nonce->references > 0) {
286  -- nonce->references;
287  } else {
288  debugs(29, DBG_IMPORTANT, "Attempt to lower nonce " << nonce << " refcount below 0!");
289  }
290 
291  debugs(29, 9, "nonce '" << nonce << "' now at '" << nonce->references << "'.");
292 
293  if (nonce->references == 0)
295 }
296 
297 const char *
298 authenticateDigestNonceNonceHex(const digest_nonce_h * nonce)
299 {
300  if (!nonce)
301  return NULL;
302 
303  return (char const *) nonce->key;
304 }
305 
306 static digest_nonce_h *
307 authenticateDigestNonceFindNonce(const char *noncehex)
308 {
309  digest_nonce_h *nonce = NULL;
310 
311  if (noncehex == NULL)
312  return NULL;
313 
314  debugs(29, 9, "looking for noncehex '" << noncehex << "' in the nonce cache.");
315 
316  nonce = static_cast < digest_nonce_h * >(hash_lookup(digest_nonce_cache, noncehex));
317 
318  if ((nonce == NULL) || (strcmp(authenticateDigestNonceNonceHex(nonce), noncehex)))
319  return NULL;
320 
321  debugs(29, 9, "Found nonce '" << nonce << "'");
322 
323  return nonce;
324 }
325 
326 int
327 authDigestNonceIsValid(digest_nonce_h * nonce, char nc[9])
328 {
329  unsigned long intnc;
330  /* do we have a nonce ? */
331 
332  if (!nonce)
333  return 0;
334 
335  intnc = strtol(nc, NULL, 16);
336 
337  /* has it already been invalidated ? */
338  if (!nonce->flags.valid) {
339  debugs(29, 4, "Nonce already invalidated");
340  return 0;
341  }
342 
343  /* is the nonce-count ok ? */
344  if (!static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->CheckNonceCount) {
345  /* Ignore client supplied NC */
346  intnc = nonce->nc + 1;
347  }
348 
349  if ((static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->NonceStrictness && intnc != nonce->nc + 1) ||
350  intnc < nonce->nc + 1) {
351  debugs(29, 4, "Nonce count doesn't match");
352  nonce->flags.valid = false;
353  return 0;
354  }
355 
356  /* increment the nonce count - we've already checked that intnc is a
357  * valid representation for us, so we don't need the test here.
358  */
359  nonce->nc = intnc;
360 
361  return !authDigestNonceIsStale(nonce);
362 }
363 
364 int
365 authDigestNonceIsStale(digest_nonce_h * nonce)
366 {
367  /* do we have a nonce ? */
368 
369  if (!nonce)
370  return -1;
371 
372  /* Is it already invalidated? */
373  if (!nonce->flags.valid)
374  return -1;
375 
376  /* has it's max duration expired? */
377  if (nonce->noncedata.creationtime + static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->noncemaxduration < current_time.tv_sec) {
378  debugs(29, 4, "Nonce is too old. " <<
379  nonce->noncedata.creationtime << " " <<
380  static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->noncemaxduration << " " <<
381  current_time.tv_sec);
382 
383  nonce->flags.valid = false;
384  return -1;
385  }
386 
387  if (nonce->nc > 99999998) {
388  debugs(29, 4, "Nonce count overflow");
389  nonce->flags.valid = false;
390  return -1;
391  }
392 
393  if (nonce->nc > static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->noncemaxuses) {
394  debugs(29, 4, "Nonce count over user limit");
395  nonce->flags.valid = false;
396  return -1;
397  }
398 
399  /* seems ok */
400  return 0;
401 }
402 
407 int
408 authDigestNonceLastRequest(digest_nonce_h * nonce)
409 {
410  if (!nonce)
411  return -1;
412 
413  if (nonce->nc == 99999997) {
414  debugs(29, 4, "Nonce count about to overflow");
415  return -1;
416  }
417 
418  if (nonce->nc >= static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->noncemaxuses - 1) {
419  debugs(29, 4, "Nonce count about to hit user limit");
420  return -1;
421  }
422 
423  /* and other tests are possible. */
424  return 0;
425 }
426 
427 void
428 authDigestNoncePurge(digest_nonce_h * nonce)
429 {
430  if (!nonce)
431  return;
432 
433  if (!nonce->flags.incache)
434  return;
435 
437 
438  nonce->flags.incache = false;
439 
440  /* the cache's link */
441  authDigestNonceUnlink(nonce);
442 }
443 
444 void
445 Auth::Digest::Config::rotateHelpers()
446 {
447  /* schedule closure of existing helpers */
448  if (digestauthenticators) {
450  }
451 
452  /* NP: dynamic helper restart will ensure they start up again as needed. */
453 }
454 
455 bool
456 Auth::Digest::Config::dump(StoreEntry * entry, const char *name, Auth::SchemeConfig * scheme) const
457 {
458  if (!Auth::SchemeConfig::dump(entry, name, scheme))
459  return false;
460 
461  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",
462  name, "digest", noncemaxuses,
463  name, "digest", (int) noncemaxduration,
464  name, "digest", (int) nonceGCInterval);
465  return true;
466 }
467 
468 bool
469 Auth::Digest::Config::active() const
470 {
471  return authdigest_initialised == 1;
472 }
473 
474 bool
475 Auth::Digest::Config::configured() const
476 {
477  if ((authenticateProgram != NULL) &&
478  (authenticateChildren.n_max != 0) &&
479  !realm.isEmpty() && (noncemaxduration > -1))
480  return true;
481 
482  return false;
483 }
484 
485 /* add the [www-|Proxy-]authenticate header on a 407 or 401 reply */
486 void
487 Auth::Digest::Config::fixHeader(Auth::UserRequest::Pointer auth_user_request, HttpReply *rep, Http::HdrType hdrType, HttpRequest *)
488 {
489  if (!authenticateProgram)
490  return;
491 
492  bool stale = false;
493  digest_nonce_h *nonce = NULL;
494 
495  /* on a 407 or 401 we always use a new nonce */
496  if (auth_user_request != NULL) {
497  Auth::Digest::User *digest_user = dynamic_cast<Auth::Digest::User *>(auth_user_request->user().getRaw());
498 
499  if (digest_user) {
500  stale = digest_user->credentials() == Auth::Handshake;
501  if (stale) {
502  nonce = digest_user->currentNonce();
503  }
504  }
505  }
506  if (!nonce) {
507  nonce = authenticateDigestNonceNew();
508  }
509 
510  debugs(29, 9, "Sending type:" << hdrType <<
511  " header: 'Digest realm=\"" << realm << "\", nonce=\"" <<
512  authenticateDigestNonceNonceHex(nonce) << "\", qop=\"" << QOP_AUTH <<
513  "\", stale=" << (stale ? "true" : "false"));
514 
515  /* in the future, for WWW auth we may want to support the domain entry */
516  httpHeaderPutStrf(&rep->header, hdrType, "Digest realm=\"" SQUIDSBUFPH "\", nonce=\"%s\", qop=\"%s\", stale=%s",
517  SQUIDSBUFPRINT(realm), authenticateDigestNonceNonceHex(nonce), QOP_AUTH, stale ? "true" : "false");
518 }
519 
520 /* Initialize helpers and the like for this auth scheme. Called AFTER parsing the
521  * config file */
522 void
523 Auth::Digest::Config::init(Auth::SchemeConfig *)
524 {
525  if (authenticateProgram) {
528 
529  if (digestauthenticators == NULL)
530  digestauthenticators = new helper("digestauthenticator");
531 
532  digestauthenticators->cmdline = authenticateProgram;
533 
534  digestauthenticators->childs.updateLimits(authenticateChildren);
535 
537 
539  }
540 }
541 
542 void
543 Auth::Digest::Config::registerWithCacheManager(void)
544 {
545  Mgr::RegisterAction("digestauthenticator",
546  "Digest User Authenticator Stats",
548 }
549 
550 /* free any allocated configuration details */
551 void
552 Auth::Digest::Config::done()
553 {
555 
557 
560 
561  if (!shutting_down)
562  return;
563 
564  delete digestauthenticators;
566 
567  if (authenticateProgram)
568  wordlistDestroy(&authenticateProgram);
569 }
570 
572  nonceGCInterval(5*60),
573  noncemaxduration(30*60),
574  noncemaxuses(50),
575  NonceStrictness(0),
576  CheckNonceCount(1),
577  PostWorkaround(0)
578 {}
579 
580 void
581 Auth::Digest::Config::parse(Auth::SchemeConfig * scheme, int n_configured, char *param_str)
582 {
583  if (strcmp(param_str, "nonce_garbage_interval") == 0) {
584  parse_time_t(&nonceGCInterval);
585  } else if (strcmp(param_str, "nonce_max_duration") == 0) {
586  parse_time_t(&noncemaxduration);
587  } else if (strcmp(param_str, "nonce_max_count") == 0) {
588  parse_int((int *) &noncemaxuses);
589  } else if (strcmp(param_str, "nonce_strictness") == 0) {
590  parse_onoff(&NonceStrictness);
591  } else if (strcmp(param_str, "check_nonce_count") == 0) {
592  parse_onoff(&CheckNonceCount);
593  } else if (strcmp(param_str, "post_workaround") == 0) {
594  parse_onoff(&PostWorkaround);
595  } else
596  Auth::SchemeConfig::parse(scheme, n_configured, param_str);
597 }
598 
599 const char *
601 {
602  return Auth::Digest::Scheme::GetInstance()->type();
603 }
604 
605 static void
607 {
609  digestauthenticators->packStatsInto(sentry, "Digest Authenticator Statistics");
610 }
611 
612 /* NonceUserUnlink: remove the reference to auth_user and unlink the node from the list */
613 
614 static void
615 authDigestNonceUserUnlink(digest_nonce_h * nonce)
616 {
617  Auth::Digest::User *digest_user;
618  dlink_node *link, *tmplink;
619 
620  if (!nonce)
621  return;
622 
623  if (!nonce->user)
624  return;
625 
626  digest_user = nonce->user;
627 
628  /* unlink from the user list. Yes we're crossing structures but this is the only
629  * time this code is needed
630  */
631  link = digest_user->nonces.head;
632 
633  while (link) {
634  tmplink = link;
635  link = link->next;
636 
637  if (tmplink->data == nonce) {
638  dlinkDelete(tmplink, &digest_user->nonces);
639  authDigestNonceUnlink(static_cast < digest_nonce_h * >(tmplink->data));
640  delete tmplink;
641  link = NULL;
642  }
643  }
644 
645  /* this reference to user was not locked because freeeing the user frees
646  * the nonce too.
647  */
648  nonce->user = NULL;
649 }
650 
651 /* authDigesteserLinkNonce: add a nonce to a given user's struct */
652 void
653 authDigestUserLinkNonce(Auth::Digest::User * user, digest_nonce_h * nonce)
654 {
655  dlink_node *node;
656 
657  if (!user || !nonce || !nonce->user)
658  return;
659 
660  Auth::Digest::User *digest_user = user;
661 
662  node = digest_user->nonces.head;
663 
664  while (node && (node->data != nonce))
665  node = node->next;
666 
667  if (node)
668  return;
669 
670  node = new dlink_node;
671 
672  dlinkAddTail(nonce, node, &digest_user->nonces);
673 
674  authDigestNonceLink(nonce);
675 
676  /* ping this nonce to this auth user */
677  assert((nonce->user == NULL) || (nonce->user == user));
678 
679  /* we don't lock this reference because removing the user removes the
680  * hash too. Of course if that changes we're stuffed so read the code huh?
681  */
682  nonce->user = user;
683 }
684 
685 /* setup the necessary info to log the username */
687 authDigestLogUsername(char *username, Auth::UserRequest::Pointer auth_user_request, const char *requestRealm)
688 {
689  assert(auth_user_request != NULL);
690 
691  /* log the username */
692  debugs(29, 9, "Creating new user for logging '" << (username?username:"[no username]") << "'");
693  Auth::User::Pointer digest_user = new Auth::Digest::User(static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest")), requestRealm);
694  /* save the credentials */
695  digest_user->username(username);
696  /* set the auth_user type */
697  digest_user->auth_type = Auth::AUTH_BROKEN;
698  /* link the request to the user */
699  auth_user_request->user(digest_user);
700  return auth_user_request;
701 }
702 
703 /*
704  * Decode a Digest [Proxy-]Auth string, placing the results in the passed
705  * Auth_user structure.
706  */
708 Auth::Digest::Config::decode(char const *proxy_auth, const HttpRequest *request, const char *aRequestRealm)
709 {
710  const char *item;
711  const char *p;
712  const char *pos = NULL;
713  char *username = NULL;
714  digest_nonce_h *nonce;
715  int ilen;
716 
717  debugs(29, 9, "beginning");
718 
719  Auth::Digest::UserRequest *digest_request = new Auth::Digest::UserRequest();
720 
721  /* trim DIGEST from string */
722 
723  while (xisgraph(*proxy_auth))
724  ++proxy_auth;
725 
726  /* Trim leading whitespace before decoding */
727  while (xisspace(*proxy_auth))
728  ++proxy_auth;
729 
730  String temp(proxy_auth);
731 
732  while (strListGetItem(&temp, ',', &item, &ilen, &pos)) {
733  /* isolate directive name & value */
734  size_t nlen;
735  size_t vlen;
736  if ((p = (const char *)memchr(item, '=', ilen)) && (p - item < ilen)) {
737  nlen = p - item;
738  ++p;
739  vlen = ilen - (p - item);
740  } else {
741  nlen = ilen;
742  vlen = 0;
743  }
744 
745  SBuf keyName(item, nlen);
746  String value;
747 
748  if (vlen > 0) {
749  // see RFC 2617 section 3.2.1 and 3.2.2 for details on the BNF
750 
751  if (keyName == SBuf("domain",6) || keyName == SBuf("uri",3)) {
752  // domain is Special. Not a quoted-string, must not be de-quoted. But is wrapped in '"'
753  // BUG 3077: uri= can also be sent to us in a mangled (invalid!) form like domain
754  if (vlen > 1 && *p == '"' && *(p + vlen -1) == '"') {
755  value.assign(p+1, vlen-2);
756  }
757  } else if (keyName == SBuf("qop",3)) {
758  // qop is more special.
759  // On request this must not be quoted-string de-quoted. But is several values wrapped in '"'
760  // On response this is a single un-quoted token.
761  if (vlen > 1 && *p == '"' && *(p + vlen -1) == '"') {
762  value.assign(p+1, vlen-2);
763  } else {
764  value.assign(p, vlen);
765  }
766  } else if (*p == '"') {
767  if (!httpHeaderParseQuotedString(p, vlen, &value)) {
768  debugs(29, 9, "Failed to parse attribute '" << item << "' in '" << temp << "'");
769  continue;
770  }
771  } else {
772  value.assign(p, vlen);
773  }
774  } else {
775  debugs(29, 9, "Failed to parse attribute '" << item << "' in '" << temp << "'");
776  continue;
777  }
778 
779  /* find type */
780  const http_digest_attr_type t = DigestFieldsLookupTable.lookup(keyName);
781 
782  switch (t) {
783  case DIGEST_USERNAME:
784  safe_free(username);
785  if (value.size() != 0) {
786  const auto v = value.termedBuf();
787  if (utf8 && !isValidUtf8String(v, v + value.size())) {
788  auto str = isCP1251EncodingAllowed(request) ? Cp1251ToUtf8(v) : Latin1ToUtf8(v);
789  value = SBufToString(str);
790  }
791  username = xstrndup(value.rawBuf(), value.size() + 1);
792  }
793  debugs(29, 9, "Found Username '" << username << "'");
794  break;
795 
796  case DIGEST_REALM:
797  safe_free(digest_request->realm);
798  if (value.size() != 0)
799  digest_request->realm = xstrndup(value.rawBuf(), value.size() + 1);
800  debugs(29, 9, "Found realm '" << digest_request->realm << "'");
801  break;
802 
803  case DIGEST_QOP:
804  safe_free(digest_request->qop);
805  if (value.size() != 0)
806  digest_request->qop = xstrndup(value.rawBuf(), value.size() + 1);
807  debugs(29, 9, "Found qop '" << digest_request->qop << "'");
808  break;
809 
810  case DIGEST_ALGORITHM:
811  safe_free(digest_request->algorithm);
812  if (value.size() != 0)
813  digest_request->algorithm = xstrndup(value.rawBuf(), value.size() + 1);
814  debugs(29, 9, "Found algorithm '" << digest_request->algorithm << "'");
815  break;
816 
817  case DIGEST_URI:
818  safe_free(digest_request->uri);
819  if (value.size() != 0)
820  digest_request->uri = xstrndup(value.rawBuf(), value.size() + 1);
821  debugs(29, 9, "Found uri '" << digest_request->uri << "'");
822  break;
823 
824  case DIGEST_NONCE:
825  safe_free(digest_request->noncehex);
826  if (value.size() != 0)
827  digest_request->noncehex = xstrndup(value.rawBuf(), value.size() + 1);
828  debugs(29, 9, "Found nonce '" << digest_request->noncehex << "'");
829  break;
830 
831  case DIGEST_NC:
832  if (value.size() != 8) {
833  debugs(29, 9, "Invalid nc '" << value << "' in '" << temp << "'");
834  }
835  xstrncpy(digest_request->nc, value.rawBuf(), value.size() + 1);
836  debugs(29, 9, "Found noncecount '" << digest_request->nc << "'");
837  break;
838 
839  case DIGEST_CNONCE:
840  safe_free(digest_request->cnonce);
841  if (value.size() != 0)
842  digest_request->cnonce = xstrndup(value.rawBuf(), value.size() + 1);
843  debugs(29, 9, "Found cnonce '" << digest_request->cnonce << "'");
844  break;
845 
846  case DIGEST_RESPONSE:
847  safe_free(digest_request->response);
848  if (value.size() != 0)
849  digest_request->response = xstrndup(value.rawBuf(), value.size() + 1);
850  debugs(29, 9, "Found response '" << digest_request->response << "'");
851  break;
852 
853  default:
854  debugs(29, 3, "Unknown attribute '" << item << "' in '" << temp << "'");
855  break;
856  }
857  }
858 
859  temp.clean();
860 
861  /* now we validate the data given to us */
862 
863  /*
864  * TODO: on invalid parameters we should return 400, not 407.
865  * Find some clean way of doing this. perhaps return a valid
866  * struct, and set the direction to clientwards combined with
867  * a change to the clientwards handling code (ie let the
868  * clientwards call set the error type (but limited to known
869  * correct values - 400/401/407
870  */
871 
872  /* 2069 requirements */
873 
874  // return value.
876  /* do we have a username ? */
877  if (!username || username[0] == '\0') {
878  debugs(29, 2, "Empty or not present username");
879  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
880  safe_free(username);
881  return rv;
882  }
883 
884  /* Sanity check of the username.
885  * " can not be allowed in usernames until * the digest helper protocol
886  * have been redone
887  */
888  if (strchr(username, '"')) {
889  debugs(29, 2, "Unacceptable username '" << username << "'");
890  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
891  safe_free(username);
892  return rv;
893  }
894 
895  /* do we have a realm ? */
896  if (!digest_request->realm || digest_request->realm[0] == '\0') {
897  debugs(29, 2, "Empty or not present realm");
898  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
899  safe_free(username);
900  return rv;
901  }
902 
903  /* and a nonce? */
904  if (!digest_request->noncehex || digest_request->noncehex[0] == '\0') {
905  debugs(29, 2, "Empty or not present nonce");
906  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
907  safe_free(username);
908  return rv;
909  }
910 
911  /* we can't check the URI just yet. We'll check it in the
912  * authenticate phase, but needs to be given */
913  if (!digest_request->uri || digest_request->uri[0] == '\0') {
914  debugs(29, 2, "Missing URI field");
915  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
916  safe_free(username);
917  return rv;
918  }
919 
920  /* is the response the correct length? */
921  if (!digest_request->response || strlen(digest_request->response) != 32) {
922  debugs(29, 2, "Response length invalid");
923  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
924  safe_free(username);
925  return rv;
926  }
927 
928  /* check the algorithm is present and supported */
929  if (!digest_request->algorithm)
930  digest_request->algorithm = xstrndup("MD5", 4);
931  else if (strcmp(digest_request->algorithm, "MD5")
932  && strcmp(digest_request->algorithm, "MD5-sess")) {
933  debugs(29, 2, "invalid algorithm specified!");
934  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
935  safe_free(username);
936  return rv;
937  }
938 
939  /* 2617 requirements, indicated by qop */
940  if (digest_request->qop) {
941 
942  /* check the qop is what we expected. */
943  if (strcmp(digest_request->qop, QOP_AUTH) != 0) {
944  /* we received a qop option we didn't send */
945  debugs(29, 2, "Invalid qop option received");
946  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
947  safe_free(username);
948  return rv;
949  }
950 
951  /* check cnonce */
952  if (!digest_request->cnonce || digest_request->cnonce[0] == '\0') {
953  debugs(29, 2, "Missing cnonce field");
954  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
955  safe_free(username);
956  return rv;
957  }
958 
959  /* check nc */
960  if (strlen(digest_request->nc) != 8 || strspn(digest_request->nc, "0123456789abcdefABCDEF") != 8) {
961  debugs(29, 2, "invalid nonce count");
962  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
963  safe_free(username);
964  return rv;
965  }
966  } else {
967  /* cnonce and nc both require qop */
968  if (digest_request->cnonce || digest_request->nc[0] != '\0') {
969  debugs(29, 2, "missing qop!");
970  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
971  safe_free(username);
972  return rv;
973  }
974  }
975 
978  /* now the nonce */
979  nonce = authenticateDigestNonceFindNonce(digest_request->noncehex);
980  /* check that we're not being hacked / the username hasn't changed */
981  if (nonce && nonce->user && strcmp(username, nonce->user->username())) {
982  debugs(29, 2, "Username for the nonce does not equal the username for the request");
983  nonce = NULL;
984  }
985 
986  if (!nonce) {
987  /* we couldn't find a matching nonce! */
988  debugs(29, 2, "Unexpected or invalid nonce received from " << username);
989  Auth::UserRequest::Pointer auth_request = authDigestLogUsername(username, digest_request, aRequestRealm);
990  auth_request->user()->credentials(Auth::Handshake);
991  safe_free(username);
992  return auth_request;
993  }
994 
995  digest_request->nonce = nonce;
996  authDigestNonceLink(nonce);
997 
998  /* check that we're not being hacked / the username hasn't changed */
999  if (nonce->user && strcmp(username, nonce->user->username())) {
1000  debugs(29, 2, "Username for the nonce does not equal the username for the request");
1001  rv = authDigestLogUsername(username, digest_request, aRequestRealm);
1002  safe_free(username);
1003  return rv;
1004  }
1005 
1006  /* the method we'll check at the authenticate step as well */
1007 
1008  /* we don't send or parse opaques. Ok so we're flexible ... */
1009 
1010  /* find the user */
1011  Auth::Digest::User *digest_user;
1012 
1013  Auth::User::Pointer auth_user;
1014 
1015  SBuf key = Auth::User::BuildUserKey(username, aRequestRealm);
1016  if (key.isEmpty() || !(auth_user = Auth::Digest::User::Cache()->lookup(key))) {
1017  /* the user doesn't exist in the username cache yet */
1018  debugs(29, 9, "Creating new digest user '" << username << "'");
1019  digest_user = new Auth::Digest::User(this, aRequestRealm);
1020  /* auth_user is a parent */
1021  auth_user = digest_user;
1022  /* save the username */
1023  digest_user->username(username);
1024  /* set the user type */
1025  digest_user->auth_type = Auth::AUTH_DIGEST;
1026  /* this auth_user struct is the one to get added to the
1027  * username cache */
1028  /* store user in hash's */
1029  digest_user->addToNameCache();
1030 
1031  /*
1032  * Add the digest to the user so we can tell if a hacking
1033  * or spoofing attack is taking place. We do this by assuming
1034  * the user agent won't change user name without warning.
1035  */
1036  authDigestUserLinkNonce(digest_user, nonce);
1037 
1038  /* auth_user is now linked, we reset these values
1039  * after external auth occurs anyway */
1040  auth_user->expiretime = current_time.tv_sec;
1041  } else {
1042  debugs(29, 9, "Found user '" << username << "' in the user cache as '" << auth_user << "'");
1043  digest_user = static_cast<Auth::Digest::User *>(auth_user.getRaw());
1044  digest_user->credentials(Auth::Unchecked);
1045  xfree(username);
1046  }
1047 
1048  /*link the request and the user */
1049  assert(digest_request != NULL);
1050 
1051  digest_request->user(digest_user);
1052  debugs(29, 9, "username = '" << digest_user->username() << "'\nrealm = '" <<
1053  digest_request->realm << "'\nqop = '" << digest_request->qop <<
1054  "'\nalgorithm = '" << digest_request->algorithm << "'\nuri = '" <<
1055  digest_request->uri << "'\nnonce = '" << digest_request->noncehex <<
1056  "'\nnc = '" << digest_request->nc << "'\ncnonce = '" <<
1057  digest_request->cnonce << "'\nresponse = '" <<
1058  digest_request->response << "'\ndigestnonce = '" << nonce << "'");
1059 
1060  return digest_request;
1061 }
1062 
void httpHeaderPutStrf(HttpHeader *hdr, Http::HdrType id, const char *fmt,...)
int httpHeaderParseQuotedString(const char *start, const int len, String *val)
#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:19
void AUTHSSTATS(StoreEntry *)
Definition: Gadgets.h:21
static void authDigestNonceUserUnlink(digest_nonce_h *nonce)
Definition: Config.cc:615
helper * digestauthenticators
Definition: Config.cc:49
static hash_table * digest_nonce_cache
Definition: Config.cc:51
digest_nonce_h * authenticateDigestNonceNew(void)
Definition: Config.cc:120
void authDigestUserLinkNonce(Auth::Digest::User *user, digest_nonce_h *nonce)
Definition: Config.cc:653
static Auth::UserRequest::Pointer authDigestLogUsername(char *username, Auth::UserRequest::Pointer auth_user_request, const char *requestRealm)
Definition: Config.cc:687
void authDigestNonceUnlink(digest_nonce_h *nonce)
Definition: Config.cc:281
static void authenticateDigestNonceDelete(digest_nonce_h *nonce)
Definition: Config.cc:190
static digest_nonce_h * authenticateDigestNonceFindNonce(const char *noncehex)
Definition: Config.cc:307
const char * authenticateDigestNonceNonceHex(const digest_nonce_h *nonce)
Definition: Config.cc:298
int authDigestNonceIsStale(digest_nonce_h *nonce)
Definition: Config.cc:365
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:327
void authenticateDigestNonceShutdown(void)
Definition: Config.cc:216
int authDigestNonceLastRequest(digest_nonce_h *nonce)
Definition: Config.cc:408
static void authenticateDigestNonceSetup(void)
Definition: Config.cc:203
void authDigestNoncePurge(digest_nonce_h *nonce)
Definition: Config.cc:428
static AUTHSSTATS authenticateDigestStats
Definition: Config.cc:47
static MemAllocator * digest_nonce_pool
Definition: Config.cc:54
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:237
static void authDigestNonceLink(digest_nonce_h *nonce)
Definition: Config.cc:272
LookupTable< http_digest_attr_type > DigestFieldsLookupTable(DIGEST_INVALID_ATTR, DigestAttrs)
void parse_time_t(time_t *var)
Definition: cache_cf.cc:2987
void parse_onoff(int *var)
Definition: cache_cf.cc:2616
void parse_int(int *var)
Definition: cache_cf.cc:2576
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:75
virtual void freeOne(void *)=0
virtual void * alloc()=0
C * getRaw() const
Definition: RefCount.h:80
Definition: SBuf.h:94
bool isEmpty() const
Definition: SBuf.h:431
char const * rawBuf() const
Definition: SquidString.h:86
void assign(const char *str, int len)
Definition: String.cc:89
char const * termedBuf() const
Definition: SquidString.h:92
size_type size() const
Definition: SquidString.h:73
Definition: helper.h:64
wordlist * cmdline
Definition: helper.h:107
void packStatsInto(Packable *p, const char *label=NULL) const
Dump some stats about the helper state to a Packable object.
Definition: helper.cc:677
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:41
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Stream.h:196
#define IPC_STREAM
Definition: defines.h:108
int type
Definition: errorpage.cc:152
void eventAdd(const char *name, EVH *func, void *arg, double when, int weight, bool cbdata)
Definition: event.cc:107
int shutting_down
#define memPoolCreate
Definition: Pool.h:325
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_lookup(hash_table *, const void *)
Definition: hash.cc:146
SQUIDCEXTERN void hash_remove_link(hash_table *, hash_link *)
Definition: hash.cc:220
SQUIDCEXTERN hash_link * hash_next(hash_table *)
Definition: hash.cc:188
SQUIDCEXTERN hash_table * hash_create(HASHCMP *, int, HASHHASH *)
Definition: hash.cc:108
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:830
Definition: parse.c:104
struct node * next
Definition: parse.c:105
time_t getCurrentTime() STUB_RETVAL(0) int tvSubUsec(struct timeval
struct _request * request(char *urlin)
Definition: tcp-banger2.c:291
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
#define NULL
Definition: types.h:166
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:30
#define xisspace(x)
Definition: xis.h:17
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