http_aws_sigv4.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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 https://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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_AWS)
  26. #include "urldata.h"
  27. #include "strcase.h"
  28. #include "strdup.h"
  29. #include "http_aws_sigv4.h"
  30. #include "curl_sha256.h"
  31. #include "transfer.h"
  32. #include "parsedate.h"
  33. #include "sendf.h"
  34. #include "escape.h"
  35. #include "strparse.h"
  36. #include <time.h>
  37. /* The last 3 #include files should be in this order */
  38. #include "curl_printf.h"
  39. #include "curl_memory.h"
  40. #include "memdebug.h"
  41. #include "slist.h"
  42. #define HMAC_SHA256(k, kl, d, dl, o) \
  43. do { \
  44. result = Curl_hmacit(&Curl_HMAC_SHA256, \
  45. (unsigned char *)k, \
  46. kl, \
  47. (unsigned char *)d, \
  48. dl, o); \
  49. if(result) { \
  50. goto fail; \
  51. } \
  52. } while(0)
  53. #define TIMESTAMP_SIZE 17
  54. /* hex-encoded with trailing null */
  55. #define SHA256_HEX_LENGTH (2 * CURL_SHA256_DIGEST_LENGTH + 1)
  56. static void sha256_to_hex(char *dst, unsigned char *sha)
  57. {
  58. Curl_hexencode(sha, CURL_SHA256_DIGEST_LENGTH,
  59. (unsigned char *)dst, SHA256_HEX_LENGTH);
  60. }
  61. static char *find_date_hdr(struct Curl_easy *data, const char *sig_hdr)
  62. {
  63. char *tmp = Curl_checkheaders(data, sig_hdr, strlen(sig_hdr));
  64. if(tmp)
  65. return tmp;
  66. return Curl_checkheaders(data, STRCONST("Date"));
  67. }
  68. /* remove whitespace, and lowercase all headers */
  69. static void trim_headers(struct curl_slist *head)
  70. {
  71. struct curl_slist *l;
  72. for(l = head; l; l = l->next) {
  73. char *value; /* to read from */
  74. char *store;
  75. size_t colon = strcspn(l->data, ":");
  76. Curl_strntolower(l->data, l->data, colon);
  77. value = &l->data[colon];
  78. if(!*value)
  79. continue;
  80. ++value;
  81. store = value;
  82. /* skip leading whitespace */
  83. while(*value && ISBLANK(*value))
  84. value++;
  85. while(*value) {
  86. int space = 0;
  87. while(*value && ISBLANK(*value)) {
  88. value++;
  89. space++;
  90. }
  91. if(space) {
  92. /* replace any number of consecutive whitespace with a single space,
  93. unless at the end of the string, then nothing */
  94. if(*value)
  95. *store++ = ' ';
  96. }
  97. else
  98. *store++ = *value++;
  99. }
  100. *store = 0; /* null terminate */
  101. }
  102. }
  103. /* maximum length for the aws sivg4 parts */
  104. #define MAX_SIGV4_LEN 64
  105. #define DATE_HDR_KEY_LEN (MAX_SIGV4_LEN + sizeof("X--Date"))
  106. /* string been x-PROVIDER-date:TIMESTAMP, I need +1 for ':' */
  107. #define DATE_FULL_HDR_LEN (DATE_HDR_KEY_LEN + TIMESTAMP_SIZE + 1)
  108. /* alphabetically compare two headers by their name, expecting
  109. headers to use ':' at this point */
  110. static int compare_header_names(const char *a, const char *b)
  111. {
  112. const char *colon_a;
  113. const char *colon_b;
  114. size_t len_a;
  115. size_t len_b;
  116. size_t min_len;
  117. int cmp;
  118. colon_a = strchr(a, ':');
  119. colon_b = strchr(b, ':');
  120. DEBUGASSERT(colon_a);
  121. DEBUGASSERT(colon_b);
  122. len_a = colon_a ? (size_t)(colon_a - a) : strlen(a);
  123. len_b = colon_b ? (size_t)(colon_b - b) : strlen(b);
  124. min_len = (len_a < len_b) ? len_a : len_b;
  125. cmp = strncmp(a, b, min_len);
  126. /* return the shorter of the two if one is shorter */
  127. if(!cmp)
  128. return (int)(len_a - len_b);
  129. return cmp;
  130. }
  131. /* timestamp should point to a buffer of at last TIMESTAMP_SIZE bytes */
  132. static CURLcode make_headers(struct Curl_easy *data,
  133. const char *hostname,
  134. char *timestamp,
  135. const char *provider1,
  136. size_t plen, /* length of provider1 */
  137. char **date_header,
  138. char *content_sha256_header,
  139. struct dynbuf *canonical_headers,
  140. struct dynbuf *signed_headers)
  141. {
  142. char date_hdr_key[DATE_HDR_KEY_LEN];
  143. char date_full_hdr[DATE_FULL_HDR_LEN];
  144. struct curl_slist *head = NULL;
  145. struct curl_slist *tmp_head = NULL;
  146. CURLcode ret = CURLE_OUT_OF_MEMORY;
  147. struct curl_slist *l;
  148. bool again = TRUE;
  149. msnprintf(date_hdr_key, DATE_HDR_KEY_LEN, "X-%.*s-Date",
  150. (int)plen, provider1);
  151. /* provider1 ucfirst */
  152. Curl_strntolower(&date_hdr_key[2], provider1, plen);
  153. date_hdr_key[2] = Curl_raw_toupper(provider1[0]);
  154. msnprintf(date_full_hdr, DATE_FULL_HDR_LEN,
  155. "x-%.*s-date:%s", (int)plen, provider1, timestamp);
  156. /* provider1 lowercase */
  157. Curl_strntolower(&date_full_hdr[2], provider1, plen);
  158. if(!Curl_checkheaders(data, STRCONST("Host"))) {
  159. char *fullhost;
  160. if(data->state.aptr.host) {
  161. /* remove /r/n as the separator for canonical request must be '\n' */
  162. size_t pos = strcspn(data->state.aptr.host, "\n\r");
  163. fullhost = Curl_memdup0(data->state.aptr.host, pos);
  164. }
  165. else
  166. fullhost = aprintf("host:%s", hostname);
  167. if(fullhost)
  168. head = Curl_slist_append_nodup(NULL, fullhost);
  169. if(!head) {
  170. free(fullhost);
  171. goto fail;
  172. }
  173. }
  174. if(*content_sha256_header) {
  175. tmp_head = curl_slist_append(head, content_sha256_header);
  176. if(!tmp_head)
  177. goto fail;
  178. head = tmp_head;
  179. }
  180. /* copy user headers to our header list. the logic is based on how http.c
  181. handles user headers.
  182. user headers in format 'name:' with no value are used to signal that an
  183. internal header of that name should be removed. those user headers are not
  184. added to this list.
  185. user headers in format 'name;' with no value are used to signal that a
  186. header of that name with no value should be sent. those user headers are
  187. added to this list but in the format that they will be sent, ie the
  188. semi-colon is changed to a colon for format 'name:'.
  189. user headers with a value of whitespace only, or without a colon or
  190. semi-colon, are not added to this list.
  191. */
  192. for(l = data->set.headers; l; l = l->next) {
  193. char *dupdata, *ptr;
  194. char *sep = strchr(l->data, ':');
  195. if(!sep)
  196. sep = strchr(l->data, ';');
  197. if(!sep || (*sep == ':' && !*(sep + 1)))
  198. continue;
  199. for(ptr = sep + 1; ISSPACE(*ptr); ++ptr)
  200. ;
  201. if(!*ptr && ptr != sep + 1) /* a value of whitespace only */
  202. continue;
  203. dupdata = strdup(l->data);
  204. if(!dupdata)
  205. goto fail;
  206. dupdata[sep - l->data] = ':';
  207. tmp_head = Curl_slist_append_nodup(head, dupdata);
  208. if(!tmp_head) {
  209. free(dupdata);
  210. goto fail;
  211. }
  212. head = tmp_head;
  213. }
  214. trim_headers(head);
  215. *date_header = find_date_hdr(data, date_hdr_key);
  216. if(!*date_header) {
  217. tmp_head = curl_slist_append(head, date_full_hdr);
  218. if(!tmp_head)
  219. goto fail;
  220. head = tmp_head;
  221. *date_header = aprintf("%s: %s\r\n", date_hdr_key, timestamp);
  222. }
  223. else {
  224. char *value;
  225. char *endp;
  226. value = strchr(*date_header, ':');
  227. if(!value) {
  228. *date_header = NULL;
  229. goto fail;
  230. }
  231. ++value;
  232. while(ISBLANK(*value))
  233. ++value;
  234. endp = value;
  235. while(*endp && ISALNUM(*endp))
  236. ++endp;
  237. /* 16 bytes => "19700101T000000Z" */
  238. if((endp - value) == TIMESTAMP_SIZE - 1) {
  239. memcpy(timestamp, value, TIMESTAMP_SIZE - 1);
  240. timestamp[TIMESTAMP_SIZE - 1] = 0;
  241. }
  242. else
  243. /* bad timestamp length */
  244. timestamp[0] = 0;
  245. *date_header = NULL;
  246. }
  247. /* alpha-sort by header name in a case sensitive manner */
  248. do {
  249. again = FALSE;
  250. for(l = head; l; l = l->next) {
  251. struct curl_slist *next = l->next;
  252. if(next && compare_header_names(l->data, next->data) > 0) {
  253. char *tmp = l->data;
  254. l->data = next->data;
  255. next->data = tmp;
  256. again = TRUE;
  257. }
  258. }
  259. } while(again);
  260. for(l = head; l; l = l->next) {
  261. char *tmp;
  262. if(Curl_dyn_add(canonical_headers, l->data))
  263. goto fail;
  264. if(Curl_dyn_add(canonical_headers, "\n"))
  265. goto fail;
  266. tmp = strchr(l->data, ':');
  267. if(tmp)
  268. *tmp = 0;
  269. if(l != head) {
  270. if(Curl_dyn_add(signed_headers, ";"))
  271. goto fail;
  272. }
  273. if(Curl_dyn_add(signed_headers, l->data))
  274. goto fail;
  275. }
  276. ret = CURLE_OK;
  277. fail:
  278. curl_slist_free_all(head);
  279. return ret;
  280. }
  281. #define CONTENT_SHA256_KEY_LEN (MAX_SIGV4_LEN + sizeof("X--Content-Sha256"))
  282. /* add 2 for ": " between header name and value */
  283. #define CONTENT_SHA256_HDR_LEN (CONTENT_SHA256_KEY_LEN + 2 + \
  284. SHA256_HEX_LENGTH)
  285. /* try to parse a payload hash from the content-sha256 header */
  286. static char *parse_content_sha_hdr(struct Curl_easy *data,
  287. const char *provider1,
  288. size_t plen,
  289. size_t *value_len)
  290. {
  291. char key[CONTENT_SHA256_KEY_LEN];
  292. size_t key_len;
  293. char *value;
  294. size_t len;
  295. key_len = msnprintf(key, sizeof(key), "x-%.*s-content-sha256",
  296. (int)plen, provider1);
  297. value = Curl_checkheaders(data, key, key_len);
  298. if(!value)
  299. return NULL;
  300. value = strchr(value, ':');
  301. if(!value)
  302. return NULL;
  303. ++value;
  304. while(*value && ISBLANK(*value))
  305. ++value;
  306. len = strlen(value);
  307. while(len > 0 && ISBLANK(value[len-1]))
  308. --len;
  309. *value_len = len;
  310. return value;
  311. }
  312. static CURLcode calc_payload_hash(struct Curl_easy *data,
  313. unsigned char *sha_hash, char *sha_hex)
  314. {
  315. const char *post_data = data->set.postfields;
  316. size_t post_data_len = 0;
  317. CURLcode result;
  318. if(post_data) {
  319. if(data->set.postfieldsize < 0)
  320. post_data_len = strlen(post_data);
  321. else
  322. post_data_len = (size_t)data->set.postfieldsize;
  323. }
  324. result = Curl_sha256it(sha_hash, (const unsigned char *) post_data,
  325. post_data_len);
  326. if(!result)
  327. sha256_to_hex(sha_hex, sha_hash);
  328. return result;
  329. }
  330. #define S3_UNSIGNED_PAYLOAD "UNSIGNED-PAYLOAD"
  331. static CURLcode calc_s3_payload_hash(struct Curl_easy *data,
  332. Curl_HttpReq httpreq, char *provider1,
  333. size_t plen,
  334. unsigned char *sha_hash,
  335. char *sha_hex, char *header)
  336. {
  337. bool empty_method = (httpreq == HTTPREQ_GET || httpreq == HTTPREQ_HEAD);
  338. /* The request method or filesize indicate no request payload */
  339. bool empty_payload = (empty_method || data->set.filesize == 0);
  340. /* The POST payload is in memory */
  341. bool post_payload = (httpreq == HTTPREQ_POST && data->set.postfields);
  342. CURLcode ret = CURLE_OUT_OF_MEMORY;
  343. if(empty_payload || post_payload) {
  344. /* Calculate a real hash when we know the request payload */
  345. ret = calc_payload_hash(data, sha_hash, sha_hex);
  346. if(ret)
  347. goto fail;
  348. }
  349. else {
  350. /* Fall back to s3's UNSIGNED-PAYLOAD */
  351. size_t len = sizeof(S3_UNSIGNED_PAYLOAD) - 1;
  352. DEBUGASSERT(len < SHA256_HEX_LENGTH); /* 16 < 65 */
  353. memcpy(sha_hex, S3_UNSIGNED_PAYLOAD, len);
  354. sha_hex[len] = 0;
  355. }
  356. /* format the required content-sha256 header */
  357. msnprintf(header, CONTENT_SHA256_HDR_LEN,
  358. "x-%.*s-content-sha256: %s", (int)plen, provider1, sha_hex);
  359. ret = CURLE_OK;
  360. fail:
  361. return ret;
  362. }
  363. struct pair {
  364. const char *p;
  365. size_t len;
  366. };
  367. static int compare_func(const void *a, const void *b)
  368. {
  369. const struct pair *aa = a;
  370. const struct pair *bb = b;
  371. /* If one element is empty, the other is always sorted higher */
  372. if(aa->len == 0)
  373. return -1;
  374. if(bb->len == 0)
  375. return 1;
  376. return strncmp(aa->p, bb->p, aa->len < bb->len ? aa->len : bb->len);
  377. }
  378. #define MAX_QUERYPAIRS 64
  379. /**
  380. * found_equals have a double meaning,
  381. * detect if an equal have been found when called from canon_query,
  382. * and mark that this function is called to compute the path,
  383. * if found_equals is NULL.
  384. */
  385. static CURLcode canon_string(const char *q, size_t len,
  386. struct dynbuf *dq, bool *found_equals)
  387. {
  388. CURLcode result = CURLE_OK;
  389. for(; len && !result; q++, len--) {
  390. if(ISALNUM(*q))
  391. result = Curl_dyn_addn(dq, q, 1);
  392. else {
  393. switch(*q) {
  394. case '-':
  395. case '.':
  396. case '_':
  397. case '~':
  398. /* allowed as-is */
  399. result = Curl_dyn_addn(dq, q, 1);
  400. break;
  401. case '%':
  402. /* uppercase the following if hexadecimal */
  403. if(ISXDIGIT(q[1]) && ISXDIGIT(q[2])) {
  404. char tmp[3]="%";
  405. tmp[1] = Curl_raw_toupper(q[1]);
  406. tmp[2] = Curl_raw_toupper(q[2]);
  407. result = Curl_dyn_addn(dq, tmp, 3);
  408. q += 2;
  409. len -= 2;
  410. }
  411. else
  412. /* '%' without a following two-digit hex, encode it */
  413. result = Curl_dyn_addn(dq, "%25", 3);
  414. break;
  415. default: {
  416. const char hex[] = "0123456789ABCDEF";
  417. char out[3]={'%'};
  418. if(!found_equals) {
  419. /* if found_equals is NULL assuming, been in path */
  420. if(*q == '/') {
  421. /* allowed as if */
  422. result = Curl_dyn_addn(dq, q, 1);
  423. break;
  424. }
  425. }
  426. else {
  427. /* allowed as-is */
  428. if(*q == '=') {
  429. result = Curl_dyn_addn(dq, q, 1);
  430. *found_equals = TRUE;
  431. break;
  432. }
  433. }
  434. /* URL encode */
  435. out[1] = hex[((unsigned char)*q) >> 4];
  436. out[2] = hex[*q & 0xf];
  437. result = Curl_dyn_addn(dq, out, 3);
  438. break;
  439. }
  440. }
  441. }
  442. }
  443. return result;
  444. }
  445. static CURLcode canon_query(struct Curl_easy *data,
  446. const char *query, struct dynbuf *dq)
  447. {
  448. CURLcode result = CURLE_OK;
  449. int entry = 0;
  450. int i;
  451. const char *p = query;
  452. struct pair array[MAX_QUERYPAIRS];
  453. struct pair *ap = &array[0];
  454. if(!query)
  455. return result;
  456. /* sort the name=value pairs first */
  457. do {
  458. char *amp;
  459. entry++;
  460. ap->p = p;
  461. amp = strchr(p, '&');
  462. if(amp)
  463. ap->len = amp - p; /* excluding the ampersand */
  464. else {
  465. ap->len = strlen(p);
  466. break;
  467. }
  468. ap++;
  469. p = amp + 1;
  470. } while(entry < MAX_QUERYPAIRS);
  471. if(entry == MAX_QUERYPAIRS) {
  472. /* too many query pairs for us */
  473. failf(data, "aws-sigv4: too many query pairs in URL");
  474. return CURLE_URL_MALFORMAT;
  475. }
  476. qsort(&array[0], entry, sizeof(struct pair), compare_func);
  477. ap = &array[0];
  478. for(i = 0; !result && (i < entry); i++, ap++) {
  479. const char *q = ap->p;
  480. bool found_equals = FALSE;
  481. if(!ap->len)
  482. continue;
  483. result = canon_string(q, ap->len, dq, &found_equals);
  484. if(!result && !found_equals) {
  485. /* queries without value still need an equals */
  486. result = Curl_dyn_addn(dq, "=", 1);
  487. }
  488. if(!result && i < entry - 1) {
  489. /* insert ampersands between query pairs */
  490. result = Curl_dyn_addn(dq, "&", 1);
  491. }
  492. }
  493. return result;
  494. }
  495. CURLcode Curl_output_aws_sigv4(struct Curl_easy *data, bool proxy)
  496. {
  497. CURLcode result = CURLE_OUT_OF_MEMORY;
  498. struct connectdata *conn = data->conn;
  499. size_t len;
  500. char *line;
  501. struct Curl_str provider0;
  502. struct Curl_str provider1;
  503. struct Curl_str region = { NULL, 0};
  504. struct Curl_str service = { NULL, 0};
  505. const char *hostname = conn->host.name;
  506. time_t clock;
  507. struct tm tm;
  508. char timestamp[TIMESTAMP_SIZE];
  509. char date[9];
  510. struct dynbuf canonical_headers;
  511. struct dynbuf signed_headers;
  512. struct dynbuf canonical_query;
  513. struct dynbuf canonical_path;
  514. char *date_header = NULL;
  515. Curl_HttpReq httpreq;
  516. const char *method = NULL;
  517. char *payload_hash = NULL;
  518. size_t payload_hash_len = 0;
  519. unsigned char sha_hash[CURL_SHA256_DIGEST_LENGTH];
  520. char sha_hex[SHA256_HEX_LENGTH];
  521. char content_sha256_hdr[CONTENT_SHA256_HDR_LEN + 2] = ""; /* add \r\n */
  522. char *canonical_request = NULL;
  523. char *request_type = NULL;
  524. char *credential_scope = NULL;
  525. char *str_to_sign = NULL;
  526. const char *user = data->state.aptr.user ? data->state.aptr.user : "";
  527. char *secret = NULL;
  528. unsigned char sign0[CURL_SHA256_DIGEST_LENGTH] = {0};
  529. unsigned char sign1[CURL_SHA256_DIGEST_LENGTH] = {0};
  530. char *auth_headers = NULL;
  531. DEBUGASSERT(!proxy);
  532. (void)proxy;
  533. if(Curl_checkheaders(data, STRCONST("Authorization"))) {
  534. /* Authorization already present, Bailing out */
  535. return CURLE_OK;
  536. }
  537. /* we init those buffers here, so goto fail will free initialized dynbuf */
  538. Curl_dyn_init(&canonical_headers, CURL_MAX_HTTP_HEADER);
  539. Curl_dyn_init(&canonical_query, CURL_MAX_HTTP_HEADER);
  540. Curl_dyn_init(&signed_headers, CURL_MAX_HTTP_HEADER);
  541. Curl_dyn_init(&canonical_path, CURL_MAX_HTTP_HEADER);
  542. /*
  543. * Parameters parsing
  544. * Google and Outscale use the same OSC or GOOG,
  545. * but Amazon uses AWS and AMZ for header arguments.
  546. * AWS is the default because most of non-amazon providers
  547. * are still using aws:amz as a prefix.
  548. */
  549. line = data->set.str[STRING_AWS_SIGV4] ?
  550. data->set.str[STRING_AWS_SIGV4] : (char *)"aws:amz";
  551. /* provider0[:provider1[:region[:service]]]
  552. No string can be longer than N bytes of non-whitespace
  553. */
  554. if(Curl_str_until(&line, &provider0, MAX_SIGV4_LEN, ':')) {
  555. failf(data, "first aws-sigv4 provider cannot be empty");
  556. result = CURLE_BAD_FUNCTION_ARGUMENT;
  557. goto fail;
  558. }
  559. if(Curl_str_single(&line, ':') ||
  560. Curl_str_until(&line, &provider1, MAX_SIGV4_LEN, ':')) {
  561. provider1.str = provider0.str;
  562. provider1.len = provider0.len;
  563. }
  564. else if(Curl_str_single(&line, ':') ||
  565. Curl_str_until(&line, &region, MAX_SIGV4_LEN, ':') ||
  566. Curl_str_single(&line, ':') ||
  567. Curl_str_until(&line, &service, MAX_SIGV4_LEN, ':')) {
  568. /* nothing to do */
  569. }
  570. if(!service.len) {
  571. char *hostdot = strchr(hostname, '.');
  572. if(!hostdot) {
  573. failf(data, "aws-sigv4: service missing in parameters and hostname");
  574. result = CURLE_URL_MALFORMAT;
  575. goto fail;
  576. }
  577. len = hostdot - hostname;
  578. if(len > MAX_SIGV4_LEN) {
  579. failf(data, "aws-sigv4: service too long in hostname");
  580. result = CURLE_URL_MALFORMAT;
  581. goto fail;
  582. }
  583. service.str = (char *)hostname;
  584. service.len = len;
  585. infof(data, "aws_sigv4: picked service %.*s from host",
  586. (int)service.len, service.str);
  587. if(!region.len) {
  588. const char *reg = hostdot + 1;
  589. const char *hostreg = strchr(reg, '.');
  590. if(!hostreg) {
  591. failf(data, "aws-sigv4: region missing in parameters and hostname");
  592. result = CURLE_URL_MALFORMAT;
  593. goto fail;
  594. }
  595. len = hostreg - reg;
  596. if(len > MAX_SIGV4_LEN) {
  597. failf(data, "aws-sigv4: region too long in hostname");
  598. result = CURLE_URL_MALFORMAT;
  599. goto fail;
  600. }
  601. region.str = (char *)reg;
  602. region.len = len;
  603. infof(data, "aws_sigv4: picked region %.*s from host",
  604. (int)region.len, region.str);
  605. }
  606. }
  607. Curl_http_method(data, conn, &method, &httpreq);
  608. payload_hash = parse_content_sha_hdr(data, provider1.str, provider1.len,
  609. &payload_hash_len);
  610. if(!payload_hash) {
  611. /* AWS S3 requires a x-amz-content-sha256 header, and supports special
  612. * values like UNSIGNED-PAYLOAD */
  613. bool sign_as_s3 = ((provider0.len == 3) &&
  614. strncasecompare(provider0.str, "aws", 3)) &&
  615. ((service.len == 2) && strncasecompare(service.str, "s3", 2));
  616. if(sign_as_s3)
  617. result = calc_s3_payload_hash(data, httpreq,
  618. provider1.str, provider1.len,
  619. sha_hash, sha_hex, content_sha256_hdr);
  620. else
  621. result = calc_payload_hash(data, sha_hash, sha_hex);
  622. if(result)
  623. goto fail;
  624. payload_hash = sha_hex;
  625. /* may be shorter than SHA256_HEX_LENGTH, like S3_UNSIGNED_PAYLOAD */
  626. payload_hash_len = strlen(sha_hex);
  627. }
  628. #ifdef DEBUGBUILD
  629. {
  630. char *force_timestamp = getenv("CURL_FORCETIME");
  631. if(force_timestamp)
  632. clock = 0;
  633. else
  634. clock = time(NULL);
  635. }
  636. #else
  637. clock = time(NULL);
  638. #endif
  639. result = Curl_gmtime(clock, &tm);
  640. if(result) {
  641. goto fail;
  642. }
  643. if(!strftime(timestamp, sizeof(timestamp), "%Y%m%dT%H%M%SZ", &tm)) {
  644. result = CURLE_OUT_OF_MEMORY;
  645. goto fail;
  646. }
  647. result = make_headers(data, hostname, timestamp,
  648. provider1.str, provider1.len,
  649. &date_header, content_sha256_hdr,
  650. &canonical_headers, &signed_headers);
  651. if(result)
  652. goto fail;
  653. if(*content_sha256_hdr) {
  654. /* make_headers() needed this without the \r\n for canonicalization */
  655. size_t hdrlen = strlen(content_sha256_hdr);
  656. DEBUGASSERT(hdrlen + 3 < sizeof(content_sha256_hdr));
  657. memcpy(content_sha256_hdr + hdrlen, "\r\n", 3);
  658. }
  659. memcpy(date, timestamp, sizeof(date));
  660. date[sizeof(date) - 1] = 0;
  661. result = canon_query(data, data->state.up.query, &canonical_query);
  662. if(result)
  663. goto fail;
  664. result = canon_string(data->state.up.path, strlen(data->state.up.path),
  665. &canonical_path, NULL);
  666. if(result)
  667. goto fail;
  668. result = CURLE_OUT_OF_MEMORY;
  669. canonical_request =
  670. aprintf("%s\n" /* HTTPRequestMethod */
  671. "%s\n" /* CanonicalURI */
  672. "%s\n" /* CanonicalQueryString */
  673. "%s\n" /* CanonicalHeaders */
  674. "%s\n" /* SignedHeaders */
  675. "%.*s", /* HashedRequestPayload in hex */
  676. method,
  677. Curl_dyn_ptr(&canonical_path),
  678. Curl_dyn_ptr(&canonical_query) ?
  679. Curl_dyn_ptr(&canonical_query) : "",
  680. Curl_dyn_ptr(&canonical_headers),
  681. Curl_dyn_ptr(&signed_headers),
  682. (int)payload_hash_len, payload_hash);
  683. if(!canonical_request)
  684. goto fail;
  685. DEBUGF(infof(data, "Canonical request: %s", canonical_request));
  686. request_type = aprintf("%.*s4_request", (int)provider0.len, provider0.str);
  687. if(!request_type)
  688. goto fail;
  689. /* provider0 is lowercased *after* aprintf() so that the buffer can be
  690. written to */
  691. Curl_strntolower(request_type, request_type, provider0.len);
  692. credential_scope = aprintf("%s/%.*s/%.*s/%s",
  693. date, (int)region.len, region.str,
  694. (int)service.len, service.str,
  695. request_type);
  696. if(!credential_scope)
  697. goto fail;
  698. if(Curl_sha256it(sha_hash, (unsigned char *) canonical_request,
  699. strlen(canonical_request)))
  700. goto fail;
  701. sha256_to_hex(sha_hex, sha_hash);
  702. /*
  703. * Google allows using RSA key instead of HMAC, so this code might change
  704. * in the future. For now we only support HMAC.
  705. */
  706. str_to_sign = aprintf("%.*s4-HMAC-SHA256\n" /* Algorithm */
  707. "%s\n" /* RequestDateTime */
  708. "%s\n" /* CredentialScope */
  709. "%s", /* HashedCanonicalRequest in hex */
  710. (int)provider0.len, provider0.str,
  711. timestamp,
  712. credential_scope,
  713. sha_hex);
  714. if(!str_to_sign)
  715. goto fail;
  716. /* make provider0 part done uppercase */
  717. Curl_strntoupper(str_to_sign, provider0.str, provider0.len);
  718. secret = aprintf("%.*s4%s", (int)provider0.len, provider0.str,
  719. data->state.aptr.passwd ?
  720. data->state.aptr.passwd : "");
  721. if(!secret)
  722. goto fail;
  723. /* make provider0 part done uppercase */
  724. Curl_strntoupper(secret, provider0.str, provider0.len);
  725. HMAC_SHA256(secret, strlen(secret), date, strlen(date), sign0);
  726. HMAC_SHA256(sign0, sizeof(sign0), region.str, region.len, sign1);
  727. HMAC_SHA256(sign1, sizeof(sign1), service.str, service.len, sign0);
  728. HMAC_SHA256(sign0, sizeof(sign0), request_type, strlen(request_type), sign1);
  729. HMAC_SHA256(sign1, sizeof(sign1), str_to_sign, strlen(str_to_sign), sign0);
  730. sha256_to_hex(sha_hex, sign0);
  731. auth_headers = aprintf("Authorization: %.*s4-HMAC-SHA256 "
  732. "Credential=%s/%s, "
  733. "SignedHeaders=%s, "
  734. "Signature=%s\r\n"
  735. /*
  736. * date_header is added here, only if it was not
  737. * user-specified (using CURLOPT_HTTPHEADER).
  738. * date_header includes \r\n
  739. */
  740. "%s"
  741. "%s", /* optional sha256 header includes \r\n */
  742. (int)provider0.len, provider0.str,
  743. user,
  744. credential_scope,
  745. Curl_dyn_ptr(&signed_headers),
  746. sha_hex,
  747. date_header ? date_header : "",
  748. content_sha256_hdr);
  749. if(!auth_headers) {
  750. goto fail;
  751. }
  752. /* provider 0 uppercase */
  753. Curl_strntoupper(&auth_headers[sizeof("Authorization: ") - 1],
  754. provider0.str, provider0.len);
  755. Curl_safefree(data->state.aptr.userpwd);
  756. data->state.aptr.userpwd = auth_headers;
  757. data->state.authhost.done = TRUE;
  758. result = CURLE_OK;
  759. fail:
  760. Curl_dyn_free(&canonical_query);
  761. Curl_dyn_free(&canonical_path);
  762. Curl_dyn_free(&canonical_headers);
  763. Curl_dyn_free(&signed_headers);
  764. free(canonical_request);
  765. free(request_type);
  766. free(credential_scope);
  767. free(str_to_sign);
  768. free(secret);
  769. free(date_header);
  770. return result;
  771. }
  772. #endif /* !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_AWS) */