Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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