Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/S3/Crypto/S3EncryptionClientV2.php

raw symbols SCIP
1 <?php
2 namespace Aws\S3\Crypto;
3
4 use Aws\Crypto\DecryptionTraitV2;
5 use Aws\Exception\CryptoException;
6 use Aws\HashingStream;
7 use Aws\MetricsBuilder;
8 use Aws\PhpHash;
9 use Aws\Crypto\AbstractCryptoClientV2;
10 use Aws\Crypto\EncryptionTraitV2;
11 use Aws\Crypto\MetadataEnvelope;
12 use Aws\Crypto\MaterialsProvider;
13 use Aws\Crypto\Cipher\CipherBuilderTrait;
14 use Aws\S3\S3Client;
15 use GuzzleHttp\Promise;
16 use GuzzleHttp\Promise\PromiseInterface;
17 use GuzzleHttp\Psr7;
18
19 /**
20 * Provides a wrapper for an S3Client that supplies functionality to encrypt
21 * data on putObject[Async] calls and decrypt data on getObject[Async] calls.
22 *
23 * AWS strongly recommends the upgrade to the S3EncryptionClientV3 (over the
24 * S3EncryptionClientV2), as it offers updated data security best practices to our
25 * customers who upgrade. S3EncryptionClientV3 contains breaking changes, so this
26 * will require planning by engineering teams to migrate. New workflows should
27 * just start with S3EncryptionClientV3.
28 *
29 * Note that for PHP versions of < 7.1, this class uses an AES-GCM polyfill
30 * for encryption since there is no native PHP support. The performance for large
31 * inputs will be a lot slower than for PHP 7.1+, so upgrading older PHP version
32 * environments may be necessary to use this effectively.
33 *
34 * Example write path:
35 *
36 * <code>
37 * use Aws\Crypto\KmsMaterialsProviderV2;
38 * use Aws\S3\Crypto\S3EncryptionClientV2;
39 * use Aws\S3\S3Client;
40 *
41 * $encryptionClient = new S3EncryptionClientV2(
42 * new S3Client([
43 * 'region' => 'us-west-2',
44 * 'version' => 'latest'
45 * ])
46 * );
47 * $materialsProvider = new KmsMaterialsProviderV2(
48 * new KmsClient([
49 * 'profile' => 'default',
50 * 'region' => 'us-east-1',
51 * 'version' => 'latest',
52 * ],
53 * 'your-kms-key-id'
54 * );
55 *
56 * $encryptionClient->putObject([
57 * '@MaterialsProvider' => $materialsProvider,
58 * '@CipherOptions' => [
59 * 'Cipher' => 'gcm',
60 * 'KeySize' => 256,
61 * ],
62 * '@KmsEncryptionContext' => ['foo' => 'bar'],
63 * 'Bucket' => 'your-bucket',
64 * 'Key' => 'your-key',
65 * 'Body' => 'your-encrypted-data',
66 * ]);
67 * </code>
68 *
69 * Example read call (using objects from previous example):
70 *
71 * <code>
72 * $encryptionClient->getObject([
73 * '@MaterialsProvider' => $materialsProvider,
74 * '@CipherOptions' => [
75 * 'Cipher' => 'gcm',
76 * 'KeySize' => 256,
77 * ],
78 * '@CommitmentPolicy' => 'FORBID_ENCRYPT_ALLOW_DECRYPT',
79 * 'Bucket' => 'your-bucket',
80 * 'Key' => 'your-key',
81 * ]);
82 * </code>
83 */
84 class S3EncryptionClientV2 extends AbstractCryptoClientV2
85 {
86 use CipherBuilderTrait;
87 use CryptoParamsTraitV2;
88 use DecryptionTraitV2;
89 use EncryptionTraitV2;
90 use UserAgentTrait;
91
92 const CRYPTO_VERSION = '2.1';
93
94 private $client;
95 private $instructionFileSuffix;
96 private $legacyWarningCount;
97
98 /**
99 * @param S3Client $client The S3Client to be used for true uploading and
100 * retrieving objects from S3 when using the
101 * encryption client.
102 * @param string|null $instructionFileSuffix Suffix for a client wide
103 * default when using instruction
104 * files for metadata storage.
105 */
106 public function __construct(
107 S3Client $client,
108 $instructionFileSuffix = null
109 ) {
110 trigger_error(
111 'S3EncryptionClientV2 will be deprecated soon and will be removed in a future ' .
112 'release due to security vulnerabilities (CVE-2024-56473). Please ' .
113 'migrate to S3EncryptionClientV3 as soon as possible.' . "\n" .
114 'See https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/' .
115 'security.html for upgrade guidance.',
116 E_USER_DEPRECATED
117 );
118 $this->client = $client;
119 $this->instructionFileSuffix = $instructionFileSuffix;
120 $this->legacyWarningCount = 0;
121 MetricsBuilder::appendMetricsCaptureMiddleware(
122 $this->client->getHandlerList(),
123 MetricsBuilder::S3_CRYPTO_V2
124 );
125 }
126
127 private static function getDefaultStrategy()
128 {
129 return new HeadersMetadataStrategy();
130 }
131
132 /**
133 * Encrypts the data in the 'Body' field of $args and promises to upload it
134 * to the specified location on S3.
135 *
136 * Note that for PHP versions of < 7.1, this operation uses an AES-GCM
137 * polyfill for encryption since there is no native PHP support. The
138 * performance for large inputs will be a lot slower than for PHP 7.1+, so
139 * upgrading older PHP version environments may be necessary to use this
140 * effectively.
141 *
142 * @param array $args Arguments for encrypting an object and uploading it
143 * to S3 via PutObject.
144 *
145 * The required configuration arguments are as follows:
146 *
147 * - @MaterialsProvider: (MaterialsProviderV2) Provides Cek, Iv, and Cek
148 * encrypting/decrypting for encryption metadata.
149 * - @CipherOptions: (array) Cipher options for encrypting data. Only the
150 * Cipher option is required. Accepts the following:
151 * - Cipher: (string) gcm
152 * See also: AbstractCryptoClientV2::$supportedCiphers
153 * - KeySize: (int) 128|256
154 * See also: MaterialsProvider::$supportedKeySizes
155 * - Aad: (string) Additional authentication data. This option is
156 * passed directly to OpenSSL when using gcm. Note if you pass in
157 * Aad, the PHP SDK will be able to decrypt the resulting object,
158 * but other AWS SDKs may not be able to do so.
159 * - @KmsEncryptionContext: (array) Only required if using
160 * KmsMaterialsProviderV2. An associative array of key-value
161 * pairs to be added to the encryption context for KMS key encryption. An
162 * empty array may be passed if no additional context is desired.
163 *
164 * The optional configuration arguments are as follows:
165 *
166 * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for storing
167 * MetadataEnvelope information. Defaults to using a
168 * HeadersMetadataStrategy. Can either be a class implementing
169 * MetadataStrategy, a class name of a predefined strategy, or empty/null
170 * to default.
171 * - @InstructionFileSuffix: (string|null) Suffix used when writing to an
172 * instruction file if using an InstructionFileMetadataHandler.
173 *
174 * @return PromiseInterface
175 *
176 * @throws \InvalidArgumentException Thrown when arguments above are not
177 * passed or are passed incorrectly.
178 */
179 public function putObjectAsync(array $args)
180 {
181 $provider = $this->getMaterialsProvider($args);
182 unset($args['@MaterialsProvider']);
183
184 $instructionFileSuffix = $this->getInstructionFileSuffix($args);
185 unset($args['@InstructionFileSuffix']);
186
187 $strategy = $this->getMetadataStrategy($args, $instructionFileSuffix);
188 unset($args['@MetadataStrategy']);
189
190 $envelope = new MetadataEnvelope();
191
192 return Promise\Create::promiseFor($this->encrypt(
193 Psr7\Utils::streamFor($args['Body']),
194 $args,
195 $provider,
196 $envelope
197 ))->then(
198 function ($encryptedBodyStream) use ($args) {
199 $hash = new PhpHash('sha256');
200 $hashingEncryptedBodyStream = new HashingStream(
201 $encryptedBodyStream,
202 $hash,
203 self::getContentShaDecorator($args)
204 );
205 return [$hashingEncryptedBodyStream, $args];
206 }
207 )->then(
208 function ($putObjectContents) use ($strategy, $envelope) {
209 list($bodyStream, $args) = $putObjectContents;
210 if ($strategy === null) {
211 $strategy = self::getDefaultStrategy();
212 }
213
214 $updatedArgs = $strategy->save($envelope, $args);
215 $updatedArgs['Body'] = $bodyStream;
216 return $updatedArgs;
217 }
218 )->then(
219 function ($args) {
220 unset($args['@CipherOptions']);
221 return $this->client->putObjectAsync($args);
222 }
223 );
224 }
225
226 private static function getContentShaDecorator(&$args)
227 {
228 return function ($hash) use (&$args) {
229 $args['ContentSHA256'] = bin2hex($hash);
230 };
231 }
232
233 /**
234 * Encrypts the data in the 'Body' field of $args and uploads it to the
235 * specified location on S3.
236 *
237 * Note that for PHP versions of < 7.1, this operation uses an AES-GCM
238 * polyfill for encryption since there is no native PHP support. The
239 * performance for large inputs will be a lot slower than for PHP 7.1+, so
240 * upgrading older PHP version environments may be necessary to use this
241 * effectively.
242 *
243 * @param array $args Arguments for encrypting an object and uploading it
244 * to S3 via PutObject.
245 *
246 * The required configuration arguments are as follows:
247 *
248 * - @MaterialsProvider: (MaterialsProvider) Provides Cek, Iv, and Cek
249 * encrypting/decrypting for encryption metadata.
250 * - @CipherOptions: (array) Cipher options for encrypting data. A Cipher
251 * is required. Accepts the following options:
252 * - Cipher: (string) gcm
253 * See also: AbstractCryptoClientV2::$supportedCiphers
254 * - KeySize: (int) 128|256
255 * See also: MaterialsProvider::$supportedKeySizes
256 * - Aad: (string) Additional authentication data. This option is
257 * passed directly to OpenSSL when using gcm. Note if you pass in
258 * Aad, the PHP SDK will be able to decrypt the resulting object,
259 * but other AWS SDKs may not be able to do so.
260 * - @KmsEncryptionContext: (array) Only required if using
261 * KmsMaterialsProviderV2. An associative array of key-value
262 * pairs to be added to the encryption context for KMS key encryption. An
263 * empty array may be passed if no additional context is desired.
264 *
265 * The optional configuration arguments are as follows:
266 *
267 * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for storing
268 * MetadataEnvelope information. Defaults to using a
269 * HeadersMetadataStrategy. Can either be a class implementing
270 * MetadataStrategy, a class name of a predefined strategy, or empty/null
271 * to default.
272 * - @InstructionFileSuffix: (string|null) Suffix used when writing to an
273 * instruction file if an using an InstructionFileMetadataHandler was
274 * determined.
275 *
276 * @return \Aws\Result PutObject call result with the details of uploading
277 * the encrypted file.
278 *
279 * @throws \InvalidArgumentException Thrown when arguments above are not
280 * passed or are passed incorrectly.
281 */
282 public function putObject(array $args)
283 {
284 return $this->putObjectAsync($args)->wait();
285 }
286
287 /**
288 * Promises to retrieve an object from S3 and decrypt the data in the
289 * 'Body' field.
290 *
291 * @param array $args Arguments for retrieving an object from S3 via
292 * GetObject and decrypting it.
293 *
294 * The required configuration argument is as follows:
295 *
296 * - @MaterialsProvider: (MaterialsProviderInterface) Provides Cek, Iv, and Cek
297 * encrypting/decrypting for decryption metadata. May have data loaded
298 * from the MetadataEnvelope upon decryption.
299 * - @SecurityProfile: (string) Must be set to 'V2' or 'V2_AND_LEGACY'.
300 * - 'V2' indicates that only objects encrypted with S3EncryptionClientV2
301 * content encryption and key wrap schemas are able to be decrypted.
302 * - 'V2_AND_LEGACY' indicates that objects encrypted with both
303 * S3EncryptionClientV2 and older legacy encryption clients are able
304 * to be decrypted.
305 * - @CommitmentPolicy: (string) Must be set to 'FORBID_ENCRYPT_ALLOW_DECRYPT'.
306 * - 'FORBID_ENCRYPT_ALLOW_DECRYPT' indicates that the client is configured
307 * to read messages encrypted with key commitment or without key commitment.
308 *
309 * The optional configuration arguments are as follows:
310 *
311 * - SaveAs: (string) The path to a file on disk to save the decrypted
312 * object data. This will be handled by file_put_contents instead of the
313 * Guzzle sink.
314 *
315 * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for reading
316 * MetadataEnvelope information. Defaults to determining based on object
317 * response headers. Can either be a class implementing MetadataStrategy,
318 * a class name of a predefined strategy, or empty/null to default.
319 * - @InstructionFileSuffix: (string) Suffix used when looking for an
320 * instruction file if an InstructionFileMetadataHandler is being used.
321 * - @CipherOptions: (array) Cipher options for decrypting data. A Cipher
322 * is required. Accepts the following options:
323 * - Aad: (string) Additional authentication data. This option is
324 * passed directly to OpenSSL when using gcm. It is ignored when
325 * using cbc.
326 * - @KmsAllowDecryptWithAnyCmk: (bool) This allows decryption with
327 * KMS materials for any KMS key ID, instead of needing the KMS key ID to
328 * be specified and provided to the decrypt operation. Ignored for non-KMS
329 * materials providers. Defaults to false.
330 *
331 * @return PromiseInterface
332 *
333 * @throws \InvalidArgumentException Thrown when required arguments are not
334 * passed or are passed incorrectly.
335 */
336 public function getObjectAsync(array $args)
337 {
338 $provider = $this->getMaterialsProvider($args);
339 unset($args['@MaterialsProvider']);
340
341 $keyCommitmentPolicy = $this->getKeyCommitmentPolicy($args);
342
343 $instructionFileSuffix = $this->getInstructionFileSuffix($args);
344 unset($args['@InstructionFileSuffix']);
345
346 $strategy = $this->getMetadataStrategy($args, $instructionFileSuffix);
347 unset($args['@MetadataStrategy']);
348
349 if (!isset($args['@SecurityProfile'])
350 || !in_array($args['@SecurityProfile'], self::$supportedSecurityProfiles)
351 ) {
352 throw new CryptoException("@SecurityProfile is required and must be"
353 . " set to 'V2' or 'V2_AND_LEGACY'");
354 }
355
356 // Only throw this legacy warning once per client
357 if (in_array($args['@SecurityProfile'], self::$legacySecurityProfiles)
358 && $this->legacyWarningCount < 1
359 ) {
360 $this->legacyWarningCount++;
361 trigger_error(
362 "This S3 Encryption Client operation is configured to"
363 . " read encrypted data with legacy encryption modes. If you"
364 . " don't have objects encrypted with these legacy modes,"
365 . " you should disable support for them to enhance security. ",
366 E_USER_WARNING
367 );
368 }
369
370 $saveAs = null;
371 if (!empty($args['SaveAs'])) {
372 $saveAs = $args['SaveAs'];
373 }
374
375 $promise = $this->client->getObjectAsync($args)
376 ->then(
377 function ($result) use (
378 $provider,
379 $instructionFileSuffix,
380 $strategy,
381 $args
382 ) {
383 if ($strategy === null) {
384 $strategy = $this->determineGetObjectStrategy(
385 $result,
386 $instructionFileSuffix
387 );
388 }
389
390 $envelope = $strategy->load($args + [
391 'Metadata' => $result['Metadata']
392 ]);
393
394 $result['Body'] = $this->decrypt(
395 $result['Body'],
396 $provider,
397 $envelope,
398 $args
399 );
400 return $result;
401 }
402 )->then(
403 function ($result) use ($saveAs) {
404 if (!empty($saveAs)) {
405 file_put_contents(
406 $saveAs,
407 (string)$result['Body'],
408 LOCK_EX
409 );
410 }
411 return $result;
412 }
413 );
414
415 return $promise;
416 }
417
418 /**
419 * Retrieves an object from S3 and decrypts the data in the 'Body' field.
420 *
421 * @param array $args Arguments for retrieving an object from S3 via
422 * GetObject and decrypting it.
423 *
424 * The required configuration argument is as follows:
425 *
426 * - @MaterialsProvider: (MaterialsProviderInterface) Provides Cek, Iv, and Cek
427 * encrypting/decrypting for decryption metadata. May have data loaded
428 * from the MetadataEnvelope upon decryption.
429 * - @SecurityProfile: (string) Must be set to 'V2' or 'V2_AND_LEGACY'.
430 * - 'V2' indicates that only objects encrypted with S3EncryptionClientV2
431 * content encryption and key wrap schemas are able to be decrypted.
432 * - 'V2_AND_LEGACY' indicates that objects encrypted with both
433 * S3EncryptionClientV2 and older legacy encryption clients are able
434 * to be decrypted.
435 * - @CommitmentPolicy: (string) Must be set to 'FORBID_ENCRYPT_ALLOW_DECRYPT'.
436 * - 'FORBID_ENCRYPT_ALLOW_DECRYPT' indicates that the client is
437 * configured to read messages encrypted with key commitment
438 * or without key commitment.
439 *
440 * The optional configuration arguments are as follows:
441 *
442 * - SaveAs: (string) The path to a file on disk to save the decrypted
443 * object data. This will be handled by file_put_contents instead of the
444 * Guzzle sink.
445 * - @InstructionFileSuffix: (string|null) Suffix used when looking for an
446 * instruction file if an InstructionFileMetadataHandler was detected.
447 * - @CipherOptions: (array) Cipher options for encrypting data. A Cipher
448 * is required. Accepts the following options:
449 * - Aad: (string) Additional authentication data. This option is
450 * passed directly to OpenSSL when using gcm. It is ignored when
451 * using cbc.
452 * - @KmsAllowDecryptWithAnyCmk: (bool) This allows decryption with
453 * KMS materials for any KMS key ID, instead of needing the KMS key ID to
454 * be specified and provided to the decrypt operation. Ignored for non-KMS
455 * materials providers. Defaults to false.
456 *
457 * @return \Aws\Result GetObject call result with the 'Body' field
458 * wrapped in a decryption stream with its metadata
459 * information.
460 *
461 * @throws \InvalidArgumentException Thrown when arguments above are not
462 * passed or are passed incorrectly.
463 */
464 public function getObject(array $args)
465 {
466 return $this->getObjectAsync($args)->wait();
467 }
468 }