curl_sasl.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2012 - 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. * RFC2195 CRAM-MD5 authentication
  22. * RFC2617 Basic and Digest Access Authentication
  23. * RFC2831 DIGEST-MD5 authentication
  24. * RFC4422 Simple Authentication and Security Layer (SASL)
  25. * RFC4616 PLAIN authentication
  26. * RFC6749 OAuth 2.0 Authorization Framework
  27. * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
  28. *
  29. ***************************************************************************/
  30. #include "curl_setup.h"
  31. #include <curl/curl.h>
  32. #include "urldata.h"
  33. #include "curl_base64.h"
  34. #include "curl_md5.h"
  35. #include "vtls/vtls.h"
  36. #include "curl_hmac.h"
  37. #include "curl_sasl.h"
  38. #include "warnless.h"
  39. #include "curl_memory.h"
  40. #include "strtok.h"
  41. #include "rawstr.h"
  42. #include "non-ascii.h" /* included for Curl_convert_... prototypes */
  43. #define _MPRINTF_REPLACE /* use our functions only */
  44. #include <curl/mprintf.h>
  45. /* The last #include file should be: */
  46. #include "memdebug.h"
  47. #if !defined(CURL_DISABLE_CRYPTO_AUTH) && !defined(USE_WINDOWS_SSPI)
  48. #define DIGEST_QOP_VALUE_AUTH (1 << 0)
  49. #define DIGEST_QOP_VALUE_AUTH_INT (1 << 1)
  50. #define DIGEST_QOP_VALUE_AUTH_CONF (1 << 2)
  51. #define DIGEST_QOP_VALUE_STRING_AUTH "auth"
  52. #define DIGEST_QOP_VALUE_STRING_AUTH_INT "auth-int"
  53. #define DIGEST_QOP_VALUE_STRING_AUTH_CONF "auth-conf"
  54. #define DIGEST_MAX_VALUE_LENGTH 256
  55. #define DIGEST_MAX_CONTENT_LENGTH 1024
  56. /* The CURL_OUTPUT_DIGEST_CONV macro below is for non-ASCII machines.
  57. It converts digest text to ASCII so the MD5 will be correct for
  58. what ultimately goes over the network.
  59. */
  60. #define CURL_OUTPUT_DIGEST_CONV(a, b) \
  61. result = Curl_convert_to_network(a, (char *)b, strlen((const char*)b)); \
  62. if(result) { \
  63. free(b); \
  64. return result; \
  65. }
  66. /*
  67. * Return 0 on success and then the buffers are filled in fine.
  68. *
  69. * Non-zero means failure to parse.
  70. */
  71. static int sasl_digest_get_pair(const char *str, char *value, char *content,
  72. const char **endptr)
  73. {
  74. int c;
  75. bool starts_with_quote = FALSE;
  76. bool escape = FALSE;
  77. for(c = DIGEST_MAX_VALUE_LENGTH - 1; (*str && (*str != '=') && c--); )
  78. *value++ = *str++;
  79. *value = 0;
  80. if('=' != *str++)
  81. /* eek, no match */
  82. return 1;
  83. if('\"' == *str) {
  84. /* this starts with a quote so it must end with one as well! */
  85. str++;
  86. starts_with_quote = TRUE;
  87. }
  88. for(c = DIGEST_MAX_CONTENT_LENGTH - 1; *str && c--; str++) {
  89. switch(*str) {
  90. case '\\':
  91. if(!escape) {
  92. /* possibly the start of an escaped quote */
  93. escape = TRUE;
  94. *content++ = '\\'; /* even though this is an escape character, we still
  95. store it as-is in the target buffer */
  96. continue;
  97. }
  98. break;
  99. case ',':
  100. if(!starts_with_quote) {
  101. /* this signals the end of the content if we didn't get a starting
  102. quote and then we do "sloppy" parsing */
  103. c = 0; /* the end */
  104. continue;
  105. }
  106. break;
  107. case '\r':
  108. case '\n':
  109. /* end of string */
  110. c = 0;
  111. continue;
  112. case '\"':
  113. if(!escape && starts_with_quote) {
  114. /* end of string */
  115. c = 0;
  116. continue;
  117. }
  118. break;
  119. }
  120. escape = FALSE;
  121. *content++ = *str;
  122. }
  123. *content = 0;
  124. *endptr = str;
  125. return 0; /* all is fine! */
  126. }
  127. /* Convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/
  128. static void sasl_digest_md5_to_ascii(unsigned char *source, /* 16 bytes */
  129. unsigned char *dest) /* 33 bytes */
  130. {
  131. int i;
  132. for(i = 0; i < 16; i++)
  133. snprintf((char *)&dest[i*2], 3, "%02x", source[i]);
  134. }
  135. /* Perform quoted-string escaping as described in RFC2616 and its errata */
  136. static char *sasl_digest_string_quoted(const char *source)
  137. {
  138. char *dest, *d;
  139. const char *s = source;
  140. size_t n = 1; /* null terminator */
  141. /* Calculate size needed */
  142. while(*s) {
  143. ++n;
  144. if(*s == '"' || *s == '\\') {
  145. ++n;
  146. }
  147. ++s;
  148. }
  149. dest = malloc(n);
  150. if(dest) {
  151. s = source;
  152. d = dest;
  153. while(*s) {
  154. if(*s == '"' || *s == '\\') {
  155. *d++ = '\\';
  156. }
  157. *d++ = *s++;
  158. }
  159. *d = 0;
  160. }
  161. return dest;
  162. }
  163. /* Retrieves the value for a corresponding key from the challenge string
  164. * returns TRUE if the key could be found, FALSE if it does not exists
  165. */
  166. static bool sasl_digest_get_key_value(const char *chlg,
  167. const char *key,
  168. char *value,
  169. size_t max_val_len,
  170. char end_char)
  171. {
  172. char *find_pos;
  173. size_t i;
  174. find_pos = strstr(chlg, key);
  175. if(!find_pos)
  176. return FALSE;
  177. find_pos += strlen(key);
  178. for(i = 0; *find_pos && *find_pos != end_char && i < max_val_len - 1; ++i)
  179. value[i] = *find_pos++;
  180. value[i] = '\0';
  181. return TRUE;
  182. }
  183. static CURLcode sasl_digest_get_qop_values(const char *options, int *value)
  184. {
  185. char *tmp;
  186. char *token;
  187. char *tok_buf;
  188. /* Initialise the output */
  189. *value = 0;
  190. /* Tokenise the list of qop values. Use a temporary clone of the buffer since
  191. strtok_r() ruins it. */
  192. tmp = strdup(options);
  193. if(!tmp)
  194. return CURLE_OUT_OF_MEMORY;
  195. token = strtok_r(tmp, ",", &tok_buf);
  196. while(token != NULL) {
  197. if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH))
  198. *value |= DIGEST_QOP_VALUE_AUTH;
  199. else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_INT))
  200. *value |= DIGEST_QOP_VALUE_AUTH_INT;
  201. else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_CONF))
  202. *value |= DIGEST_QOP_VALUE_AUTH_CONF;
  203. token = strtok_r(NULL, ",", &tok_buf);
  204. }
  205. Curl_safefree(tmp);
  206. return CURLE_OK;
  207. }
  208. #endif /* !CURL_DISABLE_CRYPTO_AUTH && !USE_WINDOWS_SSPI */
  209. #if !defined(USE_WINDOWS_SSPI)
  210. /*
  211. * Curl_sasl_build_spn()
  212. *
  213. * This is used to build a SPN string in the format service/host.
  214. *
  215. * Parameters:
  216. *
  217. * serivce [in] - The service type such as www, smtp, pop or imap.
  218. * host [in] - The host name or realm.
  219. *
  220. * Returns a pointer to the newly allocated SPN.
  221. */
  222. char *Curl_sasl_build_spn(const char *service, const char *host)
  223. {
  224. /* Generate and return our SPN */
  225. return aprintf("%s/%s", service, host);
  226. }
  227. #endif
  228. /*
  229. * Curl_sasl_create_plain_message()
  230. *
  231. * This is used to generate an already encoded PLAIN message ready
  232. * for sending to the recipient.
  233. *
  234. * Parameters:
  235. *
  236. * data [in] - The session handle.
  237. * userp [in] - The user name.
  238. * passdwp [in] - The user's password.
  239. * outptr [in/out] - The address where a pointer to newly allocated memory
  240. * holding the result will be stored upon completion.
  241. * outlen [out] - The length of the output message.
  242. *
  243. * Returns CURLE_OK on success.
  244. */
  245. CURLcode Curl_sasl_create_plain_message(struct SessionHandle *data,
  246. const char *userp,
  247. const char *passwdp,
  248. char **outptr, size_t *outlen)
  249. {
  250. CURLcode result;
  251. char *plainauth;
  252. size_t ulen;
  253. size_t plen;
  254. ulen = strlen(userp);
  255. plen = strlen(passwdp);
  256. plainauth = malloc(2 * ulen + plen + 2);
  257. if(!plainauth) {
  258. *outlen = 0;
  259. *outptr = NULL;
  260. return CURLE_OUT_OF_MEMORY;
  261. }
  262. /* Calculate the reply */
  263. memcpy(plainauth, userp, ulen);
  264. plainauth[ulen] = '\0';
  265. memcpy(plainauth + ulen + 1, userp, ulen);
  266. plainauth[2 * ulen + 1] = '\0';
  267. memcpy(plainauth + 2 * ulen + 2, passwdp, plen);
  268. /* Base64 encode the reply */
  269. result = Curl_base64_encode(data, plainauth, 2 * ulen + plen + 2, outptr,
  270. outlen);
  271. Curl_safefree(plainauth);
  272. return result;
  273. }
  274. /*
  275. * Curl_sasl_create_login_message()
  276. *
  277. * This is used to generate an already encoded LOGIN message containing the
  278. * user name or password ready for sending to the recipient.
  279. *
  280. * Parameters:
  281. *
  282. * data [in] - The session handle.
  283. * valuep [in] - The user name or user's password.
  284. * outptr [in/out] - The address where a pointer to newly allocated memory
  285. * holding the result will be stored upon completion.
  286. * outlen [out] - The length of the output message.
  287. *
  288. * Returns CURLE_OK on success.
  289. */
  290. CURLcode Curl_sasl_create_login_message(struct SessionHandle *data,
  291. const char *valuep, char **outptr,
  292. size_t *outlen)
  293. {
  294. size_t vlen = strlen(valuep);
  295. if(!vlen) {
  296. /* Calculate an empty reply */
  297. *outptr = strdup("=");
  298. if(*outptr) {
  299. *outlen = (size_t) 1;
  300. return CURLE_OK;
  301. }
  302. *outlen = 0;
  303. return CURLE_OUT_OF_MEMORY;
  304. }
  305. /* Base64 encode the value */
  306. return Curl_base64_encode(data, valuep, vlen, outptr, outlen);
  307. }
  308. #ifndef CURL_DISABLE_CRYPTO_AUTH
  309. /*
  310. * Curl_sasl_decode_cram_md5_message()
  311. *
  312. * This is used to decode an already encoded CRAM-MD5 challenge message.
  313. *
  314. * Parameters:
  315. *
  316. * chlg64 [in] - The base64 encoded challenge message.
  317. * outptr [in/out] - The address where a pointer to newly allocated memory
  318. * holding the result will be stored upon completion.
  319. * outlen [out] - The length of the output message.
  320. *
  321. * Returns CURLE_OK on success.
  322. */
  323. CURLcode Curl_sasl_decode_cram_md5_message(const char *chlg64, char **outptr,
  324. size_t *outlen)
  325. {
  326. CURLcode result = CURLE_OK;
  327. size_t chlg64len = strlen(chlg64);
  328. *outptr = NULL;
  329. *outlen = 0;
  330. /* Decode the challenge if necessary */
  331. if(chlg64len && *chlg64 != '=')
  332. result = Curl_base64_decode(chlg64, (unsigned char **) outptr, outlen);
  333. return result;
  334. }
  335. /*
  336. * Curl_sasl_create_cram_md5_message()
  337. *
  338. * This is used to generate an already encoded CRAM-MD5 response message ready
  339. * for sending to the recipient.
  340. *
  341. * Parameters:
  342. *
  343. * data [in] - The session handle.
  344. * chlg [in] - The challenge.
  345. * userp [in] - The user name.
  346. * passdwp [in] - The user's password.
  347. * outptr [in/out] - The address where a pointer to newly allocated memory
  348. * holding the result will be stored upon completion.
  349. * outlen [out] - The length of the output message.
  350. *
  351. * Returns CURLE_OK on success.
  352. */
  353. CURLcode Curl_sasl_create_cram_md5_message(struct SessionHandle *data,
  354. const char *chlg,
  355. const char *userp,
  356. const char *passwdp,
  357. char **outptr, size_t *outlen)
  358. {
  359. CURLcode result = CURLE_OK;
  360. size_t chlglen = 0;
  361. HMAC_context *ctxt;
  362. unsigned char digest[MD5_DIGEST_LEN];
  363. char *response;
  364. if(chlg)
  365. chlglen = strlen(chlg);
  366. /* Compute the digest using the password as the key */
  367. ctxt = Curl_HMAC_init(Curl_HMAC_MD5,
  368. (const unsigned char *) passwdp,
  369. curlx_uztoui(strlen(passwdp)));
  370. if(!ctxt)
  371. return CURLE_OUT_OF_MEMORY;
  372. /* Update the digest with the given challenge */
  373. if(chlglen > 0)
  374. Curl_HMAC_update(ctxt, (const unsigned char *) chlg,
  375. curlx_uztoui(chlglen));
  376. /* Finalise the digest */
  377. Curl_HMAC_final(ctxt, digest);
  378. /* Generate the response */
  379. response = aprintf(
  380. "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
  381. userp, digest[0], digest[1], digest[2], digest[3], digest[4],
  382. digest[5], digest[6], digest[7], digest[8], digest[9], digest[10],
  383. digest[11], digest[12], digest[13], digest[14], digest[15]);
  384. if(!response)
  385. return CURLE_OUT_OF_MEMORY;
  386. /* Base64 encode the response */
  387. result = Curl_base64_encode(data, response, 0, outptr, outlen);
  388. Curl_safefree(response);
  389. return result;
  390. }
  391. #ifndef USE_WINDOWS_SSPI
  392. /*
  393. * sasl_decode_digest_md5_message()
  394. *
  395. * This is used internally to decode an already encoded DIGEST-MD5 challenge
  396. * message into the seperate attributes.
  397. *
  398. * Parameters:
  399. *
  400. * chlg64 [in] - The base64 encoded challenge message.
  401. * nonce [in/out] - The buffer where the nonce will be stored.
  402. * nlen [in] - The length of the nonce buffer.
  403. * realm [in/out] - The buffer where the realm will be stored.
  404. * rlen [in] - The length of the realm buffer.
  405. * alg [in/out] - The buffer where the algorithm will be stored.
  406. * alen [in] - The length of the algorithm buffer.
  407. * qop [in/out] - The buffer where the qop-options will be stored.
  408. * qlen [in] - The length of the qop buffer.
  409. *
  410. * Returns CURLE_OK on success.
  411. */
  412. static CURLcode sasl_decode_digest_md5_message(const char *chlg64,
  413. char *nonce, size_t nlen,
  414. char *realm, size_t rlen,
  415. char *alg, size_t alen,
  416. char *qop, size_t qlen)
  417. {
  418. CURLcode result = CURLE_OK;
  419. unsigned char *chlg = NULL;
  420. size_t chlglen = 0;
  421. size_t chlg64len = strlen(chlg64);
  422. /* Decode the base-64 encoded challenge message */
  423. if(chlg64len && *chlg64 != '=') {
  424. result = Curl_base64_decode(chlg64, &chlg, &chlglen);
  425. if(result)
  426. return result;
  427. }
  428. /* Ensure we have a valid challenge message */
  429. if(!chlg)
  430. return CURLE_BAD_CONTENT_ENCODING;
  431. /* Retrieve nonce string from the challenge */
  432. if(!sasl_digest_get_key_value((char *)chlg, "nonce=\"", nonce, nlen, '\"')) {
  433. Curl_safefree(chlg);
  434. return CURLE_BAD_CONTENT_ENCODING;
  435. }
  436. /* Retrieve realm string from the challenge */
  437. if(!sasl_digest_get_key_value((char *)chlg, "realm=\"", realm, rlen, '\"')) {
  438. /* Challenge does not have a realm, set empty string [RFC2831] page 6 */
  439. strcpy(realm, "");
  440. }
  441. /* Retrieve algorithm string from the challenge */
  442. if(!sasl_digest_get_key_value((char *)chlg, "algorithm=", alg, alen, ',')) {
  443. Curl_safefree(chlg);
  444. return CURLE_BAD_CONTENT_ENCODING;
  445. }
  446. /* Retrieve qop-options string from the challenge */
  447. if(!sasl_digest_get_key_value((char *)chlg, "qop=\"", qop, qlen, '\"')) {
  448. Curl_safefree(chlg);
  449. return CURLE_BAD_CONTENT_ENCODING;
  450. }
  451. Curl_safefree(chlg);
  452. return CURLE_OK;
  453. }
  454. /*
  455. * Curl_sasl_create_digest_md5_message()
  456. *
  457. * This is used to generate an already encoded DIGEST-MD5 response message
  458. * ready for sending to the recipient.
  459. *
  460. * Parameters:
  461. *
  462. * data [in] - The session handle.
  463. * chlg64 [in] - The base64 encoded challenge message.
  464. * userp [in] - The user name.
  465. * passdwp [in] - The user's password.
  466. * service [in] - The service type such as www, smtp, pop or imap.
  467. * outptr [in/out] - The address where a pointer to newly allocated memory
  468. * holding the result will be stored upon completion.
  469. * outlen [out] - The length of the output message.
  470. *
  471. * Returns CURLE_OK on success.
  472. */
  473. CURLcode Curl_sasl_create_digest_md5_message(struct SessionHandle *data,
  474. const char *chlg64,
  475. const char *userp,
  476. const char *passwdp,
  477. const char *service,
  478. char **outptr, size_t *outlen)
  479. {
  480. CURLcode result = CURLE_OK;
  481. size_t i;
  482. MD5_context *ctxt;
  483. char *response = NULL;
  484. unsigned char digest[MD5_DIGEST_LEN];
  485. char HA1_hex[2 * MD5_DIGEST_LEN + 1];
  486. char HA2_hex[2 * MD5_DIGEST_LEN + 1];
  487. char resp_hash_hex[2 * MD5_DIGEST_LEN + 1];
  488. char nonce[64];
  489. char realm[128];
  490. char algorithm[64];
  491. char qop_options[64];
  492. int qop_values;
  493. char cnonce[33];
  494. unsigned int entropy[4];
  495. char nonceCount[] = "00000001";
  496. char method[] = "AUTHENTICATE";
  497. char qop[] = DIGEST_QOP_VALUE_STRING_AUTH;
  498. char *spn = NULL;
  499. /* Decode the challange message */
  500. result = sasl_decode_digest_md5_message(chlg64, nonce, sizeof(nonce),
  501. realm, sizeof(realm),
  502. algorithm, sizeof(algorithm),
  503. qop_options, sizeof(qop_options));
  504. if(result)
  505. return result;
  506. /* We only support md5 sessions */
  507. if(strcmp(algorithm, "md5-sess") != 0)
  508. return CURLE_BAD_CONTENT_ENCODING;
  509. /* Get the qop-values from the qop-options */
  510. result = sasl_digest_get_qop_values(qop_options, &qop_values);
  511. if(result)
  512. return result;
  513. /* We only support auth quality-of-protection */
  514. if(!(qop_values & DIGEST_QOP_VALUE_AUTH))
  515. return CURLE_BAD_CONTENT_ENCODING;
  516. /* Generate 16 bytes of random data */
  517. entropy[0] = Curl_rand(data);
  518. entropy[1] = Curl_rand(data);
  519. entropy[2] = Curl_rand(data);
  520. entropy[3] = Curl_rand(data);
  521. /* Convert the random data into a 32 byte hex string */
  522. snprintf(cnonce, sizeof(cnonce), "%08x%08x%08x%08x",
  523. entropy[0], entropy[1], entropy[2], entropy[3]);
  524. /* So far so good, now calculate A1 and H(A1) according to RFC 2831 */
  525. ctxt = Curl_MD5_init(Curl_DIGEST_MD5);
  526. if(!ctxt)
  527. return CURLE_OUT_OF_MEMORY;
  528. Curl_MD5_update(ctxt, (const unsigned char *) userp,
  529. curlx_uztoui(strlen(userp)));
  530. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  531. Curl_MD5_update(ctxt, (const unsigned char *) realm,
  532. curlx_uztoui(strlen(realm)));
  533. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  534. Curl_MD5_update(ctxt, (const unsigned char *) passwdp,
  535. curlx_uztoui(strlen(passwdp)));
  536. Curl_MD5_final(ctxt, digest);
  537. ctxt = Curl_MD5_init(Curl_DIGEST_MD5);
  538. if(!ctxt)
  539. return CURLE_OUT_OF_MEMORY;
  540. Curl_MD5_update(ctxt, (const unsigned char *) digest, MD5_DIGEST_LEN);
  541. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  542. Curl_MD5_update(ctxt, (const unsigned char *) nonce,
  543. curlx_uztoui(strlen(nonce)));
  544. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  545. Curl_MD5_update(ctxt, (const unsigned char *) cnonce,
  546. curlx_uztoui(strlen(cnonce)));
  547. Curl_MD5_final(ctxt, digest);
  548. /* Convert calculated 16 octet hex into 32 bytes string */
  549. for(i = 0; i < MD5_DIGEST_LEN; i++)
  550. snprintf(&HA1_hex[2 * i], 3, "%02x", digest[i]);
  551. /* Generate our SPN */
  552. spn = Curl_sasl_build_spn(service, realm);
  553. if(!spn)
  554. return CURLE_OUT_OF_MEMORY;
  555. /* Calculate H(A2) */
  556. ctxt = Curl_MD5_init(Curl_DIGEST_MD5);
  557. if(!ctxt) {
  558. Curl_safefree(spn);
  559. return CURLE_OUT_OF_MEMORY;
  560. }
  561. Curl_MD5_update(ctxt, (const unsigned char *) method,
  562. curlx_uztoui(strlen(method)));
  563. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  564. Curl_MD5_update(ctxt, (const unsigned char *) spn,
  565. curlx_uztoui(strlen(spn)));
  566. Curl_MD5_final(ctxt, digest);
  567. for(i = 0; i < MD5_DIGEST_LEN; i++)
  568. snprintf(&HA2_hex[2 * i], 3, "%02x", digest[i]);
  569. /* Now calculate the response hash */
  570. ctxt = Curl_MD5_init(Curl_DIGEST_MD5);
  571. if(!ctxt) {
  572. Curl_safefree(spn);
  573. return CURLE_OUT_OF_MEMORY;
  574. }
  575. Curl_MD5_update(ctxt, (const unsigned char *) HA1_hex, 2 * MD5_DIGEST_LEN);
  576. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  577. Curl_MD5_update(ctxt, (const unsigned char *) nonce,
  578. curlx_uztoui(strlen(nonce)));
  579. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  580. Curl_MD5_update(ctxt, (const unsigned char *) nonceCount,
  581. curlx_uztoui(strlen(nonceCount)));
  582. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  583. Curl_MD5_update(ctxt, (const unsigned char *) cnonce,
  584. curlx_uztoui(strlen(cnonce)));
  585. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  586. Curl_MD5_update(ctxt, (const unsigned char *) qop,
  587. curlx_uztoui(strlen(qop)));
  588. Curl_MD5_update(ctxt, (const unsigned char *) ":", 1);
  589. Curl_MD5_update(ctxt, (const unsigned char *) HA2_hex, 2 * MD5_DIGEST_LEN);
  590. Curl_MD5_final(ctxt, digest);
  591. for(i = 0; i < MD5_DIGEST_LEN; i++)
  592. snprintf(&resp_hash_hex[2 * i], 3, "%02x", digest[i]);
  593. /* Generate the response */
  594. response = aprintf("username=\"%s\",realm=\"%s\",nonce=\"%s\","
  595. "cnonce=\"%s\",nc=\"%s\",digest-uri=\"%s\",response=%s,"
  596. "qop=%s",
  597. userp, realm, nonce,
  598. cnonce, nonceCount, spn, resp_hash_hex, qop);
  599. Curl_safefree(spn);
  600. if(!response)
  601. return CURLE_OUT_OF_MEMORY;
  602. /* Base64 encode the response */
  603. result = Curl_base64_encode(data, response, 0, outptr, outlen);
  604. Curl_safefree(response);
  605. return result;
  606. }
  607. /*
  608. * Curl_sasl_decode_digest_http_message()
  609. *
  610. * This is used to decode a HTTP DIGEST challenge message into the seperate
  611. * attributes.
  612. *
  613. * Parameters:
  614. *
  615. * chlg [in] - The challenge message.
  616. * digest [in/out] - The digest data struct being used and modified.
  617. *
  618. * Returns CURLE_OK on success.
  619. */
  620. CURLcode Curl_sasl_decode_digest_http_message(const char *chlg,
  621. struct digestdata *digest)
  622. {
  623. bool before = FALSE; /* got a nonce before */
  624. bool foundAuth = FALSE;
  625. bool foundAuthInt = FALSE;
  626. char *token = NULL;
  627. char *tmp = NULL;
  628. /* If we already have received a nonce, keep that in mind */
  629. if(digest->nonce)
  630. before = TRUE;
  631. /* Clean up any former leftovers and initialise to defaults */
  632. Curl_sasl_digest_cleanup(digest);
  633. for(;;) {
  634. char value[DIGEST_MAX_VALUE_LENGTH];
  635. char content[DIGEST_MAX_CONTENT_LENGTH];
  636. /* Pass all additional spaces here */
  637. while(*chlg && ISSPACE(*chlg))
  638. chlg++;
  639. /* Extract a value=content pair */
  640. if(!sasl_digest_get_pair(chlg, value, content, &chlg)) {
  641. if(Curl_raw_equal(value, "nonce")) {
  642. digest->nonce = strdup(content);
  643. if(!digest->nonce)
  644. return CURLE_OUT_OF_MEMORY;
  645. }
  646. else if(Curl_raw_equal(value, "stale")) {
  647. if(Curl_raw_equal(content, "true")) {
  648. digest->stale = TRUE;
  649. digest->nc = 1; /* we make a new nonce now */
  650. }
  651. }
  652. else if(Curl_raw_equal(value, "realm")) {
  653. digest->realm = strdup(content);
  654. if(!digest->realm)
  655. return CURLE_OUT_OF_MEMORY;
  656. }
  657. else if(Curl_raw_equal(value, "opaque")) {
  658. digest->opaque = strdup(content);
  659. if(!digest->opaque)
  660. return CURLE_OUT_OF_MEMORY;
  661. }
  662. else if(Curl_raw_equal(value, "qop")) {
  663. char *tok_buf;
  664. /* Tokenize the list and choose auth if possible, use a temporary
  665. clone of the buffer since strtok_r() ruins it */
  666. tmp = strdup(content);
  667. if(!tmp)
  668. return CURLE_OUT_OF_MEMORY;
  669. token = strtok_r(tmp, ",", &tok_buf);
  670. while(token != NULL) {
  671. if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH)) {
  672. foundAuth = TRUE;
  673. }
  674. else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) {
  675. foundAuthInt = TRUE;
  676. }
  677. token = strtok_r(NULL, ",", &tok_buf);
  678. }
  679. free(tmp);
  680. /* Select only auth or auth-int. Otherwise, ignore */
  681. if(foundAuth) {
  682. digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH);
  683. if(!digest->qop)
  684. return CURLE_OUT_OF_MEMORY;
  685. }
  686. else if(foundAuthInt) {
  687. digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH_INT);
  688. if(!digest->qop)
  689. return CURLE_OUT_OF_MEMORY;
  690. }
  691. }
  692. else if(Curl_raw_equal(value, "algorithm")) {
  693. digest->algorithm = strdup(content);
  694. if(!digest->algorithm)
  695. return CURLE_OUT_OF_MEMORY;
  696. if(Curl_raw_equal(content, "MD5-sess"))
  697. digest->algo = CURLDIGESTALGO_MD5SESS;
  698. else if(Curl_raw_equal(content, "MD5"))
  699. digest->algo = CURLDIGESTALGO_MD5;
  700. else
  701. return CURLE_BAD_CONTENT_ENCODING;
  702. }
  703. else {
  704. /* unknown specifier, ignore it! */
  705. }
  706. }
  707. else
  708. break; /* we're done here */
  709. /* Pass all additional spaces here */
  710. while(*chlg && ISSPACE(*chlg))
  711. chlg++;
  712. /* Allow the list to be comma-separated */
  713. if(',' == *chlg)
  714. chlg++;
  715. }
  716. /* We had a nonce since before, and we got another one now without
  717. 'stale=true'. This means we provided bad credentials in the previous
  718. request */
  719. if(before && !digest->stale)
  720. return CURLE_BAD_CONTENT_ENCODING;
  721. /* We got this header without a nonce, that's a bad Digest line! */
  722. if(!digest->nonce)
  723. return CURLE_BAD_CONTENT_ENCODING;
  724. return CURLE_OK;
  725. }
  726. /*
  727. * Curl_sasl_create_digest_http_message()
  728. *
  729. * This is used to generate a HTTP DIGEST response message ready for sending
  730. * to the recipient.
  731. *
  732. * Parameters:
  733. *
  734. * data [in] - The session handle.
  735. * userp [in] - The user name.
  736. * passdwp [in] - The user's password.
  737. * request [in] - The HTTP request.
  738. * uripath [in] - The path of the HTTP uri.
  739. * digest [in/out] - The digest data struct being used and modified.
  740. * outptr [in/out] - The address where a pointer to newly allocated memory
  741. * holding the result will be stored upon completion.
  742. * outlen [out] - The length of the output message.
  743. *
  744. * Returns CURLE_OK on success.
  745. */
  746. CURLcode Curl_sasl_create_digest_http_message(struct SessionHandle *data,
  747. const char *userp,
  748. const char *passwdp,
  749. const unsigned char *request,
  750. const unsigned char *uripath,
  751. struct digestdata *digest,
  752. char **outptr, size_t *outlen)
  753. {
  754. CURLcode result;
  755. unsigned char md5buf[16]; /* 16 bytes/128 bits */
  756. unsigned char request_digest[33];
  757. unsigned char *md5this;
  758. unsigned char ha1[33];/* 32 digits and 1 zero byte */
  759. unsigned char ha2[33];/* 32 digits and 1 zero byte */
  760. char cnoncebuf[33];
  761. char *cnonce = NULL;
  762. size_t cnonce_sz = 0;
  763. char *userp_quoted;
  764. char *response = NULL;
  765. char *tmp = NULL;
  766. if(!digest->nc)
  767. digest->nc = 1;
  768. if(!digest->cnonce) {
  769. snprintf(cnoncebuf, sizeof(cnoncebuf), "%08x%08x%08x%08x",
  770. Curl_rand(data), Curl_rand(data),
  771. Curl_rand(data), Curl_rand(data));
  772. result = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf),
  773. &cnonce, &cnonce_sz);
  774. if(result)
  775. return result;
  776. digest->cnonce = cnonce;
  777. }
  778. /*
  779. if the algorithm is "MD5" or unspecified (which then defaults to MD5):
  780. A1 = unq(username-value) ":" unq(realm-value) ":" passwd
  781. if the algorithm is "MD5-sess" then:
  782. A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
  783. ":" unq(nonce-value) ":" unq(cnonce-value)
  784. */
  785. md5this = (unsigned char *)
  786. aprintf("%s:%s:%s", userp, digest->realm, passwdp);
  787. if(!md5this)
  788. return CURLE_OUT_OF_MEMORY;
  789. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  790. Curl_md5it(md5buf, md5this);
  791. Curl_safefree(md5this);
  792. sasl_digest_md5_to_ascii(md5buf, ha1);
  793. if(digest->algo == CURLDIGESTALGO_MD5SESS) {
  794. /* nonce and cnonce are OUTSIDE the hash */
  795. tmp = aprintf("%s:%s:%s", ha1, digest->nonce, digest->cnonce);
  796. if(!tmp)
  797. return CURLE_OUT_OF_MEMORY;
  798. CURL_OUTPUT_DIGEST_CONV(data, tmp); /* convert on non-ASCII machines */
  799. Curl_md5it(md5buf, (unsigned char *)tmp);
  800. Curl_safefree(tmp);
  801. sasl_digest_md5_to_ascii(md5buf, ha1);
  802. }
  803. /*
  804. If the "qop" directive's value is "auth" or is unspecified, then A2 is:
  805. A2 = Method ":" digest-uri-value
  806. If the "qop" value is "auth-int", then A2 is:
  807. A2 = Method ":" digest-uri-value ":" H(entity-body)
  808. (The "Method" value is the HTTP request method as specified in section
  809. 5.1.1 of RFC 2616)
  810. */
  811. md5this = (unsigned char *)aprintf("%s:%s", request, uripath);
  812. if(digest->qop && Curl_raw_equal(digest->qop, "auth-int")) {
  813. /* We don't support auth-int for PUT or POST at the moment.
  814. TODO: replace md5 of empty string with entity-body for PUT/POST */
  815. unsigned char *md5this2 = (unsigned char *)
  816. aprintf("%s:%s", md5this, "d41d8cd98f00b204e9800998ecf8427e");
  817. Curl_safefree(md5this);
  818. md5this = md5this2;
  819. }
  820. if(!md5this)
  821. return CURLE_OUT_OF_MEMORY;
  822. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  823. Curl_md5it(md5buf, md5this);
  824. Curl_safefree(md5this);
  825. sasl_digest_md5_to_ascii(md5buf, ha2);
  826. if(digest->qop) {
  827. md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s",
  828. ha1,
  829. digest->nonce,
  830. digest->nc,
  831. digest->cnonce,
  832. digest->qop,
  833. ha2);
  834. }
  835. else {
  836. md5this = (unsigned char *)aprintf("%s:%s:%s",
  837. ha1,
  838. digest->nonce,
  839. ha2);
  840. }
  841. if(!md5this)
  842. return CURLE_OUT_OF_MEMORY;
  843. CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */
  844. Curl_md5it(md5buf, md5this);
  845. Curl_safefree(md5this);
  846. sasl_digest_md5_to_ascii(md5buf, request_digest);
  847. /* for test case 64 (snooped from a Mozilla 1.3a request)
  848. Authorization: Digest username="testuser", realm="testrealm", \
  849. nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca"
  850. Digest parameters are all quoted strings. Username which is provided by
  851. the user will need double quotes and backslashes within it escaped. For
  852. the other fields, this shouldn't be an issue. realm, nonce, and opaque
  853. are copied as is from the server, escapes and all. cnonce is generated
  854. with web-safe characters. uri is already percent encoded. nc is 8 hex
  855. characters. algorithm and qop with standard values only contain web-safe
  856. chracters.
  857. */
  858. userp_quoted = sasl_digest_string_quoted(userp);
  859. if(!userp_quoted)
  860. return CURLE_OUT_OF_MEMORY;
  861. if(digest->qop) {
  862. response = aprintf("username=\"%s\", "
  863. "realm=\"%s\", "
  864. "nonce=\"%s\", "
  865. "uri=\"%s\", "
  866. "cnonce=\"%s\", "
  867. "nc=%08x, "
  868. "qop=%s, "
  869. "response=\"%s\"",
  870. userp_quoted,
  871. digest->realm,
  872. digest->nonce,
  873. uripath,
  874. digest->cnonce,
  875. digest->nc,
  876. digest->qop,
  877. request_digest);
  878. if(Curl_raw_equal(digest->qop, "auth"))
  879. digest->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0
  880. padded which tells to the server how many times you are
  881. using the same nonce in the qop=auth mode */
  882. }
  883. else {
  884. response = aprintf("username=\"%s\", "
  885. "realm=\"%s\", "
  886. "nonce=\"%s\", "
  887. "uri=\"%s\", "
  888. "response=\"%s\"",
  889. userp_quoted,
  890. digest->realm,
  891. digest->nonce,
  892. uripath,
  893. request_digest);
  894. }
  895. Curl_safefree(userp_quoted);
  896. if(!response)
  897. return CURLE_OUT_OF_MEMORY;
  898. /* Add the optional fields */
  899. if(digest->opaque) {
  900. /* Append the opaque */
  901. tmp = aprintf("%s, opaque=\"%s\"", response, digest->opaque);
  902. free(response);
  903. if(!tmp)
  904. return CURLE_OUT_OF_MEMORY;
  905. response = tmp;
  906. }
  907. if(digest->algorithm) {
  908. /* Append the algorithm */
  909. tmp = aprintf("%s, algorithm=\"%s\"", response, digest->algorithm);
  910. free(response);
  911. if(!tmp)
  912. return CURLE_OUT_OF_MEMORY;
  913. response = tmp;
  914. }
  915. /* Return the output */
  916. *outptr = response;
  917. *outlen = strlen(response);
  918. return CURLE_OK;
  919. }
  920. /*
  921. * Curl_sasl_digest_cleanup()
  922. *
  923. * This is used to clean up the digest specific data.
  924. *
  925. * Parameters:
  926. *
  927. * digest [in/out] - The digest data struct being cleaned up.
  928. *
  929. */
  930. void Curl_sasl_digest_cleanup(struct digestdata *digest)
  931. {
  932. Curl_safefree(digest->nonce);
  933. Curl_safefree(digest->cnonce);
  934. Curl_safefree(digest->realm);
  935. Curl_safefree(digest->opaque);
  936. Curl_safefree(digest->qop);
  937. Curl_safefree(digest->algorithm);
  938. digest->nc = 0;
  939. digest->algo = CURLDIGESTALGO_MD5; /* default algorithm */
  940. digest->stale = FALSE; /* default means normal, not stale */
  941. }
  942. #endif /* !USE_WINDOWS_SSPI */
  943. #endif /* CURL_DISABLE_CRYPTO_AUTH */
  944. #if defined(USE_NTLM) && !defined(USE_WINDOWS_SSPI)
  945. /*
  946. * Curl_sasl_ntlm_cleanup()
  947. *
  948. * This is used to clean up the ntlm specific data.
  949. *
  950. * Parameters:
  951. *
  952. * ntlm [in/out] - The ntlm data struct being cleaned up.
  953. *
  954. */
  955. void Curl_sasl_ntlm_cleanup(struct ntlmdata *ntlm)
  956. {
  957. /* Free the target info */
  958. Curl_safefree(ntlm->target_info);
  959. /* Reset any variables */
  960. ntlm->target_info_len = 0;
  961. }
  962. #endif /* USE_NTLM && !USE_WINDOWS_SSPI*/
  963. /*
  964. * Curl_sasl_create_xoauth2_message()
  965. *
  966. * This is used to generate an already encoded OAuth 2.0 message ready for
  967. * sending to the recipient.
  968. *
  969. * Parameters:
  970. *
  971. * data [in] - The session handle.
  972. * user [in] - The user name.
  973. * bearer [in] - The bearer token.
  974. * outptr [in/out] - The address where a pointer to newly allocated memory
  975. * holding the result will be stored upon completion.
  976. * outlen [out] - The length of the output message.
  977. *
  978. * Returns CURLE_OK on success.
  979. */
  980. CURLcode Curl_sasl_create_xoauth2_message(struct SessionHandle *data,
  981. const char *user,
  982. const char *bearer,
  983. char **outptr, size_t *outlen)
  984. {
  985. CURLcode result = CURLE_OK;
  986. char *xoauth = NULL;
  987. /* Generate the message */
  988. xoauth = aprintf("user=%s\1auth=Bearer %s\1\1", user, bearer);
  989. if(!xoauth)
  990. return CURLE_OUT_OF_MEMORY;
  991. /* Base64 encode the reply */
  992. result = Curl_base64_encode(data, xoauth, strlen(xoauth), outptr, outlen);
  993. Curl_safefree(xoauth);
  994. return result;
  995. }
  996. /*
  997. * Curl_sasl_cleanup()
  998. *
  999. * This is used to cleanup any libraries or curl modules used by the sasl
  1000. * functions.
  1001. *
  1002. * Parameters:
  1003. *
  1004. * conn [in] - The connection data.
  1005. * authused [in] - The authentication mechanism used.
  1006. */
  1007. void Curl_sasl_cleanup(struct connectdata *conn, unsigned int authused)
  1008. {
  1009. #if defined(USE_KERBEROS5)
  1010. /* Cleanup the gssapi structure */
  1011. if(authused == SASL_MECH_GSSAPI) {
  1012. Curl_sasl_gssapi_cleanup(&conn->krb5);
  1013. }
  1014. #endif
  1015. #if defined(USE_NTLM)
  1016. /* Cleanup the ntlm structure */
  1017. if(authused == SASL_MECH_NTLM) {
  1018. Curl_sasl_ntlm_cleanup(&conn->ntlm);
  1019. }
  1020. #endif
  1021. #if !defined(USE_KERBEROS5) && !defined(USE_NTLM)
  1022. /* Reserved for future use */
  1023. (void)conn;
  1024. (void)authused;
  1025. #endif
  1026. }