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/auth_digest.h"
43 #include "auth/digest/Scheme.h"
44 #include "auth/digest/User.h"
45 #include "auth/digest/UserRequest.h"
46 #include "auth/Gadgets.h"
47 #include "auth/State.h"
50 #include "mgr/Registration.h"
52 #include "HttpRequest.h"
53 #include "HttpReply.h"
55 #include "SquidTime.h"
59 static AUTHSSTATS authenticateDigestStats
;
61 helper
*digestauthenticators
= NULL
;
63 static hash_table
*digest_nonce_cache
;
65 static int authdigest_initialised
= 0;
66 static MemAllocator
*digest_nonce_pool
= NULL
;
68 // CBDATA_TYPE(DigestAuthenticateStateData);
70 enum http_digest_attr_type
{
83 static const HttpHeaderFieldAttrs DigestAttrs
[DIGEST_ENUM_END
] = {
84 {"username", (http_hdr_type
)DIGEST_USERNAME
},
85 {"realm", (http_hdr_type
)DIGEST_REALM
},
86 {"qop", (http_hdr_type
)DIGEST_QOP
},
87 {"algorithm", (http_hdr_type
)DIGEST_ALGORITHM
},
88 {"uri", (http_hdr_type
)DIGEST_URI
},
89 {"nonce", (http_hdr_type
)DIGEST_NONCE
},
90 {"nc", (http_hdr_type
)DIGEST_NC
},
91 {"cnonce", (http_hdr_type
)DIGEST_CNONCE
},
92 {"response", (http_hdr_type
)DIGEST_RESPONSE
},
95 static HttpHeaderFieldInfo
*DigestFieldsInfo
= NULL
;
103 static void authenticateDigestNonceCacheCleanup(void *data
);
104 static digest_nonce_h
*authenticateDigestNonceFindNonce(const char *nonceb64
);
105 static digest_nonce_h
*authenticateDigestNonceNew(void);
106 static void authenticateDigestNonceDelete(digest_nonce_h
* nonce
);
107 static void authenticateDigestNonceSetup(void);
108 static int authDigestNonceIsStale(digest_nonce_h
* nonce
);
109 static void authDigestNonceEncode(digest_nonce_h
* nonce
);
110 static void authDigestNonceLink(digest_nonce_h
* nonce
);
112 static int authDigestNonceLinks(digest_nonce_h
* nonce
);
114 static void authDigestNonceUserUnlink(digest_nonce_h
* nonce
);
117 authDigestNonceEncode(digest_nonce_h
* nonce
)
125 nonce
->key
= xstrdup(base64_encode_bin((char *) &(nonce
->noncedata
), sizeof(digest_nonce_data
)));
128 static digest_nonce_h
*
129 authenticateDigestNonceNew(void)
131 digest_nonce_h
*newnonce
= static_cast < digest_nonce_h
* >(digest_nonce_pool
->alloc());
132 digest_nonce_h
*temp
;
134 /* NONCE CREATION - NOTES AND REASONING. RBC 20010108
135 * === EXCERPT FROM RFC 2617 ===
136 * The contents of the nonce are implementation dependent. The quality
137 * of the implementation depends on a good choice. A nonce might, for
138 * example, be constructed as the base 64 encoding of
140 * time-stamp H(time-stamp ":" ETag ":" private-key)
142 * where time-stamp is a server-generated time or other non-repeating
143 * value, ETag is the value of the HTTP ETag header associated with
144 * the requested entity, and private-key is data known only to the
145 * server. With a nonce of this form a server would recalculate the
146 * hash portion after receiving the client authentication header and
147 * reject the request if it did not match the nonce from that header
148 * or if the time-stamp value is not recent enough. In this way the
149 * server can limit the time of the nonce's validity. The inclusion of
150 * the ETag prevents a replay request for an updated version of the
151 * resource. (Note: including the IP address of the client in the
152 * nonce would appear to offer the server the ability to limit the
153 * reuse of the nonce to the same client that originally got it.
154 * However, that would break proxy farms, where requests from a single
155 * user often go through different proxies in the farm. Also, IP
156 * address spoofing is not that hard.)
159 * Now for my reasoning:
160 * We will not accept a unrecognised nonce->we have all recognisable
161 * nonces stored. If we send out unique base64 encodings we guarantee
162 * that a given nonce applies to only one user (barring attacks or
163 * really bad timing with expiry and creation). Using a random
164 * component in the nonce allows us to loop to find a unique nonce.
165 * We use H(nonce_data) so the nonce is meaningless to the reciever.
166 * So our nonce looks like base64(H(timestamp,pointertohash,randomdata))
167 * And even if our randomness is not very random (probably due to
168 * bad coding on my part) we don't really care - the timestamp and
169 * memory pointer also guarantee local uniqueness in the input to the hash
173 /* create a new nonce */
175 newnonce
->flags
.valid
= 1;
176 newnonce
->noncedata
.self
= newnonce
;
177 newnonce
->noncedata
.creationtime
= current_time
.tv_sec
;
178 newnonce
->noncedata
.randomdata
= squid_random();
180 authDigestNonceEncode(newnonce
);
182 * loop until we get a unique nonce. The nonce creation must
183 * have a random factor
186 while ((temp
= authenticateDigestNonceFindNonce((char const *) (newnonce
->key
)))) {
187 /* create a new nonce */
188 newnonce
->noncedata
.randomdata
= squid_random();
189 authDigestNonceEncode(newnonce
);
192 hash_join(digest_nonce_cache
, newnonce
);
193 /* the cache's link */
194 authDigestNonceLink(newnonce
);
195 newnonce
->flags
.incache
= 1;
196 debugs(29, 5, "authenticateDigestNonceNew: created nonce " << newnonce
<< " at " << newnonce
->noncedata
.creationtime
);
201 authenticateDigestNonceDelete(digest_nonce_h
* nonce
)
204 assert(nonce
->references
== 0);
207 if (nonce
->flags
.incache
)
208 hash_remove_link(digest_nonce_cache
, nonce
);
212 assert(nonce
->flags
.incache
== 0);
214 safe_free(nonce
->key
);
216 digest_nonce_pool
->freeOne(nonce
);
221 authenticateDigestNonceSetup(void)
223 if (!digest_nonce_pool
)
224 digest_nonce_pool
= memPoolCreate("Digest Scheme nonce's", sizeof(digest_nonce_h
));
226 if (!digest_nonce_cache
) {
227 digest_nonce_cache
= hash_create((HASHCMP
*) strcmp
, 7921, hash_string
);
228 assert(digest_nonce_cache
);
229 eventAdd("Digest none cache maintenance", authenticateDigestNonceCacheCleanup
, NULL
, static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest"))->nonceGCInterval
, 1);
234 authenticateDigestNonceShutdown(void)
237 * We empty the cache of any nonces left in there.
239 digest_nonce_h
*nonce
;
241 if (digest_nonce_cache
) {
242 debugs(29, 2, "authenticateDigestNonceShutdown: Shutting down nonce cache ");
243 hash_first(digest_nonce_cache
);
245 while ((nonce
= ((digest_nonce_h
*) hash_next(digest_nonce_cache
)))) {
246 assert(nonce
->flags
.incache
);
247 authDigestNoncePurge(nonce
);
252 if (digest_nonce_pool
) {
253 delete digest_nonce_pool
;
254 digest_nonce_pool
= NULL
;
258 debugs(29, 2, "authenticateDigestNonceShutdown: Nonce cache shutdown");
262 authenticateDigestNonceCacheCleanup(void *data
)
265 * We walk the hash by nonceb64 as that is the unique key we
266 * use. For big hash tables we could consider stepping through
267 * the cache, 100/200 entries at a time. Lets see how it flies
270 digest_nonce_h
*nonce
;
271 debugs(29, 3, "authenticateDigestNonceCacheCleanup: Cleaning the nonce cache now");
272 debugs(29, 3, "authenticateDigestNonceCacheCleanup: Current time: " << current_time
.tv_sec
);
273 hash_first(digest_nonce_cache
);
275 while ((nonce
= ((digest_nonce_h
*) hash_next(digest_nonce_cache
)))) {
276 debugs(29, 3, "authenticateDigestNonceCacheCleanup: nonce entry : " << nonce
<< " '" << (char *) nonce
->key
<< "'");
277 debugs(29, 4, "authenticateDigestNonceCacheCleanup: Creation time: " << nonce
->noncedata
.creationtime
);
279 if (authDigestNonceIsStale(nonce
)) {
280 debugs(29, 4, "authenticateDigestNonceCacheCleanup: Removing nonce " << (char *) nonce
->key
<< " from cache due to timeout.");
281 assert(nonce
->flags
.incache
);
282 /* invalidate nonce so future requests fail */
283 nonce
->flags
.valid
= 0;
284 /* if it is tied to a auth_user, remove the tie */
285 authDigestNonceUserUnlink(nonce
);
286 authDigestNoncePurge(nonce
);
290 debugs(29, 3, "authenticateDigestNonceCacheCleanup: Finished cleaning the nonce cache.");
292 if (static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest"))->active())
293 eventAdd("Digest none cache maintenance", authenticateDigestNonceCacheCleanup
, NULL
, static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest"))->nonceGCInterval
, 1);
297 authDigestNonceLink(digest_nonce_h
* nonce
)
299 assert(nonce
!= NULL
);
301 debugs(29, 9, "authDigestNonceLink: nonce '" << nonce
<< "' now at '" << nonce
->references
<< "'.");
306 authDigestNonceLinks(digest_nonce_h
* nonce
)
311 return nonce
->references
;
317 authDigestNonceUnlink(digest_nonce_h
* nonce
)
319 assert(nonce
!= NULL
);
321 if (nonce
->references
> 0) {
324 debugs(29, 1, "authDigestNonceUnlink; Attempt to lower nonce " << nonce
<< " refcount below 0!");
327 debugs(29, 9, "authDigestNonceUnlink: nonce '" << nonce
<< "' now at '" << nonce
->references
<< "'.");
329 if (nonce
->references
== 0)
330 authenticateDigestNonceDelete(nonce
);
334 authenticateDigestNonceNonceb64(const digest_nonce_h
* nonce
)
339 return (char const *) nonce
->key
;
342 static digest_nonce_h
*
343 authenticateDigestNonceFindNonce(const char *nonceb64
)
345 digest_nonce_h
*nonce
= NULL
;
347 if (nonceb64
== NULL
)
350 debugs(29, 9, "authDigestNonceFindNonce:looking for nonceb64 '" << nonceb64
<< "' in the nonce cache.");
352 nonce
= static_cast < digest_nonce_h
* >(hash_lookup(digest_nonce_cache
, nonceb64
));
354 if ((nonce
== NULL
) || (strcmp(authenticateDigestNonceNonceb64(nonce
), nonceb64
)))
357 debugs(29, 9, "authDigestNonceFindNonce: Found nonce '" << nonce
<< "'");
363 authDigestNonceIsValid(digest_nonce_h
* nonce
, char nc
[9])
366 /* do we have a nonce ? */
371 intnc
= strtol(nc
, NULL
, 16);
373 /* has it already been invalidated ? */
374 if (!nonce
->flags
.valid
) {
375 debugs(29, 4, "authDigestNonceIsValid: Nonce already invalidated");
379 /* is the nonce-count ok ? */
380 if (!static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest"))->CheckNonceCount
) {
382 return -1; /* forced OK by configuration */
385 if ((static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest"))->NonceStrictness
&& intnc
!= nonce
->nc
+ 1) ||
386 intnc
< nonce
->nc
+ 1) {
387 debugs(29, 4, "authDigestNonceIsValid: Nonce count doesn't match");
388 nonce
->flags
.valid
= 0;
393 /* increment the nonce count - we've already checked that intnc is a
394 * valid representation for us, so we don't need the test here.
402 authDigestNonceIsStale(digest_nonce_h
* nonce
)
404 /* do we have a nonce ? */
409 /* has it's max duration expired? */
410 if (nonce
->noncedata
.creationtime
+ static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest"))->noncemaxduration
< current_time
.tv_sec
) {
411 debugs(29, 4, "authDigestNonceIsStale: Nonce is too old. " <<
412 nonce
->noncedata
.creationtime
<< " " <<
413 static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest"))->noncemaxduration
<< " " <<
414 current_time
.tv_sec
);
416 nonce
->flags
.valid
= 0;
420 if (nonce
->nc
> 99999998) {
421 debugs(29, 4, "authDigestNonceIsStale: Nonce count overflow");
422 nonce
->flags
.valid
= 0;
426 if (nonce
->nc
> static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest"))->noncemaxuses
) {
427 debugs(29, 4, "authDigestNoncelastRequest: Nonce count over user limit");
428 nonce
->flags
.valid
= 0;
437 * \retval 0 the digest is not stale yet
438 * \retval -1 the digest will be stale on the next request
441 authDigestNonceLastRequest(digest_nonce_h
* nonce
)
446 if (nonce
->nc
== 99999997) {
447 debugs(29, 4, "authDigestNoncelastRequest: Nonce count about to overflow");
451 if (nonce
->nc
>= static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest"))->noncemaxuses
- 1) {
452 debugs(29, 4, "authDigestNoncelastRequest: Nonce count about to hit user limit");
456 /* and other tests are possible. */
461 authDigestNoncePurge(digest_nonce_h
* nonce
)
466 if (!nonce
->flags
.incache
)
469 hash_remove_link(digest_nonce_cache
, nonce
);
471 nonce
->flags
.incache
= 0;
473 /* the cache's link */
474 authDigestNonceUnlink(nonce
);
477 /* USER related functions */
478 static Auth::User::Pointer
479 authDigestUserFindUsername(const char *username
)
481 AuthUserHashPointer
*usernamehash
;
482 debugs(29, 9, HERE
<< "Looking for user '" << username
<< "'");
484 if (username
&& (usernamehash
= static_cast < auth_user_hash_pointer
* >(hash_lookup(proxy_auth_username_cache
, username
)))) {
485 while ((usernamehash
->user()->auth_type
!= Auth::AUTH_DIGEST
) && (usernamehash
->next
))
486 usernamehash
= static_cast<AuthUserHashPointer
*>(usernamehash
->next
);
488 if (usernamehash
->user()->auth_type
== Auth::AUTH_DIGEST
) {
489 return usernamehash
->user();
497 Auth::Digest::Config::rotateHelpers()
499 /* schedule closure of existing helpers */
500 if (digestauthenticators
) {
501 helperShutdown(digestauthenticators
);
504 /* NP: dynamic helper restart will ensure they start up again as needed. */
508 Auth::Digest::Config::dump(StoreEntry
* entry
, const char *name
, Auth::Config
* scheme
)
510 wordlist
*list
= authenticateProgram
;
511 debugs(29, 9, "authDigestCfgDump: Dumping configuration");
512 storeAppendPrintf(entry
, "%s %s", name
, "digest");
514 while (list
!= NULL
) {
515 storeAppendPrintf(entry
, " %s", list
->key
);
519 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",
520 name
, "digest", digestAuthRealm
,
521 name
, "digest", authenticateChildren
.n_max
, authenticateChildren
.n_startup
, authenticateChildren
.n_idle
, authenticateChildren
.concurrency
,
522 name
, "digest", noncemaxuses
,
523 name
, "digest", (int) noncemaxduration
,
524 name
, "digest", (int) nonceGCInterval
);
528 Auth::Digest::Config::active() const
530 return authdigest_initialised
== 1;
534 Auth::Digest::Config::configured() const
536 if ((authenticateProgram
!= NULL
) &&
537 (authenticateChildren
.n_max
!= 0) &&
538 (digestAuthRealm
!= NULL
) && (noncemaxduration
> -1))
544 /* add the [www-|Proxy-]authenticate header on a 407 or 401 reply */
546 Auth::Digest::Config::fixHeader(AuthUserRequest::Pointer auth_user_request
, HttpReply
*rep
, http_hdr_type hdrType
, HttpRequest
* request
)
548 if (!authenticateProgram
)
553 if (auth_user_request
!= NULL
) {
554 AuthDigestUserRequest
*digest_request
;
555 digest_request
= dynamic_cast<AuthDigestUserRequest
*>(auth_user_request
.getRaw());
556 assert (digest_request
!= NULL
);
558 stale
= !digest_request
->flags
.invalid_password
;
561 /* on a 407 or 401 we always use a new nonce */
562 digest_nonce_h
*nonce
= authenticateDigestNonceNew();
564 debugs(29, 9, "authenticateFixHeader: Sending type:" << hdrType
<<
565 " header: 'Digest realm=\"" << digestAuthRealm
<< "\", nonce=\"" <<
566 authenticateDigestNonceNonceb64(nonce
) << "\", qop=\"" << QOP_AUTH
<<
567 "\", stale=" << (stale
? "true" : "false"));
569 /* in the future, for WWW auth we may want to support the domain entry */
570 httpHeaderPutStrf(&rep
->header
, hdrType
, "Digest realm=\"%s\", nonce=\"%s\", qop=\"%s\", stale=%s", digestAuthRealm
, authenticateDigestNonceNonceb64(nonce
), QOP_AUTH
, stale
? "true" : "false");
573 /* Initialize helpers and the like for this auth scheme. Called AFTER parsing the
576 Auth::Digest::Config::init(Auth::Config
* scheme
)
578 if (authenticateProgram
) {
579 DigestFieldsInfo
= httpHeaderBuildFieldsInfo(DigestAttrs
, DIGEST_ENUM_END
);
580 authenticateDigestNonceSetup();
581 authdigest_initialised
= 1;
583 if (digestauthenticators
== NULL
)
584 digestauthenticators
= new helper("digestauthenticator");
586 digestauthenticators
->cmdline
= authenticateProgram
;
588 digestauthenticators
->childs
= authenticateChildren
;
590 digestauthenticators
->ipc_type
= IPC_STREAM
;
592 helperOpenServers(digestauthenticators
);
594 CBDATA_INIT_TYPE(authenticateStateData
);
599 Auth::Digest::Config::registerWithCacheManager(void)
601 Mgr::RegisterAction("digestauthenticator",
602 "Digest User Authenticator Stats",
603 authenticateDigestStats
, 0, 1);
606 /* free any allocated configuration details */
608 Auth::Digest::Config::done()
610 authdigest_initialised
= 0;
612 if (digestauthenticators
)
613 helperShutdown(digestauthenticators
);
615 if (DigestFieldsInfo
) {
616 httpHeaderDestroyFieldsInfo(DigestFieldsInfo
, DIGEST_ENUM_END
);
617 DigestFieldsInfo
= NULL
;
623 delete digestauthenticators
;
624 digestauthenticators
= NULL
;
626 if (authenticateProgram
)
627 wordlistDestroy(&authenticateProgram
);
629 safe_free(digestAuthRealm
);
632 Auth::Digest::Config::Config()
634 /* TODO: move into initialisation list */
636 nonceGCInterval
= 5 * 60;
638 noncemaxduration
= 30 * 60;
641 /* Not strict nonce count behaviour */
643 /* Verify nonce count */
648 Auth::Digest::Config::parse(Auth::Config
* scheme
, int n_configured
, char *param_str
)
650 if (strcasecmp(param_str
, "program") == 0) {
651 if (authenticateProgram
)
652 wordlistDestroy(&authenticateProgram
);
654 parse_wordlist(&authenticateProgram
);
656 requirePathnameExists("auth_param digest program", authenticateProgram
->key
);
657 } else if (strcasecmp(param_str
, "children") == 0) {
658 authenticateChildren
.parseConfig();
659 } else if (strcasecmp(param_str
, "realm") == 0) {
660 parse_eol(&digestAuthRealm
);
661 } else if (strcasecmp(param_str
, "nonce_garbage_interval") == 0) {
662 parse_time_t(&nonceGCInterval
);
663 } else if (strcasecmp(param_str
, "nonce_max_duration") == 0) {
664 parse_time_t(&noncemaxduration
);
665 } else if (strcasecmp(param_str
, "nonce_max_count") == 0) {
666 parse_int((int *) &noncemaxuses
);
667 } else if (strcasecmp(param_str
, "nonce_strictness") == 0) {
668 parse_onoff(&NonceStrictness
);
669 } else if (strcasecmp(param_str
, "check_nonce_count") == 0) {
670 parse_onoff(&CheckNonceCount
);
671 } else if (strcasecmp(param_str
, "post_workaround") == 0) {
672 parse_onoff(&PostWorkaround
);
673 } else if (strcasecmp(param_str
, "utf8") == 0) {
676 debugs(29, 0, "unrecognised digest auth scheme parameter '" << param_str
<< "'");
681 Auth::Digest::Config::type() const
683 return Auth::Digest::Scheme::GetInstance()->type();
688 authenticateDigestStats(StoreEntry
* sentry
)
690 helperStats(sentry
, digestauthenticators
, "Digest Authenticator Statistics");
693 /* NonceUserUnlink: remove the reference to auth_user and unlink the node from the list */
696 authDigestNonceUserUnlink(digest_nonce_h
* nonce
)
698 Auth::Digest::User
*digest_user
;
699 dlink_node
*link
, *tmplink
;
707 digest_user
= nonce
->user
;
709 /* unlink from the user list. Yes we're crossing structures but this is the only
710 * time this code is needed
712 link
= digest_user
->nonces
.head
;
718 if (tmplink
->data
== nonce
) {
719 dlinkDelete(tmplink
, &digest_user
->nonces
);
720 authDigestNonceUnlink(static_cast < digest_nonce_h
* >(tmplink
->data
));
721 dlinkNodeDelete(tmplink
);
726 /* this reference to user was not locked because freeeing the user frees
732 /* authDigestUserLinkNonce: add a nonce to a given user's struct */
734 authDigestUserLinkNonce(Auth::Digest::User
* user
, digest_nonce_h
* nonce
)
741 Auth::Digest::User
*digest_user
= user
;
743 node
= digest_user
->nonces
.head
;
745 while (node
&& (node
->data
!= nonce
))
751 node
= dlinkNodeNew();
753 dlinkAddTail(nonce
, node
, &digest_user
->nonces
);
755 authDigestNonceLink(nonce
);
757 /* ping this nonce to this auth user */
758 assert((nonce
->user
== NULL
) || (nonce
->user
== user
));
760 /* we don't lock this reference because removing the user removes the
761 * hash too. Of course if that changes we're stuffed so read the code huh?
766 /* setup the necessary info to log the username */
767 static AuthUserRequest::Pointer
768 authDigestLogUsername(char *username
, AuthUserRequest::Pointer auth_user_request
)
770 assert(auth_user_request
!= NULL
);
772 /* log the username */
773 debugs(29, 9, "authDigestLogUsername: Creating new user for logging '" << username
<< "'");
774 Auth::User::Pointer digest_user
= new Auth::Digest::User(static_cast<Auth::Digest::Config
*>(Auth::Config::Find("digest")));
775 /* save the credentials */
776 digest_user
->username(username
);
777 /* set the auth_user type */
778 digest_user
->auth_type
= Auth::AUTH_BROKEN
;
779 /* link the request to the user */
780 auth_user_request
->user(digest_user
);
781 return auth_user_request
;
785 * Decode a Digest [Proxy-]Auth string, placing the results in the passed
786 * Auth_user structure.
788 AuthUserRequest::Pointer
789 Auth::Digest::Config::decode(char const *proxy_auth
)
793 const char *pos
= NULL
;
794 char *username
= NULL
;
795 digest_nonce_h
*nonce
;
798 debugs(29, 9, "authenticateDigestDecodeAuth: beginning");
800 AuthDigestUserRequest
*digest_request
= new AuthDigestUserRequest();
802 /* trim DIGEST from string */
804 while (xisgraph(*proxy_auth
))
807 /* Trim leading whitespace before decoding */
808 while (xisspace(*proxy_auth
))
811 String
temp(proxy_auth
);
813 while (strListGetItem(&temp
, ',', &item
, &ilen
, &pos
)) {
814 /* isolate directive name & value */
817 if ((p
= (const char *)memchr(item
, '=', ilen
)) && (p
- item
< ilen
)) {
819 vlen
= ilen
- (p
- item
);
825 /* parse value. auth-param = token "=" ( token | quoted-string ) */
829 if (!httpHeaderParseQuotedString(p
, vlen
, &value
)) {
830 debugs(29, 9, "authDigestDecodeAuth: Failed to parse attribute '" << item
<< "' in '" << temp
<< "'");
834 value
.limitInit(p
, vlen
);
837 debugs(29, 9, "authDigestDecodeAuth: Failed to parse attribute '" << item
<< "' in '" << temp
<< "'");
842 http_digest_attr_type type
= (http_digest_attr_type
)httpHeaderIdByName(item
, nlen
, DigestFieldsInfo
, DIGEST_ENUM_END
);
845 case DIGEST_USERNAME
:
847 username
= xstrndup(value
.rawBuf(), value
.size() + 1);
848 debugs(29, 9, "authDigestDecodeAuth: Found Username '" << username
<< "'");
852 safe_free(digest_request
->realm
);
853 digest_request
->realm
= xstrndup(value
.rawBuf(), value
.size() + 1);
854 debugs(29, 9, "authDigestDecodeAuth: Found realm '" << digest_request
->realm
<< "'");
858 safe_free(digest_request
->qop
);
859 digest_request
->qop
= xstrndup(value
.rawBuf(), value
.size() + 1);
860 debugs(29, 9, "authDigestDecodeAuth: Found qop '" << digest_request
->qop
<< "'");
863 case DIGEST_ALGORITHM
:
864 safe_free(digest_request
->algorithm
);
865 digest_request
->algorithm
= xstrndup(value
.rawBuf(), value
.size() + 1);
866 debugs(29, 9, "authDigestDecodeAuth: Found algorithm '" << digest_request
->algorithm
<< "'");
870 safe_free(digest_request
->uri
);
871 digest_request
->uri
= xstrndup(value
.rawBuf(), value
.size() + 1);
872 debugs(29, 9, "authDigestDecodeAuth: Found uri '" << digest_request
->uri
<< "'");
876 safe_free(digest_request
->nonceb64
);
877 digest_request
->nonceb64
= xstrndup(value
.rawBuf(), value
.size() + 1);
878 debugs(29, 9, "authDigestDecodeAuth: Found nonce '" << digest_request
->nonceb64
<< "'");
882 if (value
.size() != 8) {
883 debugs(29, 9, "authDigestDecodeAuth: Invalid nc '" << value
<< "' in '" << temp
<< "'");
885 xstrncpy(digest_request
->nc
, value
.rawBuf(), value
.size() + 1);
886 debugs(29, 9, "authDigestDecodeAuth: Found noncecount '" << digest_request
->nc
<< "'");
890 safe_free(digest_request
->cnonce
);
891 digest_request
->cnonce
= xstrndup(value
.rawBuf(), value
.size() + 1);
892 debugs(29, 9, "authDigestDecodeAuth: Found cnonce '" << digest_request
->cnonce
<< "'");
895 case DIGEST_RESPONSE
:
896 safe_free(digest_request
->response
);
897 digest_request
->response
= xstrndup(value
.rawBuf(), value
.size() + 1);
898 debugs(29, 9, "authDigestDecodeAuth: Found response '" << digest_request
->response
<< "'");
902 debugs(29, 3, "authDigestDecodeAuth: Unknown attribute '" << item
<< "' in '" << temp
<< "'");
910 /* now we validate the data given to us */
913 * TODO: on invalid parameters we should return 400, not 407.
914 * Find some clean way of doing this. perhaps return a valid
915 * struct, and set the direction to clientwards combined with
916 * a change to the clientwards handling code (ie let the
917 * clientwards call set the error type (but limited to known
918 * correct values - 400/401/407
921 /* 2069 requirements */
923 /* do we have a username ? */
924 if (!username
|| username
[0] == '\0') {
925 debugs(29, 2, "authenticateDigestDecode: Empty or not present username");
926 return authDigestLogUsername(username
, digest_request
);
929 /* Sanity check of the username.
930 * " can not be allowed in usernames until * the digest helper protocol
933 if (strchr(username
, '"')) {
934 debugs(29, 2, "authenticateDigestDecode: Unacceptable username '" << username
<< "'");
935 return authDigestLogUsername(username
, digest_request
);
938 /* do we have a realm ? */
939 if (!digest_request
->realm
|| digest_request
->realm
[0] == '\0') {
940 debugs(29, 2, "authenticateDigestDecode: Empty or not present realm");
941 return authDigestLogUsername(username
, digest_request
);
945 if (!digest_request
->nonceb64
|| digest_request
->nonceb64
[0] == '\0') {
946 debugs(29, 2, "authenticateDigestDecode: Empty or not present nonce");
947 return authDigestLogUsername(username
, digest_request
);
950 /* we can't check the URI just yet. We'll check it in the
951 * authenticate phase, but needs to be given */
952 if (!digest_request
->uri
|| digest_request
->uri
[0] == '\0') {
953 debugs(29, 2, "authenticateDigestDecode: Missing URI field");
954 return authDigestLogUsername(username
, digest_request
);
957 /* is the response the correct length? */
958 if (!digest_request
->response
|| strlen(digest_request
->response
) != 32) {
959 debugs(29, 2, "authenticateDigestDecode: Response length invalid");
960 return authDigestLogUsername(username
, digest_request
);
963 /* check the algorithm is present and supported */
964 if (!digest_request
->algorithm
)
965 digest_request
->algorithm
= xstrndup("MD5", 4);
966 else if (strcmp(digest_request
->algorithm
, "MD5")
967 && strcmp(digest_request
->algorithm
, "MD5-sess")) {
968 debugs(29, 2, "authenticateDigestDecode: invalid algorithm specified!");
969 return authDigestLogUsername(username
, digest_request
);
972 /* 2617 requirements, indicated by qop */
973 if (digest_request
->qop
) {
975 /* check the qop is what we expected. */
976 if (strcmp(digest_request
->qop
, QOP_AUTH
) != 0) {
977 /* we received a qop option we didn't send */
978 debugs(29, 2, "authenticateDigestDecode: Invalid qop option received");
979 return authDigestLogUsername(username
, digest_request
);
983 if (!digest_request
->cnonce
|| digest_request
->cnonce
[0] == '\0') {
984 debugs(29, 2, "authenticateDigestDecode: Missing cnonce field");
985 return authDigestLogUsername(username
, digest_request
);
989 if (strlen(digest_request
->nc
) != 8 || strspn(digest_request
->nc
, "0123456789abcdefABCDEF") != 8) {
990 debugs(29, 2, "authenticateDigestDecode: invalid nonce count");
991 return authDigestLogUsername(username
, digest_request
);
994 /* cnonce and nc both require qop */
995 if (digest_request
->cnonce
|| digest_request
->nc
) {
996 debugs(29, 2, "authenticateDigestDecode: missing qop!");
997 return authDigestLogUsername(username
, digest_request
);
1001 /** below nonce state dependent **/
1004 nonce
= authenticateDigestNonceFindNonce(digest_request
->nonceb64
);
1006 /* we couldn't find a matching nonce! */
1007 debugs(29, 2, "authenticateDigestDecode: Unexpected or invalid nonce received");
1008 if (digest_request
->user() != NULL
)
1009 digest_request
->user()->credentials(Auth::Failed
);
1010 return authDigestLogUsername(username
, digest_request
);
1013 digest_request
->nonce
= nonce
;
1014 authDigestNonceLink(nonce
);
1016 /* check that we're not being hacked / the username hasn't changed */
1017 if (nonce
->user
&& strcmp(username
, nonce
->user
->username())) {
1018 debugs(29, 2, "authenticateDigestDecode: Username for the nonce does not equal the username for the request");
1019 return authDigestLogUsername(username
, digest_request
);
1022 /* the method we'll check at the authenticate step as well */
1025 /* we don't send or parse opaques. Ok so we're flexable ... */
1028 Auth::Digest::User
*digest_user
;
1030 Auth::User::Pointer auth_user
;
1032 if ((auth_user
= authDigestUserFindUsername(username
)) == NULL
) {
1033 /* the user doesn't exist in the username cache yet */
1034 debugs(29, 9, "authDigestDecodeAuth: Creating new digest user '" << username
<< "'");
1035 digest_user
= new Auth::Digest::User(this);
1036 /* auth_user is a parent */
1037 auth_user
= digest_user
;
1038 /* save the username */
1039 digest_user
->username(username
);
1040 /* set the user type */
1041 digest_user
->auth_type
= Auth::AUTH_DIGEST
;
1042 /* this auth_user struct is the one to get added to the
1044 /* store user in hash's */
1045 digest_user
->addToNameCache();
1048 * Add the digest to the user so we can tell if a hacking
1049 * or spoofing attack is taking place. We do this by assuming
1050 * the user agent won't change user name without warning.
1052 authDigestUserLinkNonce(digest_user
, nonce
);
1054 debugs(29, 9, "authDigestDecodeAuth: Found user '" << username
<< "' in the user cache as '" << auth_user
<< "'");
1055 digest_user
= static_cast<Auth::Digest::User
*>(auth_user
.getRaw());
1059 /*link the request and the user */
1060 assert(digest_request
!= NULL
);
1062 digest_request
->user(digest_user
);
1063 debugs(29, 9, "username = '" << digest_user
->username() << "'\nrealm = '" <<
1064 digest_request
->realm
<< "'\nqop = '" << digest_request
->qop
<<
1065 "'\nalgorithm = '" << digest_request
->algorithm
<< "'\nuri = '" <<
1066 digest_request
->uri
<< "'\nnonce = '" << digest_request
->nonceb64
<<
1067 "'\nnc = '" << digest_request
->nc
<< "'\ncnonce = '" <<
1068 digest_request
->cnonce
<< "'\nresponse = '" <<
1069 digest_request
->response
<< "'\ndigestnonce = '" << nonce
<< "'");
1071 return digest_request
;