2
0

http_aws_sigv4.c 25 KB

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