2 * Copyright (C) 1996-2018 The Squid Software Foundation and contributors
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.
9 /* DEBUG: section 29 Authenticator */
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 */
16 #include "auth/CredentialsCache.h"
17 #include "auth/digest/Config.h"
18 #include "auth/digest/Scheme.h"
19 #include "auth/digest/User.h"
20 #include "auth/digest/UserRequest.h"
21 #include "auth/Gadgets.h"
22 #include "auth/State.h"
23 #include "base/LookupTable.h"
28 #include "HttpHeaderTools.h"
29 #include "HttpReply.h"
30 #include "HttpRequest.h"
31 #include "mgr/Registration.h"
33 #include "sbuf/SBuf.h"
34 #include "SquidTime.h"
39 /* digest_nonce_h still uses explicit alloc()/freeOne() MemPool calls.
40 * XXX: convert to MEMPROXY_CLASS() API
46 static AUTHSSTATS authenticateDigestStats
;
48 helper
*digestauthenticators
= NULL
;
50 static hash_table
*digest_nonce_cache
;
52 static int authdigest_initialised
= 0;
53 static MemAllocator
*digest_nonce_pool
= NULL
;
55 enum http_digest_attr_type
{
68 static const LookupTable
<http_digest_attr_type
>::Record
70 {"username", DIGEST_USERNAME
},
71 {"realm", DIGEST_REALM
},
73 {"algorithm", DIGEST_ALGORITHM
},
75 {"nonce", DIGEST_NONCE
},
77 {"cnonce", DIGEST_CNONCE
},
78 {"response", DIGEST_RESPONSE
},
79 {nullptr, DIGEST_INVALID_ATTR
}
82 LookupTable
<http_digest_attr_type
>
83 DigestFieldsLookupTable(DIGEST_INVALID_ATTR
, DigestAttrs
);
91 static void authenticateDigestNonceCacheCleanup(void *data
);
92 static digest_nonce_h
*authenticateDigestNonceFindNonce(const char *nonceb64
);
93 static void authenticateDigestNonceDelete(digest_nonce_h
* nonce
);
94 static void authenticateDigestNonceSetup(void);
95 static void authDigestNonceEncode(digest_nonce_h
* nonce
);
96 static void authDigestNonceLink(digest_nonce_h
* nonce
);
98 static int authDigestNonceLinks(digest_nonce_h
* nonce
);
100 static void authDigestNonceUserUnlink(digest_nonce_h
* nonce
);
103 authDigestNonceEncode(digest_nonce_h
* nonce
)
111 nonce
->key
= xcalloc(base64_encode_len(sizeof(digest_nonce_data
)), 1);
112 struct base64_encode_ctx ctx
;
113 base64_encode_init(&ctx
);
114 size_t blen
= base64_encode_update(&ctx
, reinterpret_cast<char*>(nonce
->key
), sizeof(digest_nonce_data
), reinterpret_cast<const uint8_t*>(&(nonce
->noncedata
)));
115 blen
+= base64_encode_final(&ctx
, reinterpret_cast<char*>(nonce
->key
)+blen
);
119 authenticateDigestNonceNew(void)
121 digest_nonce_h
*newnonce
= static_cast < digest_nonce_h
* >(digest_nonce_pool
->alloc());
123 /* NONCE CREATION - NOTES AND REASONING. RBC 20010108
124 * === EXCERPT FROM RFC 2617 ===
125 * The contents of the nonce are implementation dependent. The quality
126 * of the implementation depends on a good choice. A nonce might, for
127 * example, be constructed as the base 64 encoding of
129 * time-stamp H(time-stamp ":" ETag ":" private-key)
131 * where time-stamp is a server-generated time or other non-repeating
132 * value, ETag is the value of the HTTP ETag header associated with
133 * the requested entity, and private-key is data known only to the
134 * server. With a nonce of this form a server would recalculate the
135 * hash portion after receiving the client authentication header and
136 * reject the request if it did not match the nonce from that header
137 * or if the time-stamp value is not recent enough. In this way the
138 * server can limit the time of the nonce's validity. The inclusion of
139 * the ETag prevents a replay request for an updated version of the
140 * resource. (Note: including the IP address of the client in the
141 * nonce would appear to offer the server the ability to limit the
142 * reuse of the nonce to the same client that originally got it.
143 * However, that would break proxy farms, where requests from a single
144 * user often go through different proxies in the farm. Also, IP
145 * address spoofing is not that hard.)
148 * Now for my reasoning:
149 * We will not accept a unrecognised nonce->we have all recognisable
150 * nonces stored. If we send out unique base64 encodings we guarantee
151 * that a given nonce applies to only one user (barring attacks or
152 * really bad timing with expiry and creation). Using a random
153 * component in the nonce allows us to loop to find a unique nonce.
154 * We use H(nonce_data) so the nonce is meaningless to the reciever.
155 * So our nonce looks like base64(H(timestamp,pointertohash,randomdata))
156 * And even if our randomness is not very random we don't really care
157 * - the timestamp and memory pointer also guarantee local uniqueness
158 * in the input to the hash function.
160 // NP: this will likely produce the same randomness sequences for each worker
161 // since they should all start within the 1-second resolution of seed value.
162 static std::mt19937
mt(static_cast<uint32_t>(getCurrentTime() & 0xFFFFFFFF));
163 static xuniform_int_distribution
<uint32_t> newRandomData
;
165 /* create a new nonce */
167 newnonce
->flags
.valid
= true;
168 newnonce
->noncedata
.self
= newnonce
;
169 newnonce
->noncedata
.creationtime
= current_time
.tv_sec
;
170 newnonce
->noncedata
.randomdata
= newRandomData(mt
);
172 authDigestNonceEncode(newnonce
);
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
);
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
);
190 authenticateDigestNonceDelete(digest_nonce_h
* nonce
)
193 assert(nonce
->references
== 0);
196 if (nonce
->flags
.incache
)
197 hash_remove_link(digest_nonce_cache
, nonce
);
201 assert(!nonce
->flags
.incache
);
203 safe_free(nonce
->key
);
205 digest_nonce_pool
->freeOne(nonce
);
210 authenticateDigestNonceSetup(void)
212 if (!digest_nonce_pool
)
213 digest_nonce_pool
= memPoolCreate("Digest Scheme nonce's", sizeof(digest_nonce_h
));
215 if (!digest_nonce_cache
) {
216 digest_nonce_cache
= hash_create((HASHCMP
*) strcmp
, 7921, hash_string
);
217 assert(digest_nonce_cache
);
218 eventAdd("Digest nonce cache maintenance", authenticateDigestNonceCacheCleanup
, NULL
, static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest"))->nonceGCInterval
, 1);
223 authenticateDigestNonceShutdown(void)
226 * We empty the cache of any nonces left in there.
228 digest_nonce_h
*nonce
;
230 if (digest_nonce_cache
) {
231 debugs(29, 2, "Shutting down nonce cache");
232 hash_first(digest_nonce_cache
);
234 while ((nonce
= ((digest_nonce_h
*) hash_next(digest_nonce_cache
)))) {
235 assert(nonce
->flags
.incache
);
236 authDigestNoncePurge(nonce
);
241 if (digest_nonce_pool
) {
242 delete digest_nonce_pool
;
243 digest_nonce_pool
= NULL
;
247 debugs(29, 2, "Nonce cache shutdown");
251 authenticateDigestNonceCacheCleanup(void *)
254 * We walk the hash by nonceb64 as that is the unique key we
255 * use. For big hash tables we could consider stepping through
256 * the cache, 100/200 entries at a time. Lets see how it flies
259 digest_nonce_h
*nonce
;
260 debugs(29, 3, "Cleaning the nonce cache now");
261 debugs(29, 3, "Current time: " << current_time
.tv_sec
);
262 hash_first(digest_nonce_cache
);
264 while ((nonce
= ((digest_nonce_h
*) hash_next(digest_nonce_cache
)))) {
265 debugs(29, 3, "nonce entry : " << nonce
<< " '" << (char *) nonce
->key
<< "'");
266 debugs(29, 4, "Creation time: " << nonce
->noncedata
.creationtime
);
268 if (authDigestNonceIsStale(nonce
)) {
269 debugs(29, 4, "Removing nonce " << (char *) nonce
->key
<< " from cache due to timeout.");
270 assert(nonce
->flags
.incache
);
271 /* invalidate nonce so future requests fail */
272 nonce
->flags
.valid
= false;
273 /* if it is tied to a auth_user, remove the tie */
274 authDigestNonceUserUnlink(nonce
);
275 authDigestNoncePurge(nonce
);
279 debugs(29, 3, "Finished cleaning the nonce cache.");
281 if (static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest"))->active())
282 eventAdd("Digest nonce cache maintenance", authenticateDigestNonceCacheCleanup
, NULL
, static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest"))->nonceGCInterval
, 1);
286 authDigestNonceLink(digest_nonce_h
* nonce
)
288 assert(nonce
!= NULL
);
290 debugs(29, 9, "nonce '" << nonce
<< "' now at '" << nonce
->references
<< "'.");
295 authDigestNonceLinks(digest_nonce_h
* nonce
)
300 return nonce
->references
;
306 authDigestNonceUnlink(digest_nonce_h
* nonce
)
308 assert(nonce
!= NULL
);
310 if (nonce
->references
> 0) {
311 -- nonce
->references
;
313 debugs(29, DBG_IMPORTANT
, "Attempt to lower nonce " << nonce
<< " refcount below 0!");
316 debugs(29, 9, "nonce '" << nonce
<< "' now at '" << nonce
->references
<< "'.");
318 if (nonce
->references
== 0)
319 authenticateDigestNonceDelete(nonce
);
323 authenticateDigestNonceNonceb64(const digest_nonce_h
* nonce
)
328 return (char const *) nonce
->key
;
331 static digest_nonce_h
*
332 authenticateDigestNonceFindNonce(const char *nonceb64
)
334 digest_nonce_h
*nonce
= NULL
;
336 if (nonceb64
== NULL
)
339 debugs(29, 9, "looking for nonceb64 '" << nonceb64
<< "' in the nonce cache.");
341 nonce
= static_cast < digest_nonce_h
* >(hash_lookup(digest_nonce_cache
, nonceb64
));
343 if ((nonce
== NULL
) || (strcmp(authenticateDigestNonceNonceb64(nonce
), nonceb64
)))
346 debugs(29, 9, "Found nonce '" << nonce
<< "'");
352 authDigestNonceIsValid(digest_nonce_h
* nonce
, char nc
[9])
355 /* do we have a nonce ? */
360 intnc
= strtol(nc
, NULL
, 16);
362 /* has it already been invalidated ? */
363 if (!nonce
->flags
.valid
) {
364 debugs(29, 4, "Nonce already invalidated");
368 /* is the nonce-count ok ? */
369 if (!static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest"))->CheckNonceCount
) {
370 /* Ignore client supplied NC */
371 intnc
= nonce
->nc
+ 1;
374 if ((static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest"))->NonceStrictness
&& intnc
!= nonce
->nc
+ 1) ||
375 intnc
< nonce
->nc
+ 1) {
376 debugs(29, 4, "Nonce count doesn't match");
377 nonce
->flags
.valid
= false;
381 /* increment the nonce count - we've already checked that intnc is a
382 * valid representation for us, so we don't need the test here.
386 return !authDigestNonceIsStale(nonce
);
390 authDigestNonceIsStale(digest_nonce_h
* nonce
)
392 /* do we have a nonce ? */
397 /* Is it already invalidated? */
398 if (!nonce
->flags
.valid
)
401 /* has it's max duration expired? */
402 if (nonce
->noncedata
.creationtime
+ static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest"))->noncemaxduration
< current_time
.tv_sec
) {
403 debugs(29, 4, "Nonce is too old. " <<
404 nonce
->noncedata
.creationtime
<< " " <<
405 static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest"))->noncemaxduration
<< " " <<
406 current_time
.tv_sec
);
408 nonce
->flags
.valid
= false;
412 if (nonce
->nc
> 99999998) {
413 debugs(29, 4, "Nonce count overflow");
414 nonce
->flags
.valid
= false;
418 if (nonce
->nc
> static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest"))->noncemaxuses
) {
419 debugs(29, 4, "Nonce count over user limit");
420 nonce
->flags
.valid
= false;
429 * \retval 0 the digest is not stale yet
430 * \retval -1 the digest will be stale on the next request
433 authDigestNonceLastRequest(digest_nonce_h
* nonce
)
438 if (nonce
->nc
== 99999997) {
439 debugs(29, 4, "Nonce count about to overflow");
443 if (nonce
->nc
>= static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest"))->noncemaxuses
- 1) {
444 debugs(29, 4, "Nonce count about to hit user limit");
448 /* and other tests are possible. */
453 authDigestNoncePurge(digest_nonce_h
* nonce
)
458 if (!nonce
->flags
.incache
)
461 hash_remove_link(digest_nonce_cache
, nonce
);
463 nonce
->flags
.incache
= false;
465 /* the cache's link */
466 authDigestNonceUnlink(nonce
);
470 Auth::Digest::Config::rotateHelpers()
472 /* schedule closure of existing helpers */
473 if (digestauthenticators
) {
474 helperShutdown(digestauthenticators
);
477 /* NP: dynamic helper restart will ensure they start up again as needed. */
481 Auth::Digest::Config::dump(StoreEntry
* entry
, const char *name
, Auth::SchemeConfig
* scheme
) const
483 if (!Auth::SchemeConfig::dump(entry
, name
, scheme
))
486 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",
487 name
, "digest", noncemaxuses
,
488 name
, "digest", (int) noncemaxduration
,
489 name
, "digest", (int) nonceGCInterval
);
494 Auth::Digest::Config::active() const
496 return authdigest_initialised
== 1;
500 Auth::Digest::Config::configured() const
502 if ((authenticateProgram
!= NULL
) &&
503 (authenticateChildren
.n_max
!= 0) &&
504 !realm
.isEmpty() && (noncemaxduration
> -1))
510 /* add the [www-|Proxy-]authenticate header on a 407 or 401 reply */
512 Auth::Digest::Config::fixHeader(Auth::UserRequest::Pointer auth_user_request
, HttpReply
*rep
, Http::HdrType hdrType
, HttpRequest
*)
514 if (!authenticateProgram
)
518 digest_nonce_h
*nonce
= NULL
;
520 /* on a 407 or 401 we always use a new nonce */
521 if (auth_user_request
!= NULL
) {
522 Auth::Digest::User
*digest_user
= dynamic_cast<Auth::Digest::User
*>(auth_user_request
->user().getRaw());
525 stale
= digest_user
->credentials() == Auth::Handshake
;
527 nonce
= digest_user
->currentNonce();
532 nonce
= authenticateDigestNonceNew();
535 debugs(29, 9, "Sending type:" << hdrType
<<
536 " header: 'Digest realm=\"" << realm
<< "\", nonce=\"" <<
537 authenticateDigestNonceNonceb64(nonce
) << "\", qop=\"" << QOP_AUTH
<<
538 "\", stale=" << (stale
? "true" : "false"));
540 /* in the future, for WWW auth we may want to support the domain entry */
541 httpHeaderPutStrf(&rep
->header
, hdrType
, "Digest realm=\"" SQUIDSBUFPH
"\", nonce=\"%s\", qop=\"%s\", stale=%s",
542 SQUIDSBUFPRINT(realm
), authenticateDigestNonceNonceb64(nonce
), QOP_AUTH
, stale
? "true" : "false");
545 /* Initialize helpers and the like for this auth scheme. Called AFTER parsing the
548 Auth::Digest::Config::init(Auth::SchemeConfig
*)
550 if (authenticateProgram
) {
551 authenticateDigestNonceSetup();
552 authdigest_initialised
= 1;
554 if (digestauthenticators
== NULL
)
555 digestauthenticators
= new helper("digestauthenticator");
557 digestauthenticators
->cmdline
= authenticateProgram
;
559 digestauthenticators
->childs
.updateLimits(authenticateChildren
);
561 digestauthenticators
->ipc_type
= IPC_STREAM
;
563 helperOpenServers(digestauthenticators
);
568 Auth::Digest::Config::registerWithCacheManager(void)
570 Mgr::RegisterAction("digestauthenticator",
571 "Digest User Authenticator Stats",
572 authenticateDigestStats
, 0, 1);
575 /* free any allocated configuration details */
577 Auth::Digest::Config::done()
579 Auth::SchemeConfig::done();
581 authdigest_initialised
= 0;
583 if (digestauthenticators
)
584 helperShutdown(digestauthenticators
);
589 delete digestauthenticators
;
590 digestauthenticators
= NULL
;
592 if (authenticateProgram
)
593 wordlistDestroy(&authenticateProgram
);
596 Auth::Digest::Config::Config() :
597 nonceGCInterval(5*60),
598 noncemaxduration(30*60),
606 Auth::Digest::Config::parse(Auth::SchemeConfig
* scheme
, int n_configured
, char *param_str
)
608 if (strcmp(param_str
, "nonce_garbage_interval") == 0) {
609 parse_time_t(&nonceGCInterval
);
610 } else if (strcmp(param_str
, "nonce_max_duration") == 0) {
611 parse_time_t(&noncemaxduration
);
612 } else if (strcmp(param_str
, "nonce_max_count") == 0) {
613 parse_int((int *) &noncemaxuses
);
614 } else if (strcmp(param_str
, "nonce_strictness") == 0) {
615 parse_onoff(&NonceStrictness
);
616 } else if (strcmp(param_str
, "check_nonce_count") == 0) {
617 parse_onoff(&CheckNonceCount
);
618 } else if (strcmp(param_str
, "post_workaround") == 0) {
619 parse_onoff(&PostWorkaround
);
621 Auth::SchemeConfig::parse(scheme
, n_configured
, param_str
);
625 Auth::Digest::Config::type() const
627 return Auth::Digest::Scheme::GetInstance()->type();
631 authenticateDigestStats(StoreEntry
* sentry
)
633 if (digestauthenticators
)
634 digestauthenticators
->packStatsInto(sentry
, "Digest Authenticator Statistics");
637 /* NonceUserUnlink: remove the reference to auth_user and unlink the node from the list */
640 authDigestNonceUserUnlink(digest_nonce_h
* nonce
)
642 Auth::Digest::User
*digest_user
;
643 dlink_node
*link
, *tmplink
;
651 digest_user
= nonce
->user
;
653 /* unlink from the user list. Yes we're crossing structures but this is the only
654 * time this code is needed
656 link
= digest_user
->nonces
.head
;
662 if (tmplink
->data
== nonce
) {
663 dlinkDelete(tmplink
, &digest_user
->nonces
);
664 authDigestNonceUnlink(static_cast < digest_nonce_h
* >(tmplink
->data
));
670 /* this reference to user was not locked because freeeing the user frees
676 /* authDigesteserLinkNonce: add a nonce to a given user's struct */
678 authDigestUserLinkNonce(Auth::Digest::User
* user
, digest_nonce_h
* nonce
)
682 if (!user
|| !nonce
|| !nonce
->user
)
685 Auth::Digest::User
*digest_user
= user
;
687 node
= digest_user
->nonces
.head
;
689 while (node
&& (node
->data
!= nonce
))
695 node
= new dlink_node
;
697 dlinkAddTail(nonce
, node
, &digest_user
->nonces
);
699 authDigestNonceLink(nonce
);
701 /* ping this nonce to this auth user */
702 assert((nonce
->user
== NULL
) || (nonce
->user
== user
));
704 /* we don't lock this reference because removing the user removes the
705 * hash too. Of course if that changes we're stuffed so read the code huh?
710 /* setup the necessary info to log the username */
711 static Auth::UserRequest::Pointer
712 authDigestLogUsername(char *username
, Auth::UserRequest::Pointer auth_user_request
, const char *requestRealm
)
714 assert(auth_user_request
!= NULL
);
716 /* log the username */
717 debugs(29, 9, "Creating new user for logging '" << (username
?username
:"[no username]") << "'");
718 Auth::User::Pointer digest_user
= new Auth::Digest::User(static_cast<Auth::Digest::Config
*>(Auth::SchemeConfig::Find("digest")), requestRealm
);
719 /* save the credentials */
720 digest_user
->username(username
);
721 /* set the auth_user type */
722 digest_user
->auth_type
= Auth::AUTH_BROKEN
;
723 /* link the request to the user */
724 auth_user_request
->user(digest_user
);
725 return auth_user_request
;
729 * Decode a Digest [Proxy-]Auth string, placing the results in the passed
730 * Auth_user structure.
732 Auth::UserRequest::Pointer
733 Auth::Digest::Config::decode(char const *proxy_auth
, const char *aRequestRealm
)
737 const char *pos
= NULL
;
738 char *username
= NULL
;
739 digest_nonce_h
*nonce
;
742 debugs(29, 9, "beginning");
744 Auth::Digest::UserRequest
*digest_request
= new Auth::Digest::UserRequest();
746 /* trim DIGEST from string */
748 while (xisgraph(*proxy_auth
))
751 /* Trim leading whitespace before decoding */
752 while (xisspace(*proxy_auth
))
755 String
temp(proxy_auth
);
757 while (strListGetItem(&temp
, ',', &item
, &ilen
, &pos
)) {
758 /* isolate directive name & value */
761 if ((p
= (const char *)memchr(item
, '=', ilen
)) && (p
- item
< ilen
)) {
764 vlen
= ilen
- (p
- item
);
770 SBuf
keyName(item
, nlen
);
774 // see RFC 2617 section 3.2.1 and 3.2.2 for details on the BNF
776 if (keyName
== SBuf("domain",6) || keyName
== SBuf("uri",3)) {
777 // domain is Special. Not a quoted-string, must not be de-quoted. But is wrapped in '"'
778 // BUG 3077: uri= can also be sent to us in a mangled (invalid!) form like domain
779 if (*p
== '"' && *(p
+ vlen
-1) == '"') {
780 value
.limitInit(p
+1, vlen
-2);
782 } else if (keyName
== SBuf("qop",3)) {
783 // qop is more special.
784 // On request this must not be quoted-string de-quoted. But is several values wrapped in '"'
785 // On response this is a single un-quoted token.
786 if (*p
== '"' && *(p
+ vlen
-1) == '"') {
787 value
.limitInit(p
+1, vlen
-2);
789 value
.limitInit(p
, vlen
);
791 } else if (*p
== '"') {
792 if (!httpHeaderParseQuotedString(p
, vlen
, &value
)) {
793 debugs(29, 9, "Failed to parse attribute '" << item
<< "' in '" << temp
<< "'");
797 value
.limitInit(p
, vlen
);
800 debugs(29, 9, "Failed to parse attribute '" << item
<< "' in '" << temp
<< "'");
805 const http_digest_attr_type t
= DigestFieldsLookupTable
.lookup(keyName
);
808 case DIGEST_USERNAME
:
810 if (value
.size() != 0)
811 username
= xstrndup(value
.rawBuf(), value
.size() + 1);
812 debugs(29, 9, "Found Username '" << username
<< "'");
816 safe_free(digest_request
->realm
);
817 if (value
.size() != 0)
818 digest_request
->realm
= xstrndup(value
.rawBuf(), value
.size() + 1);
819 debugs(29, 9, "Found realm '" << digest_request
->realm
<< "'");
823 safe_free(digest_request
->qop
);
824 if (value
.size() != 0)
825 digest_request
->qop
= xstrndup(value
.rawBuf(), value
.size() + 1);
826 debugs(29, 9, "Found qop '" << digest_request
->qop
<< "'");
829 case DIGEST_ALGORITHM
:
830 safe_free(digest_request
->algorithm
);
831 if (value
.size() != 0)
832 digest_request
->algorithm
= xstrndup(value
.rawBuf(), value
.size() + 1);
833 debugs(29, 9, "Found algorithm '" << digest_request
->algorithm
<< "'");
837 safe_free(digest_request
->uri
);
838 if (value
.size() != 0)
839 digest_request
->uri
= xstrndup(value
.rawBuf(), value
.size() + 1);
840 debugs(29, 9, "Found uri '" << digest_request
->uri
<< "'");
844 safe_free(digest_request
->nonceb64
);
845 if (value
.size() != 0)
846 digest_request
->nonceb64
= xstrndup(value
.rawBuf(), value
.size() + 1);
847 debugs(29, 9, "Found nonce '" << digest_request
->nonceb64
<< "'");
851 if (value
.size() != 8) {
852 debugs(29, 9, "Invalid nc '" << value
<< "' in '" << temp
<< "'");
854 xstrncpy(digest_request
->nc
, value
.rawBuf(), value
.size() + 1);
855 debugs(29, 9, "Found noncecount '" << digest_request
->nc
<< "'");
859 safe_free(digest_request
->cnonce
);
860 if (value
.size() != 0)
861 digest_request
->cnonce
= xstrndup(value
.rawBuf(), value
.size() + 1);
862 debugs(29, 9, "Found cnonce '" << digest_request
->cnonce
<< "'");
865 case DIGEST_RESPONSE
:
866 safe_free(digest_request
->response
);
867 if (value
.size() != 0)
868 digest_request
->response
= xstrndup(value
.rawBuf(), value
.size() + 1);
869 debugs(29, 9, "Found response '" << digest_request
->response
<< "'");
873 debugs(29, 3, "Unknown attribute '" << item
<< "' in '" << temp
<< "'");
880 /* now we validate the data given to us */
883 * TODO: on invalid parameters we should return 400, not 407.
884 * Find some clean way of doing this. perhaps return a valid
885 * struct, and set the direction to clientwards combined with
886 * a change to the clientwards handling code (ie let the
887 * clientwards call set the error type (but limited to known
888 * correct values - 400/401/407
891 /* 2069 requirements */
894 Auth::UserRequest::Pointer rv
;
895 /* do we have a username ? */
896 if (!username
|| username
[0] == '\0') {
897 debugs(29, 2, "Empty or not present username");
898 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
903 /* Sanity check of the username.
904 * " can not be allowed in usernames until * the digest helper protocol
907 if (strchr(username
, '"')) {
908 debugs(29, 2, "Unacceptable username '" << username
<< "'");
909 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
914 /* do we have a realm ? */
915 if (!digest_request
->realm
|| digest_request
->realm
[0] == '\0') {
916 debugs(29, 2, "Empty or not present realm");
917 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
923 if (!digest_request
->nonceb64
|| digest_request
->nonceb64
[0] == '\0') {
924 debugs(29, 2, "Empty or not present nonce");
925 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
930 /* we can't check the URI just yet. We'll check it in the
931 * authenticate phase, but needs to be given */
932 if (!digest_request
->uri
|| digest_request
->uri
[0] == '\0') {
933 debugs(29, 2, "Missing URI field");
934 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
939 /* is the response the correct length? */
940 if (!digest_request
->response
|| strlen(digest_request
->response
) != 32) {
941 debugs(29, 2, "Response length invalid");
942 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
947 /* check the algorithm is present and supported */
948 if (!digest_request
->algorithm
)
949 digest_request
->algorithm
= xstrndup("MD5", 4);
950 else if (strcmp(digest_request
->algorithm
, "MD5")
951 && strcmp(digest_request
->algorithm
, "MD5-sess")) {
952 debugs(29, 2, "invalid algorithm specified!");
953 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
958 /* 2617 requirements, indicated by qop */
959 if (digest_request
->qop
) {
961 /* check the qop is what we expected. */
962 if (strcmp(digest_request
->qop
, QOP_AUTH
) != 0) {
963 /* we received a qop option we didn't send */
964 debugs(29, 2, "Invalid qop option received");
965 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
971 if (!digest_request
->cnonce
|| digest_request
->cnonce
[0] == '\0') {
972 debugs(29, 2, "Missing cnonce field");
973 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
979 if (strlen(digest_request
->nc
) != 8 || strspn(digest_request
->nc
, "0123456789abcdefABCDEF") != 8) {
980 debugs(29, 2, "invalid nonce count");
981 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
986 /* cnonce and nc both require qop */
987 if (digest_request
->cnonce
|| digest_request
->nc
[0] != '\0') {
988 debugs(29, 2, "missing qop!");
989 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
995 /** below nonce state dependent **/
998 nonce
= authenticateDigestNonceFindNonce(digest_request
->nonceb64
);
999 /* check that we're not being hacked / the username hasn't changed */
1000 if (nonce
&& nonce
->user
&& strcmp(username
, nonce
->user
->username())) {
1001 debugs(29, 2, "Username for the nonce does not equal the username for the request");
1006 /* we couldn't find a matching nonce! */
1007 debugs(29, 2, "Unexpected or invalid nonce received from " << username
);
1008 Auth::UserRequest::Pointer auth_request
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
1009 auth_request
->user()->credentials(Auth::Handshake
);
1010 safe_free(username
);
1011 return auth_request
;
1014 digest_request
->nonce
= nonce
;
1015 authDigestNonceLink(nonce
);
1017 /* check that we're not being hacked / the username hasn't changed */
1018 if (nonce
->user
&& strcmp(username
, nonce
->user
->username())) {
1019 debugs(29, 2, "Username for the nonce does not equal the username for the request");
1020 rv
= authDigestLogUsername(username
, digest_request
, aRequestRealm
);
1021 safe_free(username
);
1025 /* the method we'll check at the authenticate step as well */
1027 /* we don't send or parse opaques. Ok so we're flexable ... */
1030 Auth::Digest::User
*digest_user
;
1032 Auth::User::Pointer auth_user
;
1034 SBuf key
= Auth::User::BuildUserKey(username
, aRequestRealm
);
1035 if (key
.isEmpty() || !(auth_user
= Auth::Digest::User::Cache()->lookup(key
))) {
1036 /* the user doesn't exist in the username cache yet */
1037 debugs(29, 9, "Creating new digest user '" << username
<< "'");
1038 digest_user
= new Auth::Digest::User(this, aRequestRealm
);
1039 /* auth_user is a parent */
1040 auth_user
= digest_user
;
1041 /* save the username */
1042 digest_user
->username(username
);
1043 /* set the user type */
1044 digest_user
->auth_type
= Auth::AUTH_DIGEST
;
1045 /* this auth_user struct is the one to get added to the
1047 /* store user in hash's */
1048 digest_user
->addToNameCache();
1051 * Add the digest to the user so we can tell if a hacking
1052 * or spoofing attack is taking place. We do this by assuming
1053 * the user agent won't change user name without warning.
1055 authDigestUserLinkNonce(digest_user
, nonce
);
1057 /* auth_user is now linked, we reset these values
1058 * after external auth occurs anyway */
1059 auth_user
->expiretime
= current_time
.tv_sec
;
1061 debugs(29, 9, "Found user '" << username
<< "' in the user cache as '" << auth_user
<< "'");
1062 digest_user
= static_cast<Auth::Digest::User
*>(auth_user
.getRaw());
1063 digest_user
->credentials(Auth::Unchecked
);
1067 /*link the request and the user */
1068 assert(digest_request
!= NULL
);
1070 digest_request
->user(digest_user
);
1071 debugs(29, 9, "username = '" << digest_user
->username() << "'\nrealm = '" <<
1072 digest_request
->realm
<< "'\nqop = '" << digest_request
->qop
<<
1073 "'\nalgorithm = '" << digest_request
->algorithm
<< "'\nuri = '" <<
1074 digest_request
->uri
<< "'\nnonce = '" << digest_request
->nonceb64
<<
1075 "'\nnc = '" << digest_request
->nc
<< "'\ncnonce = '" <<
1076 digest_request
->cnonce
<< "'\nresponse = '" <<
1077 digest_request
->response
<< "'\ndigestnonce = '" << nonce
<< "'");
1079 return digest_request
;