http_digest.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2013, 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. CURLdigest 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 CURLDIGEST_NOMEM;
  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 CURLDIGEST_NOMEM;
  153. }
  154. else if(Curl_raw_equal(value, "opaque")) {
  155. d->opaque = strdup(content);
  156. if(!d->opaque)
  157. return CURLDIGEST_NOMEM;
  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 CURLDIGEST_NOMEM;
  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 CURLDIGEST_NOMEM;
  182. }
  183. else if(foundAuthInt) {
  184. d->qop = strdup("auth-int");
  185. if(!d->qop)
  186. return CURLDIGEST_NOMEM;
  187. }
  188. }
  189. else if(Curl_raw_equal(value, "algorithm")) {
  190. d->algorithm = strdup(content);
  191. if(!d->algorithm)
  192. return CURLDIGEST_NOMEM;
  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 CURLDIGEST_BADALGO;
  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 CURLDIGEST_BAD;
  218. /* We got this header without a nonce, that's a bad Digest line! */
  219. if(!d->nonce)
  220. return CURLDIGEST_BAD;
  221. }
  222. else
  223. /* else not a digest, get out */
  224. return CURLDIGEST_NONE;
  225. return CURLDIGEST_FINE;
  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 rc;
  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. rc = Curl_convert_to_network(a, (char *)b, strlen((const char*)b)); \
  296. if(rc != CURLE_OK) { \
  297. free(b); \
  298. return rc; \
  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. struct timeval now = Curl_tvnow();
  329. snprintf(cnoncebuf, sizeof(cnoncebuf), "%08x%08x%08x%08x",
  330. Curl_rand(data), Curl_rand(data),
  331. (unsigned int)now.tv_sec,
  332. (unsigned int)now.tv_usec);
  333. rc = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf),
  334. &cnonce, &cnonce_sz);
  335. if(rc)
  336. return rc;
  337. d->cnonce = cnonce;
  338. }
  339. /*
  340. if the algorithm is "MD5" or unspecified (which then defaults to MD5):
  341. A1 = unq(username-value) ":" unq(realm-value) ":" passwd
  342. if the algorithm is "MD5-sess" then:
  343. A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
  344. ":" unq(nonce-value) ":" unq(cnonce-value)
  345. */
  346. md5this = (unsigned char *)
  347. aprintf("%s:%s:%s", userp, d->realm, passwdp);
  348. if(!md5this)
  349. return CURLE_OUT_OF_MEMORY;
  350. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  351. Curl_md5it(md5buf, md5this);
  352. Curl_safefree(md5this);
  353. md5_to_ascii(md5buf, ha1);
  354. if(d->algo == CURLDIGESTALGO_MD5SESS) {
  355. /* nonce and cnonce are OUTSIDE the hash */
  356. tmp = aprintf("%s:%s:%s", ha1, d->nonce, d->cnonce);
  357. if(!tmp)
  358. return CURLE_OUT_OF_MEMORY;
  359. CURL_OUTPUT_DIGEST_CONV(data, tmp); /* convert on non-ASCII machines */
  360. Curl_md5it(md5buf, (unsigned char *)tmp);
  361. Curl_safefree(tmp);
  362. md5_to_ascii(md5buf, ha1);
  363. }
  364. /*
  365. If the "qop" directive's value is "auth" or is unspecified, then A2 is:
  366. A2 = Method ":" digest-uri-value
  367. If the "qop" value is "auth-int", then A2 is:
  368. A2 = Method ":" digest-uri-value ":" H(entity-body)
  369. (The "Method" value is the HTTP request method as specified in section
  370. 5.1.1 of RFC 2616)
  371. */
  372. /* So IE browsers < v7 cut off the URI part at the query part when they
  373. evaluate the MD5 and some (IIS?) servers work with them so we may need to
  374. do the Digest IE-style. Note that the different ways cause different MD5
  375. sums to get sent.
  376. Apache servers can be set to do the Digest IE-style automatically using
  377. the BrowserMatch feature:
  378. http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie
  379. Further details on Digest implementation differences:
  380. http://www.fngtps.com/2006/09/http-authentication
  381. */
  382. if(authp->iestyle && ((tmp = strchr((char *)uripath, '?')) != NULL))
  383. urilen = tmp - (char *)uripath;
  384. else
  385. urilen = strlen((char *)uripath);
  386. md5this = (unsigned char *)aprintf("%s:%.*s", request, urilen, uripath);
  387. if(d->qop && Curl_raw_equal(d->qop, "auth-int")) {
  388. /* We don't support auth-int for PUT or POST at the moment.
  389. TODO: replace md5 of empty string with entity-body for PUT/POST */
  390. unsigned char *md5this2 = (unsigned char *)
  391. aprintf("%s:%s", md5this, "d41d8cd98f00b204e9800998ecf8427e");
  392. Curl_safefree(md5this);
  393. md5this = md5this2;
  394. }
  395. if(!md5this)
  396. return CURLE_OUT_OF_MEMORY;
  397. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  398. Curl_md5it(md5buf, md5this);
  399. Curl_safefree(md5this);
  400. md5_to_ascii(md5buf, ha2);
  401. if(d->qop) {
  402. md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s",
  403. ha1,
  404. d->nonce,
  405. d->nc,
  406. d->cnonce,
  407. d->qop,
  408. ha2);
  409. }
  410. else {
  411. md5this = (unsigned char *)aprintf("%s:%s:%s",
  412. ha1,
  413. d->nonce,
  414. ha2);
  415. }
  416. if(!md5this)
  417. return CURLE_OUT_OF_MEMORY;
  418. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  419. Curl_md5it(md5buf, md5this);
  420. Curl_safefree(md5this);
  421. md5_to_ascii(md5buf, request_digest);
  422. /* for test case 64 (snooped from a Mozilla 1.3a request)
  423. Authorization: Digest username="testuser", realm="testrealm", \
  424. nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca"
  425. Digest parameters are all quoted strings. Username which is provided by
  426. the user will need double quotes and backslashes within it escaped. For
  427. the other fields, this shouldn't be an issue. realm, nonce, and opaque
  428. are copied as is from the server, escapes and all. cnonce is generated
  429. with web-safe characters. uri is already percent encoded. nc is 8 hex
  430. characters. algorithm and qop with standard values only contain web-safe
  431. chracters.
  432. */
  433. userp_quoted = string_quoted(userp);
  434. if(!userp_quoted)
  435. return CURLE_OUT_OF_MEMORY;
  436. if(d->qop) {
  437. *allocuserpwd =
  438. aprintf( "%sAuthorization: Digest "
  439. "username=\"%s\", "
  440. "realm=\"%s\", "
  441. "nonce=\"%s\", "
  442. "uri=\"%.*s\", "
  443. "cnonce=\"%s\", "
  444. "nc=%08x, "
  445. "qop=%s, "
  446. "response=\"%s\"",
  447. proxy?"Proxy-":"",
  448. userp_quoted,
  449. d->realm,
  450. d->nonce,
  451. urilen, uripath, /* this is the PATH part of the URL */
  452. d->cnonce,
  453. d->nc,
  454. d->qop,
  455. request_digest);
  456. if(Curl_raw_equal(d->qop, "auth"))
  457. d->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded
  458. which tells to the server how many times you are using the
  459. same nonce in the qop=auth mode. */
  460. }
  461. else {
  462. *allocuserpwd =
  463. aprintf( "%sAuthorization: Digest "
  464. "username=\"%s\", "
  465. "realm=\"%s\", "
  466. "nonce=\"%s\", "
  467. "uri=\"%.*s\", "
  468. "response=\"%s\"",
  469. proxy?"Proxy-":"",
  470. userp_quoted,
  471. d->realm,
  472. d->nonce,
  473. urilen, uripath, /* this is the PATH part of the URL */
  474. request_digest);
  475. }
  476. Curl_safefree(userp_quoted);
  477. if(!*allocuserpwd)
  478. return CURLE_OUT_OF_MEMORY;
  479. /* Add optional fields */
  480. if(d->opaque) {
  481. /* append opaque */
  482. tmp = aprintf("%s, opaque=\"%s\"", *allocuserpwd, d->opaque);
  483. if(!tmp)
  484. return CURLE_OUT_OF_MEMORY;
  485. free(*allocuserpwd);
  486. *allocuserpwd = tmp;
  487. }
  488. if(d->algorithm) {
  489. /* append algorithm */
  490. tmp = aprintf("%s, algorithm=\"%s\"", *allocuserpwd, d->algorithm);
  491. if(!tmp)
  492. return CURLE_OUT_OF_MEMORY;
  493. free(*allocuserpwd);
  494. *allocuserpwd = tmp;
  495. }
  496. /* append CRLF + zero (3 bytes) to the userpwd header */
  497. userlen = strlen(*allocuserpwd);
  498. tmp = realloc(*allocuserpwd, userlen + 3);
  499. if(!tmp)
  500. return CURLE_OUT_OF_MEMORY;
  501. strcpy(&tmp[userlen], "\r\n"); /* append the data */
  502. *allocuserpwd = tmp;
  503. return CURLE_OK;
  504. }
  505. static void digest_cleanup_one(struct digestdata *d)
  506. {
  507. Curl_safefree(d->nonce);
  508. Curl_safefree(d->cnonce);
  509. Curl_safefree(d->realm);
  510. Curl_safefree(d->opaque);
  511. Curl_safefree(d->qop);
  512. Curl_safefree(d->algorithm);
  513. d->nc = 0;
  514. d->algo = CURLDIGESTALGO_MD5; /* default algorithm */
  515. d->stale = FALSE; /* default means normal, not stale */
  516. }
  517. void Curl_digest_cleanup(struct SessionHandle *data)
  518. {
  519. digest_cleanup_one(&data->state.digest);
  520. digest_cleanup_one(&data->state.proxydigest);
  521. }
  522. #endif