2 * $Id: auth_digest.cc,v 1.60 2007/12/14 23:11:51 amosjeffries Exp $
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 "authenticate.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 auth_user_hash_pointer
*usernamehash
;
463 auth_user_t
*auth_user
;
464 debugs(29, 9, "authDigestUserFindUsername: 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)
487 * Future work: the auth framework could flush it's cache
489 auth_user_hash_pointer
*usernamehash
;
490 auth_user_t
*auth_user
;
491 hash_first(proxy_auth_username_cache
);
493 while ((usernamehash
= ((auth_user_hash_pointer
*) hash_next(proxy_auth_username_cache
)))) {
494 auth_user
= usernamehash
->user();
496 if (strcmp(auth_user
->config
->type(), "digest") == 0)
501 /* delete the digest request structure. Does NOT delete related structures */
505 /* TODO: this should be a Config call. */
507 if (digestauthenticators
)
508 helperShutdown(digestauthenticators
);
510 authdigest_initialised
= 0;
512 if (!shutting_down
) {
513 authenticateDigestNonceReconfigure();
517 if (digestauthenticators
) {
518 helperFree(digestauthenticators
);
519 digestauthenticators
= NULL
;
522 authDigestUserShutdown();
523 authenticateDigestNonceShutdown();
524 debugs(29, 2, "authenticateDigestDone: Digest authentication shut down.");
528 AuthDigestConfig::dump(StoreEntry
* entry
, const char *name
, AuthConfig
* scheme
)
530 wordlist
*list
= authenticate
;
531 debugs(29, 9, "authDigestCfgDump: Dumping configuration");
532 storeAppendPrintf(entry
, "%s %s", name
, "digest");
534 while (list
!= NULL
) {
535 storeAppendPrintf(entry
, " %s", list
->key
);
539 storeAppendPrintf(entry
, "\n%s %s realm %s\n%s %s children %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",
540 name
, "digest", digestAuthRealm
,
541 name
, "digest", authenticateChildren
,
542 name
, "digest", noncemaxuses
,
543 name
, "digest", (int) noncemaxduration
,
544 name
, "digest", (int) nonceGCInterval
);
548 AuthDigestConfig::active() const
550 return authdigest_initialised
== 1;
554 AuthDigestConfig::configured() const
556 if ((authenticate
!= NULL
) &&
557 (authenticateChildren
!= 0) &&
558 (digestAuthRealm
!= NULL
) && (noncemaxduration
> -1))
565 AuthDigestUserRequest::authenticated() const
567 if (credentials() == Ok
)
573 /* log a digest user in
576 AuthDigestUserRequest::authenticate(HttpRequest
* request
, ConnStateData::Pointer conn
, http_hdr_type type
)
578 auth_user_t
*auth_user
;
579 AuthDigestUserRequest
*digest_request
;
580 digest_user_h
*digest_user
;
586 assert(authUser() != NULL
);
587 auth_user
= authUser();
589 digest_user
= dynamic_cast < digest_user_h
* >(auth_user
);
591 assert(digest_user
!= NULL
);
593 /* if the check has corrupted the user, just return */
595 if (credentials() == Failed
) {
599 digest_request
= this;
601 /* do we have the HA1 */
603 if (!digest_user
->HA1created
) {
604 credentials(Pending
);
608 if (digest_request
->nonce
== NULL
) {
609 /* this isn't a nonce we issued */
614 DigestCalcHA1(digest_request
->algorithm
, NULL
, NULL
, NULL
,
615 authenticateDigestNonceNonceb64(digest_request
->nonce
),
616 digest_request
->cnonce
,
617 digest_user
->HA1
, SESSIONKEY
);
618 DigestCalcResponse(SESSIONKEY
, authenticateDigestNonceNonceb64(digest_request
->nonce
),
619 digest_request
->nc
, digest_request
->cnonce
, digest_request
->qop
,
620 RequestMethodStr
[request
->method
], digest_request
->uri
, HA2
, Response
);
622 debugs(29, 9, "\nResponse = '" << digest_request
->response
<< "'\nsquid is = '" << Response
<< "'");
624 if (strcasecmp(digest_request
->response
, Response
) != 0) {
625 if (!digest_request
->flags
.helper_queried
) {
626 /* Query the helper in case the password has changed */
627 digest_request
->flags
.helper_queried
= 1;
628 digest_request
->credentials_ok
= Pending
;
632 if (digestConfig
.PostWorkaround
&& request
->method
!= METHOD_GET
) {
633 /* Ugly workaround for certain very broken browsers using the
634 * wrong method to calculate the request-digest on POST request.
635 * This should be deleted once Digest authentication becomes more
636 * widespread and such broken browsers no longer are commonly
639 DigestCalcResponse(SESSIONKEY
, authenticateDigestNonceNonceb64(digest_request
->nonce
),
640 digest_request
->nc
, digest_request
->cnonce
, digest_request
->qop
,
641 RequestMethodStr
[METHOD_GET
], digest_request
->uri
, HA2
, Response
);
643 if (strcasecmp(digest_request
->response
, Response
)) {
645 digest_request
->setDenyMessage("Incorrect password");
648 const char *useragent
= request
->header
.getStr(HDR_USER_AGENT
);
650 static IPAddress last_broken_addr
;
651 static int seen_broken_client
= 0;
653 if (!seen_broken_client
) {
654 last_broken_addr
.SetNoAddr();
655 seen_broken_client
= 1;
658 if (last_broken_addr
!= request
->client_addr
) {
659 debugs(29, 1, "\nDigest POST bug detected from " <<
660 request
->client_addr
<< " using '" <<
661 (useragent
? useragent
: "-") <<
662 "'. Please upgrade browser. See Bug #630 for details.");
664 last_broken_addr
= request
->client_addr
;
669 digest_request
->setDenyMessage("Incorrect password");
673 /* check for stale nonce */
674 if (!authDigestNonceIsValid(digest_request
->nonce
, digest_request
->nc
)) {
675 debugs(29, 3, "authenticateDigestAuthenticateuser: user '" << digest_user
->username() << "' validated OK but nonce stale");
676 digest_request
->flags
.nonce_stale
= 1;
678 digest_request
->setDenyMessage("Stale nonce");
685 /* password was checked and did match */
686 debugs(29, 4, "authenticateDigestAuthenticateuser: user '" << digest_user
->username() << "' validated OK");
688 /* auth_user is now linked, we reset these values
689 * after external auth occurs anyway */
690 auth_user
->expiretime
= current_time
.tv_sec
;
695 AuthDigestUserRequest::module_direction()
697 switch (credentials()) {
711 if (flags
.nonce_stale
)
712 /* nonce is stale, send new challenge */
721 /* add the [proxy]authorisation header */
723 AuthDigestUserRequest::addHeader(HttpReply
* rep
, int accel
)
727 /* don't add to authentication error pages */
729 if ((!accel
&& rep
->sline
.status
== HTTP_PROXY_AUTHENTICATION_REQUIRED
)
730 || (accel
&& rep
->sline
.status
== HTTP_UNAUTHORIZED
))
733 type
= accel
? HDR_AUTHENTICATION_INFO
: HDR_PROXY_AUTHENTICATION_INFO
;
736 /* test for http/1.1 transfer chunked encoding */
742 if ((digestConfig
.authenticate
) && authDigestNonceLastRequest(nonce
)) {
743 flags
.authinfo_sent
= 1;
744 debugs(29, 9, "authDigestAddHead: Sending type:" << type
<< " header: 'nextnonce=\"" << authenticateDigestNonceNonceb64(nonce
) << "\"");
745 httpHeaderPutStrf(&rep
->header
, type
, "nextnonce=\"%s\"", authenticateDigestNonceNonceb64(nonce
));
750 /* add the [proxy]authorisation header */
752 AuthDigestUserRequest::addTrailer(HttpReply
* rep
, int accel
)
756 if (!auth_user_request
)
760 /* has the header already been send? */
761 if (flags
.authinfo_sent
)
764 /* don't add to authentication error pages */
765 if ((!accel
&& rep
->sline
.status
== HTTP_PROXY_AUTHENTICATION_REQUIRED
)
766 || (accel
&& rep
->sline
.status
== HTTP_UNAUTHORIZED
))
769 type
= accel
? HDR_AUTHENTICATION_INFO
: HDR_PROXY_AUTHENTICATION_INFO
;
771 if ((digestConfig
.authenticate
) && authDigestNonceLastRequest(nonce
)) {
772 debugs(29, 9, "authDigestAddTrailer: Sending type:" << type
<< " header: 'nextnonce=\"" << authenticateDigestNonceNonceb64(nonce
) << "\"");
773 httpTrailerPutStrf(&rep
->header
, type
, "nextnonce=\"%s\"", authenticateDigestNonceNonceb64(nonce
));
779 /* add the [www-|Proxy-]authenticate header on a 407 or 401 reply */
781 AuthDigestConfig::fixHeader(AuthUserRequest
*auth_user_request
, HttpReply
*rep
, http_hdr_type type
, HttpRequest
* request
)
788 if (auth_user_request
) {
789 AuthDigestUserRequest
*digest_request
;
790 digest_request
= dynamic_cast < AuthDigestUserRequest
* >(auth_user_request
);
791 assert (digest_request
!= NULL
);
793 stale
= digest_request
->flags
.nonce_stale
;
796 /* on a 407 or 401 we always use a new nonce */
797 digest_nonce_h
*nonce
= authenticateDigestNonceNew();
799 debugs(29, 9, "authenticateFixHeader: Sending type:" << type
<<
800 " header: 'Digest realm=\"" << digestAuthRealm
<< "\", nonce=\"" <<
801 authenticateDigestNonceNonceb64(nonce
) << "\", qop=\"" << QOP_AUTH
<<
802 "\", stale=" << (stale
? "true" : "false"));
804 /* in the future, for WWW auth we may want to support the domain entry */
805 httpHeaderPutStrf(&rep
->header
, type
, "Digest realm=\"%s\", nonce=\"%s\", qop=\"%s\", stale=%s", digestAuthRealm
, authenticateDigestNonceNonceb64(nonce
), QOP_AUTH
, stale
? "true" : "false");
808 DigestUser::~DigestUser()
811 dlink_node
*link
, *tmplink
;
817 dlinkDelete(tmplink
, &nonces
);
818 authDigestNoncePurge(static_cast < digest_nonce_h
* >(tmplink
->data
));
819 authDigestNonceUnlink(static_cast < digest_nonce_h
* >(tmplink
->data
));
820 dlinkNodeDelete(tmplink
);
825 authenticateDigestHandleReply(void *data
, char *reply
)
827 DigestAuthenticateStateData
*replyData
= static_cast < DigestAuthenticateStateData
* >(data
);
828 AuthUserRequest
*auth_user_request
;
829 AuthDigestUserRequest
*digest_request
;
830 digest_user_h
*digest_user
;
833 debugs(29, 9, "authenticateDigestHandleReply: {" << (reply
? reply
: "<NULL>") << "}");
836 if ((t
= strchr(reply
, ' ')))
839 if (*reply
== '\0' || *reply
== '\n')
843 assert(replyData
->auth_user_request
!= NULL
);
844 auth_user_request
= replyData
->auth_user_request
;
845 digest_request
= dynamic_cast < AuthDigestUserRequest
* >(auth_user_request
);
846 assert(digest_request
);
848 digest_user
= dynamic_cast < digest_user_h
* >(auth_user_request
->user());
849 assert(digest_user
!= NULL
);
851 if (reply
&& (strncasecmp(reply
, "ERR", 3) == 0)) {
852 digest_request
->credentials(AuthDigestUserRequest::Failed
);
855 digest_request
->setDenyMessage(t
);
857 CvtBin(reply
, digest_user
->HA1
);
858 digest_user
->HA1created
= 1;
861 if (cbdataReferenceValidDone(replyData
->data
, &cbdata
))
862 replyData
->handler(cbdata
, NULL
);
864 //we know replyData->auth_user_request != NULL, or we'd have asserted
865 AUTHUSERREQUESTUNLOCK(replyData
->auth_user_request
, "replyData");
867 cbdataFree(replyData
);
870 /* Initialize helpers and the like for this auth scheme. Called AFTER parsing the
873 AuthDigestConfig::init(AuthConfig
* scheme
)
876 authenticateDigestNonceSetup();
877 authdigest_initialised
= 1;
879 if (digestauthenticators
== NULL
)
880 digestauthenticators
= helperCreate("digestauthenticator");
882 digestauthenticators
->cmdline
= authenticate
;
884 digestauthenticators
->n_to_start
= authenticateChildren
;
886 digestauthenticators
->ipc_type
= IPC_STREAM
;
888 helperOpenServers(digestauthenticators
);
890 CBDATA_INIT_TYPE(DigestAuthenticateStateData
);
895 AuthDigestConfig::registerWithCacheManager(CacheManager
& manager
)
897 manager
.registerAction("digestauthenticator",
898 "Digest User Authenticator Stats",
899 authenticateDigestStats
, 0, 1);
902 /* free any allocated configuration details */
904 AuthDigestConfig::done()
907 wordlistDestroy(&authenticate
);
909 safe_free(digestAuthRealm
);
913 AuthDigestConfig::AuthDigestConfig()
915 /* TODO: move into initialisation list */
916 authenticateChildren
= 5;
918 nonceGCInterval
= 5 * 60;
920 noncemaxduration
= 30 * 60;
923 /* Not strict nonce count behaviour */
925 /* Verify nonce count */
930 AuthDigestConfig::parse(AuthConfig
* scheme
, int n_configured
, char *param_str
)
932 if (strcasecmp(param_str
, "program") == 0) {
934 wordlistDestroy(&authenticate
);
936 parse_wordlist(&authenticate
);
938 requirePathnameExists("authparam digest program", authenticate
->key
);
939 } else if (strcasecmp(param_str
, "children") == 0) {
940 parse_int(&authenticateChildren
);
941 } else if (strcasecmp(param_str
, "realm") == 0) {
942 parse_eol(&digestAuthRealm
);
943 } else if (strcasecmp(param_str
, "nonce_garbage_interval") == 0) {
944 parse_time_t(&nonceGCInterval
);
945 } else if (strcasecmp(param_str
, "nonce_max_duration") == 0) {
946 parse_time_t(&noncemaxduration
);
947 } else if (strcasecmp(param_str
, "nonce_max_count") == 0) {
948 parse_int((int *) &noncemaxuses
);
949 } else if (strcasecmp(param_str
, "nonce_strictness") == 0) {
950 parse_onoff(&NonceStrictness
);
951 } else if (strcasecmp(param_str
, "check_nonce_count") == 0) {
952 parse_onoff(&CheckNonceCount
);
953 } else if (strcasecmp(param_str
, "post_workaround") == 0) {
954 parse_onoff(&PostWorkaround
);
956 debugs(29, 0, "unrecognised digest auth scheme parameter '" << param_str
<< "'");
961 AuthDigestConfig::type() const
963 return digestScheme::GetInstance().type();
968 authenticateDigestStats(StoreEntry
* sentry
)
970 helperStats(sentry
, digestauthenticators
, "Digest Authenticator Statistics");
973 /* NonceUserUnlink: remove the reference to auth_user and unlink the node from the list */
976 authDigestNonceUserUnlink(digest_nonce_h
* nonce
)
978 digest_user_h
*digest_user
;
979 dlink_node
*link
, *tmplink
;
987 digest_user
= nonce
->user
;
989 /* unlink from the user list. Yes we're crossing structures but this is the only
990 * time this code is needed
992 link
= digest_user
->nonces
.head
;
998 if (tmplink
->data
== nonce
) {
999 dlinkDelete(tmplink
, &digest_user
->nonces
);
1000 authDigestNonceUnlink(static_cast < digest_nonce_h
* >(tmplink
->data
));
1001 dlinkNodeDelete(tmplink
);
1006 /* this reference to user was not locked because freeeing the user frees
1012 /* authDigestUserLinkNonce: add a nonce to a given user's struct */
1015 authDigestUserLinkNonce(DigestUser
* user
, digest_nonce_h
* nonce
)
1018 digest_user_h
*digest_user
;
1020 if (!user
|| !nonce
)
1025 node
= digest_user
->nonces
.head
;
1027 while (node
&& (node
->data
!= nonce
))
1033 node
= dlinkNodeNew();
1035 dlinkAddTail(nonce
, node
, &digest_user
->nonces
);
1037 authDigestNonceLink(nonce
);
1039 /* ping this nonce to this auth user */
1040 assert((nonce
->user
== NULL
) || (nonce
->user
= user
));
1042 /* we don't lock this reference because removing the user removes the
1043 * hash too. Of course if that changes we're stuffed so read the code huh?
1048 /* setup the necessary info to log the username */
1049 static AuthUserRequest
*
1050 authDigestLogUsername(char *username
)
1052 AuthDigestUserRequest
*auth_user_request
= new AuthDigestUserRequest();
1053 assert(auth_user_request
!= NULL
);
1055 /* log the username */
1056 debugs(29, 9, "authDigestLogUsername: Creating new user for logging '" << username
<< "'");
1057 digest_user_h
*digest_user
= new DigestUser(&digestConfig
);
1058 /* save the credentials */
1059 digest_user
->username(username
);
1060 /* set the auth_user type */
1061 digest_user
->auth_type
= AUTH_BROKEN
;
1062 /* link the request to the user */
1063 auth_user_request
->authUser(digest_user
);
1064 auth_user_request
->user(digest_user
);
1065 digest_user
->addRequest (auth_user_request
);
1066 return auth_user_request
;
1070 * Decode a Digest [Proxy-]Auth string, placing the results in the passed
1071 * Auth_user structure.
1074 AuthDigestConfig::decode(char const *proxy_auth
)
1078 const char *pos
= NULL
;
1079 char *username
= NULL
;
1080 digest_nonce_h
*nonce
;
1083 debugs(29, 9, "authenticateDigestDecodeAuth: beginning");
1085 AuthDigestUserRequest
*digest_request
= new AuthDigestUserRequest();
1087 /* trim DIGEST from string */
1089 while (xisgraph(*proxy_auth
))
1092 /* Trim leading whitespace before decoding */
1093 while (xisspace(*proxy_auth
))
1096 String
temp(proxy_auth
);
1098 while (strListGetItem(&temp
, ',', &item
, &ilen
, &pos
)) {
1099 if ((p
= strchr(item
, '=')) && (p
- item
< ilen
))
1102 if (!strncmp(item
, "username", ilen
)) {
1105 while (xisspace(*p
))
1111 username
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1113 debugs(29, 9, "authDigestDecodeAuth: Found Username '" << username
<< "'");
1114 } else if (!strncmp(item
, "realm", ilen
)) {
1117 while (xisspace(*p
))
1123 digest_request
->realm
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1125 debugs(29, 9, "authDigestDecodeAuth: Found realm '" << digest_request
->realm
<< "'");
1126 } else if (!strncmp(item
, "qop", ilen
)) {
1129 while (xisspace(*p
))
1136 digest_request
->qop
= xstrndup(p
, strcspn(p
, "\" \t\r\n()<>@,;:\\/[]?={}") + 1);
1138 debugs(29, 9, "authDigestDecodeAuth: Found qop '" << digest_request
->qop
<< "'");
1139 } else if (!strncmp(item
, "algorithm", ilen
)) {
1142 while (xisspace(*p
))
1149 digest_request
->algorithm
= xstrndup(p
, strcspn(p
, "\" \t\r\n()<>@,;:\\/[]?={}") + 1);
1151 debugs(29, 9, "authDigestDecodeAuth: Found algorithm '" << digest_request
->algorithm
<< "'");
1152 } else if (!strncmp(item
, "uri", ilen
)) {
1155 while (xisspace(*p
))
1161 digest_request
->uri
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1163 debugs(29, 9, "authDigestDecodeAuth: Found uri '" << digest_request
->uri
<< "'");
1164 } else if (!strncmp(item
, "nonce", ilen
)) {
1167 while (xisspace(*p
))
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 digest_request
->cnonce
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1196 debugs(29, 9, "authDigestDecodeAuth: Found cnonce '" << digest_request
->cnonce
<< "'");
1197 } else if (!strncmp(item
, "response", ilen
)) {
1200 while (xisspace(*p
))
1206 digest_request
->response
= xstrndup(p
, strchr(p
, '"') + 1 - p
);
1208 debugs(29, 9, "authDigestDecodeAuth: Found response '" << digest_request
->response
<< "'");
1215 /* now we validate the data given to us */
1218 * TODO: on invalid parameters we should return 400, not 407.
1219 * Find some clean way of doing this. perhaps return a valid
1220 * struct, and set the direction to clientwards combined with
1221 * a change to the clientwards handling code (ie let the
1222 * clientwards call set the error type (but limited to known
1223 * correct values - 400/401/407
1226 /* first the NONCE count */
1228 if (digest_request
->cnonce
&& strlen(digest_request
->nc
) != 8) {
1229 debugs(29, 4, "authenticateDigestDecode: nonce count length invalid");
1230 delete digest_request
;
1231 return authDigestLogUsername(username
);
1235 nonce
= authenticateDigestNonceFindNonce(digest_request
->nonceb64
);
1238 /* we couldn't find a matching nonce! */
1239 debugs(29, 4, "authenticateDigestDecode: Unexpected or invalid nonce received");
1240 delete digest_request
;
1241 return authDigestLogUsername(username
);
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
)) {
1251 /* we received a qop option we didn't send */
1252 debugs(29, 4, "authenticateDigestDecode: Invalid qop option received");
1253 delete digest_request
;
1254 return authDigestLogUsername(username
);
1257 /* we can't check the URI just yet. We'll check it in the
1258 * authenticate phase */
1260 /* is the response the correct length? */
1262 if (!digest_request
->response
|| strlen(digest_request
->response
) != 32) {
1263 debugs(29, 4, "authenticateDigestDecode: Response length invalid");
1264 delete digest_request
;
1265 return authDigestLogUsername(username
);
1268 /* do we have a username ? */
1269 if (!username
|| username
[0] == '\0') {
1270 debugs(29, 4, "authenticateDigestDecode: Empty or not present username");
1271 delete digest_request
;
1272 return authDigestLogUsername(username
);
1275 /* check that we're not being hacked / the username hasn't changed */
1276 if (nonce
->user
&& strcmp(username
, nonce
->user
->username())) {
1277 debugs(29, 4, "authenticateDigestDecode: Username for the nonce does not equal the username for the request");
1278 delete digest_request
;
1279 return authDigestLogUsername(username
);
1282 /* if we got a qop, did we get a cnonce or did we get a cnonce wihtout a qop? */
1283 if ((digest_request
->qop
&& !digest_request
->cnonce
)
1284 || (!digest_request
->qop
&& digest_request
->cnonce
)) {
1285 debugs(29, 4, "authenticateDigestDecode: qop without cnonce, or vice versa!");
1286 delete digest_request
;
1287 return authDigestLogUsername(username
);
1290 /* check the algorithm is present and supported */
1291 if (!digest_request
->algorithm
)
1292 digest_request
->algorithm
= xstrndup("MD5", 4);
1293 else if (strcmp(digest_request
->algorithm
, "MD5")
1294 && strcmp(digest_request
->algorithm
, "MD5-sess")) {
1295 debugs(29, 4, "authenticateDigestDecode: invalid algorithm specified!");
1296 delete digest_request
;
1297 return authDigestLogUsername(username
);
1300 /* the method we'll check at the authenticate step as well */
1303 /* we don't send or parse opaques. Ok so we're flexable ... */
1306 digest_user_h
*digest_user
;
1308 auth_user_t
*auth_user
;
1310 if ((auth_user
= authDigestUserFindUsername(username
)) == NULL
) {
1311 /* the user doesn't exist in the username cache yet */
1312 debugs(29, 9, "authDigestDecodeAuth: Creating new digest user '" << username
<< "'");
1313 digest_user
= new DigestUser (&digestConfig
);
1314 /* auth_user is a parent */
1315 auth_user
= digest_user
;
1316 /* save the username */
1317 digest_user
->username(username
);
1318 /* set the user type */
1319 digest_user
->auth_type
= AUTH_DIGEST
;
1320 /* this auth_user struct is the one to get added to the
1322 /* store user in hash's */
1323 digest_user
->addToNameCache();
1326 * Add the digest to the user so we can tell if a hacking
1327 * or spoofing attack is taking place. We do this by assuming
1328 * the user agent won't change user name without warning.
1330 authDigestUserLinkNonce(digest_user
, nonce
);
1332 debugs(29, 9, "authDigestDecodeAuth: Found user '" << username
<< "' in the user cache as '" << auth_user
<< "'");
1333 digest_user
= static_cast < digest_user_h
* >(auth_user
);
1337 /*link the request and the user */
1338 assert(digest_request
!= NULL
);
1340 digest_request
->authUser (digest_user
);
1342 digest_request
->user(digest_user
);
1344 digest_user
->addRequest (digest_request
);
1346 debugs(29, 9, "username = '" << digest_user
->username() << "'\nrealm = '" <<
1347 digest_request
->realm
<< "'\nqop = '" << digest_request
->qop
<<
1348 "'\nalgorithm = '" << digest_request
->algorithm
<< "'\nuri = '" <<
1349 digest_request
->uri
<< "'\nnonce = '" << digest_request
->nonceb64
<<
1350 "'\nnc = '" << digest_request
->nc
<< "'\ncnonce = '" <<
1351 digest_request
->cnonce
<< "'\nresponse = '" <<
1352 digest_request
->response
<< "'\ndigestnonce = '" << nonce
<< "'");
1354 return digest_request
;
1357 /* send the initial data to a digest authenticator module */
1359 AuthDigestUserRequest::module_start(RH
* handler
, void *data
)
1361 DigestAuthenticateStateData
*r
= NULL
;
1363 digest_user_h
*digest_user
;
1364 assert(user()->auth_type
== AUTH_DIGEST
);
1365 digest_user
= dynamic_cast < digest_user_h
* >(user());
1366 assert(digest_user
!= NULL
);
1367 debugs(29, 9, "authenticateStart: '\"" << digest_user
->username() << "\":\"" << realm
<< "\"'");
1369 if (digestConfig
.authenticate
== NULL
) {
1370 handler(data
, NULL
);
1374 r
= cbdataAlloc(DigestAuthenticateStateData
);
1375 r
->handler
= handler
;
1376 r
->data
= cbdataReference(data
);
1377 r
->auth_user_request
= this;
1378 AUTHUSERREQUESTLOCK(r
->auth_user_request
, "r");
1379 snprintf(buf
, 8192, "\"%s\":\"%s\"\n", digest_user
->username(), realm
);
1381 helperSubmit(digestauthenticators
, buf
, authenticateDigestHandleReply
, r
);
1384 DigestUser::DigestUser (AuthConfig
*config
) : AuthUser (config
), HA1created (0)
1388 AuthDigestUserRequest::authUser() const
1390 return const_cast<AuthUser
*>(user());
1394 AuthDigestUserRequest::authUser(auth_user_t
*aUser
)
1396 assert (!authUser());
1404 AuthDigestUserRequest::CredentialsState
1405 AuthDigestUserRequest::credentials() const
1407 return credentials_ok
;
1412 AuthDigestUserRequest::credentials(CredentialsState newCreds
)
1414 credentials_ok
= newCreds
;
1417 AuthDigestUserRequest::AuthDigestUserRequest() : nonceb64(NULL
) ,cnonce(NULL
) ,realm(NULL
),
1418 pszPass(NULL
) ,algorithm(NULL
) ,pszMethod(NULL
),
1419 qop(NULL
) ,uri(NULL
) ,response(NULL
),
1420 nonce(NULL
), _theUser (NULL
) ,
1421 credentials_ok (Unchecked
)
1424 /* delete the digest request structure. Does NOT delete related structures */
1425 AuthDigestUserRequest::~AuthDigestUserRequest()
1427 safe_free (nonceb64
);
1430 safe_free (pszPass
);
1431 safe_free (algorithm
);
1432 safe_free (pszMethod
);
1435 safe_free (response
);
1438 authDigestNonceUnlink(nonce
);
1442 digestScheme::createConfig()
1444 return &digestConfig
;