1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2014, 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 "vtls/vtls.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 if(checkprefix("Digest", header)) {
145 header += strlen("Digest");
147 /* If we already have received a nonce, keep that in mind */
151 /* clear off any former leftovers and init to defaults */
152 digest_cleanup_one(d);
155 char value[MAX_VALUE_LENGTH];
156 char content[MAX_CONTENT_LENGTH];
158 while(*header && ISSPACE(*header))
161 /* extract a value=content pair */
162 if(!get_pair(header, value, content, &header)) {
163 if(Curl_raw_equal(value, "nonce")) {
164 d->nonce = strdup(content);
166 return CURLDIGEST_NOMEM;
168 else if(Curl_raw_equal(value, "stale")) {
169 if(Curl_raw_equal(content, "true")) {
171 d->nc = 1; /* we make a new nonce now */
174 else if(Curl_raw_equal(value, "realm")) {
175 d->realm = strdup(content);
177 return CURLDIGEST_NOMEM;
179 else if(Curl_raw_equal(value, "opaque")) {
180 d->opaque = strdup(content);
182 return CURLDIGEST_NOMEM;
184 else if(Curl_raw_equal(value, "qop")) {
186 /* tokenize the list and choose auth if possible, use a temporary
187 clone of the buffer since strtok_r() ruins it */
188 tmp = strdup(content);
190 return CURLDIGEST_NOMEM;
191 token = strtok_r(tmp, ",", &tok_buf);
192 while(token != NULL) {
193 if(Curl_raw_equal(token, "auth")) {
196 else if(Curl_raw_equal(token, "auth-int")) {
199 token = strtok_r(NULL, ",", &tok_buf);
202 /*select only auth o auth-int. Otherwise, ignore*/
204 d->qop = strdup("auth");
206 return CURLDIGEST_NOMEM;
208 else if(foundAuthInt) {
209 d->qop = strdup("auth-int");
211 return CURLDIGEST_NOMEM;
214 else if(Curl_raw_equal(value, "algorithm")) {
215 d->algorithm = strdup(content);
217 return CURLDIGEST_NOMEM;
218 if(Curl_raw_equal(content, "MD5-sess"))
219 d->algo = CURLDIGESTALGO_MD5SESS;
220 else if(Curl_raw_equal(content, "MD5"))
221 d->algo = CURLDIGESTALGO_MD5;
223 return CURLDIGEST_BADALGO;
226 /* unknown specifier, ignore it! */
230 break; /* we're done here */
232 /* pass all additional spaces here */
233 while(*header && ISSPACE(*header))
236 /* allow the list to be comma-separated */
239 /* We had a nonce since before, and we got another one now without
240 'stale=true'. This means we provided bad credentials in the previous
242 if(before && !d->stale)
243 return CURLDIGEST_BAD;
245 /* We got this header without a nonce, that's a bad Digest line! */
247 return CURLDIGEST_BAD;
250 /* else not a digest, get out */
251 return CURLDIGEST_NONE;
253 return CURLDIGEST_FINE;
256 /* convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/
257 static void md5_to_ascii(unsigned char *source, /* 16 bytes */
258 unsigned char *dest) /* 33 bytes */
262 snprintf((char *)&dest[i*2], 3, "%02x", source[i]);
265 /* Perform quoted-string escaping as described in RFC2616 and its errata */
266 static char *string_quoted(const char *source)
269 const char *s = source;
270 size_t n = 1; /* null terminator */
272 /* Calculate size needed */
275 if(*s == '"' || *s == '\\') {
286 if(*s == '"' || *s == '\\') {
297 CURLcode Curl_output_digest(struct connectdata *conn,
299 const unsigned char *request,
300 const unsigned char *uripath)
302 /* We have a Digest setup for this, use it! Now, to get all the details for
303 this sorted out, I must urge you dear friend to read up on the RFC2617
306 unsigned char md5buf[16]; /* 16 bytes/128 bits */
307 unsigned char request_digest[33];
308 unsigned char *md5this;
309 unsigned char ha1[33];/* 32 digits and 1 zero byte */
310 unsigned char ha2[33];/* 32 digits and 1 zero byte */
313 size_t cnonce_sz = 0;
322 struct SessionHandle *data = conn->data;
323 struct digestdata *d;
325 /* The CURL_OUTPUT_DIGEST_CONV macro below is for non-ASCII machines.
326 It converts digest text to ASCII so the MD5 will be correct for
327 what ultimately goes over the network.
329 #define CURL_OUTPUT_DIGEST_CONV(a, b) \
330 rc = Curl_convert_to_network(a, (char *)b, strlen((const char*)b)); \
331 if(rc != CURLE_OK) { \
337 d = &data->state.proxydigest;
338 allocuserpwd = &conn->allocptr.proxyuserpwd;
339 userp = conn->proxyuser;
340 passwdp = conn->proxypasswd;
341 authp = &data->state.authproxy;
344 d = &data->state.digest;
345 allocuserpwd = &conn->allocptr.userpwd;
347 passwdp = conn->passwd;
348 authp = &data->state.authhost;
351 Curl_safefree(*allocuserpwd);
353 /* not set means empty */
370 snprintf(cnoncebuf, sizeof(cnoncebuf), "%08x%08x%08x%08x",
371 Curl_rand(data), Curl_rand(data),
372 Curl_rand(data), Curl_rand(data));
373 rc = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf),
374 &cnonce, &cnonce_sz);
381 if the algorithm is "MD5" or unspecified (which then defaults to MD5):
383 A1 = unq(username-value) ":" unq(realm-value) ":" passwd
385 if the algorithm is "MD5-sess" then:
387 A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
388 ":" unq(nonce-value) ":" unq(cnonce-value)
391 md5this = (unsigned char *)
392 aprintf("%s:%s:%s", userp, d->realm, passwdp);
394 return CURLE_OUT_OF_MEMORY;
396 CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
397 Curl_md5it(md5buf, md5this);
398 Curl_safefree(md5this);
399 md5_to_ascii(md5buf, ha1);
401 if(d->algo == CURLDIGESTALGO_MD5SESS) {
402 /* nonce and cnonce are OUTSIDE the hash */
403 tmp = aprintf("%s:%s:%s", ha1, d->nonce, d->cnonce);
405 return CURLE_OUT_OF_MEMORY;
406 CURL_OUTPUT_DIGEST_CONV(data, tmp); /* convert on non-ASCII machines */
407 Curl_md5it(md5buf, (unsigned char *)tmp);
409 md5_to_ascii(md5buf, ha1);
413 If the "qop" directive's value is "auth" or is unspecified, then A2 is:
415 A2 = Method ":" digest-uri-value
417 If the "qop" value is "auth-int", then A2 is:
419 A2 = Method ":" digest-uri-value ":" H(entity-body)
421 (The "Method" value is the HTTP request method as specified in section
425 /* So IE browsers < v7 cut off the URI part at the query part when they
426 evaluate the MD5 and some (IIS?) servers work with them so we may need to
427 do the Digest IE-style. Note that the different ways cause different MD5
430 Apache servers can be set to do the Digest IE-style automatically using
431 the BrowserMatch feature:
432 http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie
434 Further details on Digest implementation differences:
435 http://www.fngtps.com/2006/09/http-authentication
438 if(authp->iestyle && ((tmp = strchr((char *)uripath, '?')) != NULL))
439 urilen = tmp - (char *)uripath;
441 urilen = strlen((char *)uripath);
443 md5this = (unsigned char *)aprintf("%s:%.*s", request, urilen, uripath);
445 if(d->qop && Curl_raw_equal(d->qop, "auth-int")) {
446 /* We don't support auth-int for PUT or POST at the moment.
447 TODO: replace md5 of empty string with entity-body for PUT/POST */
448 unsigned char *md5this2 = (unsigned char *)
449 aprintf("%s:%s", md5this, "d41d8cd98f00b204e9800998ecf8427e");
450 Curl_safefree(md5this);
455 return CURLE_OUT_OF_MEMORY;
457 CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
458 Curl_md5it(md5buf, md5this);
459 Curl_safefree(md5this);
460 md5_to_ascii(md5buf, ha2);
463 md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s",
472 md5this = (unsigned char *)aprintf("%s:%s:%s",
478 return CURLE_OUT_OF_MEMORY;
480 CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
481 Curl_md5it(md5buf, md5this);
482 Curl_safefree(md5this);
483 md5_to_ascii(md5buf, request_digest);
485 /* for test case 64 (snooped from a Mozilla 1.3a request)
487 Authorization: Digest username="testuser", realm="testrealm", \
488 nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca"
490 Digest parameters are all quoted strings. Username which is provided by
491 the user will need double quotes and backslashes within it escaped. For
492 the other fields, this shouldn't be an issue. realm, nonce, and opaque
493 are copied as is from the server, escapes and all. cnonce is generated
494 with web-safe characters. uri is already percent encoded. nc is 8 hex
495 characters. algorithm and qop with standard values only contain web-safe
498 userp_quoted = string_quoted(userp);
500 return CURLE_OUT_OF_MEMORY;
504 aprintf( "%sAuthorization: Digest "
517 urilen, uripath, /* this is the PATH part of the URL */
523 if(Curl_raw_equal(d->qop, "auth"))
524 d->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded
525 which tells to the server how many times you are using the
526 same nonce in the qop=auth mode. */
530 aprintf( "%sAuthorization: Digest "
540 urilen, uripath, /* this is the PATH part of the URL */
543 Curl_safefree(userp_quoted);
545 return CURLE_OUT_OF_MEMORY;
547 /* Add optional fields */
550 tmp = aprintf("%s, opaque=\"%s\"", *allocuserpwd, d->opaque);
552 return CURLE_OUT_OF_MEMORY;
558 /* append algorithm */
559 tmp = aprintf("%s, algorithm=\"%s\"", *allocuserpwd, d->algorithm);
561 return CURLE_OUT_OF_MEMORY;
566 /* append CRLF + zero (3 bytes) to the userpwd header */
567 userlen = strlen(*allocuserpwd);
568 tmp = realloc(*allocuserpwd, userlen + 3);
570 return CURLE_OUT_OF_MEMORY;
571 strcpy(&tmp[userlen], "\r\n"); /* append the data */
577 static void digest_cleanup_one(struct digestdata *d)
579 Curl_safefree(d->nonce);
580 Curl_safefree(d->cnonce);
581 Curl_safefree(d->realm);
582 Curl_safefree(d->opaque);
583 Curl_safefree(d->qop);
584 Curl_safefree(d->algorithm);
587 d->algo = CURLDIGESTALGO_MD5; /* default algorithm */
588 d->stale = FALSE; /* default means normal, not stale */
592 void Curl_digest_cleanup(struct SessionHandle *data)
594 digest_cleanup_one(&data->state.digest);
595 digest_cleanup_one(&data->state.proxydigest);