diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index cbbdf6a1bd..f2c4f57136 100755 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -42,6 +42,7 @@ set(core_public_header include/alibabacloud/core/Error.h include/alibabacloud/core/Global.h include/alibabacloud/core/HmacSha1Signer.h + include/alibabacloud/core/HmacSha256Signer.h include/alibabacloud/core/HttpClient.h include/alibabacloud/core/HttpMessage.h include/alibabacloud/core/HttpResponse.h @@ -103,6 +104,7 @@ set(core_src src/Executor.cc src/Executor.h src/HmacSha1Signer.cc + src/HmacSha256Signer.cc src/HttpClient.cc src/HttpMessage.cc src/HttpResponse.cc diff --git a/core/include/alibabacloud/core/HmacSha256Signer.h b/core/include/alibabacloud/core/HmacSha256Signer.h new file mode 100644 index 0000000000..28e4802920 --- /dev/null +++ b/core/include/alibabacloud/core/HmacSha256Signer.h @@ -0,0 +1,34 @@ +/* + * Copyright 1999-2019 Alibaba Cloud All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CORE_INCLUDE_ALIBABACLOUD_CORE_HMACSHA256SIGNER_H_ +#define CORE_INCLUDE_ALIBABACLOUD_CORE_HMACSHA256SIGNER_H_ + +#include "Signer.h" +#include + +namespace AlibabaCloud { +class ALIBABACLOUD_CORE_EXPORT HmacSha256Signer : public Signer { +public: + HmacSha256Signer(); + ~HmacSha256Signer(); + + std::string generate(const std::string &src, + const std::string &secret) const override; +}; +} // namespace AlibabaCloud + +#endif // CORE_INCLUDE_ALIBABACLOUD_CORE_HMACSHA256SIGNER_H_ diff --git a/core/include/alibabacloud/core/RoaServiceClient.h b/core/include/alibabacloud/core/RoaServiceClient.h index d3f79cce64..de4038c6d8 100644 --- a/core/include/alibabacloud/core/RoaServiceClient.h +++ b/core/include/alibabacloud/core/RoaServiceClient.h @@ -20,6 +20,7 @@ #include "CoreClient.h" #include "CredentialsProvider.h" #include "HmacSha1Signer.h" +#include "HmacSha256Signer.h" #include "HttpRequest.h" #include "RoaServiceRequest.h" #include @@ -37,7 +38,7 @@ class ALIBABACLOUD_CORE_EXPORT RoaServiceClient : public CoreClient { const std::shared_ptr &credentialsProvider, const ClientConfiguration &configuration, const std::shared_ptr &signer = - std::make_shared()); + std::make_shared()); virtual ~RoaServiceClient(); protected: diff --git a/core/include/alibabacloud/core/RpcServiceClient.h b/core/include/alibabacloud/core/RpcServiceClient.h index 30dc3c7a90..6e3e3f3e7a 100644 --- a/core/include/alibabacloud/core/RpcServiceClient.h +++ b/core/include/alibabacloud/core/RpcServiceClient.h @@ -20,6 +20,7 @@ #include "CoreClient.h" #include "CredentialsProvider.h" #include "HmacSha1Signer.h" +#include "HmacSha256Signer.h" #include "HttpRequest.h" #include "Outcome.h" #include "RpcServiceRequest.h" @@ -39,7 +40,7 @@ class ALIBABACLOUD_CORE_EXPORT RpcServiceClient : public CoreClient { const std::shared_ptr &credentialsProvider, const ClientConfiguration &configuration, const std::shared_ptr &signer = - std::make_shared()); + std::make_shared()); virtual ~RpcServiceClient(); std::shared_ptr credentialsProvider() { diff --git a/core/include/alibabacloud/core/Signer.h b/core/include/alibabacloud/core/Signer.h index 53e869f060..068c6b6014 100644 --- a/core/include/alibabacloud/core/Signer.h +++ b/core/include/alibabacloud/core/Signer.h @@ -25,6 +25,7 @@ class ALIBABACLOUD_CORE_EXPORT Signer { public: enum Type { HmacSha1, + HmacSha256, }; virtual ~Signer(); diff --git a/core/src/CommonClient.cc b/core/src/CommonClient.cc index 36fc646a2f..006e780ab2 100644 --- a/core/src/CommonClient.cc +++ b/core/src/CommonClient.cc @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -36,14 +37,14 @@ CommonClient::CommonClient(const Credentials &credentials, : CoreClient(SERVICE_NAME, configuration), credentialsProvider_( std::make_shared(credentials)), - signer_(std::make_shared()) {} + signer_(std::make_shared()) {} CommonClient::CommonClient( const std::shared_ptr &credentialsProvider, const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration), credentialsProvider_(credentialsProvider), - signer_(std::make_shared()) {} + signer_(std::make_shared()) {} CommonClient::CommonClient(const std::string &accessKeyId, const std::string &accessKeySecret, @@ -51,7 +52,7 @@ CommonClient::CommonClient(const std::string &accessKeyId, : CoreClient(SERVICE_NAME, configuration), credentialsProvider_(std::make_shared( accessKeyId, accessKeySecret)), - signer_(std::make_shared()) {} + signer_(std::make_shared()) {} CommonClient::~CommonClient() {} diff --git a/core/src/HmacSha256Signer.cc b/core/src/HmacSha256Signer.cc new file mode 100644 index 0000000000..b80fb48216 --- /dev/null +++ b/core/src/HmacSha256Signer.cc @@ -0,0 +1,105 @@ +/* + * Copyright 1999-2019 Alibaba Cloud All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#ifdef _WIN32 +#include +#include +#include +#include +#else +#include +#endif + +namespace AlibabaCloud { + +HmacSha256Signer::HmacSha256Signer() + : Signer(HmacSha256, "HMAC-SHA256", "1.0") {} + +HmacSha256Signer::~HmacSha256Signer() {} + +std::string HmacSha256Signer::generate(const std::string &src, + const std::string &secret) const { + if (src.empty() || secret.size() > (std::numeric_limits::max)()) + return std::string(); + +#ifdef _WIN32 + if (src.size() > MAXDWORD || + secret.size() > MAXDWORD - sizeof(BLOBHEADER) - sizeof(DWORD)) + return std::string(); + + std::vector keyBlob(sizeof(BLOBHEADER) + sizeof(DWORD) + secret.size()); + auto header = reinterpret_cast(keyBlob.data()); + header->bType = PLAINTEXTKEYBLOB; + header->bVersion = CUR_BLOB_VERSION; + header->aiKeyAlg = CALG_RC2; + DWORD keySize = static_cast(secret.size()); + std::memcpy(keyBlob.data() + sizeof(BLOBHEADER), &keySize, sizeof(keySize)); + std::memcpy(keyBlob.data() + sizeof(BLOBHEADER) + sizeof(DWORD), + secret.data(), secret.size()); + + HCRYPTPROV provider = 0; + HCRYPTKEY key = 0; + HCRYPTHASH hash = 0; + BYTE digest[32]; + DWORD digestSize = sizeof(digest); + HMAC_INFO info = {}; + info.HashAlgid = CALG_SHA_256; + bool success = + CryptAcquireContext(&provider, nullptr, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, + CRYPT_VERIFYCONTEXT) && + CryptImportKey(provider, keyBlob.data(), static_cast(keyBlob.size()), + 0, CRYPT_IPSEC_HMAC_KEY, &key) && + CryptCreateHash(provider, CALG_HMAC, key, 0, &hash) && + CryptSetHashParam(hash, HP_HMAC_INFO, reinterpret_cast(&info), 0) && + CryptHashData(hash, reinterpret_cast(src.data()), + static_cast(src.size()), 0) && + CryptGetHashParam(hash, HP_HASHVAL, digest, &digestSize, 0); + + if (hash) + CryptDestroyHash(hash); + if (key) + CryptDestroyKey(key); + if (provider) + CryptReleaseContext(provider, 0); + if (!success) + return std::string(); + + DWORD encodedSize = 0; + DWORD flags = CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF; + if (!CryptBinaryToStringA(digest, digestSize, flags, nullptr, &encodedSize)) + return std::string(); + std::string encoded(encodedSize, '\0'); + if (!CryptBinaryToStringA(digest, digestSize, flags, &encoded[0], &encodedSize)) + return std::string(); + encoded.resize(std::strlen(encoded.c_str())); + return encoded; +#else + unsigned char digest[EVP_MAX_MD_SIZE]; + unsigned int digestSize = sizeof(digest); + if (HMAC(EVP_sha256(), secret.data(), secret.size(), + reinterpret_cast(src.data()), src.size(), + digest, &digestSize) == nullptr) + return std::string(); + + unsigned char encoded[4 * ((EVP_MAX_MD_SIZE + 2) / 3) + 1]; + int encodedSize = EVP_EncodeBlock(encoded, digest, digestSize); + return std::string(reinterpret_cast(encoded), encodedSize); +#endif +} + +} // namespace AlibabaCloud diff --git a/test/core/CMakeLists.txt b/test/core/CMakeLists.txt index f35de17946..d06de25297 100644 --- a/test/core/CMakeLists.txt +++ b/test/core/CMakeLists.txt @@ -53,6 +53,7 @@ add_executable(core_ut httpresponse_ut.cc httpmessage_ut.cc hmacsha1signer_ut.cc + signaturev2_ut.cc networkproxy_ut.cc roaserviceclient_ut.cc roaservicerequest_ut.cc diff --git a/test/core/commonclient_ut.cc b/test/core/commonclient_ut.cc index 512c0854c6..cfd389c67d 100644 --- a/test/core/commonclient_ut.cc +++ b/test/core/commonclient_ut.cc @@ -126,7 +126,7 @@ namespace { string signature_nonce = "fb62c51d-f735-4ec7-870d-c6ce03368214"; EXPECT_TRUE(rr.header("x-acs-signature-nonce").length() == signature_nonce.length()); - EXPECT_TRUE(rr.header("x-acs-signature-method") == "HMAC-SHA1"); + EXPECT_TRUE(rr.header("x-acs-signature-method") == "HMAC-SHA256"); EXPECT_TRUE(rr.header("x-acs-signature-version") == "1.0"); EXPECT_TRUE(rr.header("x-acs-version") == ""); EXPECT_TRUE(rr.header("x-sdk-client") == string("CPP/").append(ALIBABACLOUD_VERSION_STR)); diff --git a/test/core/signaturev2_ut.cc b/test/core/signaturev2_ut.cc new file mode 100644 index 0000000000..595e5bcbf7 --- /dev/null +++ b/test/core/signaturev2_ut.cc @@ -0,0 +1,193 @@ +#include "gtest/gtest.h" +#include "alibabacloud/core/CommonClient.h" +#include "alibabacloud/core/HmacSha1Signer.h" +#include "alibabacloud/core/HmacSha256Signer.h" +#include "alibabacloud/core/RoaServiceClient.h" +#include "alibabacloud/core/RpcServiceClient.h" +#include "alibabacloud/core/SimpleCredentialsProvider.h" +#include "alibabacloud/core/StsAssumeRoleCredentialsProvider.h" +#include "alibabacloud/core/Utils.h" +#include +#include +#include + +using namespace AlibabaCloud; + +namespace { + +class SignatureV2RpcClient : public RpcServiceClient { +public: + using RpcServiceClient::RpcServiceClient; + using RpcServiceClient::buildHttpRequest; +}; + +class SignatureV2RoaClient : public RoaServiceClient { +public: + using RoaServiceClient::RoaServiceClient; + using RoaServiceClient::buildHttpRequest; +}; + +class SignatureV2CommonClient : public CommonClient { +public: + using CommonClient::CommonClient; + using CommonClient::buildRoaHttpRequest; + using CommonClient::buildRpcHttpRequest; +}; + +class SignatureV2StsProvider : public StsAssumeRoleCredentialsProvider { +public: + using StsAssumeRoleCredentialsProvider::StsAssumeRoleCredentialsProvider; + using RpcServiceClient::buildHttpRequest; +}; + +std::map parseParameters(const std::string &query) { + std::map parameters; + std::istringstream stream(query); + std::string part; + while (std::getline(stream, part, '&')) { + const auto equal = part.find('='); + parameters[UrlDecode(part.substr(0, equal))] = + equal == std::string::npos ? "" : UrlDecode(part.substr(equal + 1)); + } + return parameters; +} + +std::string expectedSignature(const std::string &text, const std::string &secret, + bool sha1) { + return sha1 ? HmacSha1Signer().generate(text, secret) + : HmacSha256Signer().generate(text, secret); +} + +void assertRpcSignature(const HttpRequest &request, const Credentials &credentials, + bool sha1) { + auto parameters = parseParameters(request.url().query()); + const auto signature = parameters["Signature"]; + parameters.erase("Signature"); + EXPECT_EQ(sha1 ? "HMAC-SHA1" : "HMAC-SHA256", parameters["SignatureMethod"]); + EXPECT_EQ("1.0", parameters["SignatureVersion"]); + EXPECT_EQ(credentials.sessionToken(), parameters["SecurityToken"]); + if (request.hasBody()) { + for (const auto &p : parseParameters(std::string(request.body(), request.bodySize()))) + parameters[p.first] = p.second; + } + std::string canonical; + for (const auto &p : parameters) { + if (!canonical.empty()) + canonical += "&"; + canonical += UrlEncode(p.first) + "=" + UrlEncode(p.second); + } + const auto text = HttpMethodToString(request.method()) + "&" + + UrlEncode(request.url().path()) + "&" + UrlEncode(canonical); + EXPECT_EQ(expectedSignature(text, credentials.accessKeySecret() + "&", sha1), + signature); +} + +void assertRoaSignature(const HttpRequest &request, const Credentials &credentials, + bool sha1) { + EXPECT_EQ(sha1 ? "HMAC-SHA1" : "HMAC-SHA256", + request.header("x-acs-signature-method")); + EXPECT_EQ("1.0", request.header("x-acs-signature-version")); + EXPECT_EQ(credentials.sessionToken(), request.header("x-acs-security-token")); + std::string text = HttpMethodToString(request.method()) + "\n" + + request.header("Accept") + "\n" + request.header("Content-MD5") + "\n" + + request.header("Content-Type") + "\n" + request.header("Date") + "\n"; + std::map headers; + for (const auto &h : request.headers()) { + std::string name = h.first; + std::transform(name.begin(), name.end(), name.begin(), + [](unsigned char c) { return std::tolower(c); }); + if (name.compare(0, 6, "x-acs-") == 0) + headers[name] = h.second; + } + for (const auto &h : headers) + text += h.first + ":" + h.second + "\n"; + text += request.url().path(); + if (request.url().hasQuery()) + text += "?" + request.url().query(); + EXPECT_EQ("acs " + credentials.accessKeyId() + ":" + + expectedSignature(text, credentials.accessKeySecret(), sha1), + request.header("Authorization")); +} + +TEST(SignatureV2, sha256KnownVectors) { + const HmacSha256Signer signer; + EXPECT_EQ(Signer::HmacSha256, signer.type()); + EXPECT_EQ("HMAC-SHA256", signer.name()); + EXPECT_EQ("1.0", signer.version()); + // RFC 4231 test case 1. + EXPECT_EQ("sDRMYdjbOFNcqK/OrwvxK4gdwgDJgz2nJuk3bC4yz/c=", + signer.generate("Hi There", std::string(20, '\x0b'))); + EXPECT_EQ("/QgKpBrZWLNf9ci7oAKwXwXZ7P6sB+o+gzsLm6V2mpM=", + signer.generate("中文 +/~*", "secret+/=")); + EXPECT_TRUE(signer.generate("", "").empty()); +} + +TEST(SignatureV2, defaultAlgorithm) { + for (const std::string &token : {std::string(), std::string("token+/=")}) { + for (auto method : {HttpRequest::Method::Get, HttpRequest::Method::Post}) { + ClientConfiguration config("cn-hangzhou"); + const Credentials credentials("test-key", "test-secret", token); + auto provider = std::make_shared(credentials); + SignatureV2RpcClient rpc("ecs", provider, config); + RpcServiceRequest rpcRequest("Ecs", "2014-05-26", "DescribeRegions"); + rpcRequest.setBodyParameter("Value", "中文 +/~*"); + assertRpcSignature(rpc.buildHttpRequest("example.test", rpcRequest, method), + credentials, false); + + SignatureV2RoaClient roa("cs", provider, config); + RoaServiceRequest roaRequest("CS", "2015-12-15"); + roaRequest.setResourcePath("/regions/cn-hangzhou/clusters"); + const std::string body = "中文 +/~*"; + roaRequest.setContent(body.data(), body.size()); + assertRoaSignature(roa.buildHttpRequest("example.test", roaRequest, method), + credentials, false); + + CommonRequest commonRequest; + commonRequest.setVersion("2014-05-26"); + commonRequest.setBodyParameter("Value", "中文 +/~*"); + SignatureV2CommonClient common(credentials, config); + assertRpcSignature(common.buildRpcHttpRequest("example.test", commonRequest, method), + credentials, false); + assertRoaSignature(common.buildRoaHttpRequest("example.test", commonRequest, method), + credentials, false); + SignatureV2CommonClient byProvider(provider, config); + assertRpcSignature(byProvider.buildRpcHttpRequest("example.test", commonRequest, method), + credentials, false); + SignatureV2CommonClient byKey("test-key", "test-secret", config); + assertRpcSignature(byKey.buildRpcHttpRequest("example.test", commonRequest, method), + Credentials("test-key", "test-secret"), false); + } + } +} + +TEST(SignatureV2, explicitSignerIsPreserved) { + const Credentials credentials("test-key", "test-secret"); + auto provider = std::make_shared(credentials); + for (bool sha1 : {false, true}) { + ClientConfiguration config; + std::shared_ptr signer = sha1 + ? std::shared_ptr(std::make_shared()) + : std::make_shared(); + SignatureV2RpcClient rpc("ecs", provider, config, signer); + RpcServiceRequest rpcRequest("Ecs", "2014-05-26", "DescribeRegions"); + assertRpcSignature(rpc.buildHttpRequest("example.test", rpcRequest, HttpRequest::Method::Get), + credentials, sha1); + SignatureV2RoaClient roa("cs", provider, config, signer); + RoaServiceRequest roaRequest("CS", "2015-12-15"); + assertRoaSignature(roa.buildHttpRequest("example.test", roaRequest, HttpRequest::Method::Get), + credentials, sha1); + } +} + +TEST(SignatureV2, assumeRoleUsesSha256) { + const Credentials credentials("source-key", "source-secret"); + ClientConfiguration config; + SignatureV2StsProvider provider(credentials, config, "acs:ram::123:role/test", "session"); + Sts::Model::AssumeRoleRequest request; + request.setRoleArn("acs:ram::123:role/test"); + request.setRoleSessionName("session"); + assertRpcSignature(provider.buildHttpRequest("sts.example.test", request, HttpRequest::Method::Post), + credentials, false); +} + +} // namespace