http_digest.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  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.
  13. *
  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.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
  24. #include "urldata.h"
  25. #include "rawstr.h"
  26. #include "curl_base64.h"
  27. #include "curl_md5.h"
  28. #include "http_digest.h"
  29. #include "strtok.h"
  30. #include "curl_memory.h"
  31. #include "vtls/vtls.h" /* for Curl_rand() */
  32. #include "non-ascii.h" /* included for Curl_convert_... prototypes */
  33. #include "warnless.h"
  34. #define _MPRINTF_REPLACE /* use our functions only */
  35. #include <curl/mprintf.h>
  36. /* The last #include file should be: */
  37. #include "memdebug.h"
  38. #define MAX_VALUE_LENGTH 256
  39. #define MAX_CONTENT_LENGTH 1024
  40. static void digest_cleanup_one(struct digestdata *dig);
  41. /*
  42. * Return 0 on success and then the buffers are filled in fine.
  43. *
  44. * Non-zero means failure to parse.
  45. */
  46. static int get_pair(const char *str, char *value, char *content,
  47. const char **endptr)
  48. {
  49. int c;
  50. bool starts_with_quote = FALSE;
  51. bool escape = FALSE;
  52. for(c=MAX_VALUE_LENGTH-1; (*str && (*str != '=') && c--); )
  53. *value++ = *str++;
  54. *value=0;
  55. if('=' != *str++)
  56. /* eek, no match */
  57. return 1;
  58. if('\"' == *str) {
  59. /* this starts with a quote so it must end with one as well! */
  60. str++;
  61. starts_with_quote = TRUE;
  62. }
  63. for(c=MAX_CONTENT_LENGTH-1; *str && c--; str++) {
  64. switch(*str) {
  65. case '\\':
  66. if(!escape) {
  67. /* possibly the start of an escaped quote */
  68. escape = TRUE;
  69. *content++ = '\\'; /* even though this is an escape character, we still
  70. store it as-is in the target buffer */
  71. continue;
  72. }
  73. break;
  74. case ',':
  75. if(!starts_with_quote) {
  76. /* this signals the end of the content if we didn't get a starting
  77. quote and then we do "sloppy" parsing */
  78. c=0; /* the end */
  79. continue;
  80. }
  81. break;
  82. case '\r':
  83. case '\n':
  84. /* end of string */
  85. c=0;
  86. continue;
  87. case '\"':
  88. if(!escape && starts_with_quote) {
  89. /* end of string */
  90. c=0;
  91. continue;
  92. }
  93. break;
  94. }
  95. escape = FALSE;
  96. *content++ = *str;
  97. }
  98. *content=0;
  99. *endptr = str;
  100. return 0; /* all is fine! */
  101. }
  102. /* Test example headers:
  103. WWW-Authenticate: Digest realm="testrealm", nonce="1053604598"
  104. Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598"
  105. */
  106. CURLcode Curl_input_digest(struct connectdata *conn,
  107. bool proxy,
  108. const char *header) /* rest of the *-authenticate:
  109. header */
  110. {
  111. char *token = NULL;
  112. char *tmp = NULL;
  113. bool foundAuth = FALSE;
  114. bool foundAuthInt = FALSE;
  115. struct SessionHandle *data=conn->data;
  116. bool before = FALSE; /* got a nonce before */
  117. struct digestdata *d;
  118. if(proxy) {
  119. d = &data->state.proxydigest;
  120. }
  121. else {
  122. d = &data->state.digest;
  123. }
  124. if(checkprefix("Digest", header)) {
  125. header += strlen("Digest");
  126. /* If we already have received a nonce, keep that in mind */
  127. if(d->nonce)
  128. before = TRUE;
  129. /* clear off any former leftovers and init to defaults */
  130. digest_cleanup_one(d);
  131. for(;;) {
  132. char value[MAX_VALUE_LENGTH];
  133. char content[MAX_CONTENT_LENGTH];
  134. while(*header && ISSPACE(*header))
  135. header++;
  136. /* extract a value=content pair */
  137. if(!get_pair(header, value, content, &header)) {
  138. if(Curl_raw_equal(value, "nonce")) {
  139. d->nonce = strdup(content);
  140. if(!d->nonce)
  141. return CURLE_OUT_OF_MEMORY;
  142. }
  143. else if(Curl_raw_equal(value, "stale")) {
  144. if(Curl_raw_equal(content, "true")) {
  145. d->stale = TRUE;
  146. d->nc = 1; /* we make a new nonce now */
  147. }
  148. }
  149. else if(Curl_raw_equal(value, "realm")) {
  150. d->realm = strdup(content);
  151. if(!d->realm)
  152. return CURLE_OUT_OF_MEMORY;
  153. }
  154. else if(Curl_raw_equal(value, "opaque")) {
  155. d->opaque = strdup(content);
  156. if(!d->opaque)
  157. return CURLE_OUT_OF_MEMORY;
  158. }
  159. else if(Curl_raw_equal(value, "qop")) {
  160. char *tok_buf;
  161. /* tokenize the list and choose auth if possible, use a temporary
  162. clone of the buffer since strtok_r() ruins it */
  163. tmp = strdup(content);
  164. if(!tmp)
  165. return CURLE_OUT_OF_MEMORY;
  166. token = strtok_r(tmp, ",", &tok_buf);
  167. while(token != NULL) {
  168. if(Curl_raw_equal(token, "auth")) {
  169. foundAuth = TRUE;
  170. }
  171. else if(Curl_raw_equal(token, "auth-int")) {
  172. foundAuthInt = TRUE;
  173. }
  174. token = strtok_r(NULL, ",", &tok_buf);
  175. }
  176. free(tmp);
  177. /*select only auth o auth-int. Otherwise, ignore*/
  178. if(foundAuth) {
  179. d->qop = strdup("auth");
  180. if(!d->qop)
  181. return CURLE_OUT_OF_MEMORY;
  182. }
  183. else if(foundAuthInt) {
  184. d->qop = strdup("auth-int");
  185. if(!d->qop)
  186. return CURLE_OUT_OF_MEMORY;
  187. }
  188. }
  189. else if(Curl_raw_equal(value, "algorithm")) {
  190. d->algorithm = strdup(content);
  191. if(!d->algorithm)
  192. return CURLE_OUT_OF_MEMORY;
  193. if(Curl_raw_equal(content, "MD5-sess"))
  194. d->algo = CURLDIGESTALGO_MD5SESS;
  195. else if(Curl_raw_equal(content, "MD5"))
  196. d->algo = CURLDIGESTALGO_MD5;
  197. else
  198. return CURLE_BAD_CONTENT_ENCODING;
  199. }
  200. else {
  201. /* unknown specifier, ignore it! */
  202. }
  203. }
  204. else
  205. break; /* we're done here */
  206. /* pass all additional spaces here */
  207. while(*header && ISSPACE(*header))
  208. header++;
  209. if(',' == *header)
  210. /* allow the list to be comma-separated */
  211. header++;
  212. }
  213. /* We had a nonce since before, and we got another one now without
  214. 'stale=true'. This means we provided bad credentials in the previous
  215. request */
  216. if(before && !d->stale)
  217. return CURLE_BAD_CONTENT_ENCODING;
  218. /* We got this header without a nonce, that's a bad Digest line! */
  219. if(!d->nonce)
  220. return CURLE_BAD_CONTENT_ENCODING;
  221. }
  222. else
  223. /* else not a digest, get out */
  224. return CURLE_BAD_CONTENT_ENCODING;
  225. return CURLE_OK;
  226. }
  227. /* convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/
  228. static void md5_to_ascii(unsigned char *source, /* 16 bytes */
  229. unsigned char *dest) /* 33 bytes */
  230. {
  231. int i;
  232. for(i=0; i<16; i++)
  233. snprintf((char *)&dest[i*2], 3, "%02x", source[i]);
  234. }
  235. /* Perform quoted-string escaping as described in RFC2616 and its errata */
  236. static char *string_quoted(const char *source)
  237. {
  238. char *dest, *d;
  239. const char *s = source;
  240. size_t n = 1; /* null terminator */
  241. /* Calculate size needed */
  242. while(*s) {
  243. ++n;
  244. if(*s == '"' || *s == '\\') {
  245. ++n;
  246. }
  247. ++s;
  248. }
  249. dest = malloc(n);
  250. if(dest) {
  251. s = source;
  252. d = dest;
  253. while(*s) {
  254. if(*s == '"' || *s == '\\') {
  255. *d++ = '\\';
  256. }
  257. *d++ = *s++;
  258. }
  259. *d = 0;
  260. }
  261. return dest;
  262. }
  263. CURLcode Curl_output_digest(struct connectdata *conn,
  264. bool proxy,
  265. const unsigned char *request,
  266. const unsigned char *uripath)
  267. {
  268. /* We have a Digest setup for this, use it! Now, to get all the details for
  269. this sorted out, I must urge you dear friend to read up on the RFC2617
  270. section 3.2.2, */
  271. size_t urilen;
  272. unsigned char md5buf[16]; /* 16 bytes/128 bits */
  273. unsigned char request_digest[33];
  274. unsigned char *md5this;
  275. unsigned char ha1[33];/* 32 digits and 1 zero byte */
  276. unsigned char ha2[33];/* 32 digits and 1 zero byte */
  277. char cnoncebuf[33];
  278. char *cnonce = NULL;
  279. size_t cnonce_sz = 0;
  280. char *tmp = NULL;
  281. char **allocuserpwd;
  282. size_t userlen;
  283. const char *userp;
  284. char *userp_quoted;
  285. const char *passwdp;
  286. struct auth *authp;
  287. struct SessionHandle *data = conn->data;
  288. struct digestdata *d;
  289. CURLcode result;
  290. /* The CURL_OUTPUT_DIGEST_CONV macro below is for non-ASCII machines.
  291. It converts digest text to ASCII so the MD5 will be correct for
  292. what ultimately goes over the network.
  293. */
  294. #define CURL_OUTPUT_DIGEST_CONV(a, b) \
  295. result = Curl_convert_to_network(a, (char *)b, strlen((const char*)b)); \
  296. if(result) { \
  297. free(b); \
  298. return result; \
  299. }
  300. if(proxy) {
  301. d = &data->state.proxydigest;
  302. allocuserpwd = &conn->allocptr.proxyuserpwd;
  303. userp = conn->proxyuser;
  304. passwdp = conn->proxypasswd;
  305. authp = &data->state.authproxy;
  306. }
  307. else {
  308. d = &data->state.digest;
  309. allocuserpwd = &conn->allocptr.userpwd;
  310. userp = conn->user;
  311. passwdp = conn->passwd;
  312. authp = &data->state.authhost;
  313. }
  314. Curl_safefree(*allocuserpwd);
  315. /* not set means empty */
  316. if(!userp)
  317. userp="";
  318. if(!passwdp)
  319. passwdp="";
  320. if(!d->nonce) {
  321. authp->done = FALSE;
  322. return CURLE_OK;
  323. }
  324. authp->done = TRUE;
  325. if(!d->nc)
  326. d->nc = 1;
  327. if(!d->cnonce) {
  328. snprintf(cnoncebuf, sizeof(cnoncebuf), "%08x%08x%08x%08x",
  329. Curl_rand(data), Curl_rand(data),
  330. Curl_rand(data), Curl_rand(data));
  331. result = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf),
  332. &cnonce, &cnonce_sz);
  333. if(result)
  334. return result;
  335. d->cnonce = cnonce;
  336. }
  337. /*
  338. if the algorithm is "MD5" or unspecified (which then defaults to MD5):
  339. A1 = unq(username-value) ":" unq(realm-value) ":" passwd
  340. if the algorithm is "MD5-sess" then:
  341. A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
  342. ":" unq(nonce-value) ":" unq(cnonce-value)
  343. */
  344. md5this = (unsigned char *)
  345. aprintf("%s:%s:%s", userp, d->realm, passwdp);
  346. if(!md5this)
  347. return CURLE_OUT_OF_MEMORY;
  348. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  349. Curl_md5it(md5buf, md5this);
  350. Curl_safefree(md5this);
  351. md5_to_ascii(md5buf, ha1);
  352. if(d->algo == CURLDIGESTALGO_MD5SESS) {
  353. /* nonce and cnonce are OUTSIDE the hash */
  354. tmp = aprintf("%s:%s:%s", ha1, d->nonce, d->cnonce);
  355. if(!tmp)
  356. return CURLE_OUT_OF_MEMORY;
  357. CURL_OUTPUT_DIGEST_CONV(data, tmp); /* convert on non-ASCII machines */
  358. Curl_md5it(md5buf, (unsigned char *)tmp);
  359. Curl_safefree(tmp);
  360. md5_to_ascii(md5buf, ha1);
  361. }
  362. /*
  363. If the "qop" directive's value is "auth" or is unspecified, then A2 is:
  364. A2 = Method ":" digest-uri-value
  365. If the "qop" value is "auth-int", then A2 is:
  366. A2 = Method ":" digest-uri-value ":" H(entity-body)
  367. (The "Method" value is the HTTP request method as specified in section
  368. 5.1.1 of RFC 2616)
  369. */
  370. /* So IE browsers < v7 cut off the URI part at the query part when they
  371. evaluate the MD5 and some (IIS?) servers work with them so we may need to
  372. do the Digest IE-style. Note that the different ways cause different MD5
  373. sums to get sent.
  374. Apache servers can be set to do the Digest IE-style automatically using
  375. the BrowserMatch feature:
  376. http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie
  377. Further details on Digest implementation differences:
  378. http://www.fngtps.com/2006/09/http-authentication
  379. */
  380. if(authp->iestyle && ((tmp = strchr((char *)uripath, '?')) != NULL))
  381. urilen = tmp - (char *)uripath;
  382. else
  383. urilen = strlen((char *)uripath);
  384. md5this = (unsigned char *)aprintf("%s:%.*s", request, urilen, uripath);
  385. if(d->qop && Curl_raw_equal(d->qop, "auth-int")) {
  386. /* We don't support auth-int for PUT or POST at the moment.
  387. TODO: replace md5 of empty string with entity-body for PUT/POST */
  388. unsigned char *md5this2 = (unsigned char *)
  389. aprintf("%s:%s", md5this, "d41d8cd98f00b204e9800998ecf8427e");
  390. Curl_safefree(md5this);
  391. md5this = md5this2;
  392. }
  393. if(!md5this)
  394. return CURLE_OUT_OF_MEMORY;
  395. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  396. Curl_md5it(md5buf, md5this);
  397. Curl_safefree(md5this);
  398. md5_to_ascii(md5buf, ha2);
  399. if(d->qop) {
  400. md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s",
  401. ha1,
  402. d->nonce,
  403. d->nc,
  404. d->cnonce,
  405. d->qop,
  406. ha2);
  407. }
  408. else {
  409. md5this = (unsigned char *)aprintf("%s:%s:%s",
  410. ha1,
  411. d->nonce,
  412. ha2);
  413. }
  414. if(!md5this)
  415. return CURLE_OUT_OF_MEMORY;
  416. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  417. Curl_md5it(md5buf, md5this);
  418. Curl_safefree(md5this);
  419. md5_to_ascii(md5buf, request_digest);
  420. /* for test case 64 (snooped from a Mozilla 1.3a request)
  421. Authorization: Digest username="testuser", realm="testrealm", \
  422. nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca"
  423. Digest parameters are all quoted strings. Username which is provided by
  424. the user will need double quotes and backslashes within it escaped. For
  425. the other fields, this shouldn't be an issue. realm, nonce, and opaque
  426. are copied as is from the server, escapes and all. cnonce is generated
  427. with web-safe characters. uri is already percent encoded. nc is 8 hex
  428. characters. algorithm and qop with standard values only contain web-safe
  429. chracters.
  430. */
  431. userp_quoted = string_quoted(userp);
  432. if(!userp_quoted)
  433. return CURLE_OUT_OF_MEMORY;
  434. if(d->qop) {
  435. *allocuserpwd =
  436. aprintf( "%sAuthorization: Digest "
  437. "username=\"%s\", "
  438. "realm=\"%s\", "
  439. "nonce=\"%s\", "
  440. "uri=\"%.*s\", "
  441. "cnonce=\"%s\", "
  442. "nc=%08x, "
  443. "qop=%s, "
  444. "response=\"%s\"",
  445. proxy?"Proxy-":"",
  446. userp_quoted,
  447. d->realm,
  448. d->nonce,
  449. urilen, uripath, /* this is the PATH part of the URL */
  450. d->cnonce,
  451. d->nc,
  452. d->qop,
  453. request_digest);
  454. if(Curl_raw_equal(d->qop, "auth"))
  455. d->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded
  456. which tells to the server how many times you are using the
  457. same nonce in the qop=auth mode. */
  458. }
  459. else {
  460. *allocuserpwd =
  461. aprintf( "%sAuthorization: Digest "
  462. "username=\"%s\", "
  463. "realm=\"%s\", "
  464. "nonce=\"%s\", "
  465. "uri=\"%.*s\", "
  466. "response=\"%s\"",
  467. proxy?"Proxy-":"",
  468. userp_quoted,
  469. d->realm,
  470. d->nonce,
  471. urilen, uripath, /* this is the PATH part of the URL */
  472. request_digest);
  473. }
  474. Curl_safefree(userp_quoted);
  475. if(!*allocuserpwd)
  476. return CURLE_OUT_OF_MEMORY;
  477. /* Add optional fields */
  478. if(d->opaque) {
  479. /* append opaque */
  480. tmp = aprintf("%s, opaque=\"%s\"", *allocuserpwd, d->opaque);
  481. if(!tmp)
  482. return CURLE_OUT_OF_MEMORY;
  483. free(*allocuserpwd);
  484. *allocuserpwd = tmp;
  485. }
  486. if(d->algorithm) {
  487. /* append algorithm */
  488. tmp = aprintf("%s, algorithm=\"%s\"", *allocuserpwd, d->algorithm);
  489. if(!tmp)
  490. return CURLE_OUT_OF_MEMORY;
  491. free(*allocuserpwd);
  492. *allocuserpwd = tmp;
  493. }
  494. /* append CRLF + zero (3 bytes) to the userpwd header */
  495. userlen = strlen(*allocuserpwd);
  496. tmp = realloc(*allocuserpwd, userlen + 3);
  497. if(!tmp)
  498. return CURLE_OUT_OF_MEMORY;
  499. strcpy(&tmp[userlen], "\r\n"); /* append the data */
  500. *allocuserpwd = tmp;
  501. return CURLE_OK;
  502. }
  503. static void digest_cleanup_one(struct digestdata *d)
  504. {
  505. Curl_safefree(d->nonce);
  506. Curl_safefree(d->cnonce);
  507. Curl_safefree(d->realm);
  508. Curl_safefree(d->opaque);
  509. Curl_safefree(d->qop);
  510. Curl_safefree(d->algorithm);
  511. d->nc = 0;
  512. d->algo = CURLDIGESTALGO_MD5; /* default algorithm */
  513. d->stale = FALSE; /* default means normal, not stale */
  514. }
  515. void Curl_digest_cleanup(struct SessionHandle *data)
  516. {
  517. digest_cleanup_one(&data->state.digest);
  518. digest_cleanup_one(&data->state.proxydigest);
  519. }
  520. #endif