1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
25 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
29 #include "curl_base64.h"
31 #include "http_digest.h"
33 #include "curl_memory.h"
34 #include "sslgen.h" /* for Curl_rand() */
35 #include "non-ascii.h" /* included for Curl_convert_... prototypes */
38 #define _MPRINTF_REPLACE /* use our functions only */
39 #include <curl/mprintf.h>
41 /* The last #include file should be: */
44 #define MAX_VALUE_LENGTH 256
45 #define MAX_CONTENT_LENGTH 1024
47 static void digest_cleanup_one(struct digestdata *dig);
50 * Return 0 on success and then the buffers are filled in fine.
52 * Non-zero means failure to parse.
54 static int get_pair(const char *str, char *value, char *content,
58 bool starts_with_quote = FALSE;
61 for(c=MAX_VALUE_LENGTH-1; (*str && (*str != '=') && c--); )
70 /* this starts with a quote so it must end with one as well! */
72 starts_with_quote = TRUE;
75 for(c=MAX_CONTENT_LENGTH-1; *str && c--; str++) {
79 /* possibly the start of an escaped quote */
81 *content++ = '\\'; /* even though this is an escape character, we still
82 store it as-is in the target buffer */
87 if(!starts_with_quote) {
88 /* this signals the end of the content if we didn't get a starting
89 quote and then we do "sloppy" parsing */
100 if(!escape && starts_with_quote) {
114 return 0; /* all is fine! */
117 /* Test example headers:
119 WWW-Authenticate: Digest realm="testrealm", nonce="1053604598"
120 Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598"
124 CURLdigest Curl_input_digest(struct connectdata *conn,
126 const char *header) /* rest of the *-authenticate:
131 bool foundAuth = FALSE;
132 bool foundAuthInt = FALSE;
133 struct SessionHandle *data=conn->data;
134 bool before = FALSE; /* got a nonce before */
135 struct digestdata *d;
138 d = &data->state.proxydigest;
141 d = &data->state.digest;
144 /* skip initial whitespaces */
145 while(*header && ISSPACE(*header))
148 if(checkprefix("Digest", header)) {
149 header += strlen("Digest");
151 /* If we already have received a nonce, keep that in mind */
155 /* clear off any former leftovers and init to defaults */
156 digest_cleanup_one(d);
159 char value[MAX_VALUE_LENGTH];
160 char content[MAX_CONTENT_LENGTH];
162 while(*header && ISSPACE(*header))
165 /* extract a value=content pair */
166 if(!get_pair(header, value, content, &header)) {
167 if(Curl_raw_equal(value, "nonce")) {
168 d->nonce = strdup(content);
170 return CURLDIGEST_NOMEM;
172 else if(Curl_raw_equal(value, "stale")) {
173 if(Curl_raw_equal(content, "true")) {
175 d->nc = 1; /* we make a new nonce now */
178 else if(Curl_raw_equal(value, "realm")) {
179 d->realm = strdup(content);
181 return CURLDIGEST_NOMEM;
183 else if(Curl_raw_equal(value, "opaque")) {
184 d->opaque = strdup(content);
186 return CURLDIGEST_NOMEM;
188 else if(Curl_raw_equal(value, "qop")) {
190 /* tokenize the list and choose auth if possible, use a temporary
191 clone of the buffer since strtok_r() ruins it */
192 tmp = strdup(content);
194 return CURLDIGEST_NOMEM;
195 token = strtok_r(tmp, ",", &tok_buf);
196 while(token != NULL) {
197 if(Curl_raw_equal(token, "auth")) {
200 else if(Curl_raw_equal(token, "auth-int")) {
203 token = strtok_r(NULL, ",", &tok_buf);
206 /*select only auth o auth-int. Otherwise, ignore*/
208 d->qop = strdup("auth");
210 return CURLDIGEST_NOMEM;
212 else if(foundAuthInt) {
213 d->qop = strdup("auth-int");
215 return CURLDIGEST_NOMEM;
218 else if(Curl_raw_equal(value, "algorithm")) {
219 d->algorithm = strdup(content);
221 return CURLDIGEST_NOMEM;
222 if(Curl_raw_equal(content, "MD5-sess"))
223 d->algo = CURLDIGESTALGO_MD5SESS;
224 else if(Curl_raw_equal(content, "MD5"))
225 d->algo = CURLDIGESTALGO_MD5;
227 return CURLDIGEST_BADALGO;
230 /* unknown specifier, ignore it! */
234 break; /* we're done here */
236 /* pass all additional spaces here */
237 while(*header && ISSPACE(*header))
240 /* allow the list to be comma-separated */
243 /* We had a nonce since before, and we got another one now without
244 'stale=true'. This means we provided bad credentials in the previous
246 if(before && !d->stale)
247 return CURLDIGEST_BAD;
249 /* We got this header without a nonce, that's a bad Digest line! */
251 return CURLDIGEST_BAD;
254 /* else not a digest, get out */
255 return CURLDIGEST_NONE;
257 return CURLDIGEST_FINE;
260 /* convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/
261 static void md5_to_ascii(unsigned char *source, /* 16 bytes */
262 unsigned char *dest) /* 33 bytes */
266 snprintf((char *)&dest[i*2], 3, "%02x", source[i]);
269 /* Perform quoted-string escaping as described in RFC2616 and its errata */
270 static char *string_quoted(const char *source)
273 const char *s = source;
274 size_t n = 1; /* null terminator */
276 /* Calculate size needed */
279 if(*s == '"' || *s == '\\') {
290 if(*s == '"' || *s == '\\') {
301 CURLcode Curl_output_digest(struct connectdata *conn,
303 const unsigned char *request,
304 const unsigned char *uripath)
306 /* We have a Digest setup for this, use it! Now, to get all the details for
307 this sorted out, I must urge you dear friend to read up on the RFC2617
309 unsigned char md5buf[16]; /* 16 bytes/128 bits */
310 unsigned char request_digest[33];
311 unsigned char *md5this;
312 unsigned char ha1[33];/* 32 digits and 1 zero byte */
313 unsigned char ha2[33];/* 32 digits and 1 zero byte */
316 size_t cnonce_sz = 0;
325 struct SessionHandle *data = conn->data;
326 struct digestdata *d;
328 /* The CURL_OUTPUT_DIGEST_CONV macro below is for non-ASCII machines.
329 It converts digest text to ASCII so the MD5 will be correct for
330 what ultimately goes over the network.
332 #define CURL_OUTPUT_DIGEST_CONV(a, b) \
333 rc = Curl_convert_to_network(a, (char *)b, strlen((const char*)b)); \
334 if(rc != CURLE_OK) { \
340 d = &data->state.proxydigest;
341 allocuserpwd = &conn->allocptr.proxyuserpwd;
342 userp = conn->proxyuser;
343 passwdp = conn->proxypasswd;
344 authp = &data->state.authproxy;
347 d = &data->state.digest;
348 allocuserpwd = &conn->allocptr.userpwd;
350 passwdp = conn->passwd;
351 authp = &data->state.authhost;
354 Curl_safefree(*allocuserpwd);
356 /* not set means empty */
373 struct timeval now = Curl_tvnow();
374 snprintf(cnoncebuf, sizeof(cnoncebuf), "%08x%08x%08x%08x",
375 Curl_rand(data), Curl_rand(data),
376 (unsigned int)now.tv_sec,
377 (unsigned int)now.tv_usec);
379 rc = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf),
380 &cnonce, &cnonce_sz);
387 if the algorithm is "MD5" or unspecified (which then defaults to MD5):
389 A1 = unq(username-value) ":" unq(realm-value) ":" passwd
391 if the algorithm is "MD5-sess" then:
393 A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
394 ":" unq(nonce-value) ":" unq(cnonce-value)
397 md5this = (unsigned char *)
398 aprintf("%s:%s:%s", userp, d->realm, passwdp);
400 return CURLE_OUT_OF_MEMORY;
402 CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
403 Curl_md5it(md5buf, md5this);
404 Curl_safefree(md5this);
405 md5_to_ascii(md5buf, ha1);
407 if(d->algo == CURLDIGESTALGO_MD5SESS) {
408 /* nonce and cnonce are OUTSIDE the hash */
409 tmp = aprintf("%s:%s:%s", ha1, d->nonce, d->cnonce);
411 return CURLE_OUT_OF_MEMORY;
412 CURL_OUTPUT_DIGEST_CONV(data, tmp); /* convert on non-ASCII machines */
413 Curl_md5it(md5buf, (unsigned char *)tmp);
415 md5_to_ascii(md5buf, ha1);
419 If the "qop" directive's value is "auth" or is unspecified, then A2 is:
421 A2 = Method ":" digest-uri-value
423 If the "qop" value is "auth-int", then A2 is:
425 A2 = Method ":" digest-uri-value ":" H(entity-body)
427 (The "Method" value is the HTTP request method as specified in section
431 /* So IE browsers < v7 cut off the URI part at the query part when they
432 evaluate the MD5 and some (IIS?) servers work with them so we may need to
433 do the Digest IE-style. Note that the different ways cause different MD5
436 Apache servers can be set to do the Digest IE-style automatically using
437 the BrowserMatch feature:
438 http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie
440 Further details on Digest implementation differences:
441 http://www.fngtps.com/2006/09/http-authentication
443 if(authp->iestyle && ((tmp = strchr((char *)uripath, '?')) != NULL)) {
444 md5this = (unsigned char *)aprintf("%s:%.*s", request,
445 curlx_sztosi(tmp - (char *)uripath),
449 md5this = (unsigned char *)aprintf("%s:%s", request, uripath);
451 if(d->qop && Curl_raw_equal(d->qop, "auth-int")) {
452 /* We don't support auth-int for PUT or POST at the moment.
453 TODO: replace md5 of empty string with entity-body for PUT/POST */
454 unsigned char *md5this2 = (unsigned char *)
455 aprintf("%s:%s", md5this, "d41d8cd98f00b204e9800998ecf8427e");
456 Curl_safefree(md5this);
461 return CURLE_OUT_OF_MEMORY;
463 CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
464 Curl_md5it(md5buf, md5this);
465 Curl_safefree(md5this);
466 md5_to_ascii(md5buf, ha2);
469 md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s",
478 md5this = (unsigned char *)aprintf("%s:%s:%s",
484 return CURLE_OUT_OF_MEMORY;
486 CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
487 Curl_md5it(md5buf, md5this);
488 Curl_safefree(md5this);
489 md5_to_ascii(md5buf, request_digest);
491 /* for test case 64 (snooped from a Mozilla 1.3a request)
493 Authorization: Digest username="testuser", realm="testrealm", \
494 nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca"
496 Digest parameters are all quoted strings. Username which is provided by
497 the user will need double quotes and backslashes within it escaped. For
498 the other fields, this shouldn't be an issue. realm, nonce, and opaque
499 are copied as is from the server, escapes and all. cnonce is generated
500 with web-safe characters. uri is already percent encoded. nc is 8 hex
501 characters. algorithm and qop with standard values only contain web-safe
504 userp_quoted = string_quoted(userp);
506 return CURLE_OUT_OF_MEMORY;
510 aprintf( "%sAuthorization: Digest "
523 uripath, /* this is the PATH part of the URL */
529 if(Curl_raw_equal(d->qop, "auth"))
530 d->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded
531 which tells to the server how many times you are using the
532 same nonce in the qop=auth mode. */
536 aprintf( "%sAuthorization: Digest "
546 uripath, /* this is the PATH part of the URL */
549 Curl_safefree(userp_quoted);
551 return CURLE_OUT_OF_MEMORY;
553 /* Add optional fields */
556 tmp = aprintf("%s, opaque=\"%s\"", *allocuserpwd, d->opaque);
558 return CURLE_OUT_OF_MEMORY;
564 /* append algorithm */
565 tmp = aprintf("%s, algorithm=\"%s\"", *allocuserpwd, d->algorithm);
567 return CURLE_OUT_OF_MEMORY;
572 /* append CRLF + zero (3 bytes) to the userpwd header */
573 userlen = strlen(*allocuserpwd);
574 tmp = realloc(*allocuserpwd, userlen + 3);
576 return CURLE_OUT_OF_MEMORY;
577 strcpy(&tmp[userlen], "\r\n"); /* append the data */
583 static void digest_cleanup_one(struct digestdata *d)
585 Curl_safefree(d->nonce);
586 Curl_safefree(d->cnonce);
587 Curl_safefree(d->realm);
588 Curl_safefree(d->opaque);
589 Curl_safefree(d->qop);
590 Curl_safefree(d->algorithm);
593 d->algo = CURLDIGESTALGO_MD5; /* default algorithm */
594 d->stale = FALSE; /* default means normal, not stale */
598 void Curl_digest_cleanup(struct SessionHandle *data)
600 digest_cleanup_one(&data->state.digest);
601 digest_cleanup_one(&data->state.proxydigest);