1 //
2 // Copyright 2020 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 #include <grpc/support/port_platform.h>
17
18 #include "src/core/lib/security/credentials/external/aws_request_signer.h"
19
20 #include "absl/strings/ascii.h"
21 #include "absl/strings/escaping.h"
22 #include "absl/strings/str_format.h"
23 #include "absl/strings/str_join.h"
24 #include "absl/strings/str_split.h"
25 #include "absl/time/clock.h"
26 #include "absl/time/time.h"
27
28 #include <openssl/hmac.h>
29 #include <openssl/sha.h>
30
31 namespace grpc_core {
32
33 namespace {
34
35 const char kAlgorithm[] = "AWS4-HMAC-SHA256";
36 const char kDateFormat[] = "%a, %d %b %E4Y %H:%M:%S %Z";
37 const char kXAmzDateFormat[] = "%Y%m%dT%H%M%SZ";
38
SHA256(const std::string & str,unsigned char out[SHA256_DIGEST_LENGTH])39 void SHA256(const std::string& str, unsigned char out[SHA256_DIGEST_LENGTH]) {
40 SHA256_CTX sha256;
41 SHA256_Init(&sha256);
42 SHA256_Update(&sha256, str.c_str(), str.size());
43 SHA256_Final(out, &sha256);
44 }
45
SHA256Hex(const std::string & str)46 std::string SHA256Hex(const std::string& str) {
47 unsigned char hash[SHA256_DIGEST_LENGTH];
48 SHA256(str, hash);
49 std::string hash_str(reinterpret_cast<char const*>(hash),
50 SHA256_DIGEST_LENGTH);
51 return absl::BytesToHexString(hash_str);
52 }
53
HMAC(const std::string & key,const std::string & msg)54 std::string HMAC(const std::string& key, const std::string& msg) {
55 unsigned int len;
56 unsigned char digest[EVP_MAX_MD_SIZE];
57 HMAC(EVP_sha256(), key.c_str(), key.length(),
58 reinterpret_cast<const unsigned char*>(msg.c_str()), msg.length(),
59 digest, &len);
60 return std::string(digest, digest + len);
61 }
62
63 } // namespace
64
AwsRequestSigner(std::string access_key_id,std::string secret_access_key,std::string token,std::string method,std::string url,std::string region,std::string request_payload,std::map<std::string,std::string> additional_headers,grpc_error ** error)65 AwsRequestSigner::AwsRequestSigner(
66 std::string access_key_id, std::string secret_access_key, std::string token,
67 std::string method, std::string url, std::string region,
68 std::string request_payload,
69 std::map<std::string, std::string> additional_headers, grpc_error** error)
70 : access_key_id_(std::move(access_key_id)),
71 secret_access_key_(std::move(secret_access_key)),
72 token_(std::move(token)),
73 method_(std::move(method)),
74 region_(std::move(region)),
75 request_payload_(std::move(request_payload)),
76 additional_headers_(std::move(additional_headers)) {
77 auto amz_date_it = additional_headers_.find("x-amz-date");
78 auto date_it = additional_headers_.find("date");
79 if (amz_date_it != additional_headers_.end() &&
80 date_it != additional_headers_.end()) {
81 *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
82 "Only one of {date, x-amz-date} can be specified, not both.");
83 return;
84 }
85 if (amz_date_it != additional_headers_.end()) {
86 static_request_date_ = amz_date_it->second;
87 } else if (date_it != additional_headers_.end()) {
88 absl::Time request_date;
89 std::string err_str;
90 if (!absl::ParseTime(kDateFormat, date_it->second, &request_date,
91 &err_str)) {
92 *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(err_str.c_str());
93 return;
94 }
95 static_request_date_ =
96 absl::FormatTime(kXAmzDateFormat, request_date, absl::UTCTimeZone());
97 }
98 absl::StatusOr<URI> tmp_url = URI::Parse(url);
99 if (!tmp_url.ok()) {
100 *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Invalid Aws request url.");
101 return;
102 }
103 url_ = tmp_url.value();
104 }
105
GetSignedRequestHeaders()106 std::map<std::string, std::string> AwsRequestSigner::GetSignedRequestHeaders() {
107 std::string request_date_full;
108 if (!static_request_date_.empty()) {
109 if (!request_headers_.empty()) {
110 return request_headers_;
111 }
112 request_date_full = static_request_date_;
113 } else {
114 absl::Time request_date = absl::Now();
115 request_date_full =
116 absl::FormatTime(kXAmzDateFormat, request_date, absl::UTCTimeZone());
117 }
118 std::string request_date_short = request_date_full.substr(0, 8);
119 // TASK 1: Create a canonical request for Signature Version 4
120 // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
121 std::vector<absl::string_view> canonical_request_vector;
122 // 1. HTTPRequestMethod
123 canonical_request_vector.emplace_back(method_);
124 canonical_request_vector.emplace_back("\n");
125 // 2. CanonicalURI
126 canonical_request_vector.emplace_back(
127 url_.path().empty() ? "/" : absl::string_view(url_.path()));
128 canonical_request_vector.emplace_back("\n");
129 // 3. CanonicalQueryString
130 std::vector<std::string> query_vector;
131 for (const URI::QueryParam& query_kv : url_.query_parameter_pairs()) {
132 query_vector.emplace_back(absl::StrCat(query_kv.key, "=", query_kv.value));
133 }
134 std::string query = absl::StrJoin(query_vector, "&");
135 canonical_request_vector.emplace_back(query);
136 canonical_request_vector.emplace_back("\n");
137 // 4. CanonicalHeaders
138 if (request_headers_.empty()) {
139 request_headers_.insert({"host", url_.authority()});
140 if (!token_.empty()) {
141 request_headers_.insert({"x-amz-security-token", token_});
142 }
143 for (const auto& header : additional_headers_) {
144 request_headers_.insert(
145 {absl::AsciiStrToLower(header.first), header.second});
146 }
147 }
148 if (additional_headers_.find("date") == additional_headers_.end()) {
149 request_headers_["x-amz-date"] = request_date_full;
150 }
151 std::vector<absl::string_view> canonical_headers_vector;
152 for (const auto& header : request_headers_) {
153 canonical_headers_vector.emplace_back(header.first);
154 canonical_headers_vector.emplace_back(":");
155 canonical_headers_vector.emplace_back(header.second);
156 canonical_headers_vector.emplace_back("\n");
157 }
158 std::string canonical_headers = absl::StrJoin(canonical_headers_vector, "");
159 canonical_request_vector.emplace_back(canonical_headers);
160 canonical_request_vector.emplace_back("\n");
161 // 5. SignedHeaders
162 std::vector<absl::string_view> signed_headers_vector;
163 for (const auto& header : request_headers_) {
164 signed_headers_vector.emplace_back(header.first);
165 }
166 std::string signed_headers = absl::StrJoin(signed_headers_vector, ";");
167 canonical_request_vector.emplace_back(signed_headers);
168 canonical_request_vector.emplace_back("\n");
169 // 6. RequestPayload
170 std::string hashed_request_payload = SHA256Hex(request_payload_);
171 canonical_request_vector.emplace_back(hashed_request_payload);
172 std::string canonical_request = absl::StrJoin(canonical_request_vector, "");
173 // TASK 2: Create a string to sign for Signature Version 4
174 // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
175 std::vector<absl::string_view> string_to_sign_vector;
176 // 1. Algorithm
177 string_to_sign_vector.emplace_back("AWS4-HMAC-SHA256");
178 string_to_sign_vector.emplace_back("\n");
179 // 2. RequestDateTime
180 string_to_sign_vector.emplace_back(request_date_full);
181 string_to_sign_vector.emplace_back("\n");
182 // 3. CredentialScope
183 std::pair<absl::string_view, absl::string_view> host_parts =
184 absl::StrSplit(url_.authority(), absl::MaxSplits('.', 1));
185 std::string service_name(host_parts.first);
186 std::string credential_scope = absl::StrFormat(
187 "%s/%s/%s/aws4_request", request_date_short, region_, service_name);
188 string_to_sign_vector.emplace_back(credential_scope);
189 string_to_sign_vector.emplace_back("\n");
190 // 4. HashedCanonicalRequest
191 std::string hashed_canonical_request = SHA256Hex(canonical_request);
192 string_to_sign_vector.emplace_back(hashed_canonical_request);
193 std::string string_to_sign = absl::StrJoin(string_to_sign_vector, "");
194 // TASK 3: Task 3: Calculate the signature for AWS Signature Version 4
195 // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
196 // 1. Derive your signing key.
197 std::string date = HMAC("AWS4" + secret_access_key_, request_date_short);
198 std::string region = HMAC(date, region_);
199 std::string service = HMAC(region, service_name);
200 std::string signing = HMAC(service, "aws4_request");
201 // 2. Calculate the signature.
202 std::string signature_str = HMAC(signing, string_to_sign);
203 std::string signature = absl::BytesToHexString(signature_str);
204 // TASK 4: Add the signature to the HTTP request
205 // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html
206 std::string authorization_header = absl::StrFormat(
207 "%s Credential=%s/%s, SignedHeaders=%s, Signature=%s", kAlgorithm,
208 access_key_id_, credential_scope, signed_headers, signature);
209 request_headers_["Authorization"] = authorization_header;
210 return request_headers_;
211 }
212
213 } // namespace grpc_core
214