Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/Signature/SignatureV4.php

raw symbols SCIP
1 <?php
2 namespace Aws\Signature;
3
4 use Aws\Credentials\CredentialsInterface;
5 use AWS\CRT\Auth\Signable;
6 use AWS\CRT\Auth\SignatureType;
7 use AWS\CRT\Auth\SignedBodyHeaderType;
8 use AWS\CRT\Auth\Signing;
9 use AWS\CRT\Auth\SigningAlgorithm;
10 use AWS\CRT\Auth\SigningConfigAWS;
11 use AWS\CRT\Auth\StaticCredentialsProvider;
12 use AWS\CRT\HTTP\Request;
13 use Aws\Exception\CommonRuntimeException;
14 use Aws\Exception\CouldNotCreateChecksumException;
15 use GuzzleHttp\Psr7;
16 use Psr\Http\Message\RequestInterface;
17
18 /**
19 * Signature Version 4
20 * @link http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
21 */
22 class SignatureV4 implements SignatureInterface
23 {
24 use SignatureTrait;
25 const ISO8601_BASIC = 'Ymd\THis\Z';
26 const UNSIGNED_PAYLOAD = 'UNSIGNED-PAYLOAD';
27 const AMZ_CONTENT_SHA256_HEADER = 'X-Amz-Content-Sha256';
28
29 /** @var string */
30 private $service;
31
32 /** @var string */
33 protected $region;
34
35 /** @var bool */
36 private $unsigned;
37
38 /** @var bool */
39 private $useV4a;
40
41 /**
42 * The following headers are not signed because signing these headers
43 * would potentially cause a signature mismatch when sending a request
44 * through a proxy or if modified at the HTTP client level.
45 *
46 * @return array
47 */
48 protected function getHeaderBlacklist()
49 {
50 return [
51 'cache-control' => true,
52 'content-type' => true,
53 'content-length' => true,
54 'expect' => true,
55 'max-forwards' => true,
56 'pragma' => true,
57 'range' => true,
58 'te' => true,
59 'if-match' => true,
60 'if-none-match' => true,
61 'if-modified-since' => true,
62 'if-unmodified-since' => true,
63 'if-range' => true,
64 'accept' => true,
65 'authorization' => true,
66 'proxy-authorization' => true,
67 'from' => true,
68 'referer' => true,
69 'user-agent' => true,
70 'X-Amz-User-Agent' => true,
71 'x-amzn-trace-id' => true,
72 'aws-sdk-invocation-id' => true,
73 'aws-sdk-retry' => true,
74 ];
75 }
76
77 /**
78 * @param string $service Service name to use when signing
79 * @param string $region Region name to use when signing
80 * @param array $options Array of configuration options used when signing
81 * - unsigned-body: Flag to make request have unsigned payload.
82 * Unsigned body is used primarily for streaming requests.
83 */
84 public function __construct($service, $region, array $options = [])
85 {
86 $this->service = $service;
87 $this->region = $region;
88 $this->unsigned = isset($options['unsigned-body']) ? $options['unsigned-body'] : false;
89 $this->useV4a = isset($options['use_v4a']) && $options['use_v4a'] === true;
90 }
91
92 /**
93 * {@inheritdoc}
94 */
95 public function signRequest(
96 RequestInterface $request,
97 CredentialsInterface $credentials,
98 $signingService = null
99 ) {
100 $ldt = gmdate(self::ISO8601_BASIC);
101 $sdt = substr($ldt, 0, 8);
102 $parsed = $this->parseRequest($request);
103 $parsed['headers']['X-Amz-Date'] = [$ldt];
104
105 if ($token = $credentials->getSecurityToken()) {
106 $parsed['headers']['X-Amz-Security-Token'] = [$token];
107 }
108 $service = isset($signingService) ? $signingService : $this->service;
109
110 if ($this->useV4a) {
111 return $this->signWithV4a($credentials, $request, $service);
112 }
113
114 $cs = $this->createScope($sdt, $this->region, $service);
115 $payload = $this->getPayload($request);
116
117 if ($payload == self::UNSIGNED_PAYLOAD) {
118 $parsed['headers'][self::AMZ_CONTENT_SHA256_HEADER] = [$payload];
119 }
120
121 $context = $this->createContext($parsed, $payload);
122 $toSign = $this->createStringToSign($ldt, $cs, $context['creq']);
123 $signingKey = $this->getSigningKey(
124 $sdt,
125 $this->region,
126 $service,
127 $credentials->getSecretKey()
128 );
129 $signature = hash_hmac('sha256', $toSign, $signingKey);
130 $parsed['headers']['Authorization'] = [
131 "AWS4-HMAC-SHA256 "
132 . "Credential={$credentials->getAccessKeyId()}/{$cs}, "
133 . "SignedHeaders={$context['headers']}, Signature={$signature}"
134 ];
135
136 return $this->buildRequest($parsed);
137 }
138
139 /**
140 * Get the headers that were used to pre-sign the request.
141 * Used for the X-Amz-SignedHeaders header.
142 *
143 * @param array $headers
144 * @return array
145 */
146 private function getPresignHeaders(array $headers)
147 {
148 $presignHeaders = [];
149 $blacklist = $this->getHeaderBlacklist();
150 foreach ($headers as $name => $value) {
151 $lName = strtolower($name);
152 if (!isset($blacklist[$lName])
153 && $name !== self::AMZ_CONTENT_SHA256_HEADER
154 ) {
155 $presignHeaders[] = $lName;
156 }
157 }
158
159 sort($presignHeaders);
160
161 return $presignHeaders;
162 }
163
164 /**
165 * {@inheritdoc}
166 */
167 public function presign(
168 RequestInterface $request,
169 CredentialsInterface $credentials,
170 $expires,
171 array $options = []
172 ) {
173 $startTimestamp = isset($options['start_time'])
174 ? $this->convertToTimestamp($options['start_time'], null)
175 : time();
176 $expiresTimestamp = $this->convertToTimestamp($expires, $startTimestamp);
177
178 if ($this->useV4a) {
179 return $this->presignWithV4a(
180 $request,
181 $credentials,
182 $this->convertExpires($expiresTimestamp, $startTimestamp)
183 );
184 }
185
186 $parsed = $this->createPresignedRequest($request, $credentials);
187
188 $payload = $this->getPresignedPayload($request);
189 $httpDate = gmdate(self::ISO8601_BASIC, $startTimestamp);
190 $shortDate = substr($httpDate, 0, 8);
191 $scope = $this->createScope($shortDate, $this->region, $this->service);
192 $credential = $credentials->getAccessKeyId() . '/' . $scope;
193 if ($credentials->getSecurityToken()) {
194 unset($parsed['headers']['X-Amz-Security-Token']);
195 }
196 $parsed['query']['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256';
197 $parsed['query']['X-Amz-Credential'] = $credential;
198 $parsed['query']['X-Amz-Date'] = gmdate('Ymd\THis\Z', $startTimestamp);
199 $parsed['query']['X-Amz-SignedHeaders'] = implode(';', $this->getPresignHeaders($parsed['headers']));
200 $parsed['query']['X-Amz-Expires'] = $this->convertExpires($expiresTimestamp, $startTimestamp);
201 $context = $this->createContext($parsed, $payload);
202 $stringToSign = $this->createStringToSign($httpDate, $scope, $context['creq']);
203 $key = $this->getSigningKey(
204 $shortDate,
205 $this->region,
206 $this->service,
207 $credentials->getSecretKey()
208 );
209 $parsed['query']['X-Amz-Signature'] = hash_hmac('sha256', $stringToSign, $key);
210
211 return $this->buildRequest($parsed);
212 }
213
214 /**
215 * Converts a POST request to a GET request by moving POST fields into the
216 * query string.
217 *
218 * Useful for pre-signing query protocol requests.
219 *
220 * @param RequestInterface $request Request to clone
221 *
222 * @return RequestInterface
223 * @throws \InvalidArgumentException if the method is not POST
224 */
225 public static function convertPostToGet(RequestInterface $request, $additionalQueryParams = "")
226 {
227 if ($request->getMethod() !== 'POST') {
228 throw new \InvalidArgumentException('Expected a POST request but '
229 . 'received a ' . $request->getMethod() . ' request.');
230 }
231
232 $sr = $request->withMethod('GET')
233 ->withBody(Psr7\Utils::streamFor(''))
234 ->withoutHeader('Content-Type')
235 ->withoutHeader('Content-Length');
236
237 // Move POST fields to the query if they are present
238 if ($request->getHeaderLine('Content-Type') === 'application/x-www-form-urlencoded') {
239 $body = (string) $request->getBody() . $additionalQueryParams;
240 $sr = $sr->withUri($sr->getUri()->withQuery($body));
241 }
242
243 return $sr;
244 }
245
246 protected function getPayload(RequestInterface $request)
247 {
248 if ($this->unsigned && $request->getUri()->getScheme() == 'https') {
249 return self::UNSIGNED_PAYLOAD;
250 }
251 // Calculate the request signature payload
252 if ($request->hasHeader(self::AMZ_CONTENT_SHA256_HEADER)) {
253 // Handle streaming operations (e.g. Glacier.UploadArchive)
254 return $request->getHeaderLine(self::AMZ_CONTENT_SHA256_HEADER);
255 }
256
257 if (!$request->getBody()->isSeekable()) {
258 throw new CouldNotCreateChecksumException('sha256');
259 }
260
261 try {
262 return Psr7\Utils::hash($request->getBody(), 'sha256');
263 } catch (\Exception $e) {
264 throw new CouldNotCreateChecksumException('sha256', $e);
265 }
266 }
267
268 protected function getPresignedPayload(RequestInterface $request)
269 {
270 return $this->getPayload($request);
271 }
272
273 protected function createCanonicalizedPath($path)
274 {
275 $doubleEncoded = rawurlencode(ltrim($path, '/'));
276
277 return '/' . str_replace('%2F', '/', $doubleEncoded);
278 }
279
280 private function createStringToSign($longDate, $credentialScope, $creq)
281 {
282 $hash = hash('sha256', $creq);
283
284 return "AWS4-HMAC-SHA256\n{$longDate}\n{$credentialScope}\n{$hash}";
285 }
286
287 private function createPresignedRequest(
288 RequestInterface $request,
289 CredentialsInterface $credentials
290 ) {
291 $parsedRequest = $this->parseRequest($request);
292
293 // Make sure to handle temporary credentials
294 if ($token = $credentials->getSecurityToken()) {
295 $parsedRequest['headers']['X-Amz-Security-Token'] = [$token];
296 }
297
298 return $this->moveHeadersToQuery($parsedRequest);
299 }
300
301 /**
302 * @param array $parsedRequest
303 * @param string $payload Hash of the request payload
304 * @return array Returns an array of context information
305 */
306 private function createContext(array $parsedRequest, $payload)
307 {
308 $blacklist = $this->getHeaderBlacklist();
309
310 // Normalize the path as required by SigV4
311 $canon = $parsedRequest['method'] . "\n"
312 . $this->createCanonicalizedPath($parsedRequest['path']) . "\n"
313 . $this->getCanonicalizedQuery($parsedRequest['query']) . "\n";
314
315 // Case-insensitively aggregate all of the headers.
316 $aggregate = [];
317 foreach ($parsedRequest['headers'] as $key => $values) {
318 $key = strtolower($key);
319 if (!isset($blacklist[$key])) {
320 foreach ($values as $v) {
321 $aggregate[$key][] = $v;
322 }
323 }
324 }
325
326 ksort($aggregate);
327 $canonHeaders = [];
328 foreach ($aggregate as $k => $v) {
329 if (count($v) > 0) {
330 sort($v);
331 }
332 $canonHeaders[] = $k . ':' . preg_replace('/\s+/', ' ', implode(',', $v));
333 }
334
335 $signedHeadersString = implode(';', array_keys($aggregate));
336 $canon .= implode("\n", $canonHeaders) . "\n\n"
337 . $signedHeadersString . "\n"
338 . $payload;
339
340 return ['creq' => $canon, 'headers' => $signedHeadersString];
341 }
342
343 private function getCanonicalizedQuery(array $query)
344 {
345 unset($query['X-Amz-Signature']);
346
347 if (!$query) {
348 return '';
349 }
350
351 $qs = '';
352 uksort($query, static function (string $a, string $b): int {
353 return strcmp(rawurlencode($a), rawurlencode($b));
354 });
355 foreach ($query as $k => $v) {
356 if (!is_array($v)) {
357 $qs .= rawurlencode($k) . '=' . rawurlencode($v !== null ? $v : '') . '&';
358 } else {
359 sort($v, SORT_STRING);
360 foreach ($v as $value) {
361 $qs .= rawurlencode($k) . '=' . rawurlencode($value !== null ? $value : '') . '&';
362 }
363 }
364 }
365
366 return substr($qs, 0, -1);
367 }
368
369 private function convertToTimestamp($dateValue, $relativeTimeBase = null)
370 {
371 if ($dateValue instanceof \DateTimeInterface) {
372 $timestamp = $dateValue->getTimestamp();
373 } elseif (!is_numeric($dateValue)) {
374 $timestamp = strtotime($dateValue,
375 $relativeTimeBase === null ? time() : $relativeTimeBase
376 );
377 } else {
378 $timestamp = $dateValue;
379 }
380
381 return $timestamp;
382 }
383
384 private function convertExpires($expiresTimestamp, $startTimestamp)
385 {
386 $duration = $expiresTimestamp - $startTimestamp;
387
388 // Ensure that the duration of the signature is not longer than a week
389 if ($duration > 604800) {
390 throw new \InvalidArgumentException('The expiration date of a '
391 . 'signature version 4 presigned URL must be less than one '
392 . 'week');
393 }
394
395 return $duration;
396 }
397
398 private function moveHeadersToQuery(array $parsedRequest)
399 {
400 //x-amz-user-agent shouldn't be put in a query param
401 unset($parsedRequest['headers']['X-Amz-User-Agent']);
402
403 foreach ($parsedRequest['headers'] as $name => $header) {
404 $lname = strtolower($name);
405 if (substr($lname, 0, 5) == 'x-amz') {
406 $parsedRequest['query'][$name] = $header;
407 }
408 $blacklist = $this->getHeaderBlacklist();
409 if (isset($blacklist[$lname])
410 || $lname === strtolower(self::AMZ_CONTENT_SHA256_HEADER)
411 ) {
412 unset($parsedRequest['headers'][$name]);
413 }
414 }
415
416 return $parsedRequest;
417 }
418
419 private function parseRequest(RequestInterface $request)
420 {
421 // Clean up any previously set headers.
422 /** @var RequestInterface $request */
423 $request = $request
424 ->withoutHeader('X-Amz-Date')
425 ->withoutHeader('Date')
426 ->withoutHeader('Authorization');
427 $uri = $request->getUri();
428
429 return [
430 'method' => $request->getMethod(),
431 'path' => $uri->getPath(),
432 'query' => Psr7\Query::parse($uri->getQuery()),
433 'uri' => $uri,
434 'headers' => $request->getHeaders(),
435 'body' => $request->getBody(),
436 'version' => $request->getProtocolVersion()
437 ];
438 }
439
440 private function buildRequest(array $req)
441 {
442 if ($req['query']) {
443 $req['uri'] = $req['uri']->withQuery(Psr7\Query::build($req['query']));
444 }
445
446 return new Psr7\Request(
447 $req['method'],
448 $req['uri'],
449 $req['headers'],
450 $req['body'],
451 $req['version']
452 );
453 }
454
455 protected function verifyCRTLoaded()
456 {
457 if (!extension_loaded('awscrt')) {
458 throw new CommonRuntimeException(
459 "AWS Common Runtime for PHP is required to use Signature V4A"
460 . ". Please install it using the instructions found at"
461 . " https://github.com/aws/aws-sdk-php/blob/master/CRT_INSTRUCTIONS.md"
462 );
463 }
464 }
465
466 protected function createCRTStaticCredentialsProvider($credentials)
467 {
468 return new StaticCredentialsProvider([
469 'access_key_id' => $credentials->getAccessKeyId(),
470 'secret_access_key' => $credentials->getSecretKey(),
471 'session_token' => $credentials->getSecurityToken(),
472 ]);
473 }
474
475 private function removeIllegalV4aHeaders(&$request)
476 {
477 static $illegalV4aHeaders = [
478 self::AMZ_CONTENT_SHA256_HEADER,
479 'aws-sdk-invocation-id',
480 'aws-sdk-retry',
481 'x-amz-region-set',
482 'transfer-encoding'
483 ];
484 $storedHeaders = [];
485
486 foreach ($illegalV4aHeaders as $header) {
487 if ($request->hasHeader($header)) {
488 $storedHeaders[$header] = $request->getHeader($header);
489 $request = $request->withoutHeader($header);
490 }
491 }
492
493 return $storedHeaders;
494 }
495
496 private function CRTRequestFromGuzzleRequest($request)
497 {
498 return new Request(
499 $request->getMethod(),
500 (string) $request->getUri(),
501 [], //leave empty as the query is parsed from the uri object
502 array_map(function ($header) {return $header[0];}, $request->getHeaders())
503 );
504 }
505
506 /**
507 * @param CredentialsInterface $credentials
508 * @param RequestInterface $request
509 * @param $signingService
510 * @param SigningConfigAWS|null $signingConfig
511 * @return RequestInterface
512 */
513 protected function signWithV4a(
514 CredentialsInterface $credentials,
515 RequestInterface $request,
516 $signingService,
517 ?SigningConfigAWS $signingConfig = null
518 ){
519 $this->verifyCRTLoaded();
520 $signingConfig = $signingConfig ?? new SigningConfigAWS([
521 'algorithm' => SigningAlgorithm::SIGv4_ASYMMETRIC,
522 'signature_type' => SignatureType::HTTP_REQUEST_HEADERS,
523 'credentials_provider' => $this->createCRTStaticCredentialsProvider($credentials),
524 'signed_body_value' => $this->getPayload($request),
525 'should_normalize_uri_path' => true,
526 'use_double_uri_encode' => true,
527 'region' => $this->region,
528 'service' => $signingService,
529 'date' => time(),
530 ]);
531
532 $removedIllegalHeaders = $this->removeIllegalV4aHeaders($request);
533 $http_request = $this->CRTRequestFromGuzzleRequest($request);
534
535 Signing::signRequestAws(
536 Signable::fromHttpRequest($http_request),
537 $signingConfig, function ($signing_result, $error_code) use (&$http_request) {
538 $signing_result->applyToHttpRequest($http_request);
539 });
540 foreach ($removedIllegalHeaders as $header => $value) {
541 $request = $request->withHeader($header, $value);
542 }
543
544 $sigV4AHeaders = $http_request->headers();
545 foreach ($sigV4AHeaders->toArray() as $h => $v) {
546 $request = $request->withHeader($h, $v);
547 }
548
549 return $request;
550 }
551
552 protected function presignWithV4a(
553 RequestInterface $request,
554 CredentialsInterface $credentials,
555 $expires
556 )
557 {
558 $this->verifyCRTLoaded();
559 $credentials_provider = $this->createCRTStaticCredentialsProvider($credentials);
560 $signingConfig = new SigningConfigAWS([
561 'algorithm' => SigningAlgorithm::SIGv4_ASYMMETRIC,
562 'signature_type' => SignatureType::HTTP_REQUEST_QUERY_PARAMS,
563 'credentials_provider' => $credentials_provider,
564 'signed_body_value' => $this->getPresignedPayload($request),
565 'region' => "*",
566 'service' => $this->service,
567 'date' => time(),
568 'expiration_in_seconds' => $expires
569 ]);
570
571 $this->removeIllegalV4aHeaders($request);
572 foreach ($this->getHeaderBlacklist() as $headerName => $headerValue) {
573 if ($request->hasHeader($headerName)) {
574 $request = $request->withoutHeader($headerName);
575 }
576 }
577
578 $http_request = $this->CRTRequestFromGuzzleRequest($request);
579 Signing::signRequestAws(
580 Signable::fromHttpRequest($http_request),
581 $signingConfig, function ($signing_result, $error_code) use (&$http_request) {
582 $signing_result->applyToHttpRequest($http_request);
583 });
584
585 return $request->withUri(
586 new Psr7\Uri($http_request->pathAndQuery())
587 );
588 }
589 }