http_aws_sigv4.c 25 KB

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