http_digest.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 "sslgen.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. /* skip initial whitespaces */
  125. while(*header && ISSPACE(*header))
  126. header++;
  127. if(checkprefix("Digest", header)) {
  128. header += strlen("Digest");
  129. /* If we already have received a nonce, keep that in mind */
  130. if(d->nonce)
  131. before = TRUE;
  132. /* clear off any former leftovers and init to defaults */
  133. digest_cleanup_one(d);
  134. for(;;) {
  135. char value[MAX_VALUE_LENGTH];
  136. char content[MAX_CONTENT_LENGTH];
  137. while(*header && ISSPACE(*header))
  138. header++;
  139. /* extract a value=content pair */
  140. if(!get_pair(header, value, content, &header)) {
  141. if(Curl_raw_equal(value, "nonce")) {
  142. d->nonce = strdup(content);
  143. if(!d->nonce)
  144. return CURLDIGEST_NOMEM;
  145. }
  146. else if(Curl_raw_equal(value, "stale")) {
  147. if(Curl_raw_equal(content, "true")) {
  148. d->stale = TRUE;
  149. d->nc = 1; /* we make a new nonce now */
  150. }
  151. }
  152. else if(Curl_raw_equal(value, "realm")) {
  153. d->realm = strdup(content);
  154. if(!d->realm)
  155. return CURLDIGEST_NOMEM;
  156. }
  157. else if(Curl_raw_equal(value, "opaque")) {
  158. d->opaque = strdup(content);
  159. if(!d->opaque)
  160. return CURLDIGEST_NOMEM;
  161. }
  162. else if(Curl_raw_equal(value, "qop")) {
  163. char *tok_buf;
  164. /* tokenize the list and choose auth if possible, use a temporary
  165. clone of the buffer since strtok_r() ruins it */
  166. tmp = strdup(content);
  167. if(!tmp)
  168. return CURLDIGEST_NOMEM;
  169. token = strtok_r(tmp, ",", &tok_buf);
  170. while(token != NULL) {
  171. if(Curl_raw_equal(token, "auth")) {
  172. foundAuth = TRUE;
  173. }
  174. else if(Curl_raw_equal(token, "auth-int")) {
  175. foundAuthInt = TRUE;
  176. }
  177. token = strtok_r(NULL, ",", &tok_buf);
  178. }
  179. free(tmp);
  180. /*select only auth o auth-int. Otherwise, ignore*/
  181. if(foundAuth) {
  182. d->qop = strdup("auth");
  183. if(!d->qop)
  184. return CURLDIGEST_NOMEM;
  185. }
  186. else if(foundAuthInt) {
  187. d->qop = strdup("auth-int");
  188. if(!d->qop)
  189. return CURLDIGEST_NOMEM;
  190. }
  191. }
  192. else if(Curl_raw_equal(value, "algorithm")) {
  193. d->algorithm = strdup(content);
  194. if(!d->algorithm)
  195. return CURLDIGEST_NOMEM;
  196. if(Curl_raw_equal(content, "MD5-sess"))
  197. d->algo = CURLDIGESTALGO_MD5SESS;
  198. else if(Curl_raw_equal(content, "MD5"))
  199. d->algo = CURLDIGESTALGO_MD5;
  200. else
  201. return CURLDIGEST_BADALGO;
  202. }
  203. else {
  204. /* unknown specifier, ignore it! */
  205. }
  206. }
  207. else
  208. break; /* we're done here */
  209. /* pass all additional spaces here */
  210. while(*header && ISSPACE(*header))
  211. header++;
  212. if(',' == *header)
  213. /* allow the list to be comma-separated */
  214. header++;
  215. }
  216. /* We had a nonce since before, and we got another one now without
  217. 'stale=true'. This means we provided bad credentials in the previous
  218. request */
  219. if(before && !d->stale)
  220. return CURLDIGEST_BAD;
  221. /* We got this header without a nonce, that's a bad Digest line! */
  222. if(!d->nonce)
  223. return CURLDIGEST_BAD;
  224. }
  225. else
  226. /* else not a digest, get out */
  227. return CURLDIGEST_NONE;
  228. return CURLDIGEST_FINE;
  229. }
  230. /* convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/
  231. static void md5_to_ascii(unsigned char *source, /* 16 bytes */
  232. unsigned char *dest) /* 33 bytes */
  233. {
  234. int i;
  235. for(i=0; i<16; i++)
  236. snprintf((char *)&dest[i*2], 3, "%02x", source[i]);
  237. }
  238. /* Perform quoted-string escaping as described in RFC2616 and its errata */
  239. static char *string_quoted(const char *source)
  240. {
  241. char *dest, *d;
  242. const char *s = source;
  243. size_t n = 1; /* null terminator */
  244. /* Calculate size needed */
  245. while(*s) {
  246. ++n;
  247. if(*s == '"' || *s == '\\') {
  248. ++n;
  249. }
  250. ++s;
  251. }
  252. dest = malloc(n);
  253. if(dest) {
  254. s = source;
  255. d = dest;
  256. while(*s) {
  257. if(*s == '"' || *s == '\\') {
  258. *d++ = '\\';
  259. }
  260. *d++ = *s++;
  261. }
  262. *d = 0;
  263. }
  264. return dest;
  265. }
  266. CURLcode Curl_output_digest(struct connectdata *conn,
  267. bool proxy,
  268. const unsigned char *request,
  269. const unsigned char *uripath)
  270. {
  271. /* We have a Digest setup for this, use it! Now, to get all the details for
  272. this sorted out, I must urge you dear friend to read up on the RFC2617
  273. section 3.2.2, */
  274. unsigned char md5buf[16]; /* 16 bytes/128 bits */
  275. unsigned char request_digest[33];
  276. unsigned char *md5this;
  277. unsigned char ha1[33];/* 32 digits and 1 zero byte */
  278. unsigned char ha2[33];/* 32 digits and 1 zero byte */
  279. char cnoncebuf[33];
  280. char *cnonce = NULL;
  281. size_t cnonce_sz = 0;
  282. char *tmp = NULL;
  283. char **allocuserpwd;
  284. size_t userlen;
  285. const char *userp;
  286. char *userp_quoted;
  287. const char *passwdp;
  288. struct auth *authp;
  289. struct SessionHandle *data = conn->data;
  290. struct digestdata *d;
  291. CURLcode rc;
  292. /* The CURL_OUTPUT_DIGEST_CONV macro below is for non-ASCII machines.
  293. It converts digest text to ASCII so the MD5 will be correct for
  294. what ultimately goes over the network.
  295. */
  296. #define CURL_OUTPUT_DIGEST_CONV(a, b) \
  297. rc = Curl_convert_to_network(a, (char *)b, strlen((const char*)b)); \
  298. if(rc != CURLE_OK) { \
  299. free(b); \
  300. return rc; \
  301. }
  302. if(proxy) {
  303. d = &data->state.proxydigest;
  304. allocuserpwd = &conn->allocptr.proxyuserpwd;
  305. userp = conn->proxyuser;
  306. passwdp = conn->proxypasswd;
  307. authp = &data->state.authproxy;
  308. }
  309. else {
  310. d = &data->state.digest;
  311. allocuserpwd = &conn->allocptr.userpwd;
  312. userp = conn->user;
  313. passwdp = conn->passwd;
  314. authp = &data->state.authhost;
  315. }
  316. Curl_safefree(*allocuserpwd);
  317. /* not set means empty */
  318. if(!userp)
  319. userp="";
  320. if(!passwdp)
  321. passwdp="";
  322. if(!d->nonce) {
  323. authp->done = FALSE;
  324. return CURLE_OK;
  325. }
  326. authp->done = TRUE;
  327. if(!d->nc)
  328. d->nc = 1;
  329. if(!d->cnonce) {
  330. struct timeval now = Curl_tvnow();
  331. snprintf(cnoncebuf, sizeof(cnoncebuf), "%08x%08x%08x%08x",
  332. Curl_rand(data), Curl_rand(data),
  333. (unsigned int)now.tv_sec,
  334. (unsigned int)now.tv_usec);
  335. rc = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf),
  336. &cnonce, &cnonce_sz);
  337. if(rc)
  338. return rc;
  339. d->cnonce = cnonce;
  340. }
  341. /*
  342. if the algorithm is "MD5" or unspecified (which then defaults to MD5):
  343. A1 = unq(username-value) ":" unq(realm-value) ":" passwd
  344. if the algorithm is "MD5-sess" then:
  345. A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
  346. ":" unq(nonce-value) ":" unq(cnonce-value)
  347. */
  348. md5this = (unsigned char *)
  349. aprintf("%s:%s:%s", userp, d->realm, passwdp);
  350. if(!md5this)
  351. return CURLE_OUT_OF_MEMORY;
  352. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  353. Curl_md5it(md5buf, md5this);
  354. Curl_safefree(md5this);
  355. md5_to_ascii(md5buf, ha1);
  356. if(d->algo == CURLDIGESTALGO_MD5SESS) {
  357. /* nonce and cnonce are OUTSIDE the hash */
  358. tmp = aprintf("%s:%s:%s", ha1, d->nonce, d->cnonce);
  359. if(!tmp)
  360. return CURLE_OUT_OF_MEMORY;
  361. CURL_OUTPUT_DIGEST_CONV(data, tmp); /* convert on non-ASCII machines */
  362. Curl_md5it(md5buf, (unsigned char *)tmp);
  363. Curl_safefree(tmp);
  364. md5_to_ascii(md5buf, ha1);
  365. }
  366. /*
  367. If the "qop" directive's value is "auth" or is unspecified, then A2 is:
  368. A2 = Method ":" digest-uri-value
  369. If the "qop" value is "auth-int", then A2 is:
  370. A2 = Method ":" digest-uri-value ":" H(entity-body)
  371. (The "Method" value is the HTTP request method as specified in section
  372. 5.1.1 of RFC 2616)
  373. */
  374. /* So IE browsers < v7 cut off the URI part at the query part when they
  375. evaluate the MD5 and some (IIS?) servers work with them so we may need to
  376. do the Digest IE-style. Note that the different ways cause different MD5
  377. sums to get sent.
  378. Apache servers can be set to do the Digest IE-style automatically using
  379. the BrowserMatch feature:
  380. http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie
  381. Further details on Digest implementation differences:
  382. http://www.fngtps.com/2006/09/http-authentication
  383. */
  384. if(authp->iestyle && ((tmp = strchr((char *)uripath, '?')) != NULL)) {
  385. md5this = (unsigned char *)aprintf("%s:%.*s", request,
  386. curlx_sztosi(tmp - (char *)uripath),
  387. uripath);
  388. }
  389. else
  390. md5this = (unsigned char *)aprintf("%s:%s", request, uripath);
  391. if(d->qop && Curl_raw_equal(d->qop, "auth-int")) {
  392. /* We don't support auth-int for PUT or POST at the moment.
  393. TODO: replace md5 of empty string with entity-body for PUT/POST */
  394. unsigned char *md5this2 = (unsigned char *)
  395. aprintf("%s:%s", md5this, "d41d8cd98f00b204e9800998ecf8427e");
  396. Curl_safefree(md5this);
  397. md5this = md5this2;
  398. }
  399. if(!md5this)
  400. return CURLE_OUT_OF_MEMORY;
  401. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  402. Curl_md5it(md5buf, md5this);
  403. Curl_safefree(md5this);
  404. md5_to_ascii(md5buf, ha2);
  405. if(d->qop) {
  406. md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s",
  407. ha1,
  408. d->nonce,
  409. d->nc,
  410. d->cnonce,
  411. d->qop,
  412. ha2);
  413. }
  414. else {
  415. md5this = (unsigned char *)aprintf("%s:%s:%s",
  416. ha1,
  417. d->nonce,
  418. ha2);
  419. }
  420. if(!md5this)
  421. return CURLE_OUT_OF_MEMORY;
  422. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  423. Curl_md5it(md5buf, md5this);
  424. Curl_safefree(md5this);
  425. md5_to_ascii(md5buf, request_digest);
  426. /* for test case 64 (snooped from a Mozilla 1.3a request)
  427. Authorization: Digest username="testuser", realm="testrealm", \
  428. nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca"
  429. Digest parameters are all quoted strings. Username which is provided by
  430. the user will need double quotes and backslashes within it escaped. For
  431. the other fields, this shouldn't be an issue. realm, nonce, and opaque
  432. are copied as is from the server, escapes and all. cnonce is generated
  433. with web-safe characters. uri is already percent encoded. nc is 8 hex
  434. characters. algorithm and qop with standard values only contain web-safe
  435. chracters.
  436. */
  437. userp_quoted = string_quoted(userp);
  438. if(!userp_quoted)
  439. return CURLE_OUT_OF_MEMORY;
  440. if(d->qop) {
  441. *allocuserpwd =
  442. aprintf( "%sAuthorization: Digest "
  443. "username=\"%s\", "
  444. "realm=\"%s\", "
  445. "nonce=\"%s\", "
  446. "uri=\"%s\", "
  447. "cnonce=\"%s\", "
  448. "nc=%08x, "
  449. "qop=%s, "
  450. "response=\"%s\"",
  451. proxy?"Proxy-":"",
  452. userp_quoted,
  453. d->realm,
  454. d->nonce,
  455. uripath, /* this is the PATH part of the URL */
  456. d->cnonce,
  457. d->nc,
  458. d->qop,
  459. request_digest);
  460. if(Curl_raw_equal(d->qop, "auth"))
  461. d->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded
  462. which tells to the server how many times you are using the
  463. same nonce in the qop=auth mode. */
  464. }
  465. else {
  466. *allocuserpwd =
  467. aprintf( "%sAuthorization: Digest "
  468. "username=\"%s\", "
  469. "realm=\"%s\", "
  470. "nonce=\"%s\", "
  471. "uri=\"%s\", "
  472. "response=\"%s\"",
  473. proxy?"Proxy-":"",
  474. userp_quoted,
  475. d->realm,
  476. d->nonce,
  477. uripath, /* this is the PATH part of the URL */
  478. request_digest);
  479. }
  480. Curl_safefree(userp_quoted);
  481. if(!*allocuserpwd)
  482. return CURLE_OUT_OF_MEMORY;
  483. /* Add optional fields */
  484. if(d->opaque) {
  485. /* append opaque */
  486. tmp = aprintf("%s, opaque=\"%s\"", *allocuserpwd, d->opaque);
  487. if(!tmp)
  488. return CURLE_OUT_OF_MEMORY;
  489. free(*allocuserpwd);
  490. *allocuserpwd = tmp;
  491. }
  492. if(d->algorithm) {
  493. /* append algorithm */
  494. tmp = aprintf("%s, algorithm=\"%s\"", *allocuserpwd, d->algorithm);
  495. if(!tmp)
  496. return CURLE_OUT_OF_MEMORY;
  497. free(*allocuserpwd);
  498. *allocuserpwd = tmp;
  499. }
  500. /* append CRLF + zero (3 bytes) to the userpwd header */
  501. userlen = strlen(*allocuserpwd);
  502. tmp = realloc(*allocuserpwd, userlen + 3);
  503. if(!tmp)
  504. return CURLE_OUT_OF_MEMORY;
  505. strcpy(&tmp[userlen], "\r\n"); /* append the data */
  506. *allocuserpwd = tmp;
  507. return CURLE_OK;
  508. }
  509. static void digest_cleanup_one(struct digestdata *d)
  510. {
  511. Curl_safefree(d->nonce);
  512. Curl_safefree(d->cnonce);
  513. Curl_safefree(d->realm);
  514. Curl_safefree(d->opaque);
  515. Curl_safefree(d->qop);
  516. Curl_safefree(d->algorithm);
  517. d->nc = 0;
  518. d->algo = CURLDIGESTALGO_MD5; /* default algorithm */
  519. d->stale = FALSE; /* default means normal, not stale */
  520. }
  521. void Curl_digest_cleanup(struct SessionHandle *data)
  522. {
  523. digest_cleanup_one(&data->state.digest);
  524. digest_cleanup_one(&data->state.proxydigest);
  525. }
  526. #endif