Debian Codegraph @

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

raw symbols SCIP
1 <?php
2
3 namespace Aws\Crypto;
4
5 use Aws\Crypto\Cipher\CipherMethod;
6 use Aws\Exception\CryptoException;
7 use GuzzleHttp\Psr7;
8 use GuzzleHttp\Psr7\LimitStream;
9 use PHPUnit\Framework\Constraint\IsEmpty;
10 use Psr\Http\Message\StreamInterface;
11
12 trait DecryptionTraitV3
13 {
14 /**
15 * Dependency to reverse lookup the openssl_* cipher name from the AESName
16 * in the MetadataEnvelope.
17 *
18 * @param string $aesName
19 *
20 * @return string
21 *
22 * @internal
23 */
24 abstract protected function getCipherFromAesName($aesName);
25
26 /**
27 * Dependency to generate a CipherMethod from a set of inputs for loading
28 * in to an AesDecryptingStream.
29 *
30 * @param string $cipherName Name of the cipher to generate for decrypting.
31 * @param string $iv Base Initialization Vector for the cipher.
32 * @param int $keySize Size of the encryption key, in bits, that will be
33 * used.
34 *
35 * @return Cipher\CipherMethod
36 *
37 * @internal
38 */
39 abstract protected function buildCipherMethod(
40 $cipherName,
41 $iv,
42 $keySize
43 );
44
45 /**
46 * Builds an AesStreamInterface using cipher options loaded from the
47 * MetadataEnvelope and MaterialsProvider. Can decrypt data from both the
48 * legacy and V3 encryption client workflows.
49 *
50 * @param string $cipherText Plain-text data to be encrypted using the
51 * materials, algorithm, and data provided.
52 * @param MaterialsProviderInterfaceV3 $provider A provider to supply and encrypt
53 * materials used in encryption.
54 * @param MetadataEnvelope $envelope A storage envelope for encryption
55 * metadata to be read from.
56 * @param string $commitmentPolicy Commitment Policy to use for decrypting objects.
57 * @param array $options Options used for decryption.
58 *
59 * @return AesStreamInterface
60 *
61 * @throws \InvalidArgumentException Thrown when a value in $cipherOptions
62 * is not valid.
63 *
64 * @internal
65 */
66 public function decrypt(
67 string $cipherText,
68 MaterialsProviderInterfaceV3 $provider,
69 MetadataEnvelope $envelope,
70 string $commitmentPolicy,
71 array $options = []
72 ): AesStreamInterface
73 {
74 if (isset($envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_V3])) {
75 $this->checkEnvelopeForExclusiveMapKeys(
76 $envelope,
77 MetadataEnvelope::getV2Fields(),
78 "Expected V3 only fields but found V2 fields in header metadata."
79 );
80 // PHP only supports one commiting algorithm suite
81 $algorithmSuite = AlgorithmSuite::ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY;
82 $options['@CipherOptions'] = $options['@CipherOptions'] ?? [];
83 $options['@CipherOptions']['Iv'] = str_repeat("\1", 12);
84 $options['@CipherOptions']['TagLength'] = $algorithmSuite->getCipherTagLengthInBytes();
85
86 //= ../specification/s3-encryption/data-format/content-metadata.md#v3-only
87 //= type=implication
88 //# - The wrapping algorithm value "12" MUST be translated to kms+context upon retrieval, and vice versa on write.
89 $materialDescription = $this->buildMaterialDescription($envelope);
90
91 $cek = $provider->decryptCek(
92 base64_decode($envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_V3]),
93 $materialDescription,
94 $options
95 );
96
97 $options['@CipherOptions']['KeySize'] = strlen($cek) * 8;
98 $options['@CipherOptions']['Cipher'] = $this->getCipherFromAesName(
99 $this->numericalContenCipherToAesName($envelope)
100 );
101 $this->validateOptionsAndEnvelope($options, $envelope, $commitmentPolicy);
102
103 $messageId = base64_decode($envelope[MetadataEnvelope::MESSAGE_ID_V3]);
104 $commitmentKey = base64_decode($envelope[MetadataEnvelope::KEY_COMMITMENT_V3]);
105
106 if (strlen($messageId) !== ($algorithmSuite->getKeyCommitmentSaltLengthBits()) / 8) {
107 throw new CryptoException("Invalid MessageId length found in object envelope.");
108 }
109
110 if (strlen($commitmentKey) !== $algorithmSuite->getCommitmentOutputKeyLengthBytes()) {
111 throw new CryptoException("Invalid Commitment Key length found in object envelope.");
112 }
113
114 $decryptionStream = $this->getCommitingDecryptingStream(
115 $cipherText,
116 $cek,
117 $options['@CipherOptions'],
118 $messageId,
119 $commitmentKey,
120 $algorithmSuite
121 );
122 unset($cek);
123
124 return $decryptionStream;
125 } else {
126 //= ../specification/s3-encryption/key-commitment.md#commitment-policy
127 //# When the commitment policy is REQUIRE_ENCRYPT_REQUIRE_DECRYPT,
128 //# the S3EC MUST NOT allow decryption using algorithm suites which do not support key commitment.
129 if ($commitmentPolicy == "REQUIRE_ENCRYPT_REQUIRE_DECRYPT") {
130 //= ../specification/s3-encryption/client.md#key-commitment
131 //# If the configured Encryption Algorithm is incompatible with
132 //# the key commitment policy, then it MUST throw an exception.
133 throw new CryptoException("Message is encrypted with a "
134 . "non commiting algorithm but commitment policy is set "
135 . "to {$commitmentPolicy}. Select a valid commitment "
136 . "policy to decrypt this object. ");
137 }
138 $this->checkEnvelopeForExclusiveMapKeys(
139 $envelope,
140 MetadataEnvelope::getV3Fields(),
141 "Expected V2 only fields but found V3 fields in header metadata."
142 );
143 $options['@CipherOptions'] = $options['@CipherOptions'] ?? [];
144 $options['@CipherOptions']['Iv'] = base64_decode(
145 $envelope[MetadataEnvelope::IV_HEADER]
146 );
147
148 $options['@CipherOptions']['TagLength'] =
149 $envelope[MetadataEnvelope::CRYPTO_TAG_LENGTH_HEADER] / 8;
150
151 $cek = $provider->decryptCek(
152 base64_decode(
153 $envelope[MetadataEnvelope::CONTENT_KEY_V2_HEADER]
154 ),
155 json_decode(
156 $envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER],
157 true
158 ),
159 $options
160 );
161 $options['@CipherOptions']['KeySize'] = strlen($cek) * 8;
162 $options['@CipherOptions']['Cipher'] = $this->getCipherFromAesName(
163 $envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER]
164 );
165
166 //= ../specification/s3-encryption/decryption.md#key-commitment
167 //= type=implication
168 //# The S3EC MUST validate the algorithm suite used for decryption
169 //# against the key commitment policy before attempting to decrypt
170 //# the content ciphertext.
171 $this->validateOptionsAndEnvelope($options, $envelope, $commitmentPolicy);
172
173 $decryptionStream = $this->getNonCommitingDecryptingStream(
174 $cipherText,
175 $cek,
176 $options['@CipherOptions']
177 );
178 unset($cek);
179
180 return $decryptionStream;
181 }
182 }
183
184 private function checkEnvelopeForExclusiveMapKeys(
185 MetadataEnvelope $envelope,
186 array $exclusiveKeys,
187 string $errorMessage
188 ): void
189 {
190 foreach ($exclusiveKeys as $exclusiveKey) {
191 //= ../specification/s3-encryption/data-format/content-metadata.md#determining-s3ec-object-status
192 //# If there are multiple mapkeys which are meant to be exclusive, such as "x-amz-key", "x-amz-key-v2", and "x-amz-3" then the S3EC SHOULD throw an exception.
193 if (isset($envelope[$exclusiveKey])) {
194 throw new CryptoException($errorMessage);
195 }
196 }
197 }
198
199 private function numericalContenCipherToAesName(
200 MetadataEnvelope $envelope
201 ): string
202 {
203 switch ($envelope[MetadataEnvelope::CONTENT_CIPHER_V3]) {
204 case 115:
205 return 'AES/GCM/NoPadding';
206 default:
207 throw new CryptoException(
208 "Unknown Encrypted Data Key "
209 . "wrapping algorithm found: "
210 . "{$envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_ALGORITHM_V3]}"
211 );
212 }
213
214 }
215
216 private function buildMaterialDescription(
217 MetadataEnvelope $envelope
218 ): array
219 {
220 switch ($envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_ALGORITHM_V3]) {
221 case 12:
222 return json_decode(
223 $envelope[MetadataEnvelope::ENCRYPTION_CONTEXT_V3],
224 true
225 );
226 default:
227 throw new CryptoException(
228 "Unknown Encrypted Data Key "
229 . "wrapping algorithm found: "
230 . "{$envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_ALGORITHM_V3]}"
231 );
232 }
233 }
234
235 private function getTagFromCiphertextStream(
236 StreamInterface $cipherText,
237 $tagLength
238 ): string
239 {
240 $cipherTextSize = $cipherText->getSize();
241 if ($cipherTextSize == null || $cipherTextSize <= 0) {
242 throw new \RuntimeException('Cannot decrypt a stream of unknown size');
243 }
244
245 return (string) new LimitStream(
246 $cipherText,
247 $tagLength,
248 $cipherTextSize - $tagLength
249 );
250 }
251
252 private function getStrippedCiphertextStream(
253 StreamInterface $cipherText,
254 $tagLength
255 ): LimitStream
256 {
257 $cipherTextSize = $cipherText->getSize();
258 if ($cipherTextSize == null || $cipherTextSize <= 0) {
259 throw new \RuntimeException('Cannot decrypt a stream of unknown size');
260 }
261
262 return new LimitStream(
263 $cipherText,
264 $cipherTextSize - $tagLength,
265 0
266 );
267 }
268
269 private function validateOptionsAndEnvelope(
270 array $options,
271 MetadataEnvelope $envelope,
272 string $commitmentPolicy
273 ): void
274 {
275 //= ../specification/s3-encryption/key-commitment.md#commitment-policy
276 //# When the commitment policy is REQUIRE_ENCRYPT_ALLOW_DECRYPT,
277 //# the S3EC MUST allow decryption using algorithm suites which do not support key commitment.
278
279 //= ../specification/s3-encryption/key-commitment.md#commitment-policy
280 //# When the commitment policy is FORBID_ENCRYPT_ALLOW_DECRYPT,
281 //# the S3EC MUST allow decryption using algorithm suites which do not support key commitment.
282
283 $allowedCiphers = AbstractCryptoClientV3::$supportedCiphers;
284 $allowedKeywraps = AbstractCryptoClientV3::$supportedKeyWraps;
285 //= ../specification/s3-encryption/client.md#enable-legacy-wrapping-algorithms
286 //# When enabled, the S3EC MUST be able to decrypt objects encrypted with all
287 //# supported wrapping algorithms (both legacy and fully supported).
288 if ($options['@SecurityProfile'] == 'V3_AND_LEGACY') {
289 $allowedCiphers = array_unique(array_merge(
290 $allowedCiphers,
291 AbstractCryptoClient::$supportedCiphers
292 ));
293 $allowedKeywraps = array_unique(array_merge(
294 $allowedKeywraps,
295 AbstractCryptoClient::$supportedKeyWraps
296 ));
297 }
298
299 $v1SchemaException = new CryptoException("The requested object is encrypted"
300 . " with V1 encryption schemas that have been disabled by"
301 . " client configuration @SecurityProfile=V3. Retry with"
302 . " V3_AND_LEGACY enabled or reencrypt the object.");
303
304 if (!in_array($options['@CipherOptions']['Cipher'], $allowedCiphers)) {
305 //= ../specification/s3-encryption/client.md#enable-legacy-wrapping-algorithms
306 //= type=implication
307 //# When disabled, the S3EC MUST NOT decrypt objects encrypted using legacy wrapping algorithms;
308 //# it MUST throw an exception when attempting to decrypt an object encrypted with a legacy wrapping algorithm.
309
310 //= ../specification/s3-encryption/decryption.md#legacy-decryption
311 //# The S3EC MUST NOT decrypt objects encrypted using legacy unauthenticated algorithm suites unless specifically configured to do so.
312 if (in_array($options['@CipherOptions']['Cipher'], AbstractCryptoClient::$supportedCiphers)) {
313 //= ../specification/s3-encryption/decryption.md#legacy-decryption
314 //# If the S3EC is not configured to enable legacy unauthenticated content decryption, the client MUST throw an exception when attempting to decrypt an object encrypted with a legacy unauthenticated algorithm suite.
315 throw $v1SchemaException;
316 }
317
318 throw new CryptoException("The requested object is encrypted with"
319 . " the cipher '{$options['@CipherOptions']['Cipher']}', which is not"
320 . " supported for decryption with the selected security profile."
321 . " This profile allows decryption with: "
322 . implode(", ", $allowedCiphers));
323 }
324
325 if (isset($envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_V3])) {
326 if ($envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_ALGORITHM_V3] !== '12') {
327 throw new CryptoException("The requested object is encrypted with"
328 . " the keywrap schema '{$envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_ALGORITHM_V3]}',"
329 . " which is not supported for decryption with the current security"
330 . " profile.");
331 }
332 } else {
333 if (!in_array($envelope[MetadataEnvelope::KEY_WRAP_ALGORITHM_HEADER], $allowedKeywraps)) {
334 if (in_array($envelope[MetadataEnvelope::KEY_WRAP_ALGORITHM_HEADER], AbstractCryptoClient::$supportedKeyWraps)) {
335 throw $v1SchemaException;
336 }
337
338 throw new CryptoException("The requested object is encrypted with"
339 . " the keywrap schema '{$envelope[MetadataEnvelope::KEY_WRAP_ALGORITHM_HEADER]}',"
340 . " which is not supported for decryption with the current security"
341 . " profile.");
342 }
343 $matdesc = json_decode(
344 $envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER],
345 true
346 );
347 if (isset($matdesc['aws:x-amz-cek-alg'])
348 && ($envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER]
349 !== $matdesc['aws:x-amz-cek-alg'])
350 ) {
351 throw new CryptoException("There is a mismatch in specified content"
352 . " encryption algrithm between the materials description value"
353 . " and the metadata envelope value: {$matdesc['aws:x-amz-cek-alg']}"
354 . " vs. {$envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER]}.");
355 }
356 }
357 //= ../specification/s3-encryption/data-format/content-metadata.md#determining-s3ec-object-status
358 //= type=implication
359 //# - If the metadata contains "x-amz-3" and "x-amz-d" and "x-amz-i" then the object MUST be considered an S3EC-encrypted object using the V3 format.
360 if (!MetadataEnvelope::isV3Envelope($envelope)
361 && $commitmentPolicy == "REQUIRE_ENCRYPT_REQUIRE_DECRYPT"
362 ) {
363 //= ../specification/s3-encryption/decryption.md#key-commitment
364 //# If the commitment policy requires decryption using a committing algorithm suite
365 //# and the algorithm suite associated with the object does not support key commitment,
366 //# then the S3EC MUST throw an exception.
367 throw new CryptoException("There is a mismatch in specified"
368 . "commitment policy value {$commitmentPolicy} and"
369 . "Metadata Envelope found in object.");
370 }
371
372 }
373
374 /**
375 * Generates a stream that wraps the cipher text with the proper cipher and
376 * uses the content encryption key (CEK) to decrypt the data when read.
377 *
378 * @param string $cipherText Plain-text data to be encrypted using the
379 * materials, algorithm, and data provided.
380 * @param string $cek A content encryption key for use by the stream for
381 * encrypting the plaintext data.
382 * @param array $cipherOptions Options for use in determining the cipher to
383 * be used for encrypting data.
384 *
385 * @return AesStreamInterface
386 *
387 * @internal
388 */
389 protected function getNonCommitingDecryptingStream(
390 string $cipherText,
391 string $cek,
392 array $cipherOptions
393 ): AesStreamInterface
394 {
395 $cipherTextStream = Psr7\Utils::streamFor($cipherText);
396 switch ($cipherOptions['Cipher']) {
397 case 'gcm':
398 $cipherOptions['Tag'] = $this->getTagFromCiphertextStream(
399 $cipherTextStream,
400 $cipherOptions['TagLength']
401 );
402
403 return new AesGcmDecryptingStream(
404 $this->getStrippedCiphertextStream(
405 $cipherTextStream,
406 $cipherOptions['TagLength']
407 ),
408 $cek,
409 $cipherOptions['Iv'],
410 $cipherOptions['Tag'],
411 $cipherOptions['Aad'] = isset($cipherOptions['Aad'])
412 ? $cipherOptions['Aad']
413 : '',
414 $cipherOptions['TagLength'] ?: null,
415 $cipherOptions['KeySize']
416 );
417 default:
418 $cipherMethod = $this->buildCipherMethod(
419 $cipherOptions['Cipher'],
420 $cipherOptions['Iv'],
421 $cipherOptions['KeySize']
422 );
423
424 return new AesDecryptingStream(
425 $cipherTextStream,
426 $cek,
427 $cipherMethod
428 );
429 }
430 }
431
432 /**
433 * Generates a stream that wraps the cipher text with the proper cipher and
434 * uses the content encryption key (CEK) to derive both a derived content encryption key
435 * and a commitment key to decrypt the data when read.
436 *
437 * @param string $cipherText Plain-text data to be encrypted using the
438 * materials, algorithm, and data provided.
439 * @param string $cek A content encryption key for use by the stream for
440 * encrypting the plaintext data.
441 * @param array $cipherOptions Options for use in determining the cipher to
442 * be used for encrypting data.
443 * @param string $messageId a string value used to calculate both a commitment
444 * key and derived content encryption key
445 * @param string $commitmentKey a string value to compare with the calculated commitment
446 * key value, if the values don't match an exception is raised.
447 *
448 * @return AesStreamInterface | CryptoException
449 *
450 * @internal
451 */
452 protected function getCommitingDecryptingStream(
453 string $cipherText,
454 string $cek,
455 array $cipherOptions,
456 string $messageId,
457 string $commitmentKey,
458 AlgorithmSuite $algorithmSuite
459 ): AesStreamInterface|CryptoException
460 {
461 $algorithmSuiteIdAsBytes = pack('n', $algorithmSuite->getId());
462 $derivedEncryptionKeyInfo = $algorithmSuiteIdAsBytes . "DERIVEKEY";
463 $commitmentKeyInfo = $algorithmSuiteIdAsBytes . "COMMITKEY";
464 $calculatedCommitmentKey = hash_hkdf(
465 $algorithmSuite->getHashingAlgorithm(),
466 $cek,
467 $algorithmSuite->getCommitmentOutputKeyLengthBytes(),
468 $commitmentKeyInfo,
469 $messageId
470 );
471 //= ../specification/s3-encryption/decryption.md#decrypting-with-commitment
472 //= type=implication
473 //# When using an algorithm suite which supports key commitment, the client MUST verify that the [derived key commitment](./key-derivation.md#hkdf-operation) contains the same bytes as the stored key commitment retrieved from the stored object's metadata.
474 if (
475 //= ../specification/s3-encryption/decryption.md#decrypting-with-commitment
476 //= type=implication
477 //# When using an algorithm suite which supports key commitment,
478 //# the verification of the derived key commitment value MUST be done in constant time.
479 !hash_equals($commitmentKey, $calculatedCommitmentKey)
480 ) {
481 //= ../specification/s3-encryption/decryption.md#decrypting-with-commitment
482 //= type=implication
483 //# When using an algorithm suite which supports key commitment, the client MUST
484 //# throw an exception when the derived key commitment value
485 //# and stored key commitment value do not match.
486 throw new CryptoException("Calculated commitment key does "
487 . "not match expected commitment key value ");
488 }
489 //= ../specification/s3-encryption/decryption.md#decrypting-with-commitment
490 //= type=implication
491 //# When using an algorithm suite which supports key commitment,
492 //# the client MUST verify the key commitment values match before
493 //# deriving the [derived encryption key](./key-derivation.md#hkdf-operation).
494 $derivedEncryptionKey = hash_hkdf(
495 $algorithmSuite->getHashingAlgorithm(),
496 $cek,
497 $algorithmSuite->getDerivationOutputKeyLengthBytes(),
498 $derivedEncryptionKeyInfo,
499 $messageId
500 );
501
502 $cipherTextStream = Psr7\Utils::streamFor($cipherText);
503 switch ($cipherOptions['Cipher']) {
504 case 'gcm':
505 $cipherOptions['Tag'] = $this->getTagFromCiphertextStream(
506 $cipherTextStream,
507 $cipherOptions['TagLength']
508 );
509 $cipherOptions['Aad'] = isset($cipherOptions['Aad'])
510 ? $cipherOptions['Aad'] + $algorithmSuiteIdAsBytes
511 : $algorithmSuiteIdAsBytes;
512
513 return new AesGcmDecryptingStream(
514 $this->getStrippedCiphertextStream(
515 $cipherTextStream,
516 $cipherOptions['TagLength']
517 ),
518 $derivedEncryptionKey,
519 $cipherOptions['Iv'],
520 $cipherOptions['Tag'],
521 $cipherOptions['Aad'],
522 $cipherOptions['TagLength'] ?: null,
523 $cipherOptions['KeySize']
524 );
525 default:
526 throw new CryptoException("Unsupported Cipher used for key commitment messages."
527 . " Found {$cipherOptions["Cipher"]}. Only 'gcm' is supported.");
528 }
529 }
530 }