PageRenderTime 26ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/amazon-web-services/vendor/aws/Aws/S3/S3Signature.php

https://github.com/mhoofman/wordpress-heroku
PHP | 266 lines | 168 code | 33 blank | 65 comment | 14 complexity | 20820eeb37e5dd045ba91455fc64a088 MD5 | raw file
  1. <?php
  2. /**
  3. * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License").
  6. * You may not use this file except in compliance with the License.
  7. * A copy of the License is located at
  8. *
  9. * http://aws.amazon.com/apache2.0
  10. *
  11. * or in the "license" file accompanying this file. This file is distributed
  12. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  13. * express or implied. See the License for the specific language governing
  14. * permissions and limitations under the License.
  15. */
  16. namespace Aws\S3;
  17. use Aws\Common\Credentials\CredentialsInterface;
  18. use Guzzle\Http\Message\RequestInterface;
  19. use Guzzle\Http\QueryString;
  20. use Guzzle\Http\Url;
  21. /**
  22. * Default Amazon S3 signature implementation
  23. * @link http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
  24. */
  25. class S3Signature implements S3SignatureInterface
  26. {
  27. /**
  28. * @var array Query string values that must be signed
  29. */
  30. protected $signableQueryString = array (
  31. 'acl',
  32. 'cors',
  33. 'delete',
  34. 'lifecycle',
  35. 'location',
  36. 'logging',
  37. 'notification',
  38. 'partNumber',
  39. 'policy',
  40. 'requestPayment',
  41. 'response-cache-control',
  42. 'response-content-disposition',
  43. 'response-content-encoding',
  44. 'response-content-language',
  45. 'response-content-type',
  46. 'response-expires',
  47. 'restore',
  48. 'tagging',
  49. 'torrent',
  50. 'uploadId',
  51. 'uploads',
  52. 'versionId',
  53. 'versioning',
  54. 'versions',
  55. 'website',
  56. );
  57. /** @var array Sorted headers that must be signed */
  58. private $signableHeaders = array('Content-MD5', 'Content-Type');
  59. public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
  60. {
  61. // Ensure that the signable query string parameters are sorted
  62. sort($this->signableQueryString);
  63. // Add the security token header if one is being used by the credentials
  64. if ($token = $credentials->getSecurityToken()) {
  65. $request->setHeader('x-amz-security-token', $token);
  66. }
  67. $request->removeHeader('x-amz-date');
  68. $request->setHeader('Date', gmdate(\DateTime::RFC2822));
  69. $stringToSign = $this->createCanonicalizedString($request);
  70. $request->getParams()->set('aws.string_to_sign', $stringToSign);
  71. $request->setHeader(
  72. 'Authorization',
  73. 'AWS ' . $credentials->getAccessKeyId() . ':' . $this->signString($stringToSign, $credentials)
  74. );
  75. }
  76. public function createPresignedUrl(
  77. RequestInterface $request,
  78. CredentialsInterface $credentials,
  79. $expires
  80. ) {
  81. if ($expires instanceof \DateTime) {
  82. $expires = $expires->getTimestamp();
  83. } elseif (!is_numeric($expires)) {
  84. $expires = strtotime($expires);
  85. }
  86. // Operate on a clone of the request, so the original is not altered
  87. $request = clone $request;
  88. // URL encoding already occurs in the URI template expansion. Undo that and encode using the same encoding as
  89. // GET object, PUT object, etc.
  90. $path = S3Client::encodeKey(rawurldecode($request->getPath()));
  91. $request->setPath($path);
  92. // Make sure to handle temporary credentials
  93. if ($token = $credentials->getSecurityToken()) {
  94. $request->setHeader('x-amz-security-token', $token);
  95. $request->getQuery()->set('x-amz-security-token', $token);
  96. }
  97. // Set query params required for pre-signed URLs
  98. $request->getQuery()
  99. ->set('AWSAccessKeyId', $credentials->getAccessKeyId())
  100. ->set('Expires', $expires)
  101. ->set('Signature', $this->signString(
  102. $this->createCanonicalizedString($request, $expires),
  103. $credentials
  104. ));
  105. // Move X-Amz-* headers to the query string
  106. foreach ($request->getHeaders() as $name => $header) {
  107. $name = strtolower($name);
  108. if (strpos($name, 'x-amz-') === 0) {
  109. $request->getQuery()->set($name, (string) $header);
  110. $request->removeHeader($name);
  111. }
  112. }
  113. return $request->getUrl();
  114. }
  115. public function signString($string, CredentialsInterface $credentials)
  116. {
  117. return base64_encode(hash_hmac('sha1', $string, $credentials->getSecretKey(), true));
  118. }
  119. public function createCanonicalizedString(RequestInterface $request, $expires = null)
  120. {
  121. $buffer = $request->getMethod() . "\n";
  122. // Add the interesting headers
  123. foreach ($this->signableHeaders as $header) {
  124. $buffer .= (string) $request->getHeader($header) . "\n";
  125. }
  126. // Choose dates from left to right based on what's set
  127. $date = $expires ?: (string) $request->getHeader('date');
  128. $buffer .= "{$date}\n"
  129. . $this->createCanonicalizedAmzHeaders($request)
  130. . $this->createCanonicalizedResource($request);
  131. return $buffer;
  132. }
  133. /**
  134. * Create a canonicalized AmzHeaders string for a signature.
  135. *
  136. * @param RequestInterface $request Request from which to gather headers
  137. *
  138. * @return string Returns canonicalized AMZ headers.
  139. */
  140. private function createCanonicalizedAmzHeaders(RequestInterface $request)
  141. {
  142. $headers = array();
  143. foreach ($request->getHeaders() as $name => $header) {
  144. $name = strtolower($name);
  145. if (strpos($name, 'x-amz-') === 0) {
  146. $value = trim((string) $header);
  147. if ($value || $value === '0') {
  148. $headers[$name] = $name . ':' . $value;
  149. }
  150. }
  151. }
  152. if (!$headers) {
  153. return '';
  154. }
  155. ksort($headers);
  156. return implode("\n", $headers) . "\n";
  157. }
  158. /**
  159. * Create a canonicalized resource for a request
  160. *
  161. * @param RequestInterface $request Request for the resource
  162. *
  163. * @return string
  164. */
  165. private function createCanonicalizedResource(RequestInterface $request)
  166. {
  167. $buffer = $request->getParams()->get('s3.resource');
  168. // When sending a raw HTTP request (e.g. $client->get())
  169. if (null === $buffer) {
  170. $bucket = $request->getParams()->get('bucket') ?: $this->parseBucketName($request);
  171. // Use any specified bucket name, the parsed bucket name, or no bucket name when interacting with GetService
  172. $buffer = $bucket ? "/{$bucket}" : '';
  173. // Remove encoding from the path and use the S3 specific encoding
  174. $path = S3Client::encodeKey(rawurldecode($request->getPath()));
  175. // if the bucket was path style, then ensure that the bucket wasn't duplicated in the resource
  176. $buffer .= preg_replace("#^/{$bucket}/{$bucket}#", "/{$bucket}", $path);
  177. }
  178. // Remove double slashes
  179. $buffer = str_replace('//', '/', $buffer);
  180. // Add sub resource parameters
  181. $query = $request->getQuery();
  182. $first = true;
  183. foreach ($this->signableQueryString as $key) {
  184. if ($query->hasKey($key)) {
  185. $value = $query[$key];
  186. $buffer .= $first ? '?' : '&';
  187. $first = false;
  188. $buffer .= $key;
  189. // Don't add values for empty sub-resources
  190. if ($value !== '' &&
  191. $value !== false &&
  192. $value !== null &&
  193. $value !== QueryString::BLANK
  194. ) {
  195. $buffer .= "={$value}";
  196. }
  197. }
  198. }
  199. return $buffer;
  200. }
  201. /**
  202. * Parse the bucket name from a request object
  203. *
  204. * @param RequestInterface $request Request to parse
  205. *
  206. * @return string
  207. */
  208. private function parseBucketName(RequestInterface $request)
  209. {
  210. $baseUrl = Url::factory($request->getClient()->getBaseUrl());
  211. $baseHost = $baseUrl->getHost();
  212. $host = $request->getHost();
  213. if (strpos($host, $baseHost) === false) {
  214. // Does not contain the base URL, so it's either a redirect, CNAME, or using a different region
  215. $baseHost = '';
  216. // For every known S3 host, check if that host is present on the request
  217. $regions = $request->getClient()->getDescription()->getData('regions');
  218. foreach ($regions as $region) {
  219. if (strpos($host, $region['hostname']) !== false) {
  220. // This host matches the request host. Tells use the region and endpoint-- we can derive the bucket
  221. $baseHost = $region['hostname'];
  222. break;
  223. }
  224. }
  225. // If no matching base URL was found, then assume that this is a CNAME, and the CNAME is the bucket
  226. if (!$baseHost) {
  227. return $host;
  228. }
  229. }
  230. // Remove the baseURL from the host of the request to attempt to determine the bucket name
  231. return trim(str_replace($baseHost, '', $request->getHost()), ' .');
  232. }
  233. }