1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
|
/**********************************************************************
*
* Name: cpl_aws.cpp
* Project: CPL - Common Portability Library
* Purpose: Amazon Web Services routines
* Author: Even Rouault <even.rouault at spatialys.com>
*
**********************************************************************
* Copyright (c) 2015, Even Rouault <even.rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
//! @cond Doxygen_Suppress
#include "cpl_aws.h"
#include "cpl_vsi_error.h"
#include "cpl_sha256.h"
#include "cpl_time.h"
#include "cpl_minixml.h"
#include "cpl_multiproc.h"
#include "cpl_http.h"
#include <algorithm>
// #define DEBUG_VERBOSE 1
#ifdef WIN32
#if defined(HAVE_ATLBASE_H)
bool CPLFetchWindowsProductUUID(
CPLString &osStr); // defined in cpl_aws_win32.cpp
#endif
const char *CPLGetWineVersion(); // defined in cpl_vsil_win32.cpp
#endif
#ifdef HAVE_CURL
static CPLMutex *ghMutex = nullptr;
static CPLString gosIAMRole;
static CPLString gosGlobalAccessKeyId;
static CPLString gosGlobalSecretAccessKey;
static CPLString gosGlobalSessionToken;
static GIntBig gnGlobalExpiration = 0;
static std::string gosRegion;
// The below variables are used for credentials retrieved through a STS
// AssumedRole operation
static std::string gosRoleArn;
static std::string gosExternalId;
static std::string gosMFASerial;
static std::string gosRoleSessionName;
static std::string gosSourceProfileAccessKeyId;
static std::string gosSourceProfileSecretAccessKey;
static std::string gosSourceProfileSessionToken;
// The below variables are used for web identity settings in aws/config
static std::string gosRoleArnWebIdentity;
static std::string gosWebIdentityTokenFile;
/************************************************************************/
/* CPLGetLowerCaseHex() */
/************************************************************************/
static CPLString CPLGetLowerCaseHex(const GByte *pabyData, size_t nBytes)
{
CPLString osRet;
osRet.resize(nBytes * 2);
constexpr char achHex[] = "0123456789abcdef";
for (size_t i = 0; i < nBytes; ++i)
{
const int nLow = pabyData[i] & 0x0f;
const int nHigh = (pabyData[i] & 0xf0) >> 4;
osRet[i * 2] = achHex[nHigh];
osRet[i * 2 + 1] = achHex[nLow];
}
return osRet;
}
/************************************************************************/
/* CPLGetLowerCaseHexSHA256() */
/************************************************************************/
CPLString CPLGetLowerCaseHexSHA256(const void *pabyData, size_t nBytes)
{
GByte hash[CPL_SHA256_HASH_SIZE] = {};
CPL_SHA256(static_cast<const GByte *>(pabyData), nBytes, hash);
return CPLGetLowerCaseHex(hash, CPL_SHA256_HASH_SIZE);
}
/************************************************************************/
/* CPLGetLowerCaseHexSHA256() */
/************************************************************************/
CPLString CPLGetLowerCaseHexSHA256(const CPLString &osStr)
{
return CPLGetLowerCaseHexSHA256(osStr.c_str(), osStr.size());
}
/************************************************************************/
/* CPLAWSURLEncode() */
/************************************************************************/
CPLString CPLAWSURLEncode(const CPLString &osURL, bool bEncodeSlash)
{
CPLString osRet;
for (size_t i = 0; i < osURL.size(); i++)
{
char ch = osURL[i];
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') ||
(ch >= '0' && ch <= '9') || ch == '_' || ch == '-' || ch == '~' ||
ch == '.')
{
osRet += ch;
}
else if (ch == '/')
{
if (bEncodeSlash)
osRet += "%2F";
else
osRet += ch;
}
else
{
osRet += CPLSPrintf("%%%02X", static_cast<unsigned char>(ch));
}
}
return osRet;
}
/************************************************************************/
/* CPLAWSGetHeaderVal() */
/************************************************************************/
CPLString CPLAWSGetHeaderVal(const struct curl_slist *psExistingHeaders,
const char *pszKey)
{
CPLString osKey(pszKey);
osKey += ":";
const struct curl_slist *psIter = psExistingHeaders;
for (; psIter != nullptr; psIter = psIter->next)
{
if (STARTS_WITH(psIter->data, osKey.c_str()))
return CPLString(psIter->data + osKey.size()).Trim();
}
return CPLString();
}
/************************************************************************/
/* CPLGetAWS_SIGN4_Signature() */
/************************************************************************/
// See:
// http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
CPLString CPLGetAWS_SIGN4_Signature(
const CPLString &osSecretAccessKey, const CPLString &osAccessToken,
const CPLString &osRegion, const CPLString &osRequestPayer,
const CPLString &osService, const CPLString &osVerb,
const struct curl_slist *psExistingHeaders, const CPLString &osHost,
const CPLString &osCanonicalURI, const CPLString &osCanonicalQueryString,
const CPLString &osXAMZContentSHA256, bool bAddHeaderAMZContentSHA256,
const CPLString &osTimestamp, CPLString &osSignedHeaders)
{
/* -------------------------------------------------------------------- */
/* Compute canonical request string. */
/* -------------------------------------------------------------------- */
CPLString osCanonicalRequest = osVerb + "\n";
osCanonicalRequest += osCanonicalURI + "\n";
osCanonicalRequest += osCanonicalQueryString + "\n";
std::map<CPLString, CPLString> oSortedMapHeaders;
oSortedMapHeaders["host"] = osHost;
if (osXAMZContentSHA256 != "UNSIGNED-PAYLOAD" && bAddHeaderAMZContentSHA256)
{
oSortedMapHeaders["x-amz-content-sha256"] = osXAMZContentSHA256;
oSortedMapHeaders["x-amz-date"] = osTimestamp;
}
if (!osRequestPayer.empty())
oSortedMapHeaders["x-amz-request-payer"] = osRequestPayer;
if (!osAccessToken.empty())
oSortedMapHeaders["x-amz-security-token"] = osAccessToken;
CPLString osCanonicalizedHeaders(
IVSIS3LikeHandleHelper::BuildCanonicalizedHeaders(
oSortedMapHeaders, psExistingHeaders, "x-amz-"));
osCanonicalRequest += osCanonicalizedHeaders + "\n";
osSignedHeaders.clear();
std::map<CPLString, CPLString>::const_iterator oIter =
oSortedMapHeaders.begin();
for (; oIter != oSortedMapHeaders.end(); ++oIter)
{
if (!osSignedHeaders.empty())
osSignedHeaders += ";";
osSignedHeaders += oIter->first;
}
osCanonicalRequest += osSignedHeaders + "\n";
osCanonicalRequest += osXAMZContentSHA256;
#ifdef DEBUG_VERBOSE
CPLDebug("S3", "osCanonicalRequest='%s'", osCanonicalRequest.c_str());
#endif
/* -------------------------------------------------------------------- */
/* Compute StringToSign . */
/* -------------------------------------------------------------------- */
CPLString osStringToSign = "AWS4-HMAC-SHA256\n";
osStringToSign += osTimestamp + "\n";
CPLString osYYMMDD(osTimestamp);
osYYMMDD.resize(8);
CPLString osScope = osYYMMDD + "/";
osScope += osRegion;
osScope += "/";
osScope += osService;
osScope += "/aws4_request";
osStringToSign += osScope + "\n";
osStringToSign += CPLGetLowerCaseHexSHA256(osCanonicalRequest);
#ifdef DEBUG_VERBOSE
CPLDebug("S3", "osStringToSign='%s'", osStringToSign.c_str());
#endif
/* -------------------------------------------------------------------- */
/* Compute signing key. */
/* -------------------------------------------------------------------- */
GByte abySigningKeyIn[CPL_SHA256_HASH_SIZE] = {};
GByte abySigningKeyOut[CPL_SHA256_HASH_SIZE] = {};
CPLString osFirstKey(CPLString("AWS4") + osSecretAccessKey);
CPL_HMAC_SHA256(osFirstKey.c_str(), osFirstKey.size(), osYYMMDD,
osYYMMDD.size(), abySigningKeyOut);
memcpy(abySigningKeyIn, abySigningKeyOut, CPL_SHA256_HASH_SIZE);
CPL_HMAC_SHA256(abySigningKeyIn, CPL_SHA256_HASH_SIZE, osRegion.c_str(),
osRegion.size(), abySigningKeyOut);
memcpy(abySigningKeyIn, abySigningKeyOut, CPL_SHA256_HASH_SIZE);
CPL_HMAC_SHA256(abySigningKeyIn, CPL_SHA256_HASH_SIZE, osService.c_str(),
osService.size(), abySigningKeyOut);
memcpy(abySigningKeyIn, abySigningKeyOut, CPL_SHA256_HASH_SIZE);
CPL_HMAC_SHA256(abySigningKeyIn, CPL_SHA256_HASH_SIZE, "aws4_request",
strlen("aws4_request"), abySigningKeyOut);
memcpy(abySigningKeyIn, abySigningKeyOut, CPL_SHA256_HASH_SIZE);
#ifdef DEBUG_VERBOSE
CPLString osSigningKey(
CPLGetLowerCaseHex(abySigningKeyIn, CPL_SHA256_HASH_SIZE));
CPLDebug("S3", "osSigningKey='%s'", osSigningKey.c_str());
#endif
/* -------------------------------------------------------------------- */
/* Compute signature. */
/* -------------------------------------------------------------------- */
GByte abySignature[CPL_SHA256_HASH_SIZE] = {};
CPL_HMAC_SHA256(abySigningKeyIn, CPL_SHA256_HASH_SIZE, osStringToSign,
osStringToSign.size(), abySignature);
CPLString osSignature(
CPLGetLowerCaseHex(abySignature, CPL_SHA256_HASH_SIZE));
#ifdef DEBUG_VERBOSE
CPLDebug("S3", "osSignature='%s'", osSignature.c_str());
#endif
return osSignature;
}
/************************************************************************/
/* CPLGetAWS_SIGN4_Authorization() */
/************************************************************************/
CPLString CPLGetAWS_SIGN4_Authorization(
const CPLString &osSecretAccessKey, const CPLString &osAccessKeyId,
const CPLString &osAccessToken, const CPLString &osRegion,
const CPLString &osRequestPayer, const CPLString &osService,
const CPLString &osVerb, const struct curl_slist *psExistingHeaders,
const CPLString &osHost, const CPLString &osCanonicalURI,
const CPLString &osCanonicalQueryString,
const CPLString &osXAMZContentSHA256, bool bAddHeaderAMZContentSHA256,
const CPLString &osTimestamp)
{
CPLString osSignedHeaders;
CPLString osSignature(CPLGetAWS_SIGN4_Signature(
osSecretAccessKey, osAccessToken, osRegion, osRequestPayer, osService,
osVerb, psExistingHeaders, osHost, osCanonicalURI,
osCanonicalQueryString, osXAMZContentSHA256, bAddHeaderAMZContentSHA256,
osTimestamp, osSignedHeaders));
CPLString osYYMMDD(osTimestamp);
osYYMMDD.resize(8);
/* -------------------------------------------------------------------- */
/* Build authorization header. */
/* -------------------------------------------------------------------- */
CPLString osAuthorization;
osAuthorization = "AWS4-HMAC-SHA256 Credential=";
osAuthorization += osAccessKeyId;
osAuthorization += "/";
osAuthorization += osYYMMDD;
osAuthorization += "/";
osAuthorization += osRegion;
osAuthorization += "/";
osAuthorization += osService;
osAuthorization += "/";
osAuthorization += "aws4_request";
osAuthorization += ",";
osAuthorization += "SignedHeaders=";
osAuthorization += osSignedHeaders;
osAuthorization += ",";
osAuthorization += "Signature=";
osAuthorization += osSignature;
#ifdef DEBUG_VERBOSE
CPLDebug("S3", "osAuthorization='%s'", osAuthorization.c_str());
#endif
return osAuthorization;
}
/************************************************************************/
/* CPLGetAWS_SIGN4_Timestamp() */
/************************************************************************/
CPLString CPLGetAWS_SIGN4_Timestamp(GIntBig timestamp)
{
struct tm brokenDown;
CPLUnixTimeToYMDHMS(timestamp, &brokenDown);
char szTimeStamp[80] = {};
snprintf(szTimeStamp, sizeof(szTimeStamp), "%04d%02d%02dT%02d%02d%02dZ",
brokenDown.tm_year + 1900, brokenDown.tm_mon + 1,
brokenDown.tm_mday, brokenDown.tm_hour, brokenDown.tm_min,
brokenDown.tm_sec);
return szTimeStamp;
}
/************************************************************************/
/* VSIS3HandleHelper() */
/************************************************************************/
VSIS3HandleHelper::VSIS3HandleHelper(
const CPLString &osSecretAccessKey, const CPLString &osAccessKeyId,
const CPLString &osSessionToken, const CPLString &osEndpoint,
const CPLString &osRegion, const CPLString &osRequestPayer,
const CPLString &osBucket, const CPLString &osObjectKey, bool bUseHTTPS,
bool bUseVirtualHosting, AWSCredentialsSource eCredentialsSource)
: m_osURL(BuildURL(osEndpoint, osBucket, osObjectKey, bUseHTTPS,
bUseVirtualHosting)),
m_osSecretAccessKey(osSecretAccessKey), m_osAccessKeyId(osAccessKeyId),
m_osSessionToken(osSessionToken), m_osEndpoint(osEndpoint),
m_osRegion(osRegion), m_osRequestPayer(osRequestPayer),
m_osBucket(osBucket), m_osObjectKey(osObjectKey), m_bUseHTTPS(bUseHTTPS),
m_bUseVirtualHosting(bUseVirtualHosting),
m_eCredentialsSource(eCredentialsSource)
{
}
/************************************************************************/
/* ~VSIS3HandleHelper() */
/************************************************************************/
VSIS3HandleHelper::~VSIS3HandleHelper()
{
for (size_t i = 0; i < m_osSecretAccessKey.size(); i++)
m_osSecretAccessKey[i] = 0;
}
/************************************************************************/
/* BuildURL() */
/************************************************************************/
CPLString VSIS3HandleHelper::BuildURL(const CPLString &osEndpoint,
const CPLString &osBucket,
const CPLString &osObjectKey,
bool bUseHTTPS, bool bUseVirtualHosting)
{
const char *pszProtocol = (bUseHTTPS) ? "https" : "http";
if (osBucket.empty())
return CPLSPrintf("%s://%s", pszProtocol, osEndpoint.c_str());
else if (bUseVirtualHosting)
return CPLSPrintf("%s://%s.%s/%s", pszProtocol, osBucket.c_str(),
osEndpoint.c_str(),
CPLAWSURLEncode(osObjectKey, false).c_str());
else
return CPLSPrintf("%s://%s/%s/%s", pszProtocol, osEndpoint.c_str(),
osBucket.c_str(),
CPLAWSURLEncode(osObjectKey, false).c_str());
}
/************************************************************************/
/* RebuildURL() */
/************************************************************************/
void VSIS3HandleHelper::RebuildURL()
{
m_osURL = BuildURL(m_osEndpoint, m_osBucket, m_osObjectKey, m_bUseHTTPS,
m_bUseVirtualHosting);
m_osURL += GetQueryString(false);
}
/************************************************************************/
/* GetBucketAndObjectKey() */
/************************************************************************/
bool IVSIS3LikeHandleHelper::GetBucketAndObjectKey(const char *pszURI,
const char *pszFSPrefix,
bool bAllowNoObject,
CPLString &osBucket,
CPLString &osObjectKey)
{
osBucket = pszURI;
if (osBucket.empty())
{
return false;
}
size_t nPos = osBucket.find('/');
if (nPos == std::string::npos)
{
if (bAllowNoObject)
{
osObjectKey = "";
return true;
}
CPLError(CE_Failure, CPLE_AppDefined,
"Filename should be of the form %sbucket/key", pszFSPrefix);
return false;
}
osBucket.resize(nPos);
osObjectKey = pszURI + nPos + 1;
return true;
}
/************************************************************************/
/* BuildCanonicalizedHeaders() */
/************************************************************************/
CPLString IVSIS3LikeHandleHelper::BuildCanonicalizedHeaders(
std::map<CPLString, CPLString> &oSortedMapHeaders,
const struct curl_slist *psExistingHeaders, const char *pszHeaderPrefix)
{
const struct curl_slist *psIter = psExistingHeaders;
for (; psIter != nullptr; psIter = psIter->next)
{
if (STARTS_WITH_CI(psIter->data, pszHeaderPrefix) ||
STARTS_WITH_CI(psIter->data, "Content-MD5"))
{
const char *pszColumn = strstr(psIter->data, ":");
if (pszColumn)
{
CPLString osKey(psIter->data);
osKey.resize(pszColumn - psIter->data);
oSortedMapHeaders[osKey.tolower()] =
CPLString(pszColumn + strlen(":")).Trim();
}
}
}
CPLString osCanonicalizedHeaders;
std::map<CPLString, CPLString>::const_iterator oIter =
oSortedMapHeaders.begin();
for (; oIter != oSortedMapHeaders.end(); ++oIter)
{
osCanonicalizedHeaders += oIter->first + ":" + oIter->second + "\n";
}
return osCanonicalizedHeaders;
}
/************************************************************************/
/* GetRFC822DateTime() */
/************************************************************************/
CPLString IVSIS3LikeHandleHelper::GetRFC822DateTime()
{
char szDate[64];
time_t nNow = time(nullptr);
struct tm tm;
CPLUnixTimeToYMDHMS(nNow, &tm);
int nRet = CPLPrintTime(szDate, sizeof(szDate) - 1,
"%a, %d %b %Y %H:%M:%S GMT", &tm, "C");
szDate[nRet] = 0;
return szDate;
}
/************************************************************************/
/* ParseSimpleJson() */
/* */
/* Return a string list of name/value pairs extracted from a */
/* JSON doc. The EC2 IAM web service returns simple JSON */
/* responses. The parsing as done currently is very fragile */
/* and depends on JSON documents being in a very very simple */
/* form. */
/************************************************************************/
static CPLStringList ParseSimpleJson(const char *pszJson)
{
/* -------------------------------------------------------------------- */
/* We are expecting simple documents like the following with no */
/* hierarchy or complex structure. */
/* -------------------------------------------------------------------- */
/*
{
"Code" : "Success",
"LastUpdated" : "2017-07-03T16:20:17Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "bla",
"SecretAccessKey" : "bla",
"Token" : "bla",
"Expiration" : "2017-07-03T22:42:58Z"
}
*/
CPLStringList oWords(
CSLTokenizeString2(pszJson, " \n\t,:{}", CSLT_HONOURSTRINGS));
CPLStringList oNameValue;
for (int i = 0; i < oWords.size(); i += 2)
{
oNameValue.SetNameValue(oWords[i], oWords[i + 1]);
}
return oNameValue;
}
/************************************************************************/
/* Iso8601ToUnixTime() */
/************************************************************************/
static bool Iso8601ToUnixTime(const char *pszDT, GIntBig *pnUnixTime)
{
int nYear;
int nMonth;
int nDay;
int nHour;
int nMinute;
int nSecond;
if (sscanf(pszDT, "%04d-%02d-%02dT%02d:%02d:%02d", &nYear, &nMonth, &nDay,
&nHour, &nMinute, &nSecond) == 6)
{
struct tm brokendowntime;
brokendowntime.tm_year = nYear - 1900;
brokendowntime.tm_mon = nMonth - 1;
brokendowntime.tm_mday = nDay;
brokendowntime.tm_hour = nHour;
brokendowntime.tm_min = nMinute;
brokendowntime.tm_sec = nSecond;
*pnUnixTime = CPLYMDHMSToUnixTime(&brokendowntime);
return true;
}
return false;
}
/************************************************************************/
/* IsMachinePotentiallyEC2Instance() */
/************************************************************************/
static bool IsMachinePotentiallyEC2Instance()
{
#if defined(__linux) || defined(WIN32)
const auto IsMachinePotentiallyEC2InstanceFromLinuxHost = []()
{
// On the newer Nitro Hypervisor (C5, M5, H1, T3), use
// /sys/devices/virtual/dmi/id/sys_vendor = 'Amazon EC2' instead.
// On older Xen hypervisor EC2 instances, a /sys/hypervisor/uuid file
// will exist with a string beginning with 'ec2'.
// If the files exist but don't contain the correct content, then we're
// not EC2 and do not attempt any network access
// Check for Xen Hypervisor instances
// This file doesn't exist on Nitro instances
VSILFILE *fp = VSIFOpenL("/sys/hypervisor/uuid", "rb");
if (fp != nullptr)
{
char uuid[36 + 1] = {0};
VSIFReadL(uuid, 1, sizeof(uuid) - 1, fp);
VSIFCloseL(fp);
return EQUALN(uuid, "ec2", 3);
}
// Check for Nitro Hypervisor instances
// This file may exist on Xen instances with a value of 'Xen'
// (but that doesn't mean we're on EC2)
fp = VSIFOpenL("/sys/devices/virtual/dmi/id/sys_vendor", "rb");
if (fp != nullptr)
{
char buf[10 + 1] = {0};
VSIFReadL(buf, 1, sizeof(buf) - 1, fp);
VSIFCloseL(fp);
return EQUALN(buf, "Amazon EC2", 10);
}
// Fallback: Check via the network
return true;
};
#endif
#ifdef __linux
// Optimization on Linux to avoid the network request
// See
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html
// Skip if either:
// - CPL_AWS_AUTODETECT_EC2=NO
// - CPL_AWS_CHECK_HYPERVISOR_UUID=NO (deprecated)
if (!CPLTestBool(CPLGetConfigOption("CPL_AWS_AUTODETECT_EC2", "YES")))
{
return true;
}
else
{
CPLString opt = CPLGetConfigOption("CPL_AWS_CHECK_HYPERVISOR_UUID", "");
if (!opt.empty())
{
CPLDebug("AWS", "CPL_AWS_CHECK_HYPERVISOR_UUID is deprecated. Use "
"CPL_AWS_AUTODETECT_EC2 instead");
if (!CPLTestBool(opt))
{
return true;
}
}
}
return IsMachinePotentiallyEC2InstanceFromLinuxHost();
#elif defined(WIN32)
if (!CPLTestBool(CPLGetConfigOption("CPL_AWS_AUTODETECT_EC2", "YES")))
{
return true;
}
// Regular UUID is not valid for WINE, fetch from sysfs instead.
if (CPLGetWineVersion() != nullptr)
{
return IsMachinePotentiallyEC2InstanceFromLinuxHost();
}
else
{
#if defined(HAVE_ATLBASE_H)
CPLString osMachineUUID;
if (CPLFetchWindowsProductUUID(osMachineUUID))
{
if (osMachineUUID.length() >= 3 &&
EQUALN(osMachineUUID.c_str(), "EC2", 3))
{
return true;
}
else if (osMachineUUID.length() >= 8 && osMachineUUID[4] == '2' &&
osMachineUUID[6] == 'E' && osMachineUUID[7] == 'C')
{
return true;
}
else
{
return false;
}
}
#endif
}
// Fallback: Check via the network
return true;
#else
// At time of writing EC2 instances can be only Linux or Windows
return false;
#endif
}
/************************************************************************/
/* ReadAWSWebIdentityTokenFile() */
/************************************************************************/
static bool
ReadAWSWebIdentityTokenFile(const std::string &osWebIdentityTokenFile,
CPLString &webIdentityToken)
{
GByte *pabyOut = nullptr;
if (!VSIIngestFile(nullptr, osWebIdentityTokenFile.c_str(), &pabyOut,
nullptr, -1))
return false;
webIdentityToken = reinterpret_cast<char *>(pabyOut);
VSIFree(pabyOut);
// Remove trailing end-of-line character
if (!webIdentityToken.empty() && webIdentityToken.back() == '\n')
webIdentityToken.resize(webIdentityToken.size() - 1);
return !webIdentityToken.empty();
}
/************************************************************************/
/* GetConfigurationFromAssumeRoleWithWebIdentity() */
/************************************************************************/
bool VSIS3HandleHelper::GetConfigurationFromAssumeRoleWithWebIdentity(
bool bForceRefresh, const std::string &osPathForOption,
const std::string &osRoleArnIn, const std::string &osWebIdentityTokenFileIn,
CPLString &osSecretAccessKey, CPLString &osAccessKeyId,
CPLString &osSessionToken)
{
CPLMutexHolder oHolder(&ghMutex);
if (!bForceRefresh)
{
time_t nCurTime;
time(&nCurTime);
// Try to reuse credentials if they are still valid, but
// keep one minute of margin...
if (!gosGlobalAccessKeyId.empty() && nCurTime < gnGlobalExpiration - 60)
{
osAccessKeyId = gosGlobalAccessKeyId;
osSecretAccessKey = gosGlobalSecretAccessKey;
osSessionToken = gosGlobalSessionToken;
return true;
}
}
const CPLString roleArn =
!osRoleArnIn.empty() ? osRoleArnIn
: VSIGetPathSpecificOption(osPathForOption.c_str(),
"AWS_ROLE_ARN", "");
if (roleArn.empty())
{
CPLDebug("AWS", "AWS_ROLE_ARN configuration option not defined");
return false;
}
const CPLString webIdentityTokenFile =
!osWebIdentityTokenFileIn.empty()
? osWebIdentityTokenFileIn
: VSIGetPathSpecificOption(osPathForOption.c_str(),
"AWS_WEB_IDENTITY_TOKEN_FILE", "");
if (webIdentityTokenFile.empty())
{
CPLDebug(
"AWS",
"AWS_WEB_IDENTITY_TOKEN_FILE configuration option not defined");
return false;
}
const CPLString stsRegionalEndpoints = VSIGetPathSpecificOption(
osPathForOption.c_str(), "AWS_STS_REGIONAL_ENDPOINTS", "regional");
std::string osStsDefaultUrl;
if (stsRegionalEndpoints == "regional")
{
const CPLString osRegion = VSIGetPathSpecificOption(
osPathForOption.c_str(), "AWS_REGION", "us-east-1");
osStsDefaultUrl = "https://sts." + osRegion + ".amazonaws.com";
}
else
{
osStsDefaultUrl = "https://sts.amazonaws.com";
}
const CPLString osStsRootUrl(VSIGetPathSpecificOption(
osPathForOption.c_str(), "CPL_AWS_STS_ROOT_URL",
osStsDefaultUrl.c_str()));
// Get token from web identity token file
CPLString webIdentityToken;
if (!ReadAWSWebIdentityTokenFile(webIdentityTokenFile, webIdentityToken))
{
CPLDebug("AWS", "%s is empty", webIdentityTokenFile.c_str());
return false;
}
// Get credentials from sts AssumeRoleWithWebIdentity
std::string osExpiration;
{
const CPLString osSTS_asuume_role_with_web_identity_URL =
osStsRootUrl +
"/?Action=AssumeRoleWithWebIdentity&RoleSessionName=gdal"
"&Version=2011-06-15&RoleArn=" +
CPLAWSURLEncode(roleArn) +
"&WebIdentityToken=" + CPLAWSURLEncode(webIdentityToken);
CPLPushErrorHandler(CPLQuietErrorHandler);
CPLHTTPResult *psResult = CPLHTTPFetch(
osSTS_asuume_role_with_web_identity_URL.c_str(), nullptr);
CPLPopErrorHandler();
if (psResult)
{
if (psResult->nStatus == 0 && psResult->pabyData != nullptr)
{
CPLXMLTreeCloser oTree(CPLParseXMLString(
reinterpret_cast<char *>(psResult->pabyData)));
if (oTree)
{
const auto psCredentials = CPLGetXMLNode(
oTree.get(),
"=AssumeRoleWithWebIdentityResponse."
"AssumeRoleWithWebIdentityResult.Credentials");
if (psCredentials)
{
osAccessKeyId =
CPLGetXMLValue(psCredentials, "AccessKeyId", "");
osSecretAccessKey = CPLGetXMLValue(
psCredentials, "SecretAccessKey", "");
osSessionToken =
CPLGetXMLValue(psCredentials, "SessionToken", "");
osExpiration =
CPLGetXMLValue(psCredentials, "Expiration", "");
}
}
}
CPLHTTPDestroyResult(psResult);
}
}
GIntBig nExpirationUnix = 0;
if (!osAccessKeyId.empty() && !osSecretAccessKey.empty() &&
!osSessionToken.empty() &&
Iso8601ToUnixTime(osExpiration.c_str(), &nExpirationUnix))
{
gosGlobalAccessKeyId = osAccessKeyId;
gosGlobalSecretAccessKey = osSecretAccessKey;
gosGlobalSessionToken = osSessionToken;
gnGlobalExpiration = nExpirationUnix;
CPLDebug("AWS", "Storing AIM credentials until %s",
osExpiration.c_str());
}
return !osAccessKeyId.empty() && !osSecretAccessKey.empty() &&
!osSessionToken.empty();
}
/************************************************************************/
/* GetConfigurationFromEC2() */
/************************************************************************/
bool VSIS3HandleHelper::GetConfigurationFromEC2(
bool bForceRefresh, const std::string &osPathForOption,
CPLString &osSecretAccessKey, CPLString &osAccessKeyId,
CPLString &osSessionToken)
{
CPLMutexHolder oHolder(&ghMutex);
if (!bForceRefresh)
{
time_t nCurTime;
time(&nCurTime);
// Try to reuse credentials if they are still valid, but
// keep one minute of margin...
if (!gosGlobalAccessKeyId.empty() && nCurTime < gnGlobalExpiration - 60)
{
osAccessKeyId = gosGlobalAccessKeyId;
osSecretAccessKey = gosGlobalSecretAccessKey;
osSessionToken = gosGlobalSessionToken;
return true;
}
}
CPLString osURLRefreshCredentials;
const CPLString osEC2DefaultURL("http://169.254.169.254");
// coverity[tainted_data]
const CPLString osEC2RootURL(VSIGetPathSpecificOption(
osPathForOption.c_str(), "CPL_AWS_EC2_API_ROOT_URL", osEC2DefaultURL));
// coverity[tainted_data]
const CPLString osECSRelativeURI(VSIGetPathSpecificOption(
osPathForOption.c_str(), "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", ""));
CPLString osToken;
if (osEC2RootURL == osEC2DefaultURL && !osECSRelativeURI.empty())
{
// See
// https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html
osURLRefreshCredentials = "http://169.254.170.2" + osECSRelativeURI;
}
else
{
if (!IsMachinePotentiallyEC2Instance())
return false;
// Use IMDSv2 protocol:
// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
// Retrieve IMDSv2 token
{
const CPLString osEC2_IMDSv2_api_token_URL =
osEC2RootURL + "/latest/api/token";
CPLStringList aosOptions;
aosOptions.SetNameValue("TIMEOUT", "1");
aosOptions.SetNameValue("CUSTOMREQUEST", "PUT");
aosOptions.SetNameValue("HEADERS",
"X-aws-ec2-metadata-token-ttl-seconds: 10");
CPLPushErrorHandler(CPLQuietErrorHandler);
CPLHTTPResult *psResult =
CPLHTTPFetch(osEC2_IMDSv2_api_token_URL, aosOptions.List());
CPLPopErrorHandler();
if (psResult)
{
if (psResult->nStatus == 0 && psResult->pabyData != nullptr)
{
osToken = reinterpret_cast<char *>(psResult->pabyData);
}
else
{
// Failure: either we are not running on EC2 (or something
// emulating it) or this doesn't implement yet IDMSv2 Go on
// trying IDMSv1
// /latest/api/token doesn't work inside a Docker container
// that has no host networking. Cf
// https://community.grafana.com/t/imdsv2-is-not-working-from-docker/65944
if (psResult->pszErrBuf != nullptr &&
strstr(psResult->pszErrBuf,
"Operation timed out after") != nullptr)
{
aosOptions.Clear();
aosOptions.SetNameValue("TIMEOUT", "1");
CPLPushErrorHandler(CPLQuietErrorHandler);
CPLHTTPResult *psResult2 = CPLHTTPFetch(
(osEC2RootURL + "/latest/meta-data").c_str(),
aosOptions.List());
CPLPopErrorHandler();
if (psResult2)
{
if (psResult2->nStatus == 0 &&
psResult2->pabyData != nullptr)
{
VSIStatBufL sStat;
if (VSIStatL("/.dockerenv", &sStat) == 0)
{
CPLDebug("AWS",
"/latest/api/token EC2 IDMSv2 "
"request timed out, but "
"/latest/metadata succeeded. "
"Trying with IDMSv1. "
"Try running your Docker "
"container with --network=host.");
}
else
{
CPLDebug(
"AWS",
"/latest/api/token EC2 IDMSv2 request "
"timed out, but /latest/metadata "
"succeeded. "
"Trying with IDMSv1. "
"Are you running inside a container "
"that has no host networking ?");
}
}
CPLHTTPDestroyResult(psResult2);
}
}
}
CPLHTTPDestroyResult(psResult);
}
CPLErrorReset();
}
// If we don't know yet the IAM role, fetch it
const CPLString osEC2CredentialsURL =
osEC2RootURL + "/latest/meta-data/iam/security-credentials/";
if (gosIAMRole.empty())
{
CPLStringList aosOptions;
aosOptions.SetNameValue("TIMEOUT", "1");
if (!osToken.empty())
{
aosOptions.SetNameValue(
"HEADERS",
("X-aws-ec2-metadata-token: " + osToken).c_str());
}
CPLPushErrorHandler(CPLQuietErrorHandler);
CPLHTTPResult *psResult =
CPLHTTPFetch(osEC2CredentialsURL, aosOptions.List());
CPLPopErrorHandler();
if (psResult)
{
if (psResult->nStatus == 0 && psResult->pabyData != nullptr)
{
gosIAMRole = reinterpret_cast<char *>(psResult->pabyData);
}
CPLHTTPDestroyResult(psResult);
}
CPLErrorReset();
if (gosIAMRole.empty())
{
// We didn't get the IAM role. We are definitely not running
// on EC2 or an emulation of it.
return false;
}
}
osURLRefreshCredentials = osEC2CredentialsURL + gosIAMRole;
}
// Now fetch the refreshed credentials
CPLStringList oResponse;
CPLStringList aosOptions;
if (!osToken.empty())
{
aosOptions.SetNameValue(
"HEADERS", ("X-aws-ec2-metadata-token: " + osToken).c_str());
}
CPLHTTPResult *psResult =
CPLHTTPFetch(osURLRefreshCredentials.c_str(), aosOptions.List());
if (psResult)
{
if (psResult->nStatus == 0 && psResult->pabyData != nullptr)
{
const CPLString osJSon =
reinterpret_cast<char *>(psResult->pabyData);
oResponse = ParseSimpleJson(osJSon);
}
CPLHTTPDestroyResult(psResult);
}
CPLErrorReset();
osAccessKeyId = oResponse.FetchNameValueDef("AccessKeyId", "");
osSecretAccessKey = oResponse.FetchNameValueDef("SecretAccessKey", "");
osSessionToken = oResponse.FetchNameValueDef("Token", "");
const CPLString osExpiration =
oResponse.FetchNameValueDef("Expiration", "");
GIntBig nExpirationUnix = 0;
if (!osAccessKeyId.empty() && !osSecretAccessKey.empty() &&
Iso8601ToUnixTime(osExpiration, &nExpirationUnix))
{
gosGlobalAccessKeyId = osAccessKeyId;
gosGlobalSecretAccessKey = osSecretAccessKey;
gosGlobalSessionToken = osSessionToken;
gnGlobalExpiration = nExpirationUnix;
CPLDebug("AWS", "Storing AIM credentials until %s",
osExpiration.c_str());
}
return !osAccessKeyId.empty() && !osSecretAccessKey.empty();
}
/************************************************************************/
/* UpdateAndWarnIfInconsistent() */
/************************************************************************/
static void UpdateAndWarnIfInconsistent(const char *pszKeyword,
CPLString &osVal,
const CPLString &osNewVal,
const CPLString &osCredentials,
const CPLString &osConfig)
{
// nominally defined in ~/.aws/credentials but can
// be set here too. If both values exist, credentials
// has the priority
if (osVal.empty())
{
osVal = osNewVal;
}
else if (osVal != osNewVal)
{
CPLError(CE_Warning, CPLE_AppDefined,
"%s defined in both %s "
"and %s. The one of %s will be used",
pszKeyword, osCredentials.c_str(), osConfig.c_str(),
osCredentials.c_str());
}
}
/************************************************************************/
/* ReadAWSCredentials() */
/************************************************************************/
static bool ReadAWSCredentials(const std::string &osProfile,
const std::string &osCredentials,
CPLString &osSecretAccessKey,
CPLString &osAccessKeyId,
CPLString &osSessionToken)
{
osSecretAccessKey.clear();
osAccessKeyId.clear();
osSessionToken.clear();
VSILFILE *fp = VSIFOpenL(osCredentials.c_str(), "rb");
if (fp != nullptr)
{
const char *pszLine;
bool bInProfile = false;
const CPLString osBracketedProfile("[" + osProfile + "]");
while ((pszLine = CPLReadLineL(fp)) != nullptr)
{
if (pszLine[0] == '[')
{
if (bInProfile)
break;
if (CPLString(pszLine) == osBracketedProfile)
bInProfile = true;
}
else if (bInProfile)
{
char *pszKey = nullptr;
const char *pszValue = CPLParseNameValue(pszLine, &pszKey);
if (pszKey && pszValue)
{
if (EQUAL(pszKey, "aws_access_key_id"))
osAccessKeyId = pszValue;
else if (EQUAL(pszKey, "aws_secret_access_key"))
osSecretAccessKey = pszValue;
else if (EQUAL(pszKey, "aws_session_token"))
osSessionToken = pszValue;
}
CPLFree(pszKey);
}
}
VSIFCloseL(fp);
}
return !osSecretAccessKey.empty() && !osAccessKeyId.empty();
}
/************************************************************************/
/* GetConfigurationFromAWSConfigFiles() */
/************************************************************************/
bool VSIS3HandleHelper::GetConfigurationFromAWSConfigFiles(
const std::string &osPathForOption, const char *pszProfile,
CPLString &osSecretAccessKey, CPLString &osAccessKeyId,
CPLString &osSessionToken, CPLString &osRegion, CPLString &osCredentials,
CPLString &osRoleArn, CPLString &osSourceProfile, CPLString &osExternalId,
CPLString &osMFASerial, CPLString &osRoleSessionName,
CPLString &osWebIdentityTokenFile)
{
// See http://docs.aws.amazon.com/cli/latest/userguide/cli-config-files.html
// If AWS_DEFAULT_PROFILE is set (obsolete, no longer documented), use it in
// priority Otherwise use AWS_PROFILE Otherwise fallback to "default"
const char *pszProfileOri = pszProfile;
if (pszProfile == nullptr)
{
pszProfile = VSIGetPathSpecificOption(osPathForOption.c_str(),
"AWS_DEFAULT_PROFILE", "");
if (pszProfile[0] == '\0')
pszProfile = VSIGetPathSpecificOption(osPathForOption.c_str(),
"AWS_PROFILE", "");
}
const CPLString osProfile(pszProfile[0] != '\0' ? pszProfile : "default");
#ifdef WIN32
const char *pszHome = CPLGetConfigOption("USERPROFILE", nullptr);
constexpr char SEP_STRING[] = "\\";
#else
const char *pszHome = CPLGetConfigOption("HOME", nullptr);
constexpr char SEP_STRING[] = "/";
#endif
CPLString osDotAws(pszHome ? pszHome : "");
osDotAws += SEP_STRING;
osDotAws += ".aws";
// Read first ~/.aws/credential file
// GDAL specific config option (mostly for testing purpose, but also
// used in production in some cases)
const char *pszCredentials = VSIGetPathSpecificOption(
osPathForOption.c_str(), "CPL_AWS_CREDENTIALS_FILE", nullptr);
if (pszCredentials)
{
osCredentials = pszCredentials;
}
else
{
osCredentials = osDotAws;
osCredentials += SEP_STRING;
osCredentials += "credentials";
}
ReadAWSCredentials(osProfile, osCredentials, osSecretAccessKey,
osAccessKeyId, osSessionToken);
// And then ~/.aws/config file (unless AWS_CONFIG_FILE is defined)
const char *pszAWSConfigFileEnv = VSIGetPathSpecificOption(
osPathForOption.c_str(), "AWS_CONFIG_FILE", nullptr);
CPLString osConfig;
if (pszAWSConfigFileEnv)
{
osConfig = pszAWSConfigFileEnv;
}
else
{
osConfig = osDotAws;
osConfig += SEP_STRING;
osConfig += "config";
}
VSILFILE *fp = VSIFOpenL(osConfig, "rb");
if (fp != nullptr)
{
const char *pszLine;
bool bInProfile = false;
const CPLString osBracketedProfile("[" + osProfile + "]");
const CPLString osBracketedProfileProfile("[profile " + osProfile +
"]");
while ((pszLine = CPLReadLineL(fp)) != nullptr)
{
if (pszLine[0] == '[')
{
if (bInProfile)
break;
// In config file, the section name is nominally [profile foo]
// for the non default profile.
if (CPLString(pszLine) == osBracketedProfile ||
CPLString(pszLine) == osBracketedProfileProfile)
{
bInProfile = true;
}
}
else if (bInProfile)
{
char *pszKey = nullptr;
const char *pszValue = CPLParseNameValue(pszLine, &pszKey);
if (pszKey && pszValue)
{
if (EQUAL(pszKey, "aws_access_key_id"))
{
UpdateAndWarnIfInconsistent(pszKey, osAccessKeyId,
pszValue, osCredentials,
osConfig);
}
else if (EQUAL(pszKey, "aws_secret_access_key"))
{
UpdateAndWarnIfInconsistent(pszKey, osSecretAccessKey,
pszValue, osCredentials,
osConfig);
}
else if (EQUAL(pszKey, "aws_session_token"))
{
UpdateAndWarnIfInconsistent(pszKey, osSessionToken,
pszValue, osCredentials,
osConfig);
}
else if (EQUAL(pszKey, "region"))
{
osRegion = pszValue;
}
else if (strcmp(pszKey, "role_arn") == 0)
{
osRoleArn = pszValue;
}
else if (strcmp(pszKey, "source_profile") == 0)
{
osSourceProfile = pszValue;
}
else if (strcmp(pszKey, "external_id") == 0)
{
osExternalId = pszValue;
}
else if (strcmp(pszKey, "mfa_serial") == 0)
{
osMFASerial = pszValue;
}
else if (strcmp(pszKey, "role_session_name") == 0)
{
osRoleSessionName = pszValue;
}
else if (strcmp(pszKey, "web_identity_token_file") == 0)
{
osWebIdentityTokenFile = pszValue;
}
}
CPLFree(pszKey);
}
}
VSIFCloseL(fp);
}
else if (pszAWSConfigFileEnv != nullptr)
{
if (pszAWSConfigFileEnv[0] != '\0')
{
CPLError(CE_Warning, CPLE_AppDefined,
"%s does not exist or cannot be open",
pszAWSConfigFileEnv);
}
}
return (!osAccessKeyId.empty() && !osSecretAccessKey.empty()) ||
(!osRoleArn.empty() && !osSourceProfile.empty()) ||
(pszProfileOri != nullptr && !osRoleArn.empty() &&
!osWebIdentityTokenFile.empty());
}
/************************************************************************/
/* GetTemporaryCredentialsForRole() */
/************************************************************************/
// Issue a STS AssumedRole operation to get temporary credentials for an assumed
// role.
static bool GetTemporaryCredentialsForRole(
const std::string &osRoleArn, const std::string &osExternalId,
const std::string &osMFASerial, const std::string &osRoleSessionName,
const std::string &osSecretAccessKey, const std::string &osAccessKeyId,
const std::string &osSessionToken, std::string &osTempSecretAccessKey,
std::string &osTempAccessKeyId, std::string &osTempSessionToken,
std::string &osExpiration)
{
std::string osXAMZDate = CPLGetConfigOption("AWS_TIMESTAMP", "");
if (osXAMZDate.empty())
osXAMZDate = CPLGetAWS_SIGN4_Timestamp(time(nullptr));
std::string osDate(osXAMZDate);
osDate.resize(8);
const std::string osVerb("GET");
const std::string osService("sts");
const std::string osRegion(
CPLGetConfigOption("AWS_STS_REGION", "us-east-1"));
const std::string osHost(
CPLGetConfigOption("AWS_STS_ENDPOINT", "sts.amazonaws.com"));
std::map<std::string, std::string> oMap;
oMap["Version"] = "2011-06-15";
oMap["Action"] = "AssumeRole";
oMap["RoleArn"] = osRoleArn;
oMap["RoleSessionName"] =
!osRoleSessionName.empty()
? osRoleSessionName.c_str()
: CPLGetConfigOption("AWS_ROLE_SESSION_NAME", "GDAL-session");
if (!osExternalId.empty())
oMap["ExternalId"] = osExternalId;
if (!osMFASerial.empty())
oMap["SerialNumber"] = osMFASerial;
std::string osQueryString;
for (const auto &kv : oMap)
{
if (osQueryString.empty())
osQueryString += "?";
else
osQueryString += "&";
osQueryString += kv.first;
osQueryString += "=";
osQueryString += CPLAWSURLEncode(kv.second);
}
CPLString osCanonicalQueryString(osQueryString.substr(1));
const CPLString osAuthorization = CPLGetAWS_SIGN4_Authorization(
osSecretAccessKey, osAccessKeyId, osSessionToken, osRegion,
std::string(), // m_osRequestPayer,
osService, osVerb,
nullptr, // psExistingHeaders,
osHost, "/", osCanonicalQueryString,
CPLGetLowerCaseHexSHA256(std::string()),
false, // bAddHeaderAMZContentSHA256
osXAMZDate);
bool bRet = false;
const bool bUseHTTPS = CPLTestBool(CPLGetConfigOption("AWS_HTTPS", "YES"));
CPLStringList aosOptions;
std::string headers;
if (!osSessionToken.empty())
headers += "X-Amz-Security-Token: " + osSessionToken + "\r\n";
headers += "X-Amz-Date: " + osXAMZDate + "\r\n";
headers += "Authorization: " + osAuthorization;
aosOptions.AddNameValue("HEADERS", headers.c_str());
const std::string osURL =
(bUseHTTPS ? "https://" : "http://") + osHost + "/" + osQueryString;
CPLHTTPResult *psResult = CPLHTTPFetch(osURL.c_str(), aosOptions.List());
if (psResult)
{
if (psResult->nStatus == 0 && psResult->pabyData != nullptr)
{
CPLXMLTreeCloser oTree(CPLParseXMLString(
reinterpret_cast<char *>(psResult->pabyData)));
if (oTree)
{
const auto psCredentials = CPLGetXMLNode(
oTree.get(),
"=AssumeRoleResponse.AssumeRoleResult.Credentials");
if (psCredentials)
{
osTempAccessKeyId =
CPLGetXMLValue(psCredentials, "AccessKeyId", "");
osTempSecretAccessKey =
CPLGetXMLValue(psCredentials, "SecretAccessKey", "");
osTempSessionToken =
CPLGetXMLValue(psCredentials, "SessionToken", "");
osExpiration =
CPLGetXMLValue(psCredentials, "Expiration", "");
bRet = true;
}
else
{
CPLDebug("S3", "%s",
reinterpret_cast<char *>(psResult->pabyData));
}
}
}
CPLHTTPDestroyResult(psResult);
}
return bRet;
}
/************************************************************************/
/* GetOrRefreshTemporaryCredentialsForRole() */
/************************************************************************/
bool VSIS3HandleHelper::GetOrRefreshTemporaryCredentialsForRole(
bool bForceRefresh, CPLString &osSecretAccessKey, CPLString &osAccessKeyId,
CPLString &osSessionToken, CPLString &osRegion)
{
CPLMutexHolder oHolder(&ghMutex);
if (!bForceRefresh)
{
time_t nCurTime;
time(&nCurTime);
// Try to reuse credentials if they are still valid, but
// keep one minute of margin...
if (!gosGlobalAccessKeyId.empty() && nCurTime < gnGlobalExpiration - 60)
{
osAccessKeyId = gosGlobalAccessKeyId;
osSecretAccessKey = gosGlobalSecretAccessKey;
osSessionToken = gosGlobalSessionToken;
osRegion = gosRegion;
return true;
}
}
if (!gosRoleArnWebIdentity.empty())
{
if (GetConfigurationFromAssumeRoleWithWebIdentity(
bForceRefresh, std::string(), gosRoleArnWebIdentity,
gosWebIdentityTokenFile, osSecretAccessKey, osAccessKeyId,
osSessionToken))
{
gosSourceProfileSecretAccessKey = osSecretAccessKey;
gosSourceProfileAccessKeyId = osAccessKeyId;
gosSourceProfileSessionToken = osSessionToken;
}
else
{
return false;
}
}
std::string osExpiration;
gosGlobalSecretAccessKey.clear();
gosGlobalAccessKeyId.clear();
gosGlobalSessionToken.clear();
if (GetTemporaryCredentialsForRole(
gosRoleArn, gosExternalId, gosMFASerial, gosRoleSessionName,
gosSourceProfileSecretAccessKey, gosSourceProfileAccessKeyId,
gosSourceProfileSessionToken, gosGlobalSecretAccessKey,
gosGlobalAccessKeyId, gosGlobalSessionToken, osExpiration))
{
Iso8601ToUnixTime(osExpiration.c_str(), &gnGlobalExpiration);
osAccessKeyId = gosGlobalAccessKeyId;
osSecretAccessKey = gosGlobalSecretAccessKey;
osSessionToken = gosGlobalSessionToken;
osRegion = gosRegion;
return true;
}
return false;
}
/************************************************************************/
/* GetConfiguration() */
/************************************************************************/
bool VSIS3HandleHelper::GetConfiguration(
const std::string &osPathForOption, CSLConstList papszOptions,
CPLString &osSecretAccessKey, CPLString &osAccessKeyId,
CPLString &osSessionToken, CPLString &osRegion,
AWSCredentialsSource &eCredentialsSource)
{
eCredentialsSource = AWSCredentialsSource::REGULAR;
// AWS_REGION is GDAL specific. Later overloaded by standard
// AWS_DEFAULT_REGION
osRegion = CSLFetchNameValueDef(
papszOptions, "AWS_REGION",
VSIGetPathSpecificOption(osPathForOption.c_str(), "AWS_REGION",
"us-east-1"));
if (CPLTestBool(VSIGetPathSpecificOption(osPathForOption.c_str(),
"AWS_NO_SIGN_REQUEST", "NO")))
{
osSecretAccessKey.clear();
osAccessKeyId.clear();
osSessionToken.clear();
return true;
}
osSecretAccessKey = CSLFetchNameValueDef(
papszOptions, "AWS_SECRET_ACCESS_KEY",
VSIGetPathSpecificOption(osPathForOption.c_str(),
"AWS_SECRET_ACCESS_KEY", ""));
if (!osSecretAccessKey.empty())
{
osAccessKeyId = CSLFetchNameValueDef(
papszOptions, "AWS_ACCESS_KEY_ID",
VSIGetPathSpecificOption(osPathForOption.c_str(),
"AWS_ACCESS_KEY_ID", ""));
if (osAccessKeyId.empty())
{
VSIError(VSIE_AWSInvalidCredentials,
"AWS_ACCESS_KEY_ID configuration option not defined");
return false;
}
osSessionToken = CSLFetchNameValueDef(
papszOptions, "AWS_SESSION_TOKEN",
VSIGetPathSpecificOption(osPathForOption.c_str(),
"AWS_SESSION_TOKEN", ""));
return true;
}
// Next try to see if we have a current assumed role
bool bAssumedRole = false;
{
CPLMutexHolder oHolder(&ghMutex);
bAssumedRole = !gosRoleArn.empty();
}
if (bAssumedRole && GetOrRefreshTemporaryCredentialsForRole(
/* bForceRefresh = */ false, osSecretAccessKey,
osAccessKeyId, osSessionToken, osRegion))
{
eCredentialsSource = AWSCredentialsSource::ASSUMED_ROLE;
return true;
}
// Next try reading from ~/.aws/credentials and ~/.aws/config
CPLString osCredentials;
CPLString osRoleArn;
CPLString osSourceProfile;
CPLString osExternalId;
CPLString osMFASerial;
CPLString osRoleSessionName;
CPLString osWebIdentityTokenFile;
// coverity[tainted_data]
if (GetConfigurationFromAWSConfigFiles(
osPathForOption,
/* pszProfile = */ nullptr, osSecretAccessKey, osAccessKeyId,
osSessionToken, osRegion, osCredentials, osRoleArn, osSourceProfile,
osExternalId, osMFASerial, osRoleSessionName,
osWebIdentityTokenFile))
{
if (osSecretAccessKey.empty() && !osRoleArn.empty())
{
// Check if the default profile is pointing to another profile
// that has a role_arn and web_identity_token_file settings.
if (!osSourceProfile.empty())
{
CPLString osSecretAccessKeySP;
CPLString osAccessKeyIdSP;
CPLString osSessionTokenSP;
CPLString osRegionSP;
CPLString osCredentialsSP;
CPLString osRoleArnSP;
CPLString osSourceProfileSP;
CPLString osExternalIdSP;
CPLString osMFASerialSP;
CPLString osRoleSessionNameSP;
if (GetConfigurationFromAWSConfigFiles(
osPathForOption, osSourceProfile.c_str(),
osSecretAccessKeySP, osAccessKeyIdSP, osSessionTokenSP,
osRegionSP, osCredentialsSP, osRoleArnSP,
osSourceProfileSP, osExternalIdSP, osMFASerialSP,
osRoleSessionNameSP, osWebIdentityTokenFile))
{
if (GetConfigurationFromAssumeRoleWithWebIdentity(
/* bForceRefresh = */ false, osPathForOption,
osRoleArnSP, osWebIdentityTokenFile,
osSecretAccessKey, osAccessKeyId, osSessionToken))
{
CPLMutexHolder oHolder(&ghMutex);
gosRoleArnWebIdentity = osRoleArnSP;
gosWebIdentityTokenFile = osWebIdentityTokenFile;
}
}
}
if (gosRoleArnWebIdentity.empty())
{
// Get the credentials for the source profile, that will be
// used to sign the STS AssumedRole request.
if (!ReadAWSCredentials(osSourceProfile, osCredentials,
osSecretAccessKey, osAccessKeyId,
osSessionToken))
{
VSIError(
VSIE_AWSInvalidCredentials,
"Cannot retrieve credentials for source profile %s",
osSourceProfile.c_str());
return false;
}
}
std::string osTempSecretAccessKey;
std::string osTempAccessKeyId;
std::string osTempSessionToken;
std::string osExpiration;
if (GetTemporaryCredentialsForRole(
osRoleArn, osExternalId, osMFASerial, osRoleSessionName,
osSecretAccessKey, osAccessKeyId, osSessionToken,
osTempSecretAccessKey, osTempAccessKeyId,
osTempSessionToken, osExpiration))
{
CPLDebug("S3", "Using assumed role %s", osRoleArn.c_str());
{
// Store global variables to be able to reuse the
// temporary credentials
CPLMutexHolder oHolder(&ghMutex);
Iso8601ToUnixTime(osExpiration.c_str(),
&gnGlobalExpiration);
gosRoleArn = osRoleArn;
gosExternalId = osExternalId;
gosMFASerial = osMFASerial;
gosRoleSessionName = osRoleSessionName;
gosSourceProfileSecretAccessKey = osSecretAccessKey;
gosSourceProfileAccessKeyId = osAccessKeyId;
gosSourceProfileSessionToken = osSessionToken;
gosGlobalAccessKeyId = osTempAccessKeyId;
gosGlobalSecretAccessKey = osTempSecretAccessKey;
gosGlobalSessionToken = osTempSessionToken;
gosRegion = osRegion;
}
osSecretAccessKey = osTempSecretAccessKey;
osAccessKeyId = osTempAccessKeyId;
osSessionToken = osTempSessionToken;
eCredentialsSource = AWSCredentialsSource::ASSUMED_ROLE;
return true;
}
return false;
}
return true;
}
if (CPLTestBool(CPLGetConfigOption("CPL_AWS_WEB_IDENTITY_ENABLE", "YES")))
{
// WebIdentity method: use Web Identity Token
if (GetConfigurationFromAssumeRoleWithWebIdentity(
/* bForceRefresh = */ false, osPathForOption,
/* osRoleArnIn = */ std::string(),
/* osWebIdentityTokenFileIn = */ std::string(),
osSecretAccessKey, osAccessKeyId, osSessionToken))
{
eCredentialsSource = AWSCredentialsSource::WEB_IDENTITY;
return true;
}
}
// Last method: use IAM role security credentials on EC2 instances
if (GetConfigurationFromEC2(/* bForceRefresh = */ false, osPathForOption,
osSecretAccessKey, osAccessKeyId,
osSessionToken))
{
eCredentialsSource = AWSCredentialsSource::EC2;
return true;
}
VSIError(VSIE_AWSInvalidCredentials,
"AWS_SECRET_ACCESS_KEY and AWS_NO_SIGN_REQUEST configuration "
"options not defined, and %s not filled",
osCredentials.c_str());
return false;
}
/************************************************************************/
/* CleanMutex() */
/************************************************************************/
void VSIS3HandleHelper::CleanMutex()
{
if (ghMutex != nullptr)
CPLDestroyMutex(ghMutex);
ghMutex = nullptr;
}
/************************************************************************/
/* ClearCache() */
/************************************************************************/
void VSIS3HandleHelper::ClearCache()
{
CPLMutexHolder oHolder(&ghMutex);
gosIAMRole.clear();
gosGlobalAccessKeyId.clear();
gosGlobalSecretAccessKey.clear();
gosGlobalSessionToken.clear();
gnGlobalExpiration = 0;
gosRoleArn.clear();
gosExternalId.clear();
gosMFASerial.clear();
gosRoleSessionName.clear();
gosSourceProfileAccessKeyId.clear();
gosSourceProfileSecretAccessKey.clear();
gosSourceProfileSessionToken.clear();
gosRegion.clear();
gosRoleArnWebIdentity.clear();
gosWebIdentityTokenFile.clear();
}
/************************************************************************/
/* BuildFromURI() */
/************************************************************************/
VSIS3HandleHelper *VSIS3HandleHelper::BuildFromURI(const char *pszURI,
const char *pszFSPrefix,
bool bAllowNoObject,
CSLConstList papszOptions)
{
std::string osPathForOption("/vsis3/");
if (pszURI)
osPathForOption += pszURI;
CPLString osSecretAccessKey;
CPLString osAccessKeyId;
CPLString osSessionToken;
CPLString osRegion;
AWSCredentialsSource eCredentialsSource = AWSCredentialsSource::REGULAR;
if (!GetConfiguration(osPathForOption, papszOptions, osSecretAccessKey,
osAccessKeyId, osSessionToken, osRegion,
eCredentialsSource))
{
return nullptr;
}
// According to
// http://docs.aws.amazon.com/cli/latest/userguide/cli-environment.html "
// This variable overrides the default region of the in-use profile, if
// set."
const CPLString osDefaultRegion = CSLFetchNameValueDef(
papszOptions, "AWS_DEFAULT_REGION",
VSIGetPathSpecificOption(osPathForOption.c_str(), "AWS_DEFAULT_REGION",
""));
if (!osDefaultRegion.empty())
{
osRegion = osDefaultRegion;
}
const CPLString osEndpoint = VSIGetPathSpecificOption(
osPathForOption.c_str(), "AWS_S3_ENDPOINT", "s3.amazonaws.com");
const CPLString osRequestPayer = VSIGetPathSpecificOption(
osPathForOption.c_str(), "AWS_REQUEST_PAYER", "");
CPLString osBucket;
CPLString osObjectKey;
if (pszURI != nullptr && pszURI[0] != '\0' &&
!GetBucketAndObjectKey(pszURI, pszFSPrefix, bAllowNoObject, osBucket,
osObjectKey))
{
return nullptr;
}
const bool bUseHTTPS = CPLTestBool(
VSIGetPathSpecificOption(osPathForOption.c_str(), "AWS_HTTPS", "YES"));
const bool bIsValidNameForVirtualHosting =
osBucket.find('.') == std::string::npos;
const bool bUseVirtualHosting = CPLTestBool(CSLFetchNameValueDef(
papszOptions, "AWS_VIRTUAL_HOSTING",
VSIGetPathSpecificOption(osPathForOption.c_str(), "AWS_VIRTUAL_HOSTING",
bIsValidNameForVirtualHosting ? "TRUE"
: "FALSE")));
return new VSIS3HandleHelper(
osSecretAccessKey, osAccessKeyId, osSessionToken, osEndpoint, osRegion,
osRequestPayer, osBucket, osObjectKey, bUseHTTPS, bUseVirtualHosting,
eCredentialsSource);
}
/************************************************************************/
/* GetQueryString() */
/************************************************************************/
CPLString
IVSIS3LikeHandleHelper::GetQueryString(bool bAddEmptyValueAfterEqual) const
{
CPLString osQueryString;
std::map<CPLString, CPLString>::const_iterator oIter =
m_oMapQueryParameters.begin();
for (; oIter != m_oMapQueryParameters.end(); ++oIter)
{
if (oIter == m_oMapQueryParameters.begin())
osQueryString += "?";
else
osQueryString += "&";
osQueryString += oIter->first;
if (!oIter->second.empty() || bAddEmptyValueAfterEqual)
{
osQueryString += "=";
osQueryString += CPLAWSURLEncode(oIter->second);
}
}
return osQueryString;
}
/************************************************************************/
/* ResetQueryParameters() */
/************************************************************************/
void IVSIS3LikeHandleHelper::ResetQueryParameters()
{
m_oMapQueryParameters.clear();
RebuildURL();
}
/************************************************************************/
/* AddQueryParameter() */
/************************************************************************/
void IVSIS3LikeHandleHelper::AddQueryParameter(const CPLString &osKey,
const CPLString &osValue)
{
m_oMapQueryParameters[osKey] = osValue;
RebuildURL();
}
/************************************************************************/
/* GetURLNoKVP() */
/************************************************************************/
CPLString IVSIS3LikeHandleHelper::GetURLNoKVP() const
{
CPLString osURL(GetURL());
const auto nPos = osURL.find('?');
if (nPos != std::string::npos)
osURL.resize(nPos);
return osURL;
}
/************************************************************************/
/* RefreshCredentials() */
/************************************************************************/
void VSIS3HandleHelper::RefreshCredentials(const std::string &osPathForOption,
bool bForceRefresh) const
{
if (m_eCredentialsSource == AWSCredentialsSource::EC2)
{
CPLString osSecretAccessKey, osAccessKeyId, osSessionToken;
if (GetConfigurationFromEC2(bForceRefresh, osPathForOption.c_str(),
osSecretAccessKey, osAccessKeyId,
osSessionToken))
{
m_osSecretAccessKey = osSecretAccessKey;
m_osAccessKeyId = osAccessKeyId;
m_osSessionToken = osSessionToken;
}
}
else if (m_eCredentialsSource == AWSCredentialsSource::ASSUMED_ROLE)
{
CPLString osSecretAccessKey, osAccessKeyId, osSessionToken;
CPLString osRegion;
if (GetOrRefreshTemporaryCredentialsForRole(
bForceRefresh, osSecretAccessKey, osAccessKeyId, osSessionToken,
osRegion))
{
m_osSecretAccessKey = osSecretAccessKey;
m_osAccessKeyId = osAccessKeyId;
m_osSessionToken = osSessionToken;
}
}
else if (m_eCredentialsSource == AWSCredentialsSource::WEB_IDENTITY)
{
CPLString osSecretAccessKey, osAccessKeyId, osSessionToken;
CPLString osRegion;
if (GetConfigurationFromAssumeRoleWithWebIdentity(
bForceRefresh, osPathForOption.c_str(), std::string(),
std::string(), osSecretAccessKey, osAccessKeyId,
osSessionToken))
{
m_osSecretAccessKey = osSecretAccessKey;
m_osAccessKeyId = osAccessKeyId;
m_osSessionToken = osSessionToken;
}
}
}
/************************************************************************/
/* GetCurlHeaders() */
/************************************************************************/
struct curl_slist *VSIS3HandleHelper::GetCurlHeaders(
const CPLString &osVerb, const struct curl_slist *psExistingHeaders,
const void *pabyDataContent, size_t nBytesContent) const
{
std::string osPathForOption("/vsis3/");
osPathForOption += m_osBucket;
osPathForOption += '/';
osPathForOption += m_osObjectKey;
RefreshCredentials(osPathForOption, /* bForceRefresh = */ false);
CPLString osXAMZDate =
VSIGetPathSpecificOption(osPathForOption.c_str(), "AWS_TIMESTAMP", "");
if (osXAMZDate.empty())
osXAMZDate = CPLGetAWS_SIGN4_Timestamp(time(nullptr));
const CPLString osXAMZContentSHA256 =
CPLGetLowerCaseHexSHA256(pabyDataContent, nBytesContent);
CPLString osCanonicalQueryString(GetQueryString(true));
if (!osCanonicalQueryString.empty())
osCanonicalQueryString = osCanonicalQueryString.substr(1);
const CPLString osHost(m_bUseVirtualHosting && !m_osBucket.empty()
? CPLString(m_osBucket + "." + m_osEndpoint)
: m_osEndpoint);
const CPLString osAuthorization =
m_osSecretAccessKey.empty()
? CPLString()
: CPLGetAWS_SIGN4_Authorization(
m_osSecretAccessKey, m_osAccessKeyId, m_osSessionToken,
m_osRegion, m_osRequestPayer, "s3", osVerb, psExistingHeaders,
osHost,
m_bUseVirtualHosting
? CPLAWSURLEncode("/" + m_osObjectKey, false).c_str()
: CPLAWSURLEncode("/" + m_osBucket + "/" + m_osObjectKey,
false)
.c_str(),
osCanonicalQueryString, osXAMZContentSHA256,
true, // bAddHeaderAMZContentSHA256
osXAMZDate);
struct curl_slist *headers = nullptr;
headers = curl_slist_append(
headers, CPLSPrintf("x-amz-date: %s", osXAMZDate.c_str()));
headers =
curl_slist_append(headers, CPLSPrintf("x-amz-content-sha256: %s",
osXAMZContentSHA256.c_str()));
if (!m_osSessionToken.empty())
headers =
curl_slist_append(headers, CPLSPrintf("X-Amz-Security-Token: %s",
m_osSessionToken.c_str()));
if (!m_osRequestPayer.empty())
headers =
curl_slist_append(headers, CPLSPrintf("x-amz-request-payer: %s",
m_osRequestPayer.c_str()));
if (!osAuthorization.empty())
{
headers = curl_slist_append(
headers, CPLSPrintf("Authorization: %s", osAuthorization.c_str()));
}
return headers;
}
/************************************************************************/
/* CanRestartOnError() */
/************************************************************************/
bool VSIS3HandleHelper::CanRestartOnError(const char *pszErrorMsg,
const char *pszHeaders,
bool bSetError, bool *pbUpdateMap)
{
#ifdef DEBUG_VERBOSE
CPLDebug("S3", "%s", pszErrorMsg);
CPLDebug("S3", "%s", pszHeaders ? pszHeaders : "");
#endif
if (pbUpdateMap != nullptr)
*pbUpdateMap = true;
if (!STARTS_WITH(pszErrorMsg, "<?xml") &&
!STARTS_WITH(pszErrorMsg, "<Error>"))
{
if (bSetError)
{
VSIError(VSIE_AWSError, "Invalid AWS response: %s", pszErrorMsg);
}
return false;
}
CPLXMLNode *psTree = CPLParseXMLString(pszErrorMsg);
if (psTree == nullptr)
{
if (bSetError)
{
VSIError(VSIE_AWSError, "Malformed AWS XML response: %s",
pszErrorMsg);
}
return false;
}
const char *pszCode = CPLGetXMLValue(psTree, "=Error.Code", nullptr);
if (pszCode == nullptr)
{
CPLDestroyXMLNode(psTree);
if (bSetError)
{
VSIError(VSIE_AWSError, "Malformed AWS XML response: %s",
pszErrorMsg);
}
return false;
}
if (EQUAL(pszCode, "AuthorizationHeaderMalformed"))
{
const char *pszRegion =
CPLGetXMLValue(psTree, "=Error.Region", nullptr);
if (pszRegion == nullptr)
{
CPLDestroyXMLNode(psTree);
if (bSetError)
{
VSIError(VSIE_AWSError, "Malformed AWS XML response: %s",
pszErrorMsg);
}
return false;
}
SetRegion(pszRegion);
CPLDebug("S3", "Switching to region %s", m_osRegion.c_str());
CPLDestroyXMLNode(psTree);
return true;
}
if (EQUAL(pszCode, "PermanentRedirect") ||
EQUAL(pszCode, "TemporaryRedirect"))
{
const bool bIsTemporaryRedirect = EQUAL(pszCode, "TemporaryRedirect");
const char *pszEndpoint =
CPLGetXMLValue(psTree, "=Error.Endpoint", nullptr);
if (pszEndpoint == nullptr ||
(m_bUseVirtualHosting && (strncmp(pszEndpoint, m_osBucket.c_str(),
m_osBucket.size()) != 0 ||
pszEndpoint[m_osBucket.size()] != '.')))
{
CPLDestroyXMLNode(psTree);
if (bSetError)
{
VSIError(VSIE_AWSError, "Malformed AWS XML response: %s",
pszErrorMsg);
}
return false;
}
if (!m_bUseVirtualHosting &&
strncmp(pszEndpoint, m_osBucket.c_str(), m_osBucket.size()) == 0 &&
pszEndpoint[m_osBucket.size()] == '.')
{
/* If we have a body with
<Error><Code>PermanentRedirect</Code><Message>The bucket you are
attempting to access must be addressed using the specified endpoint.
Please send all future requests to this
endpoint.</Message><Bucket>bucket.with.dot</Bucket><Endpoint>bucket.with.dot.s3.amazonaws.com</Endpoint></Error>
and headers like
x-amz-bucket-region: eu-west-1
and the bucket name has dot in it,
then we must use s3.$(x-amz-bucket-region).amazon.com as endpoint.
See #7154 */
const char *pszRegionPtr =
(pszHeaders != nullptr)
? strstr(pszHeaders, "x-amz-bucket-region: ")
: nullptr;
if (strchr(m_osBucket.c_str(), '.') != nullptr &&
pszRegionPtr != nullptr)
{
CPLString osRegion(pszRegionPtr +
strlen("x-amz-bucket-region: "));
size_t nPos = osRegion.find('\r');
if (nPos != std::string::npos)
osRegion.resize(nPos);
SetEndpoint(
CPLSPrintf("s3.%s.amazonaws.com", osRegion.c_str()));
SetRegion(osRegion.c_str());
CPLDebug("S3", "Switching to endpoint %s",
m_osEndpoint.c_str());
CPLDebug("S3", "Switching to region %s", m_osRegion.c_str());
CPLDestroyXMLNode(psTree);
if (bIsTemporaryRedirect && pbUpdateMap != nullptr)
*pbUpdateMap = false;
return true;
}
m_bUseVirtualHosting = true;
CPLDebug("S3", "Switching to virtual hosting");
}
SetEndpoint(m_bUseVirtualHosting ? pszEndpoint + m_osBucket.size() + 1
: pszEndpoint);
CPLDebug("S3", "Switching to endpoint %s", m_osEndpoint.c_str());
CPLDestroyXMLNode(psTree);
if (bIsTemporaryRedirect && pbUpdateMap != nullptr)
*pbUpdateMap = false;
return true;
}
if (bSetError)
{
// Translate AWS errors into VSI errors.
const char *pszMessage =
CPLGetXMLValue(psTree, "=Error.Message", nullptr);
if (pszMessage == nullptr)
{
VSIError(VSIE_AWSError, "%s", pszErrorMsg);
}
else if (EQUAL(pszCode, "AccessDenied"))
{
VSIError(VSIE_AWSAccessDenied, "%s", pszMessage);
}
else if (EQUAL(pszCode, "NoSuchBucket"))
{
VSIError(VSIE_AWSBucketNotFound, "%s", pszMessage);
}
else if (EQUAL(pszCode, "NoSuchKey"))
{
VSIError(VSIE_AWSObjectNotFound, "%s", pszMessage);
}
else if (EQUAL(pszCode, "SignatureDoesNotMatch"))
{
VSIError(VSIE_AWSSignatureDoesNotMatch, "%s", pszMessage);
}
else
{
VSIError(VSIE_AWSError, "%s", pszMessage);
}
}
CPLDestroyXMLNode(psTree);
return false;
}
/************************************************************************/
/* SetEndpoint() */
/************************************************************************/
void VSIS3HandleHelper::SetEndpoint(const CPLString &osStr)
{
m_osEndpoint = osStr;
RebuildURL();
}
/************************************************************************/
/* SetRegion() */
/************************************************************************/
void VSIS3HandleHelper::SetRegion(const CPLString &osStr)
{
m_osRegion = osStr;
}
/************************************************************************/
/* SetRequestPayer() */
/************************************************************************/
void VSIS3HandleHelper::SetRequestPayer(const CPLString &osStr)
{
m_osRequestPayer = osStr;
}
/************************************************************************/
/* SetVirtualHosting() */
/************************************************************************/
void VSIS3HandleHelper::SetVirtualHosting(bool b)
{
m_bUseVirtualHosting = b;
RebuildURL();
}
/************************************************************************/
/* GetSignedURL() */
/************************************************************************/
CPLString VSIS3HandleHelper::GetSignedURL(CSLConstList papszOptions)
{
std::string osPathForOption("/vsis3/");
osPathForOption += m_osBucket;
osPathForOption += '/';
osPathForOption += m_osObjectKey;
CPLString osXAMZDate = CSLFetchNameValueDef(
papszOptions, "START_DATE",
VSIGetPathSpecificOption(osPathForOption.c_str(), "AWS_TIMESTAMP", ""));
if (osXAMZDate.empty())
osXAMZDate = CPLGetAWS_SIGN4_Timestamp(time(nullptr));
CPLString osDate(osXAMZDate);
osDate.resize(8);
CPLString osXAMZExpires =
CSLFetchNameValueDef(papszOptions, "EXPIRATION_DELAY", "3600");
if (m_eCredentialsSource != AWSCredentialsSource::REGULAR)
{
// For credentials that have an expiration, we must check their
// expiration compared to the expiration of the signed URL, since
// if the effective expiration is min(desired_expiration,
// credential_expiration) Cf
// https://aws.amazon.com/premiumsupport/knowledge-center/presigned-url-s3-bucket-expiration
int nYear, nMonth, nDay, nHour = 0, nMin = 0, nSec = 0;
if (sscanf(osXAMZDate, "%04d%02d%02dT%02d%02d%02dZ", &nYear, &nMonth,
&nDay, &nHour, &nMin, &nSec) < 3)
{
CPLError(CE_Failure, CPLE_AppDefined, "Bad format for START_DATE");
return CPLString();
}
struct tm brokendowntime;
brokendowntime.tm_year = nYear - 1900;
brokendowntime.tm_mon = nMonth - 1;
brokendowntime.tm_mday = nDay;
brokendowntime.tm_hour = nHour;
brokendowntime.tm_min = nMin;
brokendowntime.tm_sec = nSec;
const GIntBig nStartDate = CPLYMDHMSToUnixTime(&brokendowntime);
{
CPLMutexHolder oHolder(&ghMutex);
// Try to reuse credentials if they will still be valid after the
// desired end of the validity of the signed URL,
// with one minute of margin
if (nStartDate + CPLAtoGIntBig(osXAMZExpires.c_str()) >=
gnGlobalExpiration - 60)
{
RefreshCredentials(osPathForOption, /* bForceRefresh = */ true);
}
}
}
CPLString osVerb(CSLFetchNameValueDef(papszOptions, "VERB", "GET"));
ResetQueryParameters();
AddQueryParameter("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
AddQueryParameter("X-Amz-Credential", m_osAccessKeyId + "/" + osDate + "/" +
m_osRegion + "/s3/aws4_request");
AddQueryParameter("X-Amz-Date", osXAMZDate);
AddQueryParameter("X-Amz-Expires", osXAMZExpires);
if (!m_osSessionToken.empty())
AddQueryParameter("X-Amz-Security-Token", m_osSessionToken);
AddQueryParameter("X-Amz-SignedHeaders", "host");
CPLString osCanonicalQueryString(GetQueryString(true).substr(1));
const CPLString osHost(m_bUseVirtualHosting && !m_osBucket.empty()
? CPLString(m_osBucket + "." + m_osEndpoint)
: m_osEndpoint);
CPLString osSignedHeaders;
const CPLString osSignature = CPLGetAWS_SIGN4_Signature(
m_osSecretAccessKey,
std::string(), // sessionToken set to empty as we include it in query
// parameters
m_osRegion, m_osRequestPayer, "s3", osVerb,
nullptr, /* existing headers */
osHost,
m_bUseVirtualHosting
? CPLAWSURLEncode("/" + m_osObjectKey, false).c_str()
: CPLAWSURLEncode("/" + m_osBucket + "/" + m_osObjectKey, false)
.c_str(),
osCanonicalQueryString, "UNSIGNED-PAYLOAD",
false, // bAddHeaderAMZContentSHA256
osXAMZDate, osSignedHeaders);
AddQueryParameter("X-Amz-Signature", osSignature);
return m_osURL;
}
/************************************************************************/
/* UpdateMapFromHandle() */
/************************************************************************/
std::mutex VSIS3UpdateParams::gsMutex{};
std::map<CPLString, VSIS3UpdateParams>
VSIS3UpdateParams::goMapBucketsToS3Params{};
void VSIS3UpdateParams::UpdateMapFromHandle(
IVSIS3LikeHandleHelper *poHandleHelper)
{
std::lock_guard<std::mutex> guard(gsMutex);
VSIS3HandleHelper *poS3HandleHelper =
cpl::down_cast<VSIS3HandleHelper *>(poHandleHelper);
goMapBucketsToS3Params[poS3HandleHelper->GetBucket()] =
VSIS3UpdateParams(poS3HandleHelper);
}
/************************************************************************/
/* UpdateHandleFromMap() */
/************************************************************************/
void VSIS3UpdateParams::UpdateHandleFromMap(
IVSIS3LikeHandleHelper *poHandleHelper)
{
std::lock_guard<std::mutex> guard(gsMutex);
VSIS3HandleHelper *poS3HandleHelper =
cpl::down_cast<VSIS3HandleHelper *>(poHandleHelper);
std::map<CPLString, VSIS3UpdateParams>::iterator oIter =
goMapBucketsToS3Params.find(poS3HandleHelper->GetBucket());
if (oIter != goMapBucketsToS3Params.end())
{
oIter->second.UpdateHandlerHelper(poS3HandleHelper);
}
}
/************************************************************************/
/* ClearCache() */
/************************************************************************/
void VSIS3UpdateParams::ClearCache()
{
std::lock_guard<std::mutex> guard(gsMutex);
goMapBucketsToS3Params.clear();
}
#endif
//! @endcond
|