Debian Codegraph @

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

raw symbols SCIP
1 <?php
2 namespace Aws\Crypto;
3
4 use Aws\Crypto\Cipher\CipherMethod;
5 use Aws\Exception\CryptoException;
6 use GuzzleHttp\Psr7;
7 use GuzzleHttp\Psr7\AppendStream;
8 use GuzzleHttp\Psr7\Stream;
9 use Psr\Http\Message\StreamInterface;
10
11 trait EncryptionTraitV3
12 {
13 private static array $allowedOptions = [
14 'Cipher' => true,
15 'KeySize' => true,
16 'Aad' => true,
17 ];
18
19 private static array $encryptClasses = [
20 'gcm' => AesGcmEncryptingStream::class
21 ];
22
23 /**
24 * Dependency to generate a CipherMethod from a set of inputs for loading
25 * in to an AesEncryptingStream.
26 *
27 * @param string $cipherName Name of the cipher to generate for encrypting.
28 * @param string $iv Base Initialization Vector for the cipher.
29 * @param int $keySize Size of the encryption key, in bits, that will be
30 * used.
31 *
32 * @return Cipher\CipherMethod
33 *
34 * @internal
35 */
36 abstract protected function buildCipherMethod(
37 $cipherName,
38 $iv,
39 $keySize
40 );
41
42 /**
43 * Builds an AesStreamInterface and populates encryption metadata into the
44 * supplied envelope.
45 *
46 * @param Stream $plaintext Plain-text data to be encrypted using the
47 * materials, algorithm, and data provided.
48 * @param AlgorithmSuite $algorithmSuite Algorithm Suite for use in encryption
49 * @param array $options Options for use in encryption, including cipher
50 * options, and encryption context.
51 * @param MaterialsProviderV3 $provider A provider to supply and encrypt
52 * materials used in encryption.
53 * @param MetadataEnvelope $envelope A storage envelope for encryption
54 * metadata to be added to.
55 *
56 * @return AppendStream
57 *
58 * @throws \InvalidArgumentException Thrown when a value in $options['@CipherOptions']
59 * is not valid.
60 *s
61 * @internal
62 */
63 public function encrypt(
64 Stream $plaintext,
65 AlgorithmSuite $algorithmSuite,
66 array $options,
67 MaterialsProviderV3 $provider,
68 MetadataEnvelope $envelope
69 ): AppendStream
70 {
71 $options = array_change_key_case($options);
72 $cipherOptions = array_intersect_key(
73 $options['@cipheroptions'],
74 self::$allowedOptions
75 );
76 //= ../specification/s3-encryption/encryption.md#content-encryption
77 //= type=implication
78 //# The client MUST validate that the length of the plaintext bytes does not exceed
79 //# the algorithm suite's cipher's maximum content length in bytes.
80 if (strlen($plaintext) > $algorithmSuite->getCipherMaxContentLengthBytes()) {
81 throw new \InvalidArgumentException("The contentLength of the object you are attempting"
82 . " to encrypt exceeds the maximum length allowed for GCM encryption.");
83 }
84 $cipherOptions['Cipher'] = strtolower($cipherOptions['Cipher']);
85
86 if (!self::isSupportedCipher($cipherOptions['Cipher'])) {
87 throw new \InvalidArgumentException('The cipher requested is not'
88 . ' supported by the SDK.');
89 }
90
91 if (empty($cipherOptions['KeySize'])) {
92 $cipherOptions['KeySize'] = 256;
93 }
94
95 if (!is_int($cipherOptions['KeySize'])) {
96 throw new \InvalidArgumentException('The cipher "KeySize" must be'
97 . ' an integer.');
98 }
99
100 if (!MaterialsProviderV3::isSupportedKeySize($cipherOptions['KeySize'])) {
101 throw new \InvalidArgumentException('The cipher "KeySize" requested'
102 . ' is not supported by AES (256).');
103 }
104
105 $encryptClass = self::$encryptClasses[$algorithmSuite->getCipherName()];
106 $aesName = $encryptClass::getStaticAesName();
107 $materialsDescription = $algorithmSuite->isKeyCommitting()
108 ? ['aws:x-amz-cek-alg' => '115']
109 : ['aws:x-amz-cek-alg' => $aesName];
110
111 $keys = $provider->generateCek(
112 $algorithmSuite->getDataKeyLengthBits(),
113 $materialsDescription,
114 $options
115 );
116
117 // Some providers modify materials description based on options
118 if (isset($keys['UpdatedContext'])) {
119 $materialsDescription = $keys['UpdatedContext'];
120 }
121
122 if ($algorithmSuite->isKeyCommitting()) {
123 return $this->encryptCommitingStream(
124 $plaintext,
125 $algorithmSuite,
126 $cipherOptions,
127 $keys,
128 $materialsDescription,
129 $provider,
130 $envelope
131 );
132 } else {
133 return $this->encryptNonCommitingStream(
134 $plaintext,
135 $cipherOptions,
136 $keys,
137 $materialsDescription,
138 $aesName,
139 $provider,
140 $envelope
141 );
142 }
143 }
144
145 private function encryptNonCommitingStream(
146 Stream $plaintext,
147 array &$cipherOptions,
148 array $keys,
149 array $materialsDescription,
150 string $aesName,
151 MaterialsProviderV3 $provider,
152 MetadataEnvelope $envelope
153 ): AppendStream
154 {
155 //= ../specification/s3-encryption/encryption.md#content-encryption
156 //# The generated IV or Message ID MUST be set or returned from the
157 //# encryption process such that it can be included in the content metadata.
158 //= ../specification/s3-encryption/encryption.md#content-encryption
159 //# The client MUST generate an IV or Message ID using the length of the IV or Message ID defined in the algorithm suite.
160 $cipherOptions['Iv'] = $provider->generateIv(
161 $this->getCipherOpenSslName(
162 $cipherOptions['Cipher'],
163 $cipherOptions['KeySize']
164 )
165 );
166 // Some providers modify materials description based on options
167 if (isset($keys['UpdatedContext'])) {
168 $materialsDescription = $keys['UpdatedContext'];
169 }
170
171 $encryptingStream = $this->getNonCommittingEncryptingStream(
172 $plaintext,
173 $keys['Plaintext'],
174 $cipherOptions
175 );
176
177 // Populate envelope data
178 //= ../specification/s3-encryption/data-format/content-metadata.md#determining-s3ec-object-status
179 //# - If the metadata contains "x-amz-iv" and "x-amz-metadata-x-amz-key-v2" then the object MUST be considered as an S3EC-encrypted object using the V2 format.
180 $envelope[MetadataEnvelope::CONTENT_KEY_V2_HEADER] = $keys['Ciphertext'];
181 unset($keys);
182
183 $envelope[MetadataEnvelope::IV_HEADER] =
184 base64_encode($cipherOptions['Iv']);
185 $envelope[MetadataEnvelope::KEY_WRAP_ALGORITHM_HEADER] =
186 $provider->getWrapAlgorithmName();
187 $envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER] = $aesName;
188 $envelope[MetadataEnvelope::UNENCRYPTED_CONTENT_LENGTH_HEADER] =
189 (string) strlen($plaintext);
190 $envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER] =
191 json_encode($materialsDescription);
192 if (!empty($cipherOptions['Tag'])) {
193 $envelope[MetadataEnvelope::CRYPTO_TAG_LENGTH_HEADER] =
194 (string) (strlen($cipherOptions['Tag']) * 8);
195 }
196 if (!MetadataEnvelope::isV2Envelope($envelope)) {
197 throw new CryptoException("Error while writing metadata envelope."
198 . " Not all required fields were set.");
199 }
200
201 return $encryptingStream;
202 }
203
204 private function encryptCommitingStream(
205 Stream $plaintext,
206 AlgorithmSuite $algorithmSuite,
207 array &$options,
208 array $keys,
209 array $materialsDescription,
210 MaterialsProviderV3 $provider,
211 MetadataEnvelope $envelope
212 ): AppendStream
213 {
214 //= ../specification/s3-encryption/encryption.md#content-encryption
215 //# The generated IV or Message ID MUST be set or returned from the
216 //# encryption process such that it can be included in the content metadata.
217 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
218 //= type=implication
219 //# When encrypting or decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY,
220 //# the IV used in the AES-GCM content encryption/decryption
221 //# MUST consist entirely of bytes with the value 0x01.
222 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
223 //= type=implication
224 //# The IV's total length MUST match the IV length defined by the algorithm suite.
225 $options['Iv'] = str_repeat("\1", $algorithmSuite->getIvLengthBytes());
226 $messageId = $provider->generateIv(
227 $this->getCipherOpenSslName(
228 $algorithmSuite->getCipherName(),
229 //= ../specification/s3-encryption/encryption.md#content-encryption
230 //# The client MUST generate an IV or Message ID using the length of
231 //# the IV or Message ID defined in the algorithm suite.
232 $algorithmSuite->getKeyCommitmentSaltLengthBits()
233 )
234 );
235 // Some providers modify materials description based on options
236 if (isset($keys['UpdatedContext'])) {
237 $materialsDescription["aws:x-amz-cek-alg"] = (string) $algorithmSuite->getId();
238 }
239 $commitingEncryptingArray = $this->getCommitingEncryptionStream(
240 $plaintext,
241 $keys['Plaintext'],
242 $options,
243 $messageId,
244 $algorithmSuite
245 );
246 //= ../specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key
247 //= type=implication
248 //# The derived key commitment value MUST be set or returned from the encryption process
249 //# such that it can be included in the content metadata.
250 $commitmentKey = $commitingEncryptingArray[0];
251 $encryptionStream = $commitingEncryptingArray[1];
252
253 // Populate envelope data
254 $envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_V3] = $keys['Ciphertext'];
255 unset($keys);
256
257 $envelope[MetadataEnvelope::CONTENT_CIPHER_V3] = $algorithmSuite->getId();
258 // we are able to always set the encryption context in the envelope because PHP
259 // only supports a KMS Material Provider.
260 $envelope[MetadataEnvelope::ENCRYPTION_CONTEXT_V3] =
261 json_encode($materialsDescription);
262 //= ../specification/s3-encryption/data-format/content-metadata.md#v3-only
263 //# The Encryption Context value MUST be used for wrapping algorithm `kms+context` or `12`.
264 $envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_ALGORITHM_V3] = '12';
265 $envelope[MetadataEnvelope::KEY_COMMITMENT_V3] = $commitmentKey;
266 $envelope[MetadataEnvelope::MESSAGE_ID_V3] = base64_encode($messageId);
267 if (!MetadataEnvelope::isV3Envelope($envelope)) {
268 throw new CryptoException("Error while writing metadata envelope."
269 . " Not all required fields were set.");
270 }
271
272 return $encryptionStream;
273 }
274
275 /**
276 * Generates a stream that wraps the plaintext with the proper cipher and
277 * uses the content encryption key (CEK) to encrypt the data when read.
278 *
279 * @param Stream $plaintext Plain-text data to be encrypted using the
280 * materials, algorithm, and data provided.
281 * @param string $cek A content encryption key for use by the stream for
282 * encrypting the plaintext data.
283 * @param array $cipherOptions Options for use in determining the cipher to
284 * be used for encrypting data.
285 *
286 * @return AppendStream returns an AppendStream
287 *
288 * @internal
289 */
290 protected function getNonCommittingEncryptingStream(
291 Stream $plaintext,
292 string $cek,
293 array &$cipherOptions
294 ): AppendStream
295 {
296 // Only 'gcm' is supported for encryption currently
297 switch ($cipherOptions['Cipher']) {
298 //= ../specification/s3-encryption/encryption.md#content-encryption
299 //= type=implication
300 //# The S3EC MUST use the encryption algorithm configured during [client](./client.md) initialization.
301 case 'gcm':
302 $cipherOptions['TagLength'] = 16;
303 $encryptClass = self::$encryptClasses['gcm'];
304 //= ../specification/s3-encryption/encryption.md#alg-aes-256-gcm-iv12-tag16-no-kdf
305 //= type=implication
306 //# The client MUST initialize the cipher, or call an AES-GCM encryption API,
307 //# with the plaintext data key, the generated IV, and the tag length defined
308 //# in the Algorithm Suite when encrypting with ALG_AES_256_GCM_IV12_TAG16_NO_KDF.
309 $cipherTextStream = new $encryptClass(
310 $plaintext,
311 $cek,
312 $cipherOptions['Iv'],
313 $cipherOptions['Aad'] = isset($cipherOptions['Aad'])
314 ? $cipherOptions['Aad']
315 : '',
316 $cipherOptions['TagLength'],
317 $cipherOptions['KeySize']
318 );
319
320 if (!empty($cipherOptions['Aad'])) {
321 trigger_error("'Aad' has been supplied for content encryption"
322 . " with " . $cipherTextStream->getAesName() . ". The"
323 . " PHP SDK encryption client can decrypt an object"
324 . " encrypted in this way, but other AWS SDKs may not be"
325 . " able to.", E_USER_WARNING);
326 }
327
328 $appendStream = new AppendStream([
329 $cipherTextStream->createStream()
330 ]);
331 //= ../specification/s3-encryption/encryption.md#alg-aes-256-gcm-iv12-tag16-no-kdf
332 //= type=implication
333 //# The client MUST append the GCM auth tag to the ciphertext if the underlying
334 //# crypto provider does not do so automatically.
335 $cipherOptions['Tag'] = $cipherTextStream->getTag();
336 $appendStream->addStream(Psr7\Utils::streamFor($cipherOptions['Tag']));
337
338 return $appendStream;
339 default:
340 throw new CryptoException("Unsupported Cipher used for key commitment messages."
341 . " Found {$cipherOptions["Cipher"]}. Only 'gcm' is supported.");
342 }
343 }
344
345 /**
346 * Generates a stream that wraps the plaintext with the proper cipher and
347 * uses the content encryption key (CEK) to encrypt the data when read.
348 *
349 * @param Stream $plaintext Plain-text data to be encrypted using the
350 * materials, algorithm, and data provided.
351 * @param string $cek A content encryption key for use by the stream for
352 * encrypting the plaintext data.
353 * @param array $cipherOptions Options for use in determining the cipher to
354 * be used for encrypting data.
355 * @param string $messageId salt value used for key extraction step in the key
356 * derivation process.
357 * @param AlgorithmSuite $algorithmSuite options used for key commitment
358 *
359 * @return array returns an array with two elements as follows: [commitmentKey, AppendStream]
360 *
361 * @internal
362 */
363 protected function getCommitingEncryptionStream(
364 Stream $plaintext,
365 string $dek,
366 array &$cipherOptions,
367 string $messageId,
368 AlgorithmSuite $algorithmSuite
369 ): array
370 {
371 $algorithmSuiteIdAsBytes = pack('n', $algorithmSuite->getId());
372 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
373 //= type=implication
374 //# - The input info MUST be a concatenation of the algorithm suite ID as bytes followed by the string DERIVEKEY as UTF8 encoded bytes.
375 $derivedEncryptionKeyInfo = $algorithmSuiteIdAsBytes . "DERIVEKEY";
376 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
377 //= type=implication
378 //# - The input info MUST be a concatenation of the algorithm suite ID as bytes followed by the string COMMITKEY as UTF8 encoded bytes.
379 $commitmentKeyInfo = $algorithmSuiteIdAsBytes . "COMMITKEY";
380 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
381 //= type=implication
382 //# - The length of the input keying material MUST equal the key derivation
383 //# input length specified by the algorithm suite commit key derivation setting.
384 if (strlen($dek) !== $algorithmSuite->getDerivationInputKeyLengthBytes()) {
385 throw new CryptoException("Input Key Material length exceeds "
386 . "key derivation input length specified by the algorithm suite.");
387 }
388 //= ../specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key
389 //= type=implication
390 //# The client MUST use HKDF to derive the key commitment value and
391 //# the derived encrypting key as described in [Key Derivation](key-derivation.md).
392 $cek = hash_hkdf(
393 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
394 //= type=implication
395 //# - The hash function MUST be specified by the algorithm suite commitment settings.
396 $algorithmSuite->getHashingAlgorithm(),
397 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
398 //= type=implication
399 //# - The input keying material MUST be the plaintext data key (PDK) generated by the key provider.
400 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
401 //= type=implication
402 //# - The DEK input pseudorandom key MUST be the output from the extract step.
403 $dek,
404 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
405 //= type=implication
406 //# - The length of the output keying material MUST equal the encryption key length specified by the algorithm suite encryption settings.
407 $algorithmSuite->getDerivationOutputKeyLengthBytes(),
408 $derivedEncryptionKeyInfo,
409 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
410 //= type=implication
411 //# - The salt MUST be the Message ID with the length defined in the algorithm suite.
412 $messageId
413 );
414 $commitmentKey = hash_hkdf(
415 $algorithmSuite->getHashingAlgorithm(),
416 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
417 //= type=implication
418 //# - The CK input pseudorandom key MUST be the output from the extract step.
419 $dek,
420 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
421 //= type=implication
422 //# - The length of the output keying material MUST equal the commit key length specified by the supported algorithm suites.
423 $algorithmSuite->getCommitmentOutputKeyLengthBytes(),
424 $commitmentKeyInfo,
425 $messageId
426 );
427
428 switch ($cipherOptions['Cipher']) {
429 // Only 'gcm' is supported for encryption currently
430 case 'gcm':
431 $cipherOptions['TagLength'] = $algorithmSuite->getCipherTagLengthInBytes();
432 $encryptClass = self::$encryptClasses[$algorithmSuite->getCipherName()];
433
434 if (!empty($cipherOptions['Aad'])) {
435 trigger_error("'Aad' has been supplied for content encryption"
436 . " with " . $encryptClass->getAesName() . ". The"
437 . " PHP SDK encryption client can decrypt an object"
438 . " encrypted in this way, but other AWS SDKs may not be"
439 . " able to.", E_USER_NOTICE);
440 }
441 $cipherOptions['Aad'] = isset($cipherOptions['Aad'])
442 ? $cipherOptions['Aad'] + $algorithmSuiteIdAsBytes
443 : $algorithmSuiteIdAsBytes;
444 //= ../specification/s3-encryption/key-derivation.md#hkdf-operation
445 //= type=implication
446 //# The client MUST initialize the cipher, or call an AES-GCM encryption API,
447 //# with the derived encryption key, an IV containing only bytes with the value 0x01,
448 //# and the tag length defined in the Algorithm Suite when encrypting or
449 //# decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY.
450 $cipherTextStream = new $encryptClass(
451 $plaintext,
452 $cek,
453 $cipherOptions['Iv'],
454 $cipherOptions['Aad'],
455 $cipherOptions['TagLength'],
456 $cipherOptions['KeySize']
457 );
458
459 $appendStream = new AppendStream([
460 $cipherTextStream->createStream()
461 ]);
462 //= ../specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key
463 //= type=implication
464 //# The client MUST append the GCM auth tag to the ciphertext if the underlying
465 //# crypto provider does not do so automatically.
466 $cipherOptions['Tag'] = $cipherTextStream->getTag();
467 $appendStream->addStream(Psr7\Utils::streamFor($cipherOptions['Tag']));
468
469 return [base64_encode($commitmentKey), $appendStream];
470 default:
471 throw new CryptoException("Unsupported Cipher used for content encryption");
472 }
473 }
474 }