1
0

S3Signature.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. <?php
  2. namespace OC\Files\ObjectStore;
  3. use Aws\Credentials\CredentialsInterface;
  4. use Aws\S3\S3Client;
  5. use Aws\S3\S3UriParser;
  6. use Aws\Signature\SignatureInterface;
  7. use GuzzleHttp\Psr7;
  8. use Psr\Http\Message\RequestInterface;
  9. /**
  10. * Legacy Amazon S3 signature implementation
  11. */
  12. class S3Signature implements SignatureInterface
  13. {
  14. /** @var array Query string values that must be signed */
  15. private $signableQueryString = [
  16. 'acl', 'cors', 'delete', 'lifecycle', 'location', 'logging',
  17. 'notification', 'partNumber', 'policy', 'requestPayment',
  18. 'response-cache-control', 'response-content-disposition',
  19. 'response-content-encoding', 'response-content-language',
  20. 'response-content-type', 'response-expires', 'restore', 'tagging',
  21. 'torrent', 'uploadId', 'uploads', 'versionId', 'versioning',
  22. 'versions', 'website'
  23. ];
  24. /** @var array Sorted headers that must be signed */
  25. private $signableHeaders = ['Content-MD5', 'Content-Type'];
  26. /** @var \Aws\S3\S3UriParser S3 URI parser */
  27. private $parser;
  28. public function __construct()
  29. {
  30. $this->parser = new S3UriParser();
  31. // Ensure that the signable query string parameters are sorted
  32. sort($this->signableQueryString);
  33. }
  34. public function signRequest(
  35. RequestInterface $request,
  36. CredentialsInterface $credentials
  37. ) {
  38. $request = $this->prepareRequest($request, $credentials);
  39. $stringToSign = $this->createCanonicalizedString($request);
  40. $auth = 'AWS '
  41. . $credentials->getAccessKeyId() . ':'
  42. . $this->signString($stringToSign, $credentials);
  43. return $request->withHeader('Authorization', $auth);
  44. }
  45. public function presign(
  46. RequestInterface $request,
  47. CredentialsInterface $credentials,
  48. $expires
  49. ) {
  50. $query = [];
  51. // URL encoding already occurs in the URI template expansion. Undo that
  52. // and encode using the same encoding as GET object, PUT object, etc.
  53. $uri = $request->getUri();
  54. $path = S3Client::encodeKey(rawurldecode($uri->getPath()));
  55. $request = $request->withUri($uri->withPath($path));
  56. // Make sure to handle temporary credentials
  57. if ($token = $credentials->getSecurityToken()) {
  58. $request = $request->withHeader('X-Amz-Security-Token', $token);
  59. $query['X-Amz-Security-Token'] = $token;
  60. }
  61. if ($expires instanceof \DateTime) {
  62. $expires = $expires->getTimestamp();
  63. } elseif (!is_numeric($expires)) {
  64. $expires = strtotime($expires);
  65. }
  66. // Set query params required for pre-signed URLs
  67. $query['AWSAccessKeyId'] = $credentials->getAccessKeyId();
  68. $query['Expires'] = $expires;
  69. $query['Signature'] = $this->signString(
  70. $this->createCanonicalizedString($request, $expires),
  71. $credentials
  72. );
  73. // Move X-Amz-* headers to the query string
  74. foreach ($request->getHeaders() as $name => $header) {
  75. $name = strtolower($name);
  76. if (strpos($name, 'x-amz-') === 0) {
  77. $query[$name] = implode(',', $header);
  78. }
  79. }
  80. $queryString = http_build_query($query, null, '&', PHP_QUERY_RFC3986);
  81. return $request->withUri($request->getUri()->withQuery($queryString));
  82. }
  83. /**
  84. * @param RequestInterface $request
  85. * @param CredentialsInterface $creds
  86. *
  87. * @return RequestInterface
  88. */
  89. private function prepareRequest(
  90. RequestInterface $request,
  91. CredentialsInterface $creds
  92. ) {
  93. $modify = [
  94. 'remove_headers' => ['X-Amz-Date'],
  95. 'set_headers' => ['Date' => gmdate(\DateTime::RFC2822)]
  96. ];
  97. // Add the security token header if one is being used by the credentials
  98. if ($token = $creds->getSecurityToken()) {
  99. $modify['set_headers']['X-Amz-Security-Token'] = $token;
  100. }
  101. return Psr7\modify_request($request, $modify);
  102. }
  103. private function signString($string, CredentialsInterface $credentials)
  104. {
  105. return base64_encode(
  106. hash_hmac('sha1', $string, $credentials->getSecretKey(), true)
  107. );
  108. }
  109. private function createCanonicalizedString(
  110. RequestInterface $request,
  111. $expires = null
  112. ) {
  113. $buffer = $request->getMethod() . "\n";
  114. // Add the interesting headers
  115. foreach ($this->signableHeaders as $header) {
  116. $buffer .= $request->getHeaderLine($header) . "\n";
  117. }
  118. $date = $expires ?: $request->getHeaderLine('date');
  119. $buffer .= "{$date}\n"
  120. . $this->createCanonicalizedAmzHeaders($request)
  121. . $this->createCanonicalizedResource($request);
  122. return $buffer;
  123. }
  124. private function createCanonicalizedAmzHeaders(RequestInterface $request)
  125. {
  126. $headers = [];
  127. foreach ($request->getHeaders() as $name => $header) {
  128. $name = strtolower($name);
  129. if (strpos($name, 'x-amz-') === 0) {
  130. $value = implode(',', $header);
  131. if (strlen($value) > 0) {
  132. $headers[$name] = $name . ':' . $value;
  133. }
  134. }
  135. }
  136. if (!$headers) {
  137. return '';
  138. }
  139. ksort($headers);
  140. return implode("\n", $headers) . "\n";
  141. }
  142. private function createCanonicalizedResource(RequestInterface $request)
  143. {
  144. $data = $this->parser->parse($request->getUri());
  145. $buffer = '/';
  146. if ($data['bucket']) {
  147. $buffer .= $data['bucket'];
  148. if (!empty($data['key']) || !$data['path_style']) {
  149. $buffer .= '/' . $data['key'];
  150. }
  151. }
  152. // Add sub resource parameters if present.
  153. $query = $request->getUri()->getQuery();
  154. if ($query) {
  155. $params = Psr7\parse_query($query);
  156. $first = true;
  157. foreach ($this->signableQueryString as $key) {
  158. if (array_key_exists($key, $params)) {
  159. $value = $params[$key];
  160. $buffer .= $first ? '?' : '&';
  161. $first = false;
  162. $buffer .= $key;
  163. // Don't add values for empty sub-resources
  164. if (strlen($value)) {
  165. $buffer .= "={$value}";
  166. }
  167. }
  168. }
  169. }
  170. return $buffer;
  171. }
  172. }