4 * DEBUG: section 29 Authenticator
5 * AUTHOR: Robert Collins
7 * SQUID Internet Object Cache http://squid.nlanr.net/Squid/
8 * ----------------------------------------------------------
10 * Squid is the result of efforts by numerous individuals from the
11 * Internet community. Development is led by Duane Wessels of the
12 * National Laboratory for Applied Network Research and funded by the
13 * National Science Foundation. Squid is Copyrighted (C) 1998 by
14 * the Regents of the University of California. Please see the
15 * COPYRIGHT file for full details. Squid incorporates software
16 * developed and/or copyrighted by other sources. Please see the
17 * CREDITS file for full details.
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
35 /* The functions in this file handle authentication.
36 * They DO NOT perform access control or auditing.
37 * See acl.c for access control and client_side.c for auditing */
42 #include "auth_digest.h"
43 #include "auth/Gadgets.h"
45 #include "CacheManager.h"
47 #include "HttpRequest.h"
48 #include "HttpReply.h"
50 #include "SquidTime.h"
51 /* TODO don't include this */
52 #include "digestScheme.h"
56 static HLPCB authenticateDigestHandleReply
;
57 static AUTHSSTATS authenticateDigestStats
;
59 static helper
*digestauthenticators
= NULL
;
61 static hash_table
*digest_nonce_cache
;
63 static AuthDigestConfig digestConfig
;
65 static int authdigest_initialised
= 0;
66 static MemAllocator
*digest_nonce_pool
= NULL
;
68 CBDATA_TYPE(DigestAuthenticateStateData
);
76 static void authenticateDigestNonceCacheCleanup(void *data
);
77 static digest_nonce_h
*authenticateDigestNonceFindNonce(const char *nonceb64
);
78 static digest_nonce_h
*authenticateDigestNonceNew(void);
79 static void authenticateDigestNonceDelete(digest_nonce_h
* nonce
);
80 static void authenticateDigestNonceSetup(void);
81 static void authenticateDigestNonceShutdown(void);
82 static void authenticateDigestNonceReconfigure(void);
83 static const char *authenticateDigestNonceNonceb64(digest_nonce_h
* nonce
);
84 static int authDigestNonceIsValid(digest_nonce_h
* nonce
, char nc
[9]);
85 static int authDigestNonceIsStale(digest_nonce_h
* nonce
);
86 static void authDigestNonceEncode(digest_nonce_h
* nonce
);
87 static int authDigestNonceLastRequest(digest_nonce_h
* nonce
);
88 static void authDigestNonceLink(digest_nonce_h
* nonce
);
89 static void authDigestNonceUnlink(digest_nonce_h
* nonce
);
91 static int authDigestNonceLinks(digest_nonce_h
* nonce
);
93 static void authDigestNonceUserUnlink(digest_nonce_h
* nonce
);
94 static void authDigestNoncePurge(digest_nonce_h
* nonce
);
97 authDigestNonceEncode(digest_nonce_h
* nonce
)
105 nonce
->key
= xstrdup(base64_encode_bin((char *) &(nonce
->noncedata
), sizeof(digest_nonce_data
)));
108 static digest_nonce_h
*
109 authenticateDigestNonceNew(void)
111 digest_nonce_h
*newnonce
= static_cast < digest_nonce_h
* >(digest_nonce_pool
->alloc());
112 digest_nonce_h
*temp
;
114 /* NONCE CREATION - NOTES AND REASONING. RBC 20010108
115 * === EXCERPT FROM RFC 2617 ===
116 * The contents of the nonce are implementation dependent. The quality
117 * of the implementation depends on a good choice. A nonce might, for
118 * example, be constructed as the base 64 encoding of
120 * time-stamp H(time-stamp ":" ETag ":" private-key)
122 * where time-stamp is a server-generated time or other non-repeating
123 * value, ETag is the value of the HTTP ETag header associated with
124 * the requested entity, and private-key is data known only to the
125 * server. With a nonce of this form a server would recalculate the
126 * hash portion after receiving the client authentication header and
127 * reject the request if it did not match the nonce from that header
128 * or if the time-stamp value is not recent enough. In this way the
129 * server can limit the time of the nonce's validity. The inclusion of
130 * the ETag prevents a replay request for an updated version of the
131 * resource. (Note: including the IP address of the client in the
132 * nonce would appear to offer the server the ability to limit the
133 * reuse of the nonce to the same client that originally got it.
134 * However, that would break proxy farms, where requests from a single
135 * user often go through different proxies in the farm. Also, IP
136 * address spoofing is not that hard.)
139 * Now for my reasoning:
140 * We will not accept a unrecognised nonce->we have all recognisable
141 * nonces stored. If we send out unique base64 encodings we guarantee
142 * that a given nonce applies to only one user (barring attacks or
143 * really bad timing with expiry and creation). Using a random
144 * component in the nonce allows us to loop to find a unique nonce.
145 * We use H(nonce_data) so the nonce is meaningless to the reciever.
146 * So our nonce looks like base64(H(timestamp,pointertohash,randomdata))
147 * And even if our randomness is not very random (probably due to
148 * bad coding on my part) we don't really care - the timestamp and
149 * memory pointer also guarantee local uniqueness in the input to the hash
153 /* create a new nonce */
155 newnonce
->flags
.valid
= 1;
156 newnonce
->noncedata
.self
= newnonce
;
157 newnonce
->noncedata
.creationtime
= current_time
.tv_sec
;
158 newnonce
->noncedata
.randomdata
= squid_random();
160 authDigestNonceEncode(newnonce
);
162 * loop until we get a unique nonce. The nonce creation must
163 * have a random factor
166 while ((temp
= authenticateDigestNonceFindNonce((char const *) (newnonce
->key
)))) {
167 /* create a new nonce */
168 newnonce
->noncedata
.randomdata
= squid_random();
169 authDigestNonceEncode(newnonce
);
172 hash_join(digest_nonce_cache
, newnonce
);
173 /* the cache's link */
174 authDigestNonceLink(newnonce
);
175 newnonce
->flags
.incache
= 1;
176 debugs(29, 5, "authenticateDigestNonceNew: created nonce " << newnonce
<< " at " << newnonce
->noncedata
.creationtime
);
181 authenticateDigestNonceDelete(digest_nonce_h
* nonce
)
184 assert(nonce
->references
== 0);
187 if (nonce
->flags
.incache
)
188 hash_remove_link(digest_nonce_cache
, nonce
);
192 assert(nonce
->flags
.incache
== 0);
194 safe_free(nonce
->key
);
196 digest_nonce_pool
->free(nonce
);
201 authenticateDigestNonceSetup(void)
203 if (!digest_nonce_pool
)
204 digest_nonce_pool
= memPoolCreate("Digest Scheme nonce's", sizeof(digest_nonce_h
));
206 if (!digest_nonce_cache
) {
207 digest_nonce_cache
= hash_create((HASHCMP
*) strcmp
, 7921, hash_string
);
208 assert(digest_nonce_cache
);
209 eventAdd("Digest none cache maintenance", authenticateDigestNonceCacheCleanup
, NULL
, digestConfig
.nonceGCInterval
, 1);
214 authenticateDigestNonceShutdown(void)
217 * We empty the cache of any nonces left in there.
219 digest_nonce_h
*nonce
;
221 if (digest_nonce_cache
) {
222 debugs(29, 2, "authenticateDigestNonceShutdown: Shutting down nonce cache ");
223 hash_first(digest_nonce_cache
);
225 while ((nonce
= ((digest_nonce_h
*) hash_next(digest_nonce_cache
)))) {
226 assert(nonce
->flags
.incache
);
227 authDigestNoncePurge(nonce
);
232 if (digest_nonce_pool
) {
233 delete digest_nonce_pool
;
234 digest_nonce_pool
= NULL
;
238 debugs(29, 2, "authenticateDigestNonceShutdown: Nonce cache shutdown");
242 authenticateDigestNonceReconfigure(void)
246 authenticateDigestNonceCacheCleanup(void *data
)
249 * We walk the hash by nonceb64 as that is the unique key we
250 * use. For big hash tables we could consider stepping through
251 * the cache, 100/200 entries at a time. Lets see how it flies
254 digest_nonce_h
*nonce
;
255 debugs(29, 3, "authenticateDigestNonceCacheCleanup: Cleaning the nonce cache now");
256 debugs(29, 3, "authenticateDigestNonceCacheCleanup: Current time: " << current_time
.tv_sec
);
257 hash_first(digest_nonce_cache
);
259 while ((nonce
= ((digest_nonce_h
*) hash_next(digest_nonce_cache
)))) {
260 debugs(29, 3, "authenticateDigestNonceCacheCleanup: nonce entry : " << nonce
<< " '" << (char *) nonce
->key
<< "'");
261 debugs(29, 4, "authenticateDigestNonceCacheCleanup: Creation time: " << nonce
->noncedata
.creationtime
);
263 if (authDigestNonceIsStale(nonce
)) {
264 debugs(29, 4, "authenticateDigestNonceCacheCleanup: Removing nonce " << (char *) nonce
->key
<< " from cache due to timeout.");
265 assert(nonce
->flags
.incache
);
266 /* invalidate nonce so future requests fail */
267 nonce
->flags
.valid
= 0;
268 /* if it is tied to a auth_user, remove the tie */
269 authDigestNonceUserUnlink(nonce
);
270 authDigestNoncePurge(nonce
);
274 debugs(29, 3, "authenticateDigestNonceCacheCleanup: Finished cleaning the nonce cache.");
276 if (digestConfig
.active())
277 eventAdd("Digest none cache maintenance", authenticateDigestNonceCacheCleanup
, NULL
, digestConfig
.nonceGCInterval
, 1);
281 authDigestNonceLink(digest_nonce_h
* nonce
)
283 assert(nonce
!= NULL
);
285 debugs(29, 9, "authDigestNonceLink: nonce '" << nonce
<< "' now at '" << nonce
->references
<< "'.");
290 authDigestNonceLinks(digest_nonce_h
* nonce
)
295 return nonce
->references
;
301 authDigestNonceUnlink(digest_nonce_h
* nonce
)
303 assert(nonce
!= NULL
);
305 if (nonce
->references
> 0) {
308 debugs(29, 1, "authDigestNonceUnlink; Attempt to lower nonce " << nonce
<< " refcount below 0!");
311 debugs(29, 9, "authDigestNonceUnlink: nonce '" << nonce
<< "' now at '" << nonce
->references
<< "'.");
313 if (nonce
->references
== 0)
314 authenticateDigestNonceDelete(nonce
);
318 authenticateDigestNonceNonceb64(digest_nonce_h
* nonce
)
323 return (char const *) nonce
->key
;
326 static digest_nonce_h
*
327 authenticateDigestNonceFindNonce(const char *nonceb64
)
329 digest_nonce_h
*nonce
= NULL
;
331 if (nonceb64
== NULL
)
334 debugs(29, 9, "authDigestNonceFindNonce:looking for nonceb64 '" << nonceb64
<< "' in the nonce cache.");
336 nonce
= static_cast < digest_nonce_h
* >(hash_lookup(digest_nonce_cache
, nonceb64
));
338 if ((nonce
== NULL
) || (strcmp(authenticateDigestNonceNonceb64(nonce
), nonceb64
)))
341 debugs(29, 9, "authDigestNonceFindNonce: Found nonce '" << nonce
<< "'");
347 authDigestNonceIsValid(digest_nonce_h
* nonce
, char nc
[9])
350 /* do we have a nonce ? */
355 intnc
= strtol(nc
, NULL
, 16);
357 /* has it already been invalidated ? */
358 if (!nonce
->flags
.valid
) {
359 debugs(29, 4, "authDigestNonceIsValid: Nonce already invalidated");
363 /* is the nonce-count ok ? */
364 if (!digestConfig
.CheckNonceCount
) {
366 return -1; /* forced OK by configuration */
369 if ((digestConfig
.NonceStrictness
&& intnc
!= nonce
->nc
+ 1) ||
370 intnc
< nonce
->nc
+ 1) {
371 debugs(29, 4, "authDigestNonceIsValid: Nonce count doesn't match");
372 nonce
->flags
.valid
= 0;
377 /* increment the nonce count - we've already checked that intnc is a
378 * valid representation for us, so we don't need the test here.
386 authDigestNonceIsStale(digest_nonce_h
* nonce
)
388 /* do we have a nonce ? */
393 /* has it's max duration expired? */
394 if (nonce
->noncedata
.creationtime
+ digestConfig
.noncemaxduration
< current_time
.tv_sec
) {
395 debugs(29, 4, "authDigestNonceIsStale: Nonce is too old. " <<
396 nonce
->noncedata
.creationtime
<< " " <<
397 digestConfig
.noncemaxduration
<< " " <<
398 current_time
.tv_sec
);
400 nonce
->flags
.valid
= 0;
404 if (nonce
->nc
> 99999998) {
405 debugs(29, 4, "authDigestNonceIsStale: Nonce count overflow");
406 nonce
->flags
.valid
= 0;
410 if (nonce
->nc
> digestConfig
.noncemaxuses
) {
411 debugs(29, 4, "authDigestNoncelastRequest: Nonce count over user limit");
412 nonce
->flags
.valid
= 0;
420 /* return -1 if the digest will be stale on the next request */
422 authDigestNonceLastRequest(digest_nonce_h
* nonce
)
427 if (nonce
->nc
== 99999997) {
428 debugs(29, 4, "authDigestNoncelastRequest: Nonce count about to overflow");
432 if (nonce
->nc
>= digestConfig
.noncemaxuses
- 1) {
433 debugs(29, 4, "authDigestNoncelastRequest: Nonce count about to hit user limit");
437 /* and other tests are possible. */
442 authDigestNoncePurge(digest_nonce_h
* nonce
)
447 if (!nonce
->flags
.incache
)
450 hash_remove_link(digest_nonce_cache
, nonce
);
452 nonce
->flags
.incache
= 0;
454 /* the cache's link */
455 authDigestNonceUnlink(nonce
);
458 /* USER related functions */
460 authDigestUserFindUsername(const char *username
)
462 AuthUserHashPointer
*usernamehash
;
464 debugs(29, 9, HERE
<< "Looking for user '" << username
<< "'");
466 if (username
&& (usernamehash
= static_cast < auth_user_hash_pointer
* >(hash_lookup(proxy_auth_username_cache
, username
)))) {
467 while ((usernamehash
->user()->auth_type
!= AUTH_DIGEST
) &&
468 (usernamehash
->next
))
469 usernamehash
= static_cast < auth_user_hash_pointer
* >(usernamehash
->next
);
473 if (usernamehash
->user()->auth_type
== AUTH_DIGEST
) {
474 auth_user
= usernamehash
->user();
484 authDigestUserShutdown(void)
486 /** \todo Future work: the auth framework could flush it's cache */
487 AuthUserHashPointer
*usernamehash
;
489 hash_first(proxy_auth_username_cache
);
491 while ((usernamehash
= ((auth_user_hash_pointer
*) hash_next(proxy_auth_username_cache
)))) {
492 auth_user
= usernamehash
->user();
494 if (strcmp(auth_user
->config
->type(), "digest") == 0)
499 /** delete the digest request structure. Does NOT delete related structures */
503 /** \todo this should be a Config call. */
505 if (digestauthenticators
)
506 helperShutdown(digestauthenticators
);
508 authdigest_initialised
= 0;
510 if (!shutting_down
) {
511 authenticateDigestNonceReconfigure();
515 delete digestauthenticators
;
516 digestauthenticators
= NULL
;
518 authDigestUserShutdown();
519 authenticateDigestNonceShutdown();
520 debugs(29, 2, "authenticateDigestDone: Digest authentication shut down.");
524 AuthDigestConfig::dump(StoreEntry
* entry
, const char *name
, AuthConfig
* scheme
)
526 wordlist
*list
= authenticate
;
527 debugs(29, 9, "authDigestCfgDump: Dumping configuration");
528 storeAppendPrintf(entry
, "%s %s", name
, "digest");
530 while (list
!= NULL
) {
531 storeAppendPrintf(entry
, " %s", list
->key
);
535 storeAppendPrintf(entry
, "\n%s %s realm %s\n%s %s children %d startup=%d idle=%d concurrency=%d\n%s %s nonce_max_count %d\n%s %s nonce_max_duration %d seconds\n%s %s nonce_garbage_interval %d seconds\n",
536 name
, "digest", digestAuthRealm
,
537 name
, "digest", authenticateChildren
.n_max
, authenticateChildren
.n_startup
, authenticateChildren
.n_idle
, authenticateChildren
.concurrency
,
538 name
, "digest", noncemaxuses
,
539 name
, "digest", (int) noncemaxduration
,
540 name
, "digest", (int) nonceGCInterval
);
544 AuthDigestConfig::active() const
546 return authdigest_initialised
== 1;
550 AuthDigestConfig::configured() const
552 if ((authenticate
!= NULL
) &&
553 (authenticateChildren
.n_max
!= 0) &&
554 (digestAuthRealm
!= NULL
) && (noncemaxduration
> -1))
561 AuthDigestUserRequest::authenticated() const
563 if (credentials() == Ok
)
569 /** log a digest user in
572 AuthDigestUserRequest::authenticate(HttpRequest
* request
, ConnStateData
* conn
, http_hdr_type type
)
575 AuthDigestUserRequest
*digest_request
;
576 digest_user_h
*digest_user
;
582 assert(authUser() != NULL
);
583 auth_user
= authUser();
585 digest_user
= dynamic_cast < digest_user_h
* >(auth_user
);
587 assert(digest_user
!= NULL
);
589 /* if the check has corrupted the user, just return */
591 if (credentials() == Failed
) {
595 digest_request
= this;
597 /* do we have the HA1 */
599 if (!digest_user
->HA1created
) {
600 credentials(Pending
);
604 if (digest_request
->nonce
== NULL
) {
605 /* this isn't a nonce we issued */
610 DigestCalcHA1(digest_request
->algorithm
, NULL
, NULL
, NULL
,
611 authenticateDigestNonceNonceb64(digest_request
->nonce
),
612 digest_request
->cnonce
,
613 digest_user
->HA1
, SESSIONKEY
);
614 DigestCalcResponse(SESSIONKEY
, authenticateDigestNonceNonceb64(digest_request
->nonce
),
615 digest_request
->nc
, digest_request
->cnonce
, digest_request
->qop
,
616 RequestMethodStr(request
->method
), digest_request
->uri
, HA2
, Response
);
618 debugs(29, 9, "\nResponse = '" << digest_request
->response
<< "'\nsquid is = '" << Response
<< "'");
620 if (strcasecmp(digest_request
->response
, Response
) != 0) {
621 if (!digest_request
->flags
.helper_queried
) {
622 /* Query the helper in case the password has changed */
623 digest_request
->flags
.helper_queried
= 1;
624 digest_request
->credentials_ok
= Pending
;
628 if (digestConfig
.PostWorkaround
&& request
->method
!= METHOD_GET
) {
629 /* Ugly workaround for certain very broken browsers using the
630 * wrong method to calculate the request-digest on POST request.
631 * This should be deleted once Digest authentication becomes more
632 * widespread and such broken browsers no longer are commonly
635 DigestCalcResponse(SESSIONKEY
, authenticateDigestNonceNonceb64(digest_request
->nonce
),
636 digest_request
->nc
, digest_request
->cnonce
, digest_request
->qop
,
637 RequestMethodStr(METHOD_GET
), digest_request
->uri
, HA2
, Response
);
639 if (strcasecmp(digest_request
->response
, Response
)) {
641 digest_request
->setDenyMessage("Incorrect password");
644 const char *useragent
= request
->header
.getStr(HDR_USER_AGENT
);
646 static IpAddress last_broken_addr
;
647 static int seen_broken_client
= 0;
649 if (!seen_broken_client
) {
650 last_broken_addr
.SetNoAddr();
651 seen_broken_client
= 1;
654 if (last_broken_addr
!= request
->client_addr
) {
655 debugs(29, 1, "\nDigest POST bug detected from " <<
656 request
->client_addr
<< " using '" <<
657 (useragent
? useragent
: "-") <<
658 "'. Please upgrade browser. See Bug #630 for details.");
660 last_broken_addr
= request
->client_addr
;
665 digest_request
->flags
.invalid_password
= 1;
666 digest_request
->setDenyMessage("Incorrect password");
670 /* check for stale nonce */
671 if (!authDigestNonceIsValid(digest_request
->nonce
, digest_request
->nc
)) {
672 debugs(29, 3, "authenticateDigestAuthenticateuser: user '" << digest_user
->username() << "' validated OK but nonce stale");
674 digest_request
->setDenyMessage("Stale nonce");
681 /* password was checked and did match */
682 debugs(29, 4, "authenticateDigestAuthenticateuser: user '" << digest_user
->username() << "' validated OK");
684 /* auth_user is now linked, we reset these values
685 * after external auth occurs anyway */
686 auth_user
->expiretime
= current_time
.tv_sec
;
691 AuthDigestUserRequest::module_direction()
693 switch (credentials()) {
707 /* send new challenge */
714 /* add the [proxy]authorisation header */
716 AuthDigestUserRequest::addHeader(HttpReply
* rep
, int accel
)
720 /* don't add to authentication error pages */
722 if ((!accel
&& rep
->sline
.status
== HTTP_PROXY_AUTHENTICATION_REQUIRED
)
723 || (accel
&& rep
->sline
.status
== HTTP_UNAUTHORIZED
))
726 type
= accel
? HDR_AUTHENTICATION_INFO
: HDR_PROXY_AUTHENTICATION_INFO
;
729 /* test for http/1.1 transfer chunked encoding */
735 if ((digestConfig
.authenticate
) && authDigestNonceLastRequest(nonce
)) {
736 flags
.authinfo_sent
= 1;
737 debugs(29, 9, "authDigestAddHead: Sending type:" << type
<< " header: 'nextnonce=\"" << authenticateDigestNonceNonceb64(nonce
) << "\"");
738 httpHeaderPutStrf(&rep
->header
, type
, "nextnonce=\"%s\"", authenticateDigestNonceNonceb64(nonce
));
743 /* add the [proxy]authorisation header */
745 AuthDigestUserRequest::addTrailer(HttpReply
* rep
, int accel
)
749 if (!auth_user_request
)
753 /* has the header already been send? */
754 if (flags
.authinfo_sent
)
757 /* don't add to authentication error pages */
758 if ((!accel
&& rep
->sline
.status
== HTTP_PROXY_AUTHENTICATION_REQUIRED
)
759 || (accel
&& rep
->sline
.status
== HTTP_UNAUTHORIZED
))
762 type
= accel
? HDR_AUTHENTICATION_INFO
: HDR_PROXY_AUTHENTICATION_INFO
;
764 if ((digestConfig
.authenticate
) && authDigestNonceLastRequest(nonce
)) {
765 debugs(29, 9, "authDigestAddTrailer: Sending type:" << type
<< " header: 'nextnonce=\"" << authenticateDigestNonceNonceb64(nonce
) << "\"");
766 httpTrailerPutStrf(&rep
->header
, type
, "nextnonce=\"%s\"", authenticateDigestNonceNonceb64(nonce
));
772 /* add the [www-|Proxy-]authenticate header on a 407 or 401 reply */
774 AuthDigestConfig::fixHeader(AuthUserRequest
*auth_user_request
, HttpReply
*rep
, http_hdr_type hdrType
, HttpRequest
* request
)
781 if (auth_user_request
) {
782 AuthDigestUserRequest
*digest_request
;
783 digest_request
= dynamic_cast < AuthDigestUserRequest
* >(auth_user_request
);
784 assert (digest_request
!= NULL
);
786 stale
= !digest_request
->flags
.invalid_password
;
789 /* on a 407 or 401 we always use a new nonce */
790 digest_nonce_h
*nonce
= authenticateDigestNonceNew();
792 debugs(29, 9, "authenticateFixHeader: Sending type:" << hdrType
<<
793 " header: 'Digest realm=\"" << digestAuthRealm
<< "\", nonce=\"" <<
794 authenticateDigestNonceNonceb64(nonce
) << "\", qop=\"" << QOP_AUTH
<<
795 "\", stale=" << (stale
? "true" : "false"));
797 /* in the future, for WWW auth we may want to support the domain entry */
798 httpHeaderPutStrf(&rep
->header
, hdrType
, "Digest realm=\"%s\", nonce=\"%s\", qop=\"%s\", stale=%s", digestAuthRealm
, authenticateDigestNonceNonceb64(nonce
), QOP_AUTH
, stale
? "true" : "false");
801 DigestUser::~DigestUser()
804 dlink_node
*link
, *tmplink
;
810 dlinkDelete(tmplink
, &nonces
);
811 authDigestNoncePurge(static_cast < digest_nonce_h
* >(tmplink
->data
));
812 authDigestNonceUnlink(static_cast < digest_nonce_h
* >(tmplink
->data
));
813 dlinkNodeDelete(tmplink
);
818 authenticateDigestHandleReply(void *data
, char *reply
)
820 DigestAuthenticateStateData
*replyData
= static_cast < DigestAuthenticateStateData
* >(data
);
821 AuthUserRequest
*auth_user_request
;
822 AuthDigestUserRequest
*digest_request
;
823 digest_user_h
*digest_user
;
826 debugs(29, 9, "authenticateDigestHandleReply: {" << (reply
? reply
: "<NULL>") << "}");
829 if ((t
= strchr(reply
, ' ')))
832 if (*reply
== '\0' || *reply
== '\n')
836 assert(replyData
->auth_user_request
!= NULL
);
837 auth_user_request
= replyData
->auth_user_request
;
838 digest_request
= dynamic_cast < AuthDigestUserRequest
* >(auth_user_request
);
839 assert(digest_request
);
841 digest_user
= dynamic_cast < digest_user_h
* >(auth_user_request
->user());
842 assert(digest_user
!= NULL
);
844 if (reply
&& (strncasecmp(reply
, "ERR", 3) == 0)) {
845 digest_request
->credentials(AuthDigestUserRequest::Failed
);
846 digest_request
->flags
.invalid_password
= 1;
849 digest_request
->setDenyMessage(t
);
851 CvtBin(reply
, digest_user
->HA1
);
852 digest_user
->HA1created
= 1;
855 if (cbdataReferenceValidDone(replyData
->data
, &cbdata
))
856 replyData
->handler(cbdata
, NULL
);
858 //we know replyData->auth_user_request != NULL, or we'd have asserted
859 AUTHUSERREQUESTUNLOCK(replyData
->auth_user_request
, "replyData");
861 cbdataFree(replyData
);
864 /* Initialize helpers and the like for this auth scheme. Called AFTER parsing the
867 AuthDigestConfig::init(AuthConfig
* scheme
)
870 authenticateDigestNonceSetup();
871 authdigest_initialised
= 1;
873 if (digestauthenticators
== NULL
)
874 digestauthenticators
= new helper("digestauthenticator");
876 digestauthenticators
->cmdline
= authenticate
;
878 digestauthenticators
->childs
= authenticateChildren
;
880 digestauthenticators
->ipc_type
= IPC_STREAM
;
882 helperOpenServers(digestauthenticators
);
884 CBDATA_INIT_TYPE(DigestAuthenticateStateData
);
889 AuthDigestConfig::registerWithCacheManager(void)
891 CacheManager::GetInstance()->
892 registerAction("digestauthenticator",
893 "Digest User Authenticator Stats",
894 authenticateDigestStats
, 0, 1);
897 /* free any allocated configuration details */
899 AuthDigestConfig::done()
902 wordlistDestroy(&authenticate
);
904 safe_free(digestAuthRealm
);
907 AuthDigestConfig::AuthDigestConfig() : authenticateChildren(20)
909 /* TODO: move into initialisation list */
911 nonceGCInterval
= 5 * 60;
913 noncemaxduration
= 30 * 60;
916 /* Not strict nonce count behaviour */
918 /* Verify nonce count */
923 AuthDigestConfig::parse(AuthConfig
* scheme
, int n_configured
, char *param_str
)
925 if (strcasecmp(param_str
, "program") == 0) {
927 wordlistDestroy(&authenticate
);
929 parse_wordlist(&authenticate
);
931 requirePathnameExists("auth_param digest program", authenticate
->key
);
932 } else if (strcasecmp(param_str
, "children") == 0) {
933 authenticateChildren
.parseConfig();
934 } else if (strcasecmp(param_str
, "realm") == 0) {
935 parse_eol(&digestAuthRealm
);
936 } else if (strcasecmp(param_str
, "nonce_garbage_interval") == 0) {
937 parse_time_t(&nonceGCInterval
);
938 } else if (strcasecmp(param_str
, "nonce_max_duration") == 0) {
939 parse_time_t(&noncemaxduration
);
940 } else if (strcasecmp(param_str
, "nonce_max_count") == 0) {
941 parse_int((int *) &noncemaxuses
);
942 } else if (strcasecmp(param_str
, "nonce_strictness") == 0) {
943 parse_onoff(&NonceStrictness
);
944 } else if (strcasecmp(param_str
, "check_nonce_count") == 0) {
945 parse_onoff(&CheckNonceCount
);
946 } else if (strcasecmp(param_str
, "post_workaround") == 0) {
947 parse_onoff(&PostWorkaround
);
948 } else if (strcasecmp(param_str
, "utf8") == 0) {
951 debugs(29, 0, "unrecognised digest auth scheme parameter '" << param_str
<< "'");
956 AuthDigestConfig::type() const
958 return digestScheme::GetInstance().type();
963 authenticateDigestStats(StoreEntry
* sentry
)
965 helperStats(sentry
, digestauthenticators
, "Digest Authenticator Statistics");
968 /* NonceUserUnlink: remove the reference to auth_user and unlink the node from the list */
971 authDigestNonceUserUnlink(digest_nonce_h
* nonce
)
973 digest_user_h
*digest_user
;
974 dlink_node
*link
, *tmplink
;
982 digest_user
= nonce
->user
;
984 /* unlink from the user list. Yes we're crossing structures but this is the only
985 * time this code is needed
987 link
= digest_user
->nonces
.head
;
993 if (tmplink
->data
== nonce
) {
994 dlinkDelete(tmplink
, &digest_user
->nonces
);
995 authDigestNonceUnlink(static_cast < digest_nonce_h
* >(tmplink
->data
));
996 dlinkNodeDelete(tmplink
);
1001 /* this reference to user was not locked because freeeing the user frees
1007 /* authDigestUserLinkNonce: add a nonce to a given user's struct */
1010 authDigestUserLinkNonce(DigestUser
* user
, digest_nonce_h
* nonce
)
1013 digest_user_h
*digest_user
;
1015 if (!user
|| !nonce
)
1020 node
= digest_user
->nonces
.head
;
1022 while (node
&& (node
->data
!= nonce
))
1028 node
= dlinkNodeNew();
1030 dlinkAddTail(nonce
, node
, &digest_user
->nonces
);
1032 authDigestNonceLink(nonce
);
1034 /* ping this nonce to this auth user */
1035 assert((nonce
->user
== NULL
) || (nonce
->user
== user
));
1037 /* we don't lock this reference because removing the user removes the
1038 * hash too. Of course if that changes we're stuffed so read the code huh?
1043 /* setup the necessary info to log the username */
1044 static AuthUserRequest
*
1045 authDigestLogUsername(char *username
, AuthDigestUserRequest
*auth_user_request
)
1047 assert(auth_user_request
!= NULL
);
1049 /* log the username */
1050 debugs(29, 9, "authDigestLogUsername: Creating new user for logging '" << username
<< "'");
1051 digest_user_h
*digest_user
= new DigestUser(&digestConfig
);
1052 /* save the credentials */
1053 digest_user
->username(username
);
1054 /* set the auth_user type */
1055 digest_user
->auth_type
= AUTH_BROKEN
;
1056 /* link the request to the user */
1057 auth_user_request
->authUser(digest_user
);
1058 auth_user_request
->user(digest_user
);
1059 digest_user
->addRequest (auth_user_request
);
1060 return auth_user_request
;
1064 * Decode a Digest [Proxy-]Auth string, placing the results in the passed
1065 * Auth_user structure.
1068 AuthDigestConfig::decode(char const *proxy_auth
)
1072 const char *pos
= NULL
;
1073 char *username
= NULL
;
1074 digest_nonce_h
*nonce
;
1077 debugs(29, 9, "authenticateDigestDecodeAuth: beginning");
1079 AuthDigestUserRequest
*digest_request
= new AuthDigestUserRequest();
1081 /* trim DIGEST from string */
1083 while (xisgraph(*proxy_auth
))
1086 /* Trim leading whitespace before decoding */
1087 while (xisspace(*proxy_auth
))
1090 String
temp(proxy_auth
);
1092 while (strListGetItem(&temp
, ',', &item
, &ilen
, &pos
)) {
1093 if ((p
= strchr(item
, '=')) && (p
- item
< ilen
))
1096 if (!strncmp(item
, "username", ilen
)) {
1099 while (xisspace(*p
))
1105 safe_free(username
);
1106 username
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1108 debugs(29, 9, "authDigestDecodeAuth: Found Username '" << username
<< "'");
1109 } else if (!strncmp(item
, "realm", ilen
)) {
1112 while (xisspace(*p
))
1118 safe_free(digest_request
->realm
);
1119 digest_request
->realm
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1121 debugs(29, 9, "authDigestDecodeAuth: Found realm '" << digest_request
->realm
<< "'");
1122 } else if (!strncmp(item
, "qop", ilen
)) {
1125 while (xisspace(*p
))
1132 safe_free(digest_request
->qop
);
1133 digest_request
->qop
= xstrndup(p
, strcspn(p
, "\" \t\r\n()<>@,;:\\/[]?={}") + 1);
1135 debugs(29, 9, "authDigestDecodeAuth: Found qop '" << digest_request
->qop
<< "'");
1136 } else if (!strncmp(item
, "algorithm", ilen
)) {
1139 while (xisspace(*p
))
1146 safe_free(digest_request
->algorithm
);
1147 digest_request
->algorithm
= xstrndup(p
, strcspn(p
, "\" \t\r\n()<>@,;:\\/[]?={}") + 1);
1149 debugs(29, 9, "authDigestDecodeAuth: Found algorithm '" << digest_request
->algorithm
<< "'");
1150 } else if (!strncmp(item
, "uri", ilen
)) {
1153 while (xisspace(*p
))
1159 safe_free(digest_request
->uri
);
1160 digest_request
->uri
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1162 debugs(29, 9, "authDigestDecodeAuth: Found uri '" << digest_request
->uri
<< "'");
1163 } else if (!strncmp(item
, "nonce", ilen
)) {
1166 while (xisspace(*p
))
1172 safe_free(digest_request
->nonceb64
);
1173 digest_request
->nonceb64
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1175 debugs(29, 9, "authDigestDecodeAuth: Found nonce '" << digest_request
->nonceb64
<< "'");
1176 } else if (!strncmp(item
, "nc", ilen
)) {
1179 while (xisspace(*p
))
1182 xstrncpy(digest_request
->nc
, p
, 9);
1184 debugs(29, 9, "authDigestDecodeAuth: Found noncecount '" << digest_request
->nc
<< "'");
1185 } else if (!strncmp(item
, "cnonce", ilen
)) {
1188 while (xisspace(*p
))
1194 safe_free(digest_request
->cnonce
);
1195 digest_request
->cnonce
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1197 debugs(29, 9, "authDigestDecodeAuth: Found cnonce '" << digest_request
->cnonce
<< "'");
1198 } else if (!strncmp(item
, "response", ilen
)) {
1201 while (xisspace(*p
))
1207 safe_free(digest_request
->response
);
1208 digest_request
->response
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1210 debugs(29, 9, "authDigestDecodeAuth: Found response '" << digest_request
->response
<< "'");
1217 /* now we validate the data given to us */
1220 * TODO: on invalid parameters we should return 400, not 407.
1221 * Find some clean way of doing this. perhaps return a valid
1222 * struct, and set the direction to clientwards combined with
1223 * a change to the clientwards handling code (ie let the
1224 * clientwards call set the error type (but limited to known
1225 * correct values - 400/401/407
1228 /* first the NONCE count */
1230 if (digest_request
->cnonce
&& strlen(digest_request
->nc
) != 8) {
1231 debugs(29, 4, "authenticateDigestDecode: nonce count length invalid");
1232 return authDigestLogUsername(username
, digest_request
);
1236 nonce
= authenticateDigestNonceFindNonce(digest_request
->nonceb64
);
1239 /* we couldn't find a matching nonce! */
1240 debugs(29, 4, "authenticateDigestDecode: Unexpected or invalid nonce received");
1241 return authDigestLogUsername(username
, digest_request
);
1244 digest_request
->nonce
= nonce
;
1245 authDigestNonceLink(nonce
);
1247 /* check the qop is what we expected. Note that for compatability with
1248 * RFC 2069 we should support a missing qop. Tough. */
1250 if (digest_request
->qop
&& strcmp(digest_request
->qop
, QOP_AUTH
) != 0) {
1251 /* we received a qop option we didn't send */
1252 debugs(29, 4, "authenticateDigestDecode: Invalid qop option received");
1253 return authDigestLogUsername(username
, digest_request
);
1256 /* we can't check the URI just yet. We'll check it in the
1257 * authenticate phase */
1259 /* is the response the correct length? */
1261 if (!digest_request
->response
|| strlen(digest_request
->response
) != 32) {
1262 debugs(29, 4, "authenticateDigestDecode: Response length invalid");
1263 return authDigestLogUsername(username
, digest_request
);
1266 /* do we have a username ? */
1267 if (!username
|| username
[0] == '\0') {
1268 debugs(29, 4, "authenticateDigestDecode: Empty or not present username");
1269 return authDigestLogUsername(username
, digest_request
);
1272 /* check that we're not being hacked / the username hasn't changed */
1273 if (nonce
->user
&& strcmp(username
, nonce
->user
->username())) {
1274 debugs(29, 4, "authenticateDigestDecode: Username for the nonce does not equal the username for the request");
1275 return authDigestLogUsername(username
, digest_request
);
1278 /* if we got a qop, did we get a cnonce or did we get a cnonce wihtout a qop? */
1279 if ((digest_request
->qop
&& !digest_request
->cnonce
)
1280 || (!digest_request
->qop
&& digest_request
->cnonce
)) {
1281 debugs(29, 4, "authenticateDigestDecode: qop without cnonce, or vice versa!");
1282 return authDigestLogUsername(username
, digest_request
);
1285 /* check the algorithm is present and supported */
1286 if (!digest_request
->algorithm
)
1287 digest_request
->algorithm
= xstrndup("MD5", 4);
1288 else if (strcmp(digest_request
->algorithm
, "MD5")
1289 && strcmp(digest_request
->algorithm
, "MD5-sess")) {
1290 debugs(29, 4, "authenticateDigestDecode: invalid algorithm specified!");
1291 return authDigestLogUsername(username
, digest_request
);
1294 /* the method we'll check at the authenticate step as well */
1297 /* we don't send or parse opaques. Ok so we're flexable ... */
1300 digest_user_h
*digest_user
;
1302 AuthUser
*auth_user
;
1304 if ((auth_user
= authDigestUserFindUsername(username
)) == NULL
) {
1305 /* the user doesn't exist in the username cache yet */
1306 debugs(29, 9, "authDigestDecodeAuth: Creating new digest user '" << username
<< "'");
1307 digest_user
= new DigestUser (&digestConfig
);
1308 /* auth_user is a parent */
1309 auth_user
= digest_user
;
1310 /* save the username */
1311 digest_user
->username(username
);
1312 /* set the user type */
1313 digest_user
->auth_type
= AUTH_DIGEST
;
1314 /* this auth_user struct is the one to get added to the
1316 /* store user in hash's */
1317 digest_user
->addToNameCache();
1320 * Add the digest to the user so we can tell if a hacking
1321 * or spoofing attack is taking place. We do this by assuming
1322 * the user agent won't change user name without warning.
1324 authDigestUserLinkNonce(digest_user
, nonce
);
1326 debugs(29, 9, "authDigestDecodeAuth: Found user '" << username
<< "' in the user cache as '" << auth_user
<< "'");
1327 digest_user
= static_cast < digest_user_h
* >(auth_user
);
1331 /*link the request and the user */
1332 assert(digest_request
!= NULL
);
1334 digest_request
->authUser (digest_user
);
1336 digest_request
->user(digest_user
);
1338 digest_user
->addRequest (digest_request
);
1340 debugs(29, 9, "username = '" << digest_user
->username() << "'\nrealm = '" <<
1341 digest_request
->realm
<< "'\nqop = '" << digest_request
->qop
<<
1342 "'\nalgorithm = '" << digest_request
->algorithm
<< "'\nuri = '" <<
1343 digest_request
->uri
<< "'\nnonce = '" << digest_request
->nonceb64
<<
1344 "'\nnc = '" << digest_request
->nc
<< "'\ncnonce = '" <<
1345 digest_request
->cnonce
<< "'\nresponse = '" <<
1346 digest_request
->response
<< "'\ndigestnonce = '" << nonce
<< "'");
1348 return digest_request
;
1351 /* send the initial data to a digest authenticator module */
1353 AuthDigestUserRequest::module_start(RH
* handler
, void *data
)
1355 DigestAuthenticateStateData
*r
= NULL
;
1357 digest_user_h
*digest_user
;
1358 assert(user()->auth_type
== AUTH_DIGEST
);
1359 digest_user
= dynamic_cast < digest_user_h
* >(user());
1360 assert(digest_user
!= NULL
);
1361 debugs(29, 9, "authenticateStart: '\"" << digest_user
->username() << "\":\"" << realm
<< "\"'");
1363 if (digestConfig
.authenticate
== NULL
) {
1364 handler(data
, NULL
);
1368 r
= cbdataAlloc(DigestAuthenticateStateData
);
1369 r
->handler
= handler
;
1370 r
->data
= cbdataReference(data
);
1371 r
->auth_user_request
= this;
1372 AUTHUSERREQUESTLOCK(r
->auth_user_request
, "r");
1373 if (digestConfig
.utf8
) {
1375 latin1_to_utf8(userstr
, sizeof(userstr
), digest_user
->username());
1376 snprintf(buf
, 8192, "\"%s\":\"%s\"\n", userstr
, realm
);
1378 snprintf(buf
, 8192, "\"%s\":\"%s\"\n", digest_user
->username(), realm
);
1381 helperSubmit(digestauthenticators
, buf
, authenticateDigestHandleReply
, r
);
1384 DigestUser::DigestUser (AuthConfig
*aConfig
) : AuthUser (aConfig
), HA1created (0)
1388 AuthDigestUserRequest::authUser() const
1390 return const_cast<AuthUser
*>(user());
1394 AuthDigestUserRequest::authUser(AuthUser
*aUser
)
1396 assert(!authUser());
1401 AuthDigestUserRequest::CredentialsState
1402 AuthDigestUserRequest::credentials() const
1404 return credentials_ok
;
1408 AuthDigestUserRequest::credentials(CredentialsState newCreds
)
1410 credentials_ok
= newCreds
;
1413 AuthDigestUserRequest::AuthDigestUserRequest() : nonceb64(NULL
) ,cnonce(NULL
) ,realm(NULL
),
1414 pszPass(NULL
) ,algorithm(NULL
) ,pszMethod(NULL
),
1415 qop(NULL
) ,uri(NULL
) ,response(NULL
),
1416 nonce(NULL
), _theUser (NULL
) ,
1417 credentials_ok (Unchecked
)
1420 /** delete the digest request structure. Does NOT delete related structures */
1421 AuthDigestUserRequest::~AuthDigestUserRequest()
1423 safe_free (nonceb64
);
1426 safe_free (pszPass
);
1427 safe_free (algorithm
);
1428 safe_free (pszMethod
);
1431 safe_free (response
);
1434 authDigestNonceUnlink(nonce
);
1438 digestScheme::createConfig()
1440 return &digestConfig
;