diff --git a/compliance_exceptions/decryption_exceptions.md b/compliance_exceptions/decryption_exceptions.md new file mode 100644 index 00000000..4919f2ce --- /dev/null +++ b/compliance_exceptions/decryption_exceptions.md @@ -0,0 +1,49 @@ +# Compliance Exceptions for Decryption Implementation + +## Summary + +The Python S3 Encryption Client does not currently support Ranged Gets. +Ranged Gets allow downloading and decrypting a subset of bytes from an encrypted S3 object. +This is an optional feature per the specification ("MAY support") and is planned for a future release. + +## Ranged Gets + +##= specification/s3-encryption/decryption.md#ranged-gets +##= type=exception +##% The S3EC MAY support the "range" parameter on GetObject which specifies a subset of bytes to download and decrypt. + +Justification: Ranged Gets are not yet implemented in the Python S3 Encryption Client. The specification uses MAY, making this an optional feature. This is planned for a future release. + +--- + +##= specification/s3-encryption/decryption.md#ranged-gets +##= type=exception +##% If the S3EC supports Ranged Gets, the S3EC MUST adjust the customer-provided range to include the beginning and end of the cipher blocks for the given range. + +Justification: Not applicable since Ranged Gets are not yet supported. When Ranged Gets are implemented, this requirement will be fulfilled. + +--- + +##= specification/s3-encryption/decryption.md#ranged-gets +##= type=exception +##% If the object was encrypted with ALG_AES_256_GCM_IV12_TAG16_NO_KDF, then ALG_AES_256_CTR_IV16_TAG16_NO_KDF MUST be used to decrypt the range of the object. + +Justification: Not applicable since Ranged Gets are not yet supported. When Ranged Gets are implemented, the correct CTR-mode algorithm suite will be used for GCM-encrypted objects. + +--- + +##= specification/s3-encryption/decryption.md#ranged-gets +##= type=exception +##% If the object was encrypted with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, then ALG_AES_256_CTR_HKDF_SHA512_COMMIT_KEY MUST be used to decrypt the range of the object. + +Justification: Not applicable since Ranged Gets are not yet supported. When Ranged Gets are implemented, the correct CTR-mode algorithm suite will be used for key-committing objects. + +--- + +##= specification/s3-encryption/decryption.md#ranged-gets +##= type=exception +##% If the GetObject response contains a range, but the GetObject request does not contain a range, the S3EC MUST throw an exception. + +Justification: Not applicable since Ranged Gets are not yet supported. When Ranged Gets are implemented, this validation will be added to detect unexpected range responses. + +--- diff --git a/compliance_exceptions/encryption_exceptions.md b/compliance_exceptions/encryption_exceptions.md new file mode 100644 index 00000000..bf7d9f62 --- /dev/null +++ b/compliance_exceptions/encryption_exceptions.md @@ -0,0 +1,63 @@ +# Compliance Exceptions for Encryption Implementation + +## Summary + +The Python S3 Encryption Client does not implement AES-CTR algorithm suites (used only for ranged-get decryption), +does not yet validate IV/Message ID for zero values, does not validate maximum plaintext length, +and relies on Python's `cryptography` library to automatically append GCM auth tags. + +## AES-CTR Algorithm Suites + +##= specification/s3-encryption/encryption.md#alg-aes-256-ctr-hkdf-sha512-commit-key +##= type=exception +##% Attempts to encrypt using key committing AES-CTR MUST fail. + +Justification: The AES-CTR algorithm suites are only used for ranged-get decryption. Since ranged gets are not yet implemented, these algorithm suites are not defined in the `AlgorithmSuite` enum and cannot be selected for encryption. The constraint is satisfied structurally. + +--- + +##= specification/s3-encryption/encryption.md#alg-aes-256-ctr-iv16-tag16-no-kdf +##= type=exception +##% Attempts to encrypt using AES-CTR MUST fail. + +Justification: Same as above. AES-CTR is not available as an algorithm suite option, so it cannot be used for encryption. + +--- + +## GCM Auth Tag Appending + +##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key +##= type=exception +##% The client MUST append the GCM auth tag to the ciphertext if the underlying crypto provider does not do so automatically. + +Justification: Python's `cryptography` library (`AESGCM.encrypt`) automatically appends the GCM authentication tag to the ciphertext. No manual appending is needed. + +--- + +##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-iv12-tag16-no-kdf +##= type=exception +##% The client MUST append the GCM auth tag to the ciphertext if the underlying crypto provider does not do so automatically. + +Justification: Python's `cryptography` library (`AESGCM.encrypt`) automatically appends the GCM authentication tag to the ciphertext. No manual appending is needed. + +--- + +## Cipher Initialization Validation + +##= specification/s3-encryption/encryption.md#cipher-initialization +##= type=exception +##% The client SHOULD validate that the generated IV or Message ID is not zeros. + +Justification: This SHOULD-level validation is not yet implemented. The IV and Message ID are generated using `os.urandom()`, which is cryptographically secure and extremely unlikely to produce all-zero output. This validation is planned for a future release. + +--- + +## Plaintext Length Validation + +##= specification/s3-encryption/encryption.md#content-encryption +##= type=exception +##% The client MUST validate that the length of the plaintext bytes does not exceed the algorithm suite's cipher's maximum content length in bytes. + +Justification: Maximum plaintext length validation is not yet implemented. For AES-GCM with a 12-byte IV, the maximum plaintext size is approximately 64 GiB, which exceeds practical S3 single-object upload limits. This validation is planned for a future release. + +--- diff --git a/src/s3_encryption/__init__.py b/src/s3_encryption/__init__.py index a3558195..f2af6d7a 100644 --- a/src/s3_encryption/__init__.py +++ b/src/s3_encryption/__init__.py @@ -15,16 +15,39 @@ DefaultCryptoMaterialsManager, ) from .materials.keyring import AbstractKeyring +from .materials.materials import AlgorithmSuite, CommitmentPolicy from .pipelines import GetEncryptedObjectPipeline, PutEncryptedObjectPipeline S3_METADATA_PREFIX = "x-amz-meta-" +# Thread-local context attribute names +_CTX_ENCRYPTION_CONTEXT = "encryption_context" +_CTX_BUCKET = "bucket" +_CTX_KEY = "key" +_CTX_S3_CLIENT = "s3_client" +_CTX_INSTRUCTION_FILE_MODE = "instruction_file_mode" + +# Attributes to clean up after get_object completes +# (s3_client is intentionally excluded — it is not request-scoped) +_GET_OBJECT_CLEANUP_ATTRS = (_CTX_ENCRYPTION_CONTEXT, _CTX_BUCKET, _CTX_KEY) + @define class S3EncryptionClientConfig: """Configuration object for the S3 Encryption Client.""" keyring: AbstractKeyring + encryption_algorithm: AlgorithmSuite = field( + default=AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + commitment_policy: CommitmentPolicy = field( + default=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT + ) + ##= specification/s3-encryption/client.md#enable-legacy-unauthenticated-modes + ##% The S3EC MUST support the option to enable or disable legacy unauthenticated modes (content encryption algorithms). + ##= specification/s3-encryption/client.md#enable-legacy-unauthenticated-modes + ##% The option to enable legacy unauthenticated modes MUST be set to false by default. + enable_legacy_unauthenticated_modes: bool = field(default=False) cmm: AbstractCryptoMaterialsManager = field() ##= specification/s3-encryption/data-format/metadata-strategy.md#instruction-file ##= type=implementation @@ -41,6 +64,51 @@ class S3EncryptionClientConfig: def _default_cmm_for_keyring(self): return DefaultCryptoMaterialsManager(self.keyring) + ##= specification/s3-encryption/client.md#encryption-algorithm + ##% The S3EC MUST validate that the configured encryption algorithm is not legacy. + ##= specification/s3-encryption/client.md#encryption-algorithm + ##% If the configured encryption algorithm is legacy, then the S3EC MUST throw an exception. + ##= specification/s3-encryption/client.md#key-commitment + ##% The S3EC MUST validate the configured Encryption Algorithm against the provided key commitment policy. + ##= specification/s3-encryption/client.md#key-commitment + ##% If the configured Encryption Algorithm is incompatible with the key commitment policy, then it MUST throw an exception. + def __attrs_post_init__(self): + """Validate algorithm suite and commitment policy configuration.""" + if self.encryption_algorithm.is_legacy: + raise S3EncryptionClientError( + f"Cannot configure S3 Encryption Client with legacy algorithm suite " + f"{self.encryption_algorithm.name}. Legacy algorithm suites are only " + f"supported for decryption (and enable_legacy_unauthenticated_modes is True)." + ) + + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##% When the commitment policy is REQUIRE_ENCRYPT_ALLOW_DECRYPT, the S3EC MUST only encrypt using an algorithm suite which supports key commitment. + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##% When the commitment policy is REQUIRE_ENCRYPT_REQUIRE_DECRYPT, the S3EC MUST only encrypt using an algorithm suite which supports key commitment. + if ( + self.commitment_policy + in ( + CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT, + CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + ) + and not self.encryption_algorithm.supports_key_commitment + ): + raise S3EncryptionClientError( + f"Commitment policy {self.commitment_policy.name} requires a key-committing " + f"algorithm suite, but {self.encryption_algorithm.name} does not support key commitment." + ) + + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##% When the commitment policy is FORBID_ENCRYPT_ALLOW_DECRYPT, the S3EC MUST NOT encrypt using an algorithm suite which supports key commitment. + if ( + self.commitment_policy == CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT + and self.encryption_algorithm.supports_key_commitment + ): + raise S3EncryptionClientError( + f"Commitment policy {self.commitment_policy.name} forbids key-committing " + f"algorithm suites, but {self.encryption_algorithm.name} supports key commitment." + ) + class S3EncryptionClientPlugin: """Plugin that adds encryption/decryption capabilities to a boto3 S3 client. @@ -67,7 +135,7 @@ def on_put_object_before_call(self, params, **kwargs): params: Dictionary of parameters for the PutObject call (after serialization) **kwargs: Additional event arguments """ - if getattr(self._context, "instruction_file_mode", False): + if getattr(self._context, _CTX_INSTRUCTION_FILE_MODE, False): raise S3EncryptionClientError( "Instruction file mode is exclusively for reading instruction files " "and not supported in put_object!" @@ -88,11 +156,12 @@ def on_put_object_before_call(self, params, **kwargs): # Unexpected body type - should not happen as boto3 validates before this point raise S3EncryptionClientError("Unexpected type of body parameter!") - encryption_context = getattr(self._context, "encryption_context", None) + encryption_context = getattr(self._context, _CTX_ENCRYPTION_CONTEXT, None) - pipeline = PutEncryptedObjectPipeline(self.config.cmm) + pipeline = PutEncryptedObjectPipeline(self.config.cmm, self.config.encryption_algorithm) encrypted_data, encryption_metadata = pipeline.encrypt( - body_bytes, encryption_context=encryption_context + body_bytes, + encryption_context=encryption_context, ) params["body"] = encrypted_data @@ -118,12 +187,12 @@ def on_get_object_after_call(self, parsed, **kwargs): **kwargs: Additional event arguments (includes 'params' with request parameters) """ # Check if plaintext mode is enabled via thread-local flag - if getattr(self._context, "instruction_file_mode", False): + if getattr(self._context, _CTX_INSTRUCTION_FILE_MODE, False): self.process_instruction_file(parsed) return # Get encryption context from thread-local storage (set by get_object wrapper) - encryption_context = getattr(self._context, "encryption_context", None) + encryption_context = getattr(self._context, _CTX_ENCRYPTION_CONTEXT, None) # The parsed response already has the Body as a StreamingBody # We need to read it, decrypt it, and replace it @@ -137,13 +206,15 @@ def on_get_object_after_call(self, parsed, **kwargs): # Create a pipeline and decrypt the data pipeline = GetEncryptedObjectPipeline( self.config.cmm, - s3_client=getattr(self._context, "s3_client", None), + commitment_policy=self.config.commitment_policy, + s3_client=getattr(self._context, _CTX_S3_CLIENT, None), + enable_legacy_unauthenticated_modes=self.config.enable_legacy_unauthenticated_modes, ) decrypted_data = pipeline.decrypt( response, encryption_context, - bucket=getattr(self._context, "bucket", None), - key=getattr(self._context, "key", None), + bucket=getattr(self._context, _CTX_BUCKET, None), + key=getattr(self._context, _CTX_KEY, None), instruction_suffix=self.config.instruction_file_suffix, ) @@ -163,7 +234,7 @@ def process_instruction_file(self, parsed): Args: parsed: Dictionary containing the parsed response """ - instruction_key = getattr(self._context, "key", None) + instruction_key = getattr(self._context, _CTX_KEY, None) # In plaintext mode, parse instruction file and append to metadata existing_metadata = parsed.get("Metadata", {}) @@ -242,8 +313,8 @@ def put_object(self, **kwargs): raise S3EncryptionClientError(f"Failed to encrypt object: {str(e)}") from e finally: # Clean up thread-local storage - if hasattr(self._plugin._context, "encryption_context"): - delattr(self._plugin._context, "encryption_context") + if hasattr(self._plugin._context, _CTX_ENCRYPTION_CONTEXT): + delattr(self._plugin._context, _CTX_ENCRYPTION_CONTEXT) def get_object(self, **kwargs): """Download and decrypt an object from S3. @@ -266,12 +337,12 @@ def get_object(self, **kwargs): encryption_context = kwargs.pop("EncryptionContext", None) # Store encryption context in thread-local storage for the event handler - self._plugin._context.encryption_context = encryption_context + setattr(self._plugin._context, _CTX_ENCRYPTION_CONTEXT, encryption_context) # Store wrapped client in thread-local storage for # the event handler to fetch instruction files - self._plugin._context.s3_client = self.wrapped_s3_client - self._plugin._context.bucket = kwargs.get("Bucket") - self._plugin._context.key = kwargs.get("Key") + setattr(self._plugin._context, _CTX_S3_CLIENT, self.wrapped_s3_client) + setattr(self._plugin._context, _CTX_BUCKET, kwargs.get("Bucket")) + setattr(self._plugin._context, _CTX_KEY, kwargs.get("Key")) try: return self.wrapped_s3_client.get_object(**kwargs) @@ -284,7 +355,6 @@ def get_object(self, **kwargs): finally: # Clean up thread-local storage; # do not clean up the client as it is not thread local only - attrs = ["encryption_context", "Bucket", "Key"] - for attr in attrs: + for attr in _GET_OBJECT_CLEANUP_ATTRS: if hasattr(self._plugin._context, attr): delattr(self._plugin._context, attr) diff --git a/src/s3_encryption/key_derivation.py b/src/s3_encryption/key_derivation.py new file mode 100644 index 00000000..8183f5f3 --- /dev/null +++ b/src/s3_encryption/key_derivation.py @@ -0,0 +1,163 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Key derivation for S3 Encryption Client key-committing algorithm suites. + +Implements HKDF-based key derivation as specified in: + specification/s3-encryption/key-derivation.md + +For ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY: + - Extract: HKDF-SHA512, salt = Message ID (28 bytes), IKM = plaintext data key + - Expand (DEK): info = suite_id_bytes + b"DERIVEKEY", output = 32 bytes + - Expand (Commit Key): info = suite_id_bytes + b"COMMITKEY", output = 28 bytes +""" + +from __future__ import annotations + +import hmac +from typing import TYPE_CHECKING + +from cryptography.hazmat.primitives.hashes import SHA512 +from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand + +from .exceptions import S3EncryptionClientError, S3EncryptionClientSecurityError + +if TYPE_CHECKING: + from .materials.materials import AlgorithmSuite + +# Map of supported KDF hash algorithm names to cryptography hash classes. +_HASH_ALGORITHMS = { + "sha512": SHA512, +} + + +def _hkdf_extract(salt: bytes, ikm: bytes, hash_algorithm: str) -> bytes: + """HKDF extract step using HMAC. + + Args: + salt: The salt value (Message ID). + ikm: Input keying material (plaintext data key). + hash_algorithm: Hash algorithm name (e.g. "sha512"). + + Returns: + The pseudorandom key (PRK). + """ + return hmac.new(salt, ikm, hash_algorithm).digest() + + +def _hkdf_expand(prk: bytes, info: bytes, length: int, hash_algorithm: str) -> bytes: + """HKDF expand step. + + Args: + prk: Pseudorandom key from extract step. + info: Context/application-specific info string. + length: Desired output length in bytes. + hash_algorithm: Hash algorithm name (e.g. "sha512"). + + Returns: + Output keying material of the requested length. + + Raises: + S3EncryptionClientError: If the hash algorithm is not supported. + """ + hash_cls = _HASH_ALGORITHMS.get(hash_algorithm) + if hash_cls is None: + raise S3EncryptionClientError(f"Unsupported KDF hash algorithm: {hash_algorithm}") + hkdf = HKDFExpand(algorithm=hash_cls(), length=length, info=info) + return hkdf.derive(prk) + + +def derive_keys( + plaintext_data_key: bytes, + message_id: bytes, + algorithm_suite: AlgorithmSuite, +) -> tuple[bytes, bytes]: + """Derive the encryption key and commitment key from a plaintext data key. + + Uses HKDF with SHA-512 as specified in the S3EC key derivation spec. + + Args: + plaintext_data_key: The plaintext data key from the keyring. + message_id: The generated Message ID used as the HKDF salt. + algorithm_suite: The algorithm suite whose parameters drive key lengths + and info strings. + + Returns: + A tuple of (derived_encryption_key, commit_key). + """ + suite_id = algorithm_suite.suite_id_bytes + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The length of the output keying material MUST equal the encryption key length specified by the algorithm suite encryption settings. + enc_key_len = algorithm_suite.data_key_length_bytes + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The length of the output keying material MUST equal the commit key length specified by the supported algorithm suites. + commit_key_len = algorithm_suite.commitment_length_bytes + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The hash function MUST be specified by the algorithm suite commitment settings. + hash_alg = algorithm_suite.kdf_hash_algorithm + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The length of the input keying material MUST equal the key derivation input length specified by the algorithm suite commit key derivation setting. + if len(plaintext_data_key) != enc_key_len: + raise S3EncryptionClientError( + f"Plaintext data key length ({len(plaintext_data_key)}) does not match " + f"the key derivation input length ({enc_key_len}) specified by the algorithm suite." + ) + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The input keying material MUST be the plaintext data key (PDK) generated by the key provider. + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The salt MUST be the Message ID with the length defined in the algorithm suite. + prk = _hkdf_extract(salt=message_id, ikm=plaintext_data_key, hash_algorithm=hash_alg) + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The DEK input pseudorandom key MUST be the output from the extract step. + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The input info MUST be a concatenation of the algorithm suite ID as bytes + ##% followed by the string DERIVEKEY as UTF8 encoded bytes. + derived_encryption_key = _hkdf_expand( + prk, info=suite_id + b"DERIVEKEY", length=enc_key_len, hash_algorithm=hash_alg + ) + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The CK input pseudorandom key MUST be the output from the extract step. + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% - The input info MUST be a concatenation of the algorithm suite ID as bytes + ##% followed by the string COMMITKEY as UTF8 encoded bytes. + commit_key = _hkdf_expand( + prk, info=suite_id + b"COMMITKEY", length=commit_key_len, hash_algorithm=hash_alg + ) + + return derived_encryption_key, commit_key + + +def verify_commitment(stored_commitment: bytes, derived_commitment: bytes) -> None: + """Verify key commitment in constant time. + + Args: + stored_commitment: The commitment value from the object metadata. + derived_commitment: The commitment value derived from the data key. + + Raises: + S3EncryptionClientSecurityError: If the commitment values do not match. + """ + ##= specification/s3-encryption/decryption.md#decrypting-with-commitment + ##= type=implementation + ##% When using an algorithm suite which supports key commitment, the verification of the derived key commitment value MUST be done in constant time. + ##= specification/s3-encryption/decryption.md#decrypting-with-commitment + ##= type=implementation + ##% When using an algorithm suite which supports key commitment, the client MUST throw an exception when the derived key commitment value + ##% and stored key commitment value do not match. + if not hmac.compare_digest(stored_commitment, derived_commitment): + raise S3EncryptionClientSecurityError( + "Key commitment verification failed: stored commitment does not match derived commitment." + ) diff --git a/src/s3_encryption/materials/__init__.py b/src/s3_encryption/materials/__init__.py index c67d5802..c5cc7d6d 100644 --- a/src/s3_encryption/materials/__init__.py +++ b/src/s3_encryption/materials/__init__.py @@ -10,7 +10,7 @@ from .encrypted_data_key import EncryptedDataKey from .keyring import AbstractKeyring from .kms_keyring import KmsKeyring -from .materials import EncryptionMaterials +from .materials import AlgorithmSuite, CommitmentPolicy, EncryptionMaterials __all__ = [ "AbstractKeyring", @@ -18,5 +18,7 @@ "AbstractCryptoMaterialsManager", "DefaultCryptoMaterialsManager", "EncryptedDataKey", + "AlgorithmSuite", + "CommitmentPolicy", "EncryptionMaterials", ] diff --git a/src/s3_encryption/materials/kms_keyring.py b/src/s3_encryption/materials/kms_keyring.py index a32493fc..edf1d27b 100644 --- a/src/s3_encryption/materials/kms_keyring.py +++ b/src/s3_encryption/materials/kms_keyring.py @@ -10,6 +10,7 @@ from botocore import client from ..exceptions import S3EncryptionClientError +from ..materials.materials import AlgorithmSuite from .encrypted_data_key import EncryptedDataKey from .keyring import S3Keyring @@ -76,7 +77,20 @@ def on_encrypt(self, enc_materials): ##= specification/s3-encryption/materials/s3-kms-keyring.md#supported-wrapping-algorithm-modes ##= type=implication ##% The KmsKeyring MUST NOT support encryption using KmsV1 mode. - encryption_context["aws:x-amz-cek-alg"] = "AES/GCM/NoPadding" + # For committing algorithm suites (V3), the encryption context algorithm + # value is the algorithm suite ID as a string ("115"), not the cipher name. + # For non-committing suites (V2), use the cipher name ("AES/GCM/NoPadding"). + if ( + enc_materials.encryption_algorithm + == AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ): + encryption_context["aws:x-amz-cek-alg"] = str( + enc_materials.encryption_algorithm.suite_id + ) + else: + encryption_context["aws:x-amz-cek-alg"] = ( + enc_materials.encryption_algorithm.cipher_name + ) # Python implementation uses KMS GenerateDataKey instead of the spec's # EncryptDataKey pattern diff --git a/src/s3_encryption/materials/materials.py b/src/s3_encryption/materials/materials.py index 3966e17c..f2e8fd4f 100644 --- a/src/s3_encryption/materials/materials.py +++ b/src/s3_encryption/materials/materials.py @@ -7,6 +7,7 @@ and decryption operations. """ +from enum import Enum from typing import Any from attrs import define, field @@ -14,6 +15,172 @@ from .encrypted_data_key import EncryptedDataKey +class AlgorithmSuite(Enum): + """Algorithm suites supported by the S3 Encryption Client. + + Each member consolidates all cryptographic parameters for a given suite, + modeled after the Java reference implementation. The tuple values are: + + (id, is_legacy, data_key_algorithm, data_key_length_bits, + cipher_name, cipher_block_size_bits, cipher_iv_length_bits, + cipher_tag_length_bits, is_committing, commitment_length_bits, + commitment_nonce_length_bits, kdf_hash_algorithm, suite_id_bytes) + """ + + ALG_AES_256_CBC_IV16_NO_KDF = ( + 0x0070, # id + True, # is_legacy + "AES", # data_key_algorithm + 256, # data_key_length_bits + "AES/CBC/PKCS5Padding", # cipher_name + 128, # cipher_block_size_bits + 128, # cipher_iv_length_bits (16 bytes) + 0, # cipher_tag_length_bits (CBC has no auth tag) + False, # is_committing + 0, # commitment_length_bits + 0, # commitment_nonce_length_bits + None, # kdf_hash_algorithm + b"", # suite_id_bytes + ) + + ALG_AES_256_GCM_IV12_TAG16_NO_KDF = ( + 0x0072, # id + False, # is_legacy + "AES", # data_key_algorithm + 256, # data_key_length_bits + "AES/GCM/NoPadding", # cipher_name + 128, # cipher_block_size_bits + 96, # cipher_iv_length_bits (12 bytes) + 128, # cipher_tag_length_bits (16 bytes) + False, # is_committing + 0, # commitment_length_bits + 0, # commitment_nonce_length_bits + None, # kdf_hash_algorithm + b"", # suite_id_bytes + ) + + ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY = ( + 0x0073, # id + False, # is_legacy + "AES", # data_key_algorithm + 256, # data_key_length_bits + "AES/GCM/HKDF/CommitKey", # cipher_name + 128, # cipher_block_size_bits + 96, # cipher_iv_length_bits (12 bytes) + 128, # cipher_tag_length_bits (16 bytes) + True, # is_committing + 224, # commitment_length_bits (28 bytes) + 224, # commitment_nonce_length_bits (28 bytes = message_id) + "sha512", # kdf_hash_algorithm + b"\x00\x73", # suite_id_bytes + ) + + def __init__( + self, + suite_id: int, + is_legacy: bool, + data_key_algorithm: str, + data_key_length_bits: int, + cipher_name: str, + cipher_block_size_bits: int, + cipher_iv_length_bits: int, + cipher_tag_length_bits: int, + is_committing: bool, + commitment_length_bits: int, + commitment_nonce_length_bits: int, + kdf_hash_algorithm: str | None, + suite_id_bytes: bytes, + ): + """Initialize algorithm suite parameters from the enum tuple.""" + self._id = suite_id + self._is_legacy = is_legacy + self._data_key_algorithm = data_key_algorithm + self._data_key_length_bits = data_key_length_bits + self._cipher_name = cipher_name + self._cipher_block_size_bits = cipher_block_size_bits + self._cipher_iv_length_bits = cipher_iv_length_bits + self._cipher_tag_length_bits = cipher_tag_length_bits + self._is_committing = is_committing + self._commitment_length_bits = commitment_length_bits + self._commitment_nonce_length_bits = commitment_nonce_length_bits + self._kdf_hash_algorithm = kdf_hash_algorithm + self._suite_id_bytes = suite_id_bytes + + # --- Convenience properties --- + + @property + def suite_id(self) -> int: + """Numeric identifier for this algorithm suite.""" + return self._id + + @property + def is_legacy(self) -> bool: + """Return True if this algorithm suite is a legacy unauthenticated mode.""" + return self._is_legacy + + @property + def supports_key_commitment(self) -> bool: + """Return True if this algorithm suite supports key commitment.""" + return self._is_committing + + @property + def data_key_length_bytes(self) -> int: + """Data key length in bytes.""" + return self._data_key_length_bits // 8 + + @property + def cipher_name(self) -> str: + """Cipher transformation string (e.g. 'AES/GCM/NoPadding').""" + return self._cipher_name + + @property + def cipher_iv_length_bytes(self) -> int: + """Initialization vector length in bytes.""" + return self._cipher_iv_length_bits // 8 + + @property + def commitment_length_bytes(self) -> int: + """Key commitment value length in bytes.""" + return self._commitment_length_bits // 8 + + @property + def commitment_nonce_length_bytes(self) -> int: + """Length of the message ID / HKDF salt in bytes.""" + return self._commitment_nonce_length_bits // 8 + + @property + def suite_id_bytes(self) -> bytes: + """Algorithm suite ID as raw bytes for use in HKDF info strings.""" + return self._suite_id_bytes + + @property + def kdf_hash_algorithm(self) -> str | None: + """Hash algorithm name for HKDF, usable with hmac (e.g. 'sha512').""" + return self._kdf_hash_algorithm + + @property + def kc_gcm_iv(self) -> bytes: + """Fixed IV for key-committing GCM: all 0x01 bytes of cipher_iv_length.""" + if not self._is_committing: + raise ValueError(f"{self.name} does not support key commitment") + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% The IV's total length MUST match the IV length defined by the algorithm suite. + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% When encrypting or decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, + ##% the IV used in the AES-GCM content encryption/decryption MUST consist entirely of bytes with the value 0x01. + return b"\x01" * self.cipher_iv_length_bytes + + +class CommitmentPolicy(Enum): + """Commitment policies controlling key-commitment behavior.""" + + FORBID_ENCRYPT_ALLOW_DECRYPT = "ForbidEncryptAllowDecrypt" + REQUIRE_ENCRYPT_ALLOW_DECRYPT = "RequireEncryptAllowDecrypt" + REQUIRE_ENCRYPT_REQUIRE_DECRYPT = "RequireEncryptRequireDecrypt" + + @define class EncryptionMaterials: """Class representing encryption materials for S3 encryption. @@ -27,6 +194,9 @@ class EncryptionMaterials: plaintext_data_key (Optional[bytes]): The plaintext data key """ + encryption_algorithm: AlgorithmSuite = field( + default=AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) encryption_context: dict[str, str] = field(factory=dict) encrypted_data_key: EncryptedDataKey | None = field(default=None) plaintext_data_key: bytes | None = field(default=None) @@ -87,6 +257,7 @@ class DecryptionMaterials: encryption_context_stored: dict[str, str] = field(factory=dict) encryption_context_from_request: dict[str, str] = field(factory=dict) plaintext_data_key: bytes | None = field(default=None) + algorithm_suite: AlgorithmSuite | None = field(default=None) @classmethod def from_dict(cls, materials_dict: dict[str, Any]) -> "DecryptionMaterials": diff --git a/src/s3_encryption/metadata.py b/src/s3_encryption/metadata.py index 5c8bbda3..0b0fbce6 100644 --- a/src/s3_encryption/metadata.py +++ b/src/s3_encryption/metadata.py @@ -51,8 +51,8 @@ class ObjectMetadata: # V3 format fields (compressed) content_cipher_v3: str | None = field(default=None) encrypted_data_key_v3: str | None = field(default=None) - mat_desc_v3: str | None = field(default=None) - encryption_context_v3: str | None = field(default=None) + mat_desc_v3: str | dict | None = field(default=None) + encryption_context_v3: str | dict | None = field(default=None) encrypted_data_key_algorithm_v3: str | None = field(default=None) key_commitment_v3: str | None = field(default=None) message_id_v3: str | None = field(default=None) @@ -137,7 +137,7 @@ def to_dict(self) -> dict[str, str]: if self.content_cipher is not None: result[self.CONTENT_CIPHER] = self.content_cipher - if self.content_cipher_tag_length is not None: + if self.content_cipher_tag_length is not None and not self.is_v3_format(): result[self.CONTENT_CIPHER_TAG_LENGTH] = self.content_cipher_tag_length if self.instruction_file is not None: @@ -150,10 +150,16 @@ def to_dict(self) -> dict[str, str]: result[self.ENCRYPTED_DATA_KEY_V3] = self.encrypted_data_key_v3 if self.mat_desc_v3 is not None: - result[self.MAT_DESC_V3] = self.mat_desc_v3 + if isinstance(self.mat_desc_v3, dict): + result[self.MAT_DESC_V3] = json.dumps(self.mat_desc_v3) + else: + result[self.MAT_DESC_V3] = self.mat_desc_v3 if self.encryption_context_v3 is not None: - result[self.ENCRYPTION_CONTEXT_V3] = self.encryption_context_v3 + if isinstance(self.encryption_context_v3, dict): + result[self.ENCRYPTION_CONTEXT_V3] = json.dumps(self.encryption_context_v3) + else: + result[self.ENCRYPTION_CONTEXT_V3] = self.encryption_context_v3 if self.encrypted_data_key_algorithm_v3 is not None: result[self.ENCRYPTED_DATA_KEY_ALGORITHM_V3] = self.encrypted_data_key_algorithm_v3 diff --git a/src/s3_encryption/pipelines.py b/src/s3_encryption/pipelines.py index 02a5a9c9..d0e9ba79 100644 --- a/src/s3_encryption/pipelines.py +++ b/src/s3_encryption/pipelines.py @@ -7,16 +7,25 @@ """ import base64 +import json import os from attrs import define, field +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.padding import PKCS7 -from .exceptions import S3EncryptionClientError +from .exceptions import S3EncryptionClientError, S3EncryptionClientSecurityError from .instruction_file import fetch_instruction_file +from .key_derivation import derive_keys, verify_commitment from .materials.crypto_materials_manager import AbstractCryptoMaterialsManager from .materials.encrypted_data_key import EncryptedDataKey -from .materials.materials import DecryptionMaterials, EncryptionMaterials +from .materials.materials import ( + AlgorithmSuite, + CommitmentPolicy, + DecryptionMaterials, + EncryptionMaterials, +) from .metadata import ObjectMetadata @@ -29,6 +38,7 @@ class PutEncryptedObjectPipeline: """ cmm: AbstractCryptoMaterialsManager = field() + encryption_algorithm: AlgorithmSuite = field() def encrypt(self, plaintext, encryption_context=None): """Encrypt the data before it is stored in S3. @@ -41,34 +51,53 @@ def encrypt(self, plaintext, encryption_context=None): bytes: The encrypted data dict: Metadata about the encryption to be stored with the object """ - # Create encryption materials request with encryption context copy + ##= specification/s3-encryption/encryption.md#content-encryption + ##= type=implementation + ##% The S3EC MUST use the encryption algorithm configured during + ##% [client](./client.md) initialization. enc_mats_request = EncryptionMaterials( - encryption_context={} if encryption_context is None else encryption_context.copy() + encryption_algorithm=self.encryption_algorithm, + encryption_context={} if encryption_context is None else encryption_context.copy(), ) # Get encryption materials from the crypto materials manager enc_mats = self.cmm.get_encryption_materials(enc_mats_request) - # Generate initialization vector - iv = os.urandom(12) - - # Encrypt the data if enc_mats.plaintext_data_key is None: raise RuntimeError("No plaintext data key found!") - - aesgcm = AESGCM(enc_mats.plaintext_data_key) - ciphertext = aesgcm.encrypt(nonce=iv, data=plaintext, associated_data=None) - encrypted_data = ciphertext - b64_iv = base64.b64encode(iv).decode("utf-8") - - # Get the encrypted data key if enc_mats.encrypted_data_key is None: raise RuntimeError("No encrypted data key found!") edk_bytes = enc_mats.encrypted_data_key.encrypted_data_key + + if self.encryption_algorithm == AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY: + return self._encrypt_kc_gcm(plaintext, enc_mats, edk_bytes) + return self._encrypt_gcm(plaintext, enc_mats, edk_bytes) + + def _encrypt_gcm(self, plaintext, enc_mats, edk_bytes): + """Encrypt using ALG_AES_256_GCM_IV12_TAG16_NO_KDF (V2 format).""" + ##= specification/s3-encryption/encryption.md#content-encryption + ##= type=implementation + ##% The client MUST generate an IV or Message ID using the length of the IV + ##% or Message ID defined in the algorithm suite. + iv = os.urandom(enc_mats.encryption_algorithm.cipher_iv_length_bytes) + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-iv12-tag16-no-kdf + ##= type=implementation + ##% The client MUST initialize the cipher, or call an AES-GCM encryption API, + ##% with the plaintext data key, the generated IV, and the tag length defined + ##% in the Algorithm Suite when encrypting with ALG_AES_256_GCM_IV12_TAG16_NO_KDF. + aesgcm = AESGCM(enc_mats.plaintext_data_key) + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-iv12-tag16-no-kdf + ##= type=implementation + ##% The client MUST NOT provide any AAD when encrypting with ALG_AES_256_GCM_IV12_TAG16_NO_KDF. + encrypted_data = aesgcm.encrypt(nonce=iv, data=plaintext, associated_data=None) + + b64_iv = base64.b64encode(iv).decode("utf-8") b64_edk = base64.b64encode(edk_bytes).decode("utf-8") - # Create metadata using the ObjectMetadata class + ##= specification/s3-encryption/encryption.md#content-encryption + ##= type=implementation + ##% The generated IV or Message ID MUST be set or returned from the encryption metadata = ObjectMetadata( encrypted_data_key_v2=b64_edk, encrypted_data_key_algorithm="kms+context", @@ -77,10 +106,63 @@ def encrypt(self, plaintext, encryption_context=None): encrypted_data_key_context=enc_mats.encryption_context, ) - # Convert to dictionary for storage in S3 metadata - encryption_metadata = metadata.to_dict() + return encrypted_data, metadata.to_dict() + + def _encrypt_kc_gcm(self, plaintext, enc_mats, edk_bytes): + """Encrypt using ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY (V3 format).""" + ##= specification/s3-encryption/encryption.md#content-encryption + ##= type=implementation + ##% The client MUST generate an IV or Message ID using the length of the IV + ##% or Message ID defined in the algorithm suite. + algorithm_suite = enc_mats.encryption_algorithm + message_id = os.urandom(algorithm_suite.commitment_nonce_length_bytes) + + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key + ##= type=implementation + ##% The client MUST use HKDF to derive the key commitment value and the derived + ##% encrypting key as described in [Key Derivation](key-derivation.md). + derived_encryption_key, commit_key = derive_keys( + enc_mats.plaintext_data_key, message_id, algorithm_suite + ) + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% The client MUST initialize the cipher, or call an AES-GCM encryption API, with the derived encryption key, an IV containing only bytes with the value 0x01, + ##% and the tag length defined in the Algorithm Suite when encrypting or decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY. + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% The client MUST set the AAD to the Algorithm Suite ID represented as bytes. + aesgcm = AESGCM(derived_encryption_key) + encrypted_data = aesgcm.encrypt( + nonce=algorithm_suite.kc_gcm_iv, + data=plaintext, + associated_data=algorithm_suite.suite_id_bytes, + ) + + b64_edk = base64.b64encode(edk_bytes).decode("utf-8") + b64_message_id = base64.b64encode(message_id).decode("utf-8") + b64_commit_key = base64.b64encode(commit_key).decode("utf-8") + + ##= specification/s3-encryption/encryption.md#content-encryption + ##= type=implementation + ##% The generated IV or Message ID MUST be set or returned from the encryption + ##% process such that it can be included in the content metadata. + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key + ##= type=implementation + ##% The derived key commitment value MUST be set or returned from the encryption + ##% process such that it can be included in the content metadata. + metadata = ObjectMetadata( + content_cipher_v3=str(algorithm_suite.suite_id), + encrypted_data_key_algorithm_v3="12", + encrypted_data_key_v3=b64_edk, + message_id_v3=b64_message_id, + key_commitment_v3=b64_commit_key, + encryption_context_v3=( + enc_mats.encryption_context if enc_mats.encryption_context else None + ), + ) - return encrypted_data, encryption_metadata + return encrypted_data, metadata.to_dict() @define @@ -92,7 +174,50 @@ class GetEncryptedObjectPipeline: """ cmm: AbstractCryptoMaterialsManager = field() + commitment_policy: CommitmentPolicy = field() s3_client: object = field(default=None) + enable_legacy_unauthenticated_modes: bool = field(default=False) + + # Map content cipher metadata values to AlgorithmSuite + _CONTENT_CIPHER_TO_ALGORITHM_SUITE = { + "AES/CBC/PKCS5Padding": AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF, + "AES/GCM/NoPadding": AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + "115": AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, + } + + def _determine_algorithm_suite(self, metadata) -> AlgorithmSuite: + """Determine the algorithm suite from object metadata. + + V1 objects are always CBC. + V2/V3 objects check x-amz-cek-alg / x-amz-c to determine the content algorithm. + """ + if metadata.is_v1_format(): + ##= specification/s3-encryption/data-format/content-metadata.md#algorithm-suite-and-message-format-version-compatibility + ##= type=citation + ##% Objects encrypted with ALG_AES_256_CBC_IV16_NO_KDF MAY use either the V1 or V2 message format version. + return AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF + + if metadata.is_v2_format(): + cek_alg = metadata.content_cipher + if cek_alg is None: + raise S3EncryptionClientError( + "V2 format object missing required x-amz-cek-alg metadata." + ) + suite = self._CONTENT_CIPHER_TO_ALGORITHM_SUITE.get(cek_alg) + if suite is None: + raise S3EncryptionClientError(f"Unknown content encryption algorithm: {cek_alg}") + return suite + + if metadata.is_v3_format(): + cek_alg = metadata.content_cipher_v3 + if cek_alg is None: + raise S3EncryptionClientError("V3 format object missing required x-amz-c metadata.") + suite = self._CONTENT_CIPHER_TO_ALGORITHM_SUITE.get(cek_alg) + if suite is None: + raise S3EncryptionClientError(f"Unknown content encryption algorithm: {cek_alg}") + return suite + + raise S3EncryptionClientError("Unable to determine S3 Encryption Client message format.") def decrypt( self, @@ -129,11 +254,38 @@ def decrypt( if self.s3_client is None: raise S3EncryptionClientError("s3_client required to fetch instruction file") + # TODO: we should validate that these parameters must be None + # when not in instruction file mode. if bucket is None or key is None: raise S3EncryptionClientError("Bucket and key required to fetch instruction file") instruction_key = key + instruction_suffix instruction_metadata = fetch_instruction_file(self.s3_client, bucket, instruction_key) + + ##= specification/s3-encryption/data-format/metadata-strategy.md#v3-instruction-files + ##= type=implementation + ##% - The V3 message format MUST NOT store the mapkey "x-amz-c" and its value in the Instruction File. + ##= specification/s3-encryption/data-format/metadata-strategy.md#v3-instruction-files + ##= type=implementation + ##% - The V3 message format MUST NOT store the mapkey "x-amz-d" and its value in the Instruction File. + ##= specification/s3-encryption/data-format/metadata-strategy.md#v3-instruction-files + ##= type=implementation + ##% - The V3 message format MUST NOT store the mapkey "x-amz-i" and its value in the Instruction File. + v3_object_metadata_exclusive_keys = { + ObjectMetadata.CONTENT_CIPHER_V3, + ObjectMetadata.KEY_COMMITMENT_V3, + ObjectMetadata.MESSAGE_ID_V3, + } + forbidden_keys_in_instruction = ( + set(instruction_metadata.keys()) & v3_object_metadata_exclusive_keys + ) + if forbidden_keys_in_instruction: + raise S3EncryptionClientError( + "Instruction file is tampered, instruction file contains object metadata " + f"exclusive mapkeys: {forbidden_keys_in_instruction}. " + f"bucket: {bucket}\n key:{key}\n instruction_file:{instruction_key}" + ) + instruction_metadata.update(encryption_metadata) metadata = ObjectMetadata.from_dict(instruction_metadata) ##= specification/s3-encryption/data-format/metadata-strategy.md#v1-v2-instruction-files @@ -152,6 +304,10 @@ def decrypt( "BUT Instruction File is being used. This is an illegal combination. " f"bucket: {bucket}\n key:{key}\n instruction_file:{instruction_key}" ) + + # Determine the algorithm suite from the metadata + algorithm_suite = self._determine_algorithm_suite(metadata) + # Determine which format we're dealing with and get decryption materials if metadata.is_v1_format(): dec_materials = self._decrypt_v1(metadata, encryption_context) @@ -164,58 +320,257 @@ def decrypt( "Unable to determine S3 Encryption Client message format." ) + dec_materials.algorithm_suite = algorithm_suite + ##= specification/s3-encryption/decryption.md#cbc-decryption - ##= type=TODO + ##= type=implementation ##% If an object is encrypted with ALG_AES_256_CBC_IV16_NO_KDF and ##% [legacy unauthenticated algorithm suites](#legacy-decryption) is NOT enabled, ##% the S3EC MUST throw an error which details that client was ##% not configured to decrypt objects with ALG_AES_256_CBC_IV16_NO_KDF. + if ( + algorithm_suite.is_legacy and not self.enable_legacy_unauthenticated_modes + ): # noqa: SIM102 + ##= specification/s3-encryption/decryption.md#legacy-decryption + ##= type=implementation + ##% The S3EC MUST NOT decrypt objects encrypted using legacy unauthenticated algorithm suites + ##% unless specifically configured to do so. + ##= specification/s3-encryption/decryption.md#legacy-decryption + ##= type=implementation + ##% 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. + raise S3EncryptionClientError( + "Cannot decrypt object encrypted with ALG_AES_256_CBC_IV16_NO_KDF. " + "The S3 Encryption Client is not configured to decrypt objects using " + "legacy unauthenticated algorithm suites. " + "Set enable_legacy_unauthenticated_modes=True to allow decryption " + "of objects encrypted with CBC." + ) + + ##= specification/s3-encryption/decryption.md#key-commitment + ##= type=implementation + ##% The S3EC MUST validate the algorithm suite used for decryption against the + ##% key commitment policy before attempting to decrypt the content ciphertext. + ##= specification/s3-encryption/decryption.md#key-commitment + ##= type=implementation + ##% If the commitment policy requires decryption using a committing algorithm suite, + ##% and the algorithm suite associated with the object does not support key commitment, + ##% then the S3EC MUST throw an exception. + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##= type=implementation + ##% When the commitment policy is REQUIRE_ENCRYPT_REQUIRE_DECRYPT, the S3EC MUST NOT allow decryption using algorithm suites which do not support key commitment. + if ( + self.commitment_policy == CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT + and not dec_materials.algorithm_suite.supports_key_commitment + ): + raise S3EncryptionClientError( + "Configuration conflict: cannot decrypt non-key-committing object " + "when commitment policy is REQUIRE_ENCRYPT_REQUIRE_DECRYPT. " + "Use REQUIRE_ENCRYPT_ALLOW_DECRYPT or FORBID_ENCRYPT_ALLOW_DECRYPT " + "to allow decryption of non-committing objects." + ) - # Perform decryption - aesgcm = AESGCM(dec_materials.plaintext_data_key) - return aesgcm.decrypt(nonce=dec_materials.iv, data=encrypted_data, associated_data=None) + # The FORBID_ENCRYPT_ALLOW_DECRYPT and REQUIRE_ENCRYPT_ALLOW_DECRYPT policies + # allow decryption with non-committing algorithm suites — no additional check needed. + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##= type=implementation + ##% When the commitment policy is FORBID_ENCRYPT_ALLOW_DECRYPT, the S3EC MUST allow decryption using algorithm suites which do not support key commitment. + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##= type=implementation + ##% When the commitment policy is REQUIRE_ENCRYPT_ALLOW_DECRYPT, the S3EC MUST allow decryption using algorithm suites which do not support key commitment. + + # Perform decryption based on algorithm suite + match dec_materials.algorithm_suite: + case AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF: + return self._decrypt_cbc_content(dec_materials, encrypted_data) + case AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF: + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-iv12-tag16-no-kdf + ##= type=implementation + ##% The client MUST NOT provide any AAD when encrypting with + ##% ALG_AES_256_GCM_IV12_TAG16_NO_KDF. + aesgcm = AESGCM(dec_materials.plaintext_data_key) + return aesgcm.decrypt( + nonce=dec_materials.iv, data=encrypted_data, associated_data=None + ) + case AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY: + return self._decrypt_kc_gcm_content(dec_materials, encrypted_data, metadata) + case _: + raise S3EncryptionClientError("Unknown algorithm suite!") def _decrypt_v2(self, metadata, encryption_context) -> DecryptionMaterials: """Prepare V2 decryption materials.""" - iv_bytes = base64.b64decode(metadata.content_iv) - edk_bytes = base64.b64decode(metadata.encrypted_data_key_v2) + return self._decrypt_v1_v2( + iv_b64=metadata.content_iv, + edk_b64=metadata.encrypted_data_key_v2, + wrap_alg=metadata.encrypted_data_key_algorithm, + stored_context=metadata.encrypted_data_key_context or {}, + encryption_context=encryption_context, + ) + + def _decrypt_v1(self, metadata, encryption_context) -> DecryptionMaterials: + """Prepare V1 decryption materials.""" + return self._decrypt_v1_v2( + iv_b64=metadata.content_iv, + edk_b64=metadata.encrypted_data_key_v1, + wrap_alg=metadata.encrypted_data_key_algorithm, + stored_context=metadata.encrypted_data_key_context or {}, + encryption_context=encryption_context, + ) + + def _decrypt_v1_v2( + self, iv_b64, edk_b64, wrap_alg, stored_context, encryption_context + ) -> DecryptionMaterials: + """Shared logic for preparing V1/V2 decryption materials.""" + iv_bytes = base64.b64decode(iv_b64) + edk_bytes = base64.b64decode(edk_b64) encrypted_data_key = EncryptedDataKey( key_provider_id=b"S3Keyring", - key_provider_info=metadata.encrypted_data_key_algorithm, + key_provider_info=wrap_alg, encrypted_data_key=edk_bytes, ) dec_materials = DecryptionMaterials( iv=iv_bytes, encrypted_data_keys=[encrypted_data_key], - encryption_context_stored=metadata.encrypted_data_key_context or {}, + encryption_context_stored=stored_context, encryption_context_from_request=encryption_context, ) return self.cmm.decrypt_materials(dec_materials) - def _decrypt_v1(self, metadata, encryption_context) -> DecryptionMaterials: - """Prepare V1 decryption materials.""" - iv_bytes = base64.b64decode(metadata.content_iv) - edk_bytes = base64.b64decode(metadata.encrypted_data_key_v1) + def _decrypt_cbc_content(self, dec_materials, encrypted_data): + """Decrypt content encrypted with ALG_AES_256_CBC_IV16_NO_KDF.""" + ##= specification/s3-encryption/decryption.md#cbc-decryption + ##= type=implementation + ##% If an object is encrypted with ALG_AES_256_CBC_IV16_NO_KDF and + ##% [legacy unauthenticated algorithm suites](#legacy-decryption) is enabled, + ##% then the S3EC MUST create a cipher with AES in CBC Mode with PKCS5Padding or + ##% PKCS7Padding compatible padding for a 16-byte block cipher + ##% (example: for the Java JCE, this is "AES/CBC/PKCS5Padding"). + ##= specification/s3-encryption/decryption.md#cbc-decryption + ##= type=implementation + ##% If the cipher object cannot be created as described above, + ##% Decryption MUST fail. + ##= specification/s3-encryption/decryption.md#cbc-decryption + ##= type=implementation + ##% The error SHOULD detail why the cipher could not be initialized + ##% (such as CBC or PKCS5Padding is not supported by the underlying crypto provider). + try: + cipher = Cipher( + algorithms.AES(dec_materials.plaintext_data_key), + modes.CBC(dec_materials.iv), + ) + decryptor = cipher.decryptor() + padded_plaintext = decryptor.update(encrypted_data) + decryptor.finalize() + + # Remove PKCS7 padding (compatible with PKCS5Padding for 16-byte block ciphers) + unpadder = PKCS7(128).unpadder() + return unpadder.update(padded_plaintext) + unpadder.finalize() + except Exception as e: + raise S3EncryptionClientSecurityError( + f"Failed to decrypt CBC content: {e}. " + "Ensure the underlying crypto provider supports AES/CBC/PKCS7Padding." + ) from e + + ##= specification/s3-encryption/data-format/content-metadata.md#v3-only + ##% The V3 format uses compression here such that each wrapping algorithm is represented by a two digit string. + ##= specification/s3-encryption/data-format/content-metadata.md#v3-only + ##% - The wrapping algorithm value "02" MUST be translated to AES/GCM upon retrieval, and vice versa on write. + ##= specification/s3-encryption/data-format/content-metadata.md#v3-only + ##% - The wrapping algorithm value "12" MUST be translated to kms+context upon retrieval, and vice versa on write. + ##= specification/s3-encryption/data-format/content-metadata.md#v3-only + ##% - The wrapping algorithm value "22" MUST be translated to RSA-OAEP-SHA1 upon retrieval, and vice versa on write. + _V3_WRAP_ALG_MAP = { + "02": "AES/GCM", + "12": "kms+context", + "22": "RSA-OAEP-SHA1", + } + + def _decrypt_v3(self, metadata, encryption_context) -> DecryptionMaterials: + """Prepare V3 decryption materials.""" + edk_bytes = base64.b64decode(metadata.encrypted_data_key_v3) + + # Map V3 compressed wrapping algorithm to canonical key_provider_info + raw_wrap_alg = metadata.encrypted_data_key_algorithm_v3 or "12" + wrap_alg = self._V3_WRAP_ALG_MAP.get(raw_wrap_alg, raw_wrap_alg) encrypted_data_key = EncryptedDataKey( key_provider_id=b"S3Keyring", - key_provider_info=metadata.encrypted_data_key_algorithm, + key_provider_info=wrap_alg, encrypted_data_key=edk_bytes, ) + ##= specification/s3-encryption/data-format/content-metadata.md#v3-only + ##% The Encryption Context value MUST be used for wrapping algorithm `kms+context` or `12`. + ##= specification/s3-encryption/data-format/content-metadata.md#v3-only + ##% The Material Description MUST be used for wrapping algorithms `AES/GCM` (`02`) and `RSA-OAEP-SHA1` (`22`). + # For kms+context, the stored context comes from x-amz-t (encryption_context_v3). + # For AES/GCM and RSA-OAEP-SHA1, it comes from x-amz-m (mat_desc_v3). + stored_context = {} + if wrap_alg == "kms+context": + raw_ctx = metadata.encryption_context_v3 + else: + raw_ctx = metadata.mat_desc_v3 + + if raw_ctx is not None: + if isinstance(raw_ctx, dict): + stored_context = raw_ctx + elif isinstance(raw_ctx, str): + stored_context = json.loads(raw_ctx) + dec_materials = DecryptionMaterials( - iv=iv_bytes, encrypted_data_keys=[encrypted_data_key], - encryption_context_stored=metadata.encrypted_data_key_context or {}, + encryption_context_stored=stored_context, encryption_context_from_request=encryption_context, ) return self.cmm.decrypt_materials(dec_materials) - def _decrypt_v3(self, metadata, encryption_context) -> DecryptionMaterials: - """Prepare V3 decryption materials.""" - # TODO: Implement V3 decryption - raise NotImplementedError("V3 decryption not yet implemented") + def _decrypt_kc_gcm_content(self, dec_materials, encrypted_data, metadata): + """Decrypt content encrypted with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY. + + Performs HKDF key derivation, key commitment verification, and AES-GCM decryption. + """ + message_id = base64.b64decode(metadata.message_id_v3) + stored_commitment = base64.b64decode(metadata.key_commitment_v3) + + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key + ##= type=implementation + ##% The client MUST use HKDF to derive the key commitment value and the derived encrypting key as described in [Key Derivation](key-derivation.md). + derived_encryption_key, derived_commitment = derive_keys( + dec_materials.plaintext_data_key, message_id, dec_materials.algorithm_suite + ) + + ##= specification/s3-encryption/decryption.md#decrypting-with-commitment + ##= type=implementation + ##% 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. + ##= specification/s3-encryption/decryption.md#decrypting-with-commitment + ##= type=implementation + ##% When using an algorithm suite which supports key commitment, the client MUST verify the key commitment values match before deriving + ##% the [derived encryption key](./key-derivation.md#hkdf-operation). + verify_commitment(stored_commitment, derived_commitment) + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% When encrypting or decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, + ##% the IV used in the AES-GCM content encryption/decryption MUST consist entirely of bytes with the value 0x01. + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% The IV's total length MUST match the IV length defined by the algorithm suite. + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% The client MUST initialize the cipher, or call an AES-GCM encryption API, with the derived encryption key, an IV containing only bytes with the value 0x01, + ##% and the tag length defined in the Algorithm Suite when encrypting or decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY. + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=implementation + ##% The client MUST set the AAD to the Algorithm Suite ID represented as bytes. + aesgcm = AESGCM(derived_encryption_key) + return aesgcm.decrypt( + nonce=dec_materials.algorithm_suite.kc_gcm_iv, + data=encrypted_data, + associated_data=dec_materials.algorithm_suite.suite_id_bytes, + ) diff --git a/test-server/java-tests/src/it/java/software/amazon/encryption/s3/KeyCommitmentPolicyEncryptFailureTests.java b/test-server/java-tests/src/it/java/software/amazon/encryption/s3/KeyCommitmentPolicyEncryptFailureTests.java new file mode 100644 index 00000000..46df7de1 --- /dev/null +++ b/test-server/java-tests/src/it/java/software/amazon/encryption/s3/KeyCommitmentPolicyEncryptFailureTests.java @@ -0,0 +1,91 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +package software.amazon.encryption.s3; + +import static software.amazon.encryption.s3.TestUtils.*; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import software.amazon.encryption.s3.client.S3ECTestServerClient; +import software.amazon.encryption.s3.model.CommitmentPolicy; +import software.amazon.encryption.s3.model.EncryptionAlgorithm; +import software.amazon.encryption.s3.model.KeyMaterial; +import software.amazon.encryption.s3.model.S3ECConfig; + +/** + * Key Commitment Policy — Encryption Failure Tests + * + * Per the specification (key-commitment.md): + * "When the commitment policy is REQUIRE_ENCRYPT_ALLOW_DECRYPT, + * the S3EC MUST only encrypt using an algorithm suite which supports key commitment." + * "When the commitment policy is REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + * the S3EC MUST only encrypt using an algorithm suite which supports key commitment." + * "When the commitment policy is FORBID_ENCRYPT_ALLOW_DECRYPT, + * the S3EC MUST NOT encrypt using an algorithm suite which supports key commitment." + * + * These tests verify that attempting to encrypt with an algorithm that conflicts + * with the commitment policy is rejected by the S3EC — either at client creation + * or at PutObject time. + * + * Currently scoped to Python V3 only. Other languages can be enabled by + * switching the MethodSource to a broader provider (e.g. improvedClientsForTest). + */ +@DisplayName("Key Commitment Policy — Encrypt Failures") +public class KeyCommitmentPolicyEncryptFailureTests { + + private static final KeyMaterial kmsKeyArn = KeyMaterial.builder() + .kmsKeyId(TestUtils.KMS_KEY_ARN) + .build(); + + @ParameterizedTest(name = "{0}: REQUIRE_ENCRYPT_ALLOW_DECRYPT with non-committing GCM MUST fail to encrypt") + @MethodSource("software.amazon.encryption.s3.TestUtils#pythonV3ClientForTest") + void require_encrypt_allow_decrypt_with_non_committing_gcm_must_fail( + TestUtils.LanguageServerTarget language + ) { + S3ECTestServerClient client = TestUtils.testServerClientFor(language); + S3ECConfig config = S3ECConfig.builder() + .keyMaterial(kmsKeyArn) + .commitmentPolicy(CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT) + .encryptionAlgorithm(EncryptionAlgorithm.ALG_AES_256_GCM_IV12_TAG16_NO_KDF) + .build(); + + TestUtils.Encrypt_fails(client, config, + appendTestSuffix("test-kc-policy-fail-REAC-gcm-" + language.getLanguageName())); + } + + @ParameterizedTest(name = "{0}: REQUIRE_ENCRYPT_REQUIRE_DECRYPT with non-committing GCM MUST fail to encrypt") + @MethodSource("software.amazon.encryption.s3.TestUtils#pythonV3ClientForTest") + void require_encrypt_require_decrypt_with_non_committing_gcm_must_fail( + TestUtils.LanguageServerTarget language + ) { + S3ECTestServerClient client = TestUtils.testServerClientFor(language); + S3ECConfig config = S3ECConfig.builder() + .keyMaterial(kmsKeyArn) + .commitmentPolicy(CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT) + .encryptionAlgorithm(EncryptionAlgorithm.ALG_AES_256_GCM_IV12_TAG16_NO_KDF) + .build(); + + TestUtils.Encrypt_fails(client, config, + appendTestSuffix("test-kc-policy-fail-RERD-gcm-" + language.getLanguageName())); + } + + @ParameterizedTest(name = "{0}: FORBID_ENCRYPT_ALLOW_DECRYPT with committing GCM MUST fail to encrypt") + @MethodSource("software.amazon.encryption.s3.TestUtils#pythonV3ClientForTest") + void forbid_encrypt_allow_decrypt_with_committing_gcm_must_fail( + TestUtils.LanguageServerTarget language + ) { + S3ECTestServerClient client = TestUtils.testServerClientFor(language); + S3ECConfig config = S3ECConfig.builder() + .keyMaterial(kmsKeyArn) + .commitmentPolicy(CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT) + .encryptionAlgorithm(EncryptionAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) + .build(); + + TestUtils.Encrypt_fails(client, config, + appendTestSuffix("test-kc-policy-fail-FEAD-kc-gcm-" + language.getLanguageName())); + } +} diff --git a/test-server/java-tests/src/it/java/software/amazon/encryption/s3/TestUtils.java b/test-server/java-tests/src/it/java/software/amazon/encryption/s3/TestUtils.java index 2b9cd062..d488fd2d 100644 --- a/test-server/java-tests/src/it/java/software/amazon/encryption/s3/TestUtils.java +++ b/test-server/java-tests/src/it/java/software/amazon/encryption/s3/TestUtils.java @@ -35,12 +35,15 @@ import org.junit.jupiter.params.provider.Arguments; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; +import software.amazon.encryption.s3.model.CreateClientInput; +import software.amazon.encryption.s3.model.CreateClientOutput; import software.amazon.encryption.s3.model.EncryptionAlgorithm; import software.amazon.encryption.s3.model.GetObjectInput; import software.amazon.encryption.s3.model.GetObjectOutput; import software.amazon.encryption.s3.model.KeyMaterial; import software.amazon.encryption.s3.model.PutObjectInput; import software.amazon.encryption.s3.model.PutObjectOutput; +import software.amazon.encryption.s3.model.S3ECConfig; import software.amazon.encryption.s3.model.S3EncryptionClientError; import software.amazon.smithy.java.aws.client.restjson.RestJsonClientProtocol; import software.amazon.smithy.java.client.core.ClientConfig; @@ -155,7 +158,7 @@ public class TestUtils { public static final Set IMPROVED_VERSIONS = Set.of( JAVA_V4, - // PYTHON_V3, + PYTHON_V3, GO_V4, NET_V4, CPP_V3, @@ -358,6 +361,17 @@ public static Stream improvedClientsForTest() { .map(Arguments::of); } + /** + * Get stream of arguments for the Python V3 client only. + * Other languages can be added to this set as their commitment policy + * validation is confirmed. + */ + public static Stream pythonV3ClientForTest() { + return serverMap.values().stream() + .filter(target -> PYTHON_V3.equals(target.getLanguageName())) + .map(Arguments::of); + } + /** * Get stream of arguments for clients that support RAW AES (includes CPP). */ @@ -666,6 +680,40 @@ public static void DecryptWithMaterialsDescription( } } + /** + * Attempts to encrypt an object and expects the operation to fail with an S3EncryptionClientError. + * This is used for negative tests where the client configuration should prevent encryption + * (e.g., commitment policy violations). + * + * The failure may occur during client creation (CreateClient) or during the PutObject call, + * depending on when the server-side S3EC validates the configuration. + */ + public static void Encrypt_fails( + S3ECTestServerClient client, + S3ECConfig config, + String objectKey + ) { + try { + CreateClientOutput clientOutput = client.createClient(CreateClientInput.builder() + .config(config) + .build()); + String S3ECId = clientOutput.getClientId(); + + client.putObject(PutObjectInput.builder() + .clientID(S3ECId) + .key(objectKey) + .bucket(TestUtils.BUCKET) + .body(ByteBuffer.wrap(objectKey.getBytes(StandardCharsets.UTF_8))) + .build()); + + fail("Encryption should have failed for object: " + objectKey + + " with config commitmentPolicy=" + config.getCommitmentPolicy() + + " encryptionAlgorithm=" + config.getEncryptionAlgorithm()); + } catch (S3EncryptionClientError e) { + // Expected - the S3EC should reject this configuration + } + } + public static void Decrypt_fails( S3ECTestServerClient client, String S3ECId, List crossLanguageObjects, diff --git a/test-server/python-v3-server/src/main.py b/test-server/python-v3-server/src/main.py index 6c57c6bd..cee2ab4e 100755 --- a/test-server/python-v3-server/src/main.py +++ b/test-server/python-v3-server/src/main.py @@ -7,6 +7,7 @@ from s3_encryption import S3EncryptionClient, S3EncryptionClientConfig from s3_encryption.exceptions import S3EncryptionClientError from s3_encryption.materials.kms_keyring import KmsKeyring +from s3_encryption.materials.materials import AlgorithmSuite, CommitmentPolicy import boto3 import uvicorn import json @@ -67,6 +68,19 @@ def create_s3_encryption_client_error( ) +# Maps from Smithy model enum strings to Python AlgorithmSuite/CommitmentPolicy enums +_ALGORITHM_SUITE_MAP = { + "ALG_AES_256_GCM_IV12_TAG16_NO_KDF": AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + "ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY": AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, +} + +_COMMITMENT_POLICY_MAP = { + "FORBID_ENCRYPT_ALLOW_DECRYPT": CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + "REQUIRE_ENCRYPT_ALLOW_DECRYPT": CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT, + "REQUIRE_ENCRYPT_REQUIRE_DECRYPT": CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, +} + + @app.put("/object/{bucket}/{key}") async def put_object(bucket: str, key: str, request: Request): """ @@ -175,6 +189,7 @@ async def client_endpoint(request: Request): key_material = config_data.get("keyMaterial", {}) enable_legacy_wrapping_algorithms = config_data.get("enableLegacyWrappingAlgorithms", False) + enable_legacy_unauthenticated_modes = config_data.get("enableLegacyUnauthenticatedModes", False) # TODO pull region from ARN kms_client = boto3.client("kms", region_name="us-west-2") @@ -185,7 +200,26 @@ async def client_endpoint(request: Request): enable_legacy_wrapping_algorithms=enable_legacy_wrapping_algorithms, ) wrapped_client = boto3.client("s3") - client_config = S3EncryptionClientConfig(keyring) + + # Build config kwargs, only including algorithm_suite and commitment_policy if provided + config_kwargs = { + "keyring": keyring, + "enable_legacy_unauthenticated_modes": enable_legacy_unauthenticated_modes, + } + + encryption_algorithm = config_data.get("encryptionAlgorithm") + if encryption_algorithm is not None: + if encryption_algorithm not in _ALGORITHM_SUITE_MAP: + raise ValueError(f"Unknown encryption algorithm: {encryption_algorithm}") + config_kwargs["encryption_algorithm"] = _ALGORITHM_SUITE_MAP[encryption_algorithm] + + commitment_policy = config_data.get("commitmentPolicy") + if commitment_policy is not None: + if commitment_policy not in _COMMITMENT_POLICY_MAP: + raise ValueError(f"Unknown commitment policy: {commitment_policy}") + config_kwargs["commitment_policy"] = _COMMITMENT_POLICY_MAP[commitment_policy] + + client_config = S3EncryptionClientConfig(**config_kwargs) # Create S3EncryptionClient client = S3EncryptionClient(wrapped_client, client_config) diff --git a/test/integration/test_i_s3_encryption.py b/test/integration/test_i_s3_encryption.py index 616f8da4..15133c05 100644 --- a/test/integration/test_i_s3_encryption.py +++ b/test/integration/test_i_s3_encryption.py @@ -9,6 +9,7 @@ from s3_encryption import S3EncryptionClient, S3EncryptionClientConfig from s3_encryption.exceptions import S3EncryptionClientError from s3_encryption.materials.kms_keyring import KmsKeyring +from s3_encryption.materials.materials import AlgorithmSuite, CommitmentPolicy bucket = os.environ.get("CI_S3_BUCKET", "s3ec-python-github-test-bucket") region = os.environ.get("CI_AWS_REGION", "us-west-2") @@ -16,457 +17,238 @@ "CI_KMS_KEY_ALIAS", "arn:aws:kms:us-west-2:370957321024:alias/S3EC-Python-Github-KMS-Key" ) - -def test_simple_roundtrip_ascii_string(): - key = "simple-rt" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") - - data = "test input for simple v3 round trip" - +# Parameterized algorithm suite configurations. +# Each entry is (algorithm_suite, commitment_policy, id_label). +# "default" uses the client defaults (KC GCM + Require/Require). +ALGORITHM_CONFIGS = [ + pytest.param( + AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + id="AES_GCM", + ), + pytest.param( + AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, + CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + id="KC_GCM", + ), +] + + +def _make_client(algorithm_suite, commitment_policy): + """Create an S3EncryptionClient with the given algorithm config.""" kms_client = boto3.client("kms", region_name=region) - keyring = KmsKeyring(kms_client, kms_key_id) - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) - s3ec.put_object(Bucket=bucket, Key=key, Body=data) - get_req = {"Bucket": bucket, "Key": key} - response = s3ec.get_object(**get_req) - output = response["Body"].read().decode("utf-8") - if output != data: - print("Uh oh! Input and output don't match!") - print("Input:") - print(input) - print("Output:") - print(output) - raise RuntimeError - print("Success!") - + config = S3EncryptionClientConfig( + keyring, + encryption_algorithm=algorithm_suite, + commitment_policy=commitment_policy, + ) + return S3EncryptionClient(wrapped_client, config) -def test_empty_string_roundtrip(): - key = "empty-string-rt" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") - data = "" # Empty string as test data +def _unique_key(prefix): + """Generate a unique S3 key with a timestamp suffix.""" + return prefix + datetime.now().strftime("%Y-%m-%d-%H:%M:%S-%f") - kms_client = boto3.client("kms", region_name=region) - keyring = KmsKeyring(kms_client, kms_key_id) +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_simple_roundtrip_ascii_string(algorithm_suite, commitment_policy): + key = _unique_key("simple-rt-") + data = "test input for simple v3 round trip" - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key, Body=data) - get_req = {"Bucket": bucket, "Key": key} - response = s3ec.get_object(**get_req) + response = s3ec.get_object(Bucket=bucket, Key=key) output = response["Body"].read().decode("utf-8") - if output != data: - print("Uh oh! Input and output don't match!") - print("Input:") - print(repr(data)) # Using repr to clearly show it's an empty string - print("Output:") - print(repr(output)) - raise RuntimeError - print("Success! Empty string encrypted and decrypted correctly.") + assert output == data -def test_no_body_roundtrip(): - key = "no-body-rt" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_empty_string_roundtrip(algorithm_suite, commitment_policy): + key = _unique_key("empty-string-rt-") + data = "" - # Expected data when no Body is provided (empty bytes) - expected_data = b"" + s3ec = _make_client(algorithm_suite, commitment_policy) + s3ec.put_object(Bucket=bucket, Key=key, Body=data) + response = s3ec.get_object(Bucket=bucket, Key=key) + output = response["Body"].read().decode("utf-8") + assert output == data - kms_client = boto3.client("kms", region_name=region) - keyring = KmsKeyring(kms_client, kms_key_id) - - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_no_body_roundtrip(algorithm_suite, commitment_policy): + key = _unique_key("no-body-rt-") + expected_data = b"" - # Call put_object without providing a Body parameter + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key) - - get_req = {"Bucket": bucket, "Key": key} - response = s3ec.get_object(**get_req) + response = s3ec.get_object(Bucket=bucket, Key=key) output = response["Body"].read() + assert output == expected_data - if output != expected_data: - print("Uh oh! Output doesn't match expected empty bytes!") - print("Expected:") - print(repr(expected_data)) - print("Output:") - print(repr(output)) - raise RuntimeError - print( - "Success! Object with no Body parameter encrypted and decrypted correctly as empty bytes." - ) - - -def test_unicode_string_roundtrip(): - key = "unicode-string-rt" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") - # String with unusual Unicode characters +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_unicode_string_roundtrip(algorithm_suite, commitment_policy): + key = _unique_key("unicode-string-rt-") data = "Unicode test: 你好, こんにちは, 안녕하세요, Привет, مرحبا, ¡Hola!, ½⅓¼⅕⅙⅐⅛⅑⅒⅔⅖⅗⅘⅙⅚⅜⅝⅞" - kms_client = boto3.client("kms", region_name=region) - - keyring = KmsKeyring(kms_client, kms_key_id) - - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key, Body=data) - get_req = {"Bucket": bucket, "Key": key} - response = s3ec.get_object(**get_req) - - # Boto3 encodes to utf-8 in put_object but does not - # decode in get_object; do so manually to complete the - # round trip + response = s3ec.get_object(Bucket=bucket, Key=key) output = response["Body"].read().decode("utf-8") - if output != data: - print("Uh oh! Input and output don't match!") - print("Input:") - print(repr(data)) - print("Output:") - print(repr(output)) - raise RuntimeError - print("Success! Unicode string encrypted and decrypted correctly.") - + assert output == data -def test_specific_encoding_utf8_roundtrip(): - key = "utf8-encoding-rt" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") - # String with mixed characters +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_specific_encoding_utf8_roundtrip(algorithm_suite, commitment_policy): + key = _unique_key("utf8-encoding-rt-") data = "UTF-8 encoding test: 你好, こんにちは, 안녕하세요, Привет, مرحبا, ¡Hola!" - - # Explicitly encode as UTF-8 before sending encoded_data = data.encode("utf-8") - kms_client = boto3.client("kms", region_name=region) - - keyring = KmsKeyring(kms_client, kms_key_id) - - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) - - # Pass the pre-encoded bytes to put_object + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key, Body=encoded_data) - - get_req = {"Bucket": bucket, "Key": key} - response = s3ec.get_object(**get_req) - - # Read raw bytes and decode with the same encoding + response = s3ec.get_object(Bucket=bucket, Key=key) output = response["Body"].read().decode("utf-8") + assert output == data - if output != data: - print("Uh oh! Input and output don't match!") - print("Input:") - print(repr(data)) - print("Output:") - print(repr(output)) - raise RuntimeError - print("Success! UTF-8 encoded string encrypted and decrypted correctly.") - - -def test_specific_encoding_latin1_roundtrip(): - key = "latin1-encoding-rt" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") - # String with Latin-1 compatible characters +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_specific_encoding_latin1_roundtrip(algorithm_suite, commitment_policy): + key = _unique_key("latin1-encoding-rt-") data = "Latin-1 encoding test: éèêë àâäãåá çñ ¿¡ øæå ØÆÅÉÈÊËÀÂÄÃÅÁ" - - # Explicitly encode as Latin-1 before sending encoded_data = data.encode("latin-1") - kms_client = boto3.client("kms", region_name=region) - - keyring = KmsKeyring(kms_client, kms_key_id) - - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) - - # Pass the pre-encoded bytes to put_object + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key, Body=encoded_data) - - get_req = {"Bucket": bucket, "Key": key} - response = s3ec.get_object(**get_req) - - # Read raw bytes and decode with the same encoding + response = s3ec.get_object(Bucket=bucket, Key=key) output = response["Body"].read().decode("latin-1") + assert output == data - if output != data: - print("Uh oh! Input and output don't match!") - print("Input:") - print(repr(data)) - print("Output:") - print(repr(output)) - raise RuntimeError - print("Success! Latin-1 encoded string encrypted and decrypted correctly.") - - -def test_binary_data_roundtrip(): - key = "binary-data-rt" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") - # Create some binary data (not valid in any particular encoding) +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_binary_data_roundtrip(algorithm_suite, commitment_policy): + key = _unique_key("binary-data-rt-") data = bytes(range(256)) - kms_client = boto3.client("kms", region_name=region) - - keyring = KmsKeyring(kms_client, kms_key_id) - - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) - - # Pass the binary data directly + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key, Body=data) - - get_req = {"Bucket": bucket, "Key": key} - response = s3ec.get_object(**get_req) - - # Read raw bytes without decoding + response = s3ec.get_object(Bucket=bucket, Key=key) output = response["Body"].read() - - if output != data: - print("Uh oh! Input and output don't match!") - print("Input:") - print(repr(data)) - print("Output:") - print(repr(output)) - raise RuntimeError - print("Success! Binary data encrypted and decrypted correctly.") + assert output == data -def test_invalid_body_types(): +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_invalid_body_types(algorithm_suite, commitment_policy): """Test that put_object raises an exception when given invalid body types.""" - key = "invalid-body-type" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") - - kms_client = boto3.client("kms", region_name=region) - keyring = KmsKeyring(kms_client, kms_key_id) - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) - - # Test with integer - with pytest.raises(S3EncryptionClientError) as excinfo: - s3ec.put_object(Bucket=bucket, Key=key, Body=42) - assert "Invalid type for parameter Body" in str(excinfo.value) - - # Test with float - with pytest.raises(S3EncryptionClientError) as excinfo: - s3ec.put_object(Bucket=bucket, Key=key, Body=3.14) - assert "Invalid type for parameter Body" in str(excinfo.value) - - # Test with list - with pytest.raises(S3EncryptionClientError) as excinfo: - s3ec.put_object(Bucket=bucket, Key=key, Body=[1, 2, 3]) - assert "Invalid type for parameter Body" in str(excinfo.value) - - # Test with dictionary - with pytest.raises(S3EncryptionClientError) as excinfo: - s3ec.put_object(Bucket=bucket, Key=key, Body={"key": "value"}) - assert "Invalid type for parameter Body" in str(excinfo.value) - - # Test with boolean - with pytest.raises(S3EncryptionClientError) as excinfo: - s3ec.put_object(Bucket=bucket, Key=key, Body=True) - assert "Invalid type for parameter Body" in str(excinfo.value) + key = _unique_key("invalid-body-type-") - # Test with None (also raises an exception) - with pytest.raises(S3EncryptionClientError) as excinfo: - s3ec.put_object(Bucket=bucket, Key=key, Body=None) - assert "Invalid type for parameter Body" in str(excinfo.value) + s3ec = _make_client(algorithm_suite, commitment_policy) - print("Success! All invalid body types correctly raised exceptions.") + for body in [42, 3.14, [1, 2, 3], {"key": "value"}, True, None]: + with pytest.raises(S3EncryptionClientError) as excinfo: + s3ec.put_object(Bucket=bucket, Key=key, Body=body) + assert "Invalid type for parameter Body" in str(excinfo.value) -def test_user_metadata_preservation(): +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_user_metadata_preservation(algorithm_suite, commitment_policy): """Test that user-provided metadata is preserved during encryption.""" - key = "metadata-preservation-rt" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") - + key = _unique_key("metadata-preservation-rt-") data = "Test data with user metadata" - - # User metadata to include user_metadata = { "author": "test-user", "version": "1.0", "description": "Test object with custom metadata", } - kms_client = boto3.client("kms", region_name=region) - keyring = KmsKeyring(kms_client, kms_key_id) - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) - - # Put object with user metadata + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key, Body=data, Metadata=user_metadata) + response = s3ec.get_object(Bucket=bucket, Key=key) - # Get the object back - get_req = {"Bucket": bucket, "Key": key} - response = s3ec.get_object(**get_req) - - # Verify the data decrypts correctly output = response["Body"].read().decode("utf-8") - if output != data: - print("Uh oh! Input and output don't match!") - print("Input:") - print(repr(data)) - print("Output:") - print(repr(output)) - raise RuntimeError - - # Verify user metadata is preserved - returned_metadata = response.get("Metadata", {}) + assert output == data + returned_metadata = response.get("Metadata", {}) for key_name, expected_value in user_metadata.items(): - if key_name not in returned_metadata: - print(f"Uh oh! User metadata key '{key_name}' is missing!") - print("Expected metadata:") - print(user_metadata) - print("Returned metadata:") - print(returned_metadata) - raise RuntimeError - - if returned_metadata[key_name] != expected_value: - print(f"Uh oh! User metadata value for '{key_name}' doesn't match!") - print(f"Expected: {expected_value}") - print(f"Got: {returned_metadata[key_name]}") - raise RuntimeError - - print("Success! User metadata preserved correctly during encryption/decryption.") - print(f"User metadata: {user_metadata}") - print(f"Returned metadata keys: {list(returned_metadata.keys())}") - - -def test_encryption_context_roundtrip(): - """Test that EncryptionContext is properly used during encryption and required for decryption.""" - key = "encryption-context-rt" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") + assert key_name in returned_metadata, f"User metadata key '{key_name}' is missing" + assert returned_metadata[key_name] == expected_value - data = "Test data with encryption context" - # Encryption context to use for additional authenticated data +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_encryption_context_roundtrip(algorithm_suite, commitment_policy): + """Test that EncryptionContext is properly used during encryption and required for decryption.""" + key = _unique_key("encryption-context-rt-") + data = "Test data with encryption context" encryption_context = { "department": "engineering", "project": "s3-encryption", "environment": "test", } - kms_client = boto3.client("kms", region_name=region) - keyring = KmsKeyring(kms_client, kms_key_id) - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) - - # Put object with encryption context + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key, Body=data, EncryptionContext=encryption_context) + response = s3ec.get_object(Bucket=bucket, Key=key, EncryptionContext=encryption_context) - # Get the object back WITH the same encryption context - get_req = {"Bucket": bucket, "Key": key, "EncryptionContext": encryption_context} - response = s3ec.get_object(**get_req) - - # Verify the data decrypts correctly output = response["Body"].read().decode("utf-8") - if output != data: - print("Uh oh! Input and output don't match!") - print("Input:") - print(repr(data)) - print("Output:") - print(repr(output)) - raise RuntimeError + assert output == data - print("Success! Encryption context used correctly during encryption/decryption.") - print(f"Encryption context: {encryption_context}") - -def test_encryption_context_mismatch(): +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_encryption_context_mismatch(algorithm_suite, commitment_policy): """Test that decryption fails when EncryptionContext doesn't match.""" - key = "encryption-context-mismatch" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") - + key = _unique_key("encryption-context-mismatch-") data = "Test data with encryption context" - - # Original encryption context encryption_context = {"department": "engineering", "project": "s3-encryption"} - - # Wrong encryption context for decryption wrong_encryption_context = {"department": "marketing", "project": "s3-encryption"} - kms_client = boto3.client("kms", region_name=region) - keyring = KmsKeyring(kms_client, kms_key_id) - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) - - # Put object with encryption context + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key, Body=data, EncryptionContext=encryption_context) - # Try to get the object back with WRONG encryption context - should fail - get_req = {"Bucket": bucket, "Key": key, "EncryptionContext": wrong_encryption_context} - - try: - s3ec.get_object(**get_req) - # If we get here, the test failed - decryption should have failed - print("Uh oh! Decryption succeeded with wrong encryption context!") - print(f"Original context: {encryption_context}") - print(f"Wrong context used: {wrong_encryption_context}") - raise RuntimeError("Expected decryption to fail with mismatched encryption context") - except S3EncryptionClientError as e: - # This is expected - decryption should fail - print("Success! Decryption correctly failed with mismatched encryption context.") - print(f"Error message: {str(e)}") - except Exception as e: - # Some other error occurred - print(f"Unexpected error type: {type(e).__name__}") - print(f"Error message: {str(e)}") - raise - - -def test_encryption_context_missing_on_decrypt(): - """Test that decryption fails when encryption context is not provided for an object encrypted with context.""" - key = "encryption-context-missing" - key += datetime.now().strftime("%Y-%m-%d-%H:%M:%S") + with pytest.raises(S3EncryptionClientError): + s3ec.get_object(Bucket=bucket, Key=key, EncryptionContext=wrong_encryption_context) - data = "Test data with encryption context" - # Encryption context used during encryption +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_encryption_context_missing_on_decrypt(algorithm_suite, commitment_policy): + """Test that decryption fails when encryption context is not provided for an object encrypted with context.""" + key = _unique_key("encryption-context-missing-") + data = "Test data with encryption context" encryption_context = {"department": "engineering", "project": "s3-encryption"} - kms_client = boto3.client("kms", region_name=region) - keyring = KmsKeyring(kms_client, kms_key_id) - wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) - s3ec = S3EncryptionClient(wrapped_client, config) - - # Put object with encryption context + s3ec = _make_client(algorithm_suite, commitment_policy) s3ec.put_object(Bucket=bucket, Key=key, Body=data, EncryptionContext=encryption_context) - # Try to get the object back WITHOUT encryption context - should fail - get_req = {"Bucket": bucket, "Key": key} - - try: - s3ec.get_object(**get_req) - # If we get here, the test failed - decryption should have failed - print("Uh oh! Decryption succeeded without providing required encryption context!") - print(f"Original context: {encryption_context}") - raise RuntimeError("Expected decryption to fail when encryption context not provided") - except S3EncryptionClientError as e: - # This is expected - decryption should fail - print("Success! Decryption correctly failed when encryption context was not provided.") - print(f"Error message: {str(e)}") - except Exception as e: - # Some other error occurred - print(f"Unexpected error type: {type(e).__name__}") - print(f"Error message: {str(e)}") - raise + with pytest.raises(S3EncryptionClientError): + s3ec.get_object(Bucket=bucket, Key=key) + + +# Expected metadata key that identifies the content encryption algorithm, +# keyed by algorithm suite. +_EXPECTED_ALGORITHM_METADATA = { + AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF: ("x-amz-cek-alg", "AES/GCM/NoPadding"), + AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY: ("x-amz-c", "115"), +} + + +##= specification/s3-encryption/encryption.md#content-encryption +##= type=test +##% The S3EC MUST use the encryption algorithm configured during +##% [client](./client.md) initialization. +@pytest.mark.parametrize("algorithm_suite,commitment_policy", ALGORITHM_CONFIGS) +def test_put_object_uses_configured_algorithm(algorithm_suite, commitment_policy): + """PutObject MUST encrypt using the algorithm suite configured at client init.""" + key = _unique_key("configured-alg-") + data = b"test configured algorithm" + + s3ec = _make_client(algorithm_suite, commitment_policy) + s3ec.put_object(Bucket=bucket, Key=key, Body=data) + + # Read back with a plain S3 client to inspect the raw metadata + plain_s3 = boto3.client("s3") + response = plain_s3.head_object(Bucket=bucket, Key=key) + metadata = response.get("Metadata", {}) + + meta_key, expected_value = _EXPECTED_ALGORITHM_METADATA[algorithm_suite] + assert meta_key in metadata, f"Expected metadata key '{meta_key}' not found in {metadata}" + assert metadata[meta_key] == expected_value diff --git a/test/integration/test_i_s3_encryption_instruction_file.py b/test/integration/test_i_s3_encryption_instruction_file.py index 467ddc7a..f4f70704 100644 --- a/test/integration/test_i_s3_encryption_instruction_file.py +++ b/test/integration/test_i_s3_encryption_instruction_file.py @@ -7,6 +7,7 @@ from s3_encryption import S3EncryptionClient, S3EncryptionClientConfig from s3_encryption.materials.kms_keyring import KmsKeyring +from s3_encryption.materials.materials import AlgorithmSuite, CommitmentPolicy # Static test objects bucket bucket = os.environ.get("CI_S3_STATIC_TEST_BUCKET", "s3ec-static-test-objects") @@ -26,8 +27,6 @@ } -# TODO(cbc): enable once CBC decryption is implemented -@pytest.mark.skip(reason="V1 CBC decryption not yet implemented") def test_decrypt_v1_instruction_file(): """Test decrypting V1 object with instruction file. @@ -39,7 +38,12 @@ def test_decrypt_v1_instruction_file(): kms_client = boto3.client("kms", region_name=region) keyring = KmsKeyring(kms_client, kms_key_id, enable_legacy_wrapping_algorithms=True) wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) + config = S3EncryptionClientConfig( + keyring, + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + enable_legacy_unauthenticated_modes=True, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + ) s3ec = S3EncryptionClient(wrapped_client, config) response = s3ec.get_object(Bucket=bucket, Key=key) @@ -60,7 +64,11 @@ def test_decrypt_v2_instruction_file(): kms_client = boto3.client("kms", region_name=region) keyring = KmsKeyring(kms_client, kms_key_id) wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) + config = S3EncryptionClientConfig( + keyring, + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + ) s3ec = S3EncryptionClient(wrapped_client, config) response = s3ec.get_object(Bucket=bucket, Key=key) @@ -70,8 +78,6 @@ def test_decrypt_v2_instruction_file(): print("Success! V2 instruction file decryption completed.") -# TODO(v3): enable once v3 is implemented -@pytest.mark.skip(reason="V3 decryption not yet implemented") def test_decrypt_v3_instruction_file(): """Test decrypting V3 object with instruction file. @@ -83,13 +89,16 @@ def test_decrypt_v3_instruction_file(): kms_client = boto3.client("kms", region_name=region) keyring = KmsKeyring(kms_client, kms_key_id) wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) + config = S3EncryptionClientConfig( + keyring, + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + ) s3ec = S3EncryptionClient(wrapped_client, config) response = s3ec.get_object(Bucket=bucket, Key=key) output = response["Body"].read().decode("utf-8") - assert output != "static-v3-instruction-file-from-java-v4" + assert output == "static-v3-instruction-file-from-java-v4" print("Success! V3 instruction file decryption completed.") @@ -115,8 +124,6 @@ def test_decrypt_invalid_instruction_file(): print(f"Error message: {exc_info.value}") -# TODO(v3): enable once v3 is implemented -@pytest.mark.skip(reason="V3 decryption not yet implemented") def test_decrypt_v3_instruction_file_custom_suffix(): """Test decrypting V3 object with a custom instruction file suffix.""" key = TEST_OBJECTS["v3_instruction_file"] @@ -124,7 +131,11 @@ def test_decrypt_v3_instruction_file_custom_suffix(): kms_client = boto3.client("kms", region_name=region) keyring = KmsKeyring(kms_client, kms_key_id) wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring, instruction_file_suffix=".custom-suffix-instruction") + config = S3EncryptionClientConfig( + keyring, + instruction_file_suffix=".custom-suffix-instruction", + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + ) s3ec = S3EncryptionClient(wrapped_client, config) response = s3ec.get_object(Bucket=bucket, Key=key) @@ -141,7 +152,12 @@ def test_decrypt_v2_instruction_file_custom_suffix(): kms_client = boto3.client("kms", region_name=region) keyring = KmsKeyring(kms_client, kms_key_id) wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring, instruction_file_suffix=".custom-suffix-instruction") + config = S3EncryptionClientConfig( + keyring, + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + instruction_file_suffix=".custom-suffix-instruction", + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + ) s3ec = S3EncryptionClient(wrapped_client, config) response = s3ec.get_object(Bucket=bucket, Key=key) diff --git a/test/integration/test_i_s3_encryption_multithreaded.py b/test/integration/test_i_s3_encryption_multithreaded.py index 419ca7ea..e71a17df 100644 --- a/test/integration/test_i_s3_encryption_multithreaded.py +++ b/test/integration/test_i_s3_encryption_multithreaded.py @@ -16,6 +16,7 @@ from s3_encryption import S3EncryptionClient, S3EncryptionClientConfig from s3_encryption.exceptions import S3EncryptionClientError from s3_encryption.materials.kms_keyring import KmsKeyring +from s3_encryption.materials.materials import AlgorithmSuite, CommitmentPolicy bucket = os.environ.get("CI_S3_BUCKET", "s3ec-python-github-test-bucket") region = os.environ.get("CI_AWS_REGION", "us-west-2") @@ -38,7 +39,11 @@ def test_multithreaded_encryption_context_isolation(): kms_client = boto3.client("kms", region_name=region) keyring = KmsKeyring(kms_client, kms_key_id) wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) + config = S3EncryptionClientConfig( + keyring, + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + ) s3ec = S3EncryptionClient(wrapped_client, config) # Number of threads to test with @@ -150,7 +155,11 @@ def test_multithreaded_rapid_context_switching(): kms_client = boto3.client("kms", region_name=region) keyring = KmsKeyring(kms_client, kms_key_id) wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) + config = S3EncryptionClientConfig( + keyring, + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + ) s3ec = S3EncryptionClient(wrapped_client, config) num_iterations = 20 @@ -228,7 +237,11 @@ def test_multithreaded_mixed_with_and_without_context(): kms_client = boto3.client("kms", region_name=region) keyring = KmsKeyring(kms_client, kms_key_id) wrapped_client = boto3.client("s3") - config = S3EncryptionClientConfig(keyring) + config = S3EncryptionClientConfig( + keyring, + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + ) s3ec = S3EncryptionClient(wrapped_client, config) errors = [] diff --git a/test/test_decryption.py b/test/test_decryption.py new file mode 100644 index 00000000..6d22d439 --- /dev/null +++ b/test/test_decryption.py @@ -0,0 +1,390 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Tests for decryption specification compliance annotations. + +Each test in this module corresponds to a MUST/SHOULD requirement from +specification/s3-encryption/decryption.md and carries a type=test annotation +that mirrors the type=implementation annotation in the source code. +""" + +import base64 +import os +from io import BytesIO +from unittest.mock import Mock + +import pytest + +from s3_encryption.exceptions import S3EncryptionClientError, S3EncryptionClientSecurityError +from s3_encryption.key_derivation import derive_keys, verify_commitment +from s3_encryption.materials.crypto_materials_manager import DefaultCryptoMaterialsManager +from s3_encryption.materials.keyring import S3Keyring +from s3_encryption.materials.materials import ( + AlgorithmSuite, + CommitmentPolicy, + DecryptionMaterials, +) +from s3_encryption.pipelines import GetEncryptedObjectPipeline + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _make_pipeline( + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + enable_legacy=False, + s3_client=None, + keyring_side_effect=None, + keyring_return=None, +): + """Create a GetEncryptedObjectPipeline with a mocked CMM/keyring.""" + mock_keyring = Mock(spec=S3Keyring) + if keyring_side_effect is not None: + mock_keyring.on_decrypt.side_effect = keyring_side_effect + elif keyring_return is not None: + mock_keyring.on_decrypt.return_value = keyring_return + cmm = DefaultCryptoMaterialsManager(mock_keyring) + return GetEncryptedObjectPipeline( + cmm, + s3_client=s3_client, + commitment_policy=commitment_policy, + enable_legacy_unauthenticated_modes=enable_legacy, + ) + + +def _v1_cbc_metadata(): + """Return V1 (CBC) object metadata dict.""" + return { + "x-amz-iv": base64.b64encode(os.urandom(16)).decode(), + "x-amz-key": base64.b64encode(b"encrypted-key").decode(), + "x-amz-matdesc": '{"kms_cmk_id": "key-id"}', + } + + +def _v2_gcm_metadata(): + """Return V2 (GCM, no KDF) object metadata dict.""" + return { + "x-amz-iv": base64.b64encode(os.urandom(12)).decode(), + "x-amz-key-v2": base64.b64encode(b"encrypted-key").decode(), + "x-amz-wrap-alg": "kms+context", + "x-amz-matdesc": "{}", + "x-amz-cek-alg": "AES/GCM/NoPadding", + "x-amz-tag-len": "128", + } + + +def _response(metadata, body=b"ciphertext"): + return {"Body": BytesIO(body), "Metadata": metadata} + + +# --------------------------------------------------------------------------- +# CBC Decryption +# --------------------------------------------------------------------------- + + +class TestCBCDecryption: + """Tests for specification/s3-encryption/decryption.md#cbc-decryption.""" + + ##= specification/s3-encryption/decryption.md#cbc-decryption + ##= type=test + ##% If an object is encrypted with ALG_AES_256_CBC_IV16_NO_KDF and + ##% [legacy unauthenticated algorithm suites](#legacy-decryption) is NOT enabled, + ##% the S3EC MUST throw an error which details that client was + ##% not configured to decrypt objects with ALG_AES_256_CBC_IV16_NO_KDF. + def test_cbc_object_rejected_when_legacy_disabled(self): + """CBC-encrypted objects MUST be rejected when legacy modes are disabled.""" + plaintext_key = os.urandom(32) + dec_mats = DecryptionMaterials( + iv=os.urandom(16), + plaintext_data_key=plaintext_key, + algorithm_suite=AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF, + ) + pipeline = _make_pipeline( + enable_legacy=False, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + keyring_return=dec_mats, + ) + + with pytest.raises(S3EncryptionClientError, match="ALG_AES_256_CBC_IV16_NO_KDF"): + pipeline.decrypt(_response(_v1_cbc_metadata())) + + ##= specification/s3-encryption/decryption.md#cbc-decryption + ##= type=test + ##% If an object is encrypted with ALG_AES_256_CBC_IV16_NO_KDF and + ##% [legacy unauthenticated algorithm suites](#legacy-decryption) is enabled, + ##% then the S3EC MUST create a cipher with AES in CBC Mode with PKCS5Padding or + ##% PKCS7Padding compatible padding for a 16-byte block cipher + ##% (example: for the Java JCE, this is "AES/CBC/PKCS5Padding"). + def test_cbc_decryption_succeeds_when_legacy_enabled(self): + """CBC decryption MUST work with PKCS7-compatible padding when legacy is enabled.""" + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.primitives.padding import PKCS7 + + plaintext = b"hello world, this is a CBC test!!" + key = os.urandom(32) + iv = os.urandom(16) + + # Encrypt with AES-CBC + PKCS7 padding + padder = PKCS7(128).padder() + padded = padder.update(plaintext) + padder.finalize() + cipher = Cipher(algorithms.AES(key), modes.CBC(iv)) + encryptor = cipher.encryptor() + ciphertext = encryptor.update(padded) + encryptor.finalize() + + metadata = { + "x-amz-iv": base64.b64encode(iv).decode(), + "x-amz-key": base64.b64encode(b"encrypted-key").decode(), + "x-amz-matdesc": '{"kms_cmk_id": "key-id"}', + } + + dec_mats = DecryptionMaterials( + iv=iv, + plaintext_data_key=key, + algorithm_suite=AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF, + ) + pipeline = _make_pipeline( + enable_legacy=True, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + keyring_return=dec_mats, + ) + + result = pipeline.decrypt(_response(metadata, ciphertext)) + assert result == plaintext + + ##= specification/s3-encryption/decryption.md#cbc-decryption + ##= type=test + ##% If the cipher object cannot be created as described above, + ##% Decryption MUST fail. + ##= specification/s3-encryption/decryption.md#cbc-decryption + ##= type=test + ##% The error SHOULD detail why the cipher could not be initialized + ##% (such as CBC or PKCS5Padding is not supported by the underlying crypto provider). + def test_cbc_decryption_fails_with_wrong_key(self): + """CBC decryption MUST fail (with detail) when the cipher cannot decrypt.""" + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.primitives.padding import PKCS7 + + plaintext = b"hello world, this is a CBC test!!" + real_key = os.urandom(32) + wrong_key = os.urandom(32) + iv = os.urandom(16) + + padder = PKCS7(128).padder() + padded = padder.update(plaintext) + padder.finalize() + cipher = Cipher(algorithms.AES(real_key), modes.CBC(iv)) + encryptor = cipher.encryptor() + ciphertext = encryptor.update(padded) + encryptor.finalize() + + metadata = { + "x-amz-iv": base64.b64encode(iv).decode(), + "x-amz-key": base64.b64encode(b"encrypted-key").decode(), + "x-amz-matdesc": '{"kms_cmk_id": "key-id"}', + } + + dec_mats = DecryptionMaterials( + iv=iv, + plaintext_data_key=wrong_key, + algorithm_suite=AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF, + ) + pipeline = _make_pipeline( + enable_legacy=True, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + keyring_return=dec_mats, + ) + + with pytest.raises(S3EncryptionClientSecurityError, match="Failed to decrypt CBC content"): + pipeline.decrypt(_response(metadata, ciphertext)) + + +# --------------------------------------------------------------------------- +# Decrypting with Commitment +# --------------------------------------------------------------------------- + + +class TestDecryptingWithCommitment: + """Tests for specification/s3-encryption/decryption.md#decrypting-with-commitment.""" + + ##= specification/s3-encryption/decryption.md#decrypting-with-commitment + ##= type=test + ##% 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. + def test_commitment_verified_against_stored_metadata(self): + """The derived commitment MUST match the stored commitment from metadata.""" + key = os.urandom(32) + message_id = os.urandom(28) + _, correct_commitment = derive_keys( + key, message_id, AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + + # Should not raise + verify_commitment(correct_commitment, correct_commitment) + + # Tampered commitment must fail + tampered = bytearray(correct_commitment) + tampered[0] ^= 0xFF + with pytest.raises(S3EncryptionClientSecurityError): + verify_commitment(bytes(tampered), correct_commitment) + + ##= specification/s3-encryption/decryption.md#decrypting-with-commitment + ##= type=test + ##% When using an algorithm suite which supports key commitment, the verification of the derived key commitment value MUST be done in constant time. + def test_commitment_verification_uses_constant_time_compare(self): + """Verification MUST use constant-time comparison (hmac.compare_digest).""" + stored = os.urandom(28) + derived = os.urandom(28) + + # verify_commitment delegates to hmac.compare_digest; confirm it raises + # on mismatch (the constant-time property is guaranteed by hmac.compare_digest). + with pytest.raises(S3EncryptionClientSecurityError): + verify_commitment(stored, derived) + + ##= specification/s3-encryption/decryption.md#decrypting-with-commitment + ##= type=test + ##% When using an algorithm suite which supports key commitment, the client MUST throw an exception when the derived key commitment value + ##% and stored key commitment value do not match. + def test_commitment_mismatch_throws_exception(self): + """Mismatched commitment values MUST raise an exception.""" + stored = os.urandom(28) + derived = os.urandom(28) + + with pytest.raises( + S3EncryptionClientSecurityError, match="Key commitment verification failed" + ): + verify_commitment(stored, derived) + + ##= specification/s3-encryption/decryption.md#decrypting-with-commitment + ##= type=test + ##% When using an algorithm suite which supports key commitment, the client MUST verify the key commitment values match before deriving + ##% the [derived encryption key](./key-derivation.md#hkdf-operation). + def test_commitment_verified_before_content_decryption(self): + """Commitment verification MUST happen before content decryption is attempted.""" + key = os.urandom(32) + message_id = os.urandom(28) + _, real_commitment = derive_keys( + key, message_id, AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + + # Build V3 metadata with a wrong commitment + wrong_commitment = os.urandom(28) + metadata = { + "x-amz-c": "115", + "x-amz-3": base64.b64encode(b"encrypted-key").decode(), + "x-amz-w": "12", + "x-amz-t": "{}", + "x-amz-d": base64.b64encode(wrong_commitment).decode(), + "x-amz-i": base64.b64encode(message_id).decode(), + } + + dec_mats = DecryptionMaterials( + plaintext_data_key=key, + algorithm_suite=AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, + ) + pipeline = _make_pipeline( + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + keyring_return=dec_mats, + ) + + # Must fail at commitment check, not at AES-GCM decryption + with pytest.raises( + S3EncryptionClientSecurityError, match="Key commitment verification failed" + ): + pipeline.decrypt(_response(metadata, b"fake-ciphertext")) + + +# --------------------------------------------------------------------------- +# Key Commitment Policy +# --------------------------------------------------------------------------- + + +class TestKeyCommitmentPolicy: + """Tests for specification/s3-encryption/decryption.md#key-commitment.""" + + ##= specification/s3-encryption/decryption.md#key-commitment + ##= type=test + ##% The S3EC MUST validate the algorithm suite used for decryption against the + ##% key commitment policy before attempting to decrypt the content ciphertext. + ##= specification/s3-encryption/decryption.md#key-commitment + ##= type=test + ##% If the commitment policy requires decryption using a committing algorithm suite, + ##% and the algorithm suite associated with the object does not support key commitment, + ##% then the S3EC MUST throw an exception. + def test_require_decrypt_rejects_non_committing_suite(self): + """REQUIRE_ENCRYPT_REQUIRE_DECRYPT MUST reject non-committing algorithm suites.""" + dec_mats = DecryptionMaterials( + iv=os.urandom(12), + plaintext_data_key=os.urandom(32), + algorithm_suite=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + ) + pipeline = _make_pipeline( + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + keyring_return=dec_mats, + ) + + with pytest.raises(S3EncryptionClientError, match="cannot decrypt non-key-committing"): + pipeline.decrypt(_response(_v2_gcm_metadata())) + + def test_allow_decrypt_accepts_non_committing_suite(self): + """REQUIRE_ENCRYPT_ALLOW_DECRYPT MUST allow non-committing algorithm suites.""" + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + key = os.urandom(32) + iv = os.urandom(12) + plaintext = b"test data for allow-decrypt policy" + ciphertext = AESGCM(key).encrypt(iv, plaintext, None) + + metadata = { + "x-amz-iv": base64.b64encode(iv).decode(), + "x-amz-key-v2": base64.b64encode(b"encrypted-key").decode(), + "x-amz-wrap-alg": "kms+context", + "x-amz-matdesc": "{}", + "x-amz-cek-alg": "AES/GCM/NoPadding", + "x-amz-tag-len": "128", + } + + dec_mats = DecryptionMaterials( + iv=iv, + plaintext_data_key=key, + algorithm_suite=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + ) + pipeline = _make_pipeline( + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT, + keyring_return=dec_mats, + ) + + result = pipeline.decrypt(_response(metadata, ciphertext)) + assert result == plaintext + + +# --------------------------------------------------------------------------- +# Legacy Decryption +# --------------------------------------------------------------------------- + + +class TestLegacyDecryption: + """Tests for specification/s3-encryption/decryption.md#legacy-decryption.""" + + ##= specification/s3-encryption/decryption.md#legacy-decryption + ##= type=test + ##% The S3EC MUST NOT decrypt objects encrypted using legacy unauthenticated algorithm suites + ##% unless specifically configured to do so. + ##= specification/s3-encryption/decryption.md#legacy-decryption + ##= type=test + ##% 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. + def test_legacy_cbc_rejected_by_default(self): + """Legacy CBC objects MUST be rejected unless enable_legacy_unauthenticated_modes is True.""" + dec_mats = DecryptionMaterials( + iv=os.urandom(16), + plaintext_data_key=os.urandom(32), + algorithm_suite=AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF, + ) + pipeline = _make_pipeline( + enable_legacy=False, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + keyring_return=dec_mats, + ) + + with pytest.raises(S3EncryptionClientError, match="not configured to decrypt"): + pipeline.decrypt(_response(_v1_cbc_metadata())) diff --git a/test/test_default_algorithm_commitment.py b/test/test_default_algorithm_commitment.py new file mode 100644 index 00000000..1640451a --- /dev/null +++ b/test/test_default_algorithm_commitment.py @@ -0,0 +1,95 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Integration test: the default encryption algorithm MUST use key commitment. + +When S3EncryptionClientConfig is created with no explicit encryption_algorithm, +the default (ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) MUST produce ciphertext +that is decryptable under REQUIRE_ENCRYPT_REQUIRE_DECRYPT commitment policy. +""" + +import os +from io import BytesIO +from unittest.mock import MagicMock + +from s3_encryption import S3EncryptionClientConfig +from s3_encryption.materials.crypto_materials_manager import DefaultCryptoMaterialsManager +from s3_encryption.materials.encrypted_data_key import EncryptedDataKey +from s3_encryption.materials.keyring import S3Keyring +from s3_encryption.materials.materials import ( + AlgorithmSuite, + CommitmentPolicy, +) +from s3_encryption.pipelines import GetEncryptedObjectPipeline, PutEncryptedObjectPipeline + + +def _mock_keyring(key=None): + """Return a mock keyring that populates encryption/decryption materials.""" + if key is None: + key = os.urandom(32) + mock = MagicMock(spec=S3Keyring) + + def on_encrypt(mats): + mats.plaintext_data_key = key + mats.encrypted_data_key = EncryptedDataKey( + key_provider_id=b"S3Keyring", + key_provider_info="kms+context", + encrypted_data_key=b"encrypted-key", + ) + return mats + + def on_decrypt(mats, encrypted_data_keys=None): + mats.plaintext_data_key = key + return mats + + mock.on_encrypt.side_effect = on_encrypt + mock.on_decrypt.side_effect = on_decrypt + return mock, key + + +class TestDefaultAlgorithmUsesKeyCommitment: + """The default encryption algorithm MUST be key-committing.""" + + def test_default_config_encrypts_with_committing_algorithm(self): + """S3EncryptionClientConfig with no explicit algorithm MUST default to a + key-committing suite. + """ + keyring, _ = _mock_keyring() + config = S3EncryptionClientConfig(keyring=keyring) + assert config.encryption_algorithm == AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + + def test_encryption_materials_defaults_to_committing_algorithm(self): + """EncryptionMaterials with no explicit algorithm MUST default to a + key-committing suite. + """ + from s3_encryption.materials.materials import EncryptionMaterials + + mats = EncryptionMaterials() + assert mats.encryption_algorithm == AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + + def test_default_encryption_decryptable_with_require_decrypt(self): + """Ciphertext produced with the default algorithm MUST be decryptable + when the commitment policy is REQUIRE_ENCRYPT_REQUIRE_DECRYPT. + """ + keyring, key = _mock_keyring() + config = S3EncryptionClientConfig(keyring=keyring) + cmm = DefaultCryptoMaterialsManager(keyring) + + # Encrypt using the default algorithm (no override) + pipeline = PutEncryptedObjectPipeline(cmm, config.encryption_algorithm) + plaintext = b"integration test: default algorithm uses key commitment" + ciphertext, metadata = pipeline.encrypt(plaintext) + + # Build a response dict as if we fetched this object from S3 + response = { + "Body": BytesIO(ciphertext), + "Metadata": metadata, + } + + # Decrypt with REQUIRE_ENCRYPT_REQUIRE_DECRYPT — this will reject + # non-committing algorithm suites, so success proves the default commits. + decrypt_pipeline = GetEncryptedObjectPipeline( + cmm, + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + ) + result = decrypt_pipeline.decrypt(response) + assert result == plaintext diff --git a/test/test_encryption.py b/test/test_encryption.py new file mode 100644 index 00000000..a384afbd --- /dev/null +++ b/test/test_encryption.py @@ -0,0 +1,240 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Tests for encryption specification compliance annotations. + +Each test in this module corresponds to a MUST/SHOULD requirement from +specification/s3-encryption/encryption.md and carries a type=test annotation +that mirrors the type=implementation annotation in the source code. +""" + +import base64 +import os +from unittest.mock import MagicMock + +import pytest +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from s3_encryption.key_derivation import derive_keys +from s3_encryption.materials.crypto_materials_manager import DefaultCryptoMaterialsManager +from s3_encryption.materials.encrypted_data_key import EncryptedDataKey +from s3_encryption.materials.materials import AlgorithmSuite, CommitmentPolicy + +_KC_SUITE = AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY +KC_GCM_IV = _KC_SUITE.kc_gcm_iv +MESSAGE_ID_LENGTH = _KC_SUITE.commitment_nonce_length_bytes +SUITE_ID_BYTES = _KC_SUITE.suite_id_bytes +from s3_encryption import S3EncryptionClientConfig +from s3_encryption.pipelines import PutEncryptedObjectPipeline + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _mock_cmm(plaintext_key=None, encrypted_key=b"encrypted-key"): + """Return a CMM backed by a mock keyring that returns the given keys.""" + if plaintext_key is None: + plaintext_key = os.urandom(32) + + mock_keyring = MagicMock() + mock_keyring.on_encrypt.side_effect = lambda mats: _fill_materials( + mats, plaintext_key, encrypted_key + ) + return DefaultCryptoMaterialsManager(mock_keyring), plaintext_key + + +def _fill_materials(mats, plaintext_key, encrypted_key): + mats.plaintext_data_key = plaintext_key + mats.encrypted_data_key = EncryptedDataKey( + key_provider_id=b"S3Keyring", + key_provider_info="kms+context", + encrypted_data_key=encrypted_key, + ) + return mats + + +# --------------------------------------------------------------------------- +# Content Encryption — General +# --------------------------------------------------------------------------- + + +class TestContentEncryption: + """Tests for specification/s3-encryption/encryption.md#content-encryption.""" + + def test_uses_configured_algorithm_suite(self): + """The pipeline MUST encrypt using the algorithm suite configured in the client.""" + cmm, key = _mock_cmm() + plaintext = b"test data" + + # V2 (GCM no KDF) + config_v2 = S3EncryptionClientConfig( + keyring=MagicMock(), + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + cmm=cmm, + ) + pipeline_v2 = PutEncryptedObjectPipeline(config_v2.cmm, config_v2.encryption_algorithm) + _, meta_v2 = pipeline_v2.encrypt(plaintext) + assert "x-amz-cek-alg" in meta_v2 + assert meta_v2["x-amz-cek-alg"] == "AES/GCM/NoPadding" + + # V3 (KC GCM) + config_v3 = S3EncryptionClientConfig( + keyring=MagicMock(), + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, + cmm=cmm, + ) + pipeline_v3 = PutEncryptedObjectPipeline(config_v3.cmm, config_v3.encryption_algorithm) + _, meta_v3 = pipeline_v3.encrypt(plaintext) + assert "x-amz-c" in meta_v3 + assert meta_v3["x-amz-c"] == "115" + + ##= specification/s3-encryption/encryption.md#content-encryption + ##= type=test + ##% The client MUST generate an IV or Message ID using the length of the IV + ##% or Message ID defined in the algorithm suite. + def test_iv_generated_with_correct_length_gcm(self): + """GCM encryption MUST produce a 12-byte IV.""" + cmm, _ = _mock_cmm() + pipeline = PutEncryptedObjectPipeline(cmm, AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF) + + _, meta = pipeline.encrypt(b"test") + iv_bytes = base64.b64decode(meta["x-amz-iv"]) + assert len(iv_bytes) == 12 + + def test_message_id_generated_with_correct_length_kc(self): + """KC-GCM encryption MUST produce a 28-byte Message ID.""" + cmm, _ = _mock_cmm() + pipeline = PutEncryptedObjectPipeline( + cmm, AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + + _, meta = pipeline.encrypt(b"test") + message_id_bytes = base64.b64decode(meta["x-amz-i"]) + assert len(message_id_bytes) == MESSAGE_ID_LENGTH + + ##= specification/s3-encryption/encryption.md#content-encryption + ##= type=test + ##% The generated IV or Message ID MUST be set or returned from the encryption + ##% process such that it can be included in the content metadata. + def test_iv_included_in_metadata_gcm(self): + """GCM encryption MUST include the IV in the returned metadata.""" + cmm, _ = _mock_cmm() + pipeline = PutEncryptedObjectPipeline(cmm, AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF) + + _, meta = pipeline.encrypt(b"test") + assert "x-amz-iv" in meta + + def test_message_id_included_in_metadata_kc(self): + """KC-GCM encryption MUST include the Message ID in the returned metadata.""" + cmm, _ = _mock_cmm() + pipeline = PutEncryptedObjectPipeline( + cmm, AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + + _, meta = pipeline.encrypt(b"test") + assert "x-amz-i" in meta + + +# --------------------------------------------------------------------------- +# ALG_AES_256_GCM_IV12_TAG16_NO_KDF +# --------------------------------------------------------------------------- + + +class TestGcmNoKdf: + """Tests for specification/s3-encryption/encryption.md#alg-aes-256-gcm-iv12-tag16-no-kdf.""" + + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-iv12-tag16-no-kdf + ##= type=test + ##% The client MUST initialize the cipher, or call an AES-GCM encryption API, + ##% with the plaintext data key, the generated IV, and the tag length defined + ##% in the Algorithm Suite when encrypting with ALG_AES_256_GCM_IV12_TAG16_NO_KDF. + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-iv12-tag16-no-kdf + ##= type=test + ##% The client MUST NOT provide any AAD when encrypting with ALG_AES_256_GCM_IV12_TAG16_NO_KDF. + def test_gcm_encrypt_decrypt_roundtrip_no_aad(self): + """GCM encryption MUST use the data key, generated IV, and no AAD.""" + cmm, key = _mock_cmm() + pipeline = PutEncryptedObjectPipeline(cmm, AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF) + plaintext = b"roundtrip test for GCM no KDF" + + ciphertext, meta = pipeline.encrypt(plaintext) + + # Decrypt with the same key, IV, and no AAD + iv = base64.b64decode(meta["x-amz-iv"]) + aesgcm = AESGCM(key) + decrypted = aesgcm.decrypt(nonce=iv, data=ciphertext, associated_data=None) + assert decrypted == plaintext + + def test_gcm_decrypt_fails_with_aad(self): + """Ciphertext produced with no AAD MUST NOT decrypt with AAD.""" + cmm, key = _mock_cmm() + pipeline = PutEncryptedObjectPipeline(cmm, AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF) + + ciphertext, meta = pipeline.encrypt(b"test") + + iv = base64.b64decode(meta["x-amz-iv"]) + aesgcm = AESGCM(key) + with pytest.raises(Exception): + aesgcm.decrypt(nonce=iv, data=ciphertext, associated_data=b"unexpected-aad") + + +# --------------------------------------------------------------------------- +# ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY +# --------------------------------------------------------------------------- + + +class TestKcGcm: + """Tests for specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key.""" + + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key + ##= type=test + ##% The client MUST use HKDF to derive the key commitment value and the derived + ##% encrypting key as described in [Key Derivation](key-derivation.md). + def test_kc_gcm_uses_hkdf_derived_key(self): + """KC-GCM encryption MUST use HKDF-derived keys, not the raw data key.""" + cmm, raw_key = _mock_cmm() + pipeline = PutEncryptedObjectPipeline( + cmm, AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + plaintext = b"roundtrip test for KC GCM" + + ciphertext, meta = pipeline.encrypt(plaintext) + + message_id = base64.b64decode(meta["x-amz-i"]) + derived_key, _ = derive_keys( + raw_key, message_id, AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + + # Decrypt with the HKDF-derived key, fixed IV, and suite ID as AAD + aesgcm = AESGCM(derived_key) + decrypted = aesgcm.decrypt(nonce=KC_GCM_IV, data=ciphertext, associated_data=SUITE_ID_BYTES) + assert decrypted == plaintext + + # Decrypting with the raw key must fail + aesgcm_raw = AESGCM(raw_key) + with pytest.raises(Exception): + aesgcm_raw.decrypt(nonce=KC_GCM_IV, data=ciphertext, associated_data=SUITE_ID_BYTES) + + ##= specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key + ##= type=test + ##% The derived key commitment value MUST be set or returned from the encryption + ##% process such that it can be included in the content metadata. + def test_kc_gcm_commitment_in_metadata(self): + """KC-GCM encryption MUST include the key commitment in metadata.""" + cmm, raw_key = _mock_cmm() + pipeline = PutEncryptedObjectPipeline( + cmm, AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + + _, meta = pipeline.encrypt(b"test") + + assert "x-amz-d" in meta + commitment_bytes = base64.b64decode(meta["x-amz-d"]) + + # Verify the commitment matches what HKDF would produce + message_id = base64.b64decode(meta["x-amz-i"]) + _, expected_commitment = derive_keys( + raw_key, message_id, AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + assert commitment_bytes == expected_commitment diff --git a/test/test_encryption_materials_integration.py b/test/test_encryption_materials_integration.py index 4b6bfefd..e9e59023 100644 --- a/test/test_encryption_materials_integration.py +++ b/test/test_encryption_materials_integration.py @@ -35,7 +35,7 @@ def test_keyring_on_encrypt(self): assert isinstance(result, EncryptionMaterials) assert result.encryption_context == { "key1": "value1", - "aws:x-amz-cek-alg": "AES/GCM/NoPadding", + "aws:x-amz-cek-alg": "115", } def test_cmm_get_encryption_materials_with_dict(self): diff --git a/test/test_key_commitment.py b/test/test_key_commitment.py new file mode 100644 index 00000000..a82fc9fd --- /dev/null +++ b/test/test_key_commitment.py @@ -0,0 +1,157 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Tests for key commitment policy specification compliance annotations. + +Each test in this module corresponds to a MUST/SHOULD requirement from +specification/s3-encryption/key-commitment.md and carries a type=test annotation +that mirrors the type=implementation annotation in the source code. +""" + +import base64 +import os +from io import BytesIO +from unittest.mock import Mock + +import pytest +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from s3_encryption.exceptions import S3EncryptionClientError +from s3_encryption.key_derivation import derive_keys +from s3_encryption.materials.crypto_materials_manager import DefaultCryptoMaterialsManager +from s3_encryption.materials.keyring import S3Keyring +from s3_encryption.materials.materials import ( + AlgorithmSuite, + CommitmentPolicy, + DecryptionMaterials, +) +from s3_encryption.pipelines import GetEncryptedObjectPipeline + +_KC_SUITE = AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY +KC_GCM_IV = _KC_SUITE.kc_gcm_iv +SUITE_ID_BYTES = _KC_SUITE.suite_id_bytes + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _make_pipeline(commitment_policy, keyring_return=None): + """Create a GetEncryptedObjectPipeline with a mocked CMM/keyring.""" + mock_keyring = Mock(spec=S3Keyring) + if keyring_return is not None: + mock_keyring.on_decrypt.return_value = keyring_return + cmm = DefaultCryptoMaterialsManager(mock_keyring) + return GetEncryptedObjectPipeline( + cmm, + commitment_policy=commitment_policy, + enable_legacy_unauthenticated_modes=True, + ) + + +def _v2_gcm_response(key, plaintext=b"test data"): + """Create a V2 GCM-encrypted response with real ciphertext.""" + iv = os.urandom(12) + ciphertext = AESGCM(key).encrypt(iv, plaintext, None) + metadata = { + "x-amz-iv": base64.b64encode(iv).decode(), + "x-amz-key-v2": base64.b64encode(b"encrypted-key").decode(), + "x-amz-wrap-alg": "kms+context", + "x-amz-matdesc": "{}", + "x-amz-cek-alg": "AES/GCM/NoPadding", + "x-amz-tag-len": "128", + } + dec_mats = DecryptionMaterials( + iv=iv, + plaintext_data_key=key, + algorithm_suite=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + ) + return {"Body": BytesIO(ciphertext), "Metadata": metadata}, dec_mats, plaintext + + +def _v3_kc_gcm_response(key, plaintext=b"test data"): + """Create a V3 KC-GCM-encrypted response with real ciphertext.""" + message_id = os.urandom(28) + derived_key, commitment = derive_keys( + key, message_id, AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY + ) + ciphertext = AESGCM(derived_key).encrypt(KC_GCM_IV, plaintext, SUITE_ID_BYTES) + metadata = { + "x-amz-c": "115", + "x-amz-3": base64.b64encode(b"encrypted-key").decode(), + "x-amz-w": "12", + "x-amz-t": "{}", + "x-amz-d": base64.b64encode(commitment).decode(), + "x-amz-i": base64.b64encode(message_id).decode(), + } + dec_mats = DecryptionMaterials( + plaintext_data_key=key, + algorithm_suite=AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, + ) + return {"Body": BytesIO(ciphertext), "Metadata": metadata}, dec_mats, plaintext + + +# --------------------------------------------------------------------------- +# Commitment Policy Tests +# --------------------------------------------------------------------------- + + +class TestCommitmentPolicy: + """Tests for specification/s3-encryption/key-commitment.md#commitment-policy.""" + + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##= type=test + ##% When the commitment policy is FORBID_ENCRYPT_ALLOW_DECRYPT, the S3EC MUST allow decryption using algorithm suites which do not support key commitment. + def test_forbid_encrypt_allows_non_committing_decrypt(self): + """FORBID_ENCRYPT_ALLOW_DECRYPT MUST allow decryption with non-committing suites.""" + key = os.urandom(32) + response, dec_mats, plaintext = _v2_gcm_response(key) + + pipeline = _make_pipeline( + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + keyring_return=dec_mats, + ) + result = pipeline.decrypt(response) + assert result == plaintext + + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##= type=test + ##% When the commitment policy is REQUIRE_ENCRYPT_ALLOW_DECRYPT, the S3EC MUST allow decryption using algorithm suites which do not support key commitment. + def test_require_encrypt_allow_decrypt_allows_non_committing_decrypt(self): + """REQUIRE_ENCRYPT_ALLOW_DECRYPT MUST allow decryption with non-committing suites.""" + key = os.urandom(32) + response, dec_mats, plaintext = _v2_gcm_response(key) + + pipeline = _make_pipeline( + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT, + keyring_return=dec_mats, + ) + result = pipeline.decrypt(response) + assert result == plaintext + + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##= type=test + ##% When the commitment policy is REQUIRE_ENCRYPT_REQUIRE_DECRYPT, the S3EC MUST NOT allow decryption using algorithm suites which do not support key commitment. + def test_require_require_rejects_non_committing_decrypt(self): + """REQUIRE_ENCRYPT_REQUIRE_DECRYPT MUST reject non-committing algorithm suites.""" + key = os.urandom(32) + response, dec_mats, _ = _v2_gcm_response(key) + + pipeline = _make_pipeline( + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + keyring_return=dec_mats, + ) + with pytest.raises(S3EncryptionClientError, match="cannot decrypt non-key-committing"): + pipeline.decrypt(response) + + def test_require_require_allows_committing_decrypt(self): + """REQUIRE_ENCRYPT_REQUIRE_DECRYPT MUST allow decryption with committing suites.""" + key = os.urandom(32) + response, dec_mats, plaintext = _v3_kc_gcm_response(key) + + pipeline = _make_pipeline( + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + keyring_return=dec_mats, + ) + result = pipeline.decrypt(response) + assert result == plaintext diff --git a/test/test_key_commitment_encrypt.py b/test/test_key_commitment_encrypt.py new file mode 100644 index 00000000..ed8e8f3e --- /dev/null +++ b/test/test_key_commitment_encrypt.py @@ -0,0 +1,108 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Tests for key commitment policy enforcement on the encryption path. + +Per specification/s3-encryption/key-commitment.md#commitment-policy: + - REQUIRE_ENCRYPT_ALLOW_DECRYPT: the S3EC MUST only encrypt using an + algorithm suite which supports key commitment. + - REQUIRE_ENCRYPT_REQUIRE_DECRYPT: the S3EC MUST only encrypt using an + algorithm suite which supports key commitment. + - FORBID_ENCRYPT_ALLOW_DECRYPT: the S3EC MUST NOT encrypt using an + algorithm suite which supports key commitment. + +Per specification/s3-encryption/client.md#key-commitment: + - The S3EC MUST validate the configured Encryption Algorithm against the + provided key commitment policy. + - If the configured Encryption Algorithm is incompatible with the key + commitment policy, then it MUST throw an exception. + +These tests verify that the S3EC rejects mismatched commitment policy and +algorithm suite configurations. The rejection may occur at client config +creation time or at encrypt time. +""" + +import os +from unittest.mock import MagicMock + +import pytest + +from s3_encryption import S3EncryptionClientConfig +from s3_encryption.exceptions import S3EncryptionClientError +from s3_encryption.materials.encrypted_data_key import EncryptedDataKey +from s3_encryption.materials.materials import AlgorithmSuite, CommitmentPolicy + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _mock_keyring(): + """Return a mock keyring that populates encryption materials.""" + key = os.urandom(32) + mock = MagicMock() + + def on_encrypt(mats): + mats.plaintext_data_key = key + mats.encrypted_data_key = EncryptedDataKey( + key_provider_id=b"S3Keyring", + key_provider_info="kms+context", + encrypted_data_key=b"encrypted-key", + ) + return mats + + mock.on_encrypt.side_effect = on_encrypt + return mock + + +# --------------------------------------------------------------------------- +# REQUIRE_ENCRYPT_* with non-committing algorithm → MUST fail +# --------------------------------------------------------------------------- + + +class TestRequireEncryptRejectsNonCommitting: + """Configuring REQUIRE_ENCRYPT_* with a non-committing algorithm MUST fail.""" + + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##= type=test + ##% When the commitment policy is REQUIRE_ENCRYPT_ALLOW_DECRYPT, the S3EC MUST only encrypt using an algorithm suite which supports key commitment. + def test_require_encrypt_allow_decrypt_rejects_non_committing_gcm(self): + keyring = _mock_keyring() + with pytest.raises(S3EncryptionClientError): + S3EncryptionClientConfig( + keyring=keyring, + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT, + ) + + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##= type=test + ##% When the commitment policy is REQUIRE_ENCRYPT_REQUIRE_DECRYPT, the S3EC MUST only encrypt using an algorithm suite which supports key commitment. + def test_require_encrypt_require_decrypt_rejects_non_committing_gcm(self): + keyring = _mock_keyring() + with pytest.raises(S3EncryptionClientError): + S3EncryptionClientConfig( + keyring=keyring, + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + ) + + +# --------------------------------------------------------------------------- +# FORBID_ENCRYPT_ALLOW_DECRYPT with committing algorithm → MUST fail +# --------------------------------------------------------------------------- + + +class TestForbidEncryptRejectsCommitting: + """Configuring FORBID_ENCRYPT_ALLOW_DECRYPT with a committing algorithm MUST fail.""" + + ##= specification/s3-encryption/key-commitment.md#commitment-policy + ##= type=test + ##% When the commitment policy is FORBID_ENCRYPT_ALLOW_DECRYPT, the S3EC MUST NOT encrypt using an algorithm suite which supports key commitment. + def test_forbid_encrypt_allow_decrypt_rejects_committing_gcm(self): + keyring = _mock_keyring() + with pytest.raises(S3EncryptionClientError): + S3EncryptionClientConfig( + keyring=keyring, + encryption_algorithm=AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, + commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, + ) diff --git a/test/test_key_derivation.py b/test/test_key_derivation.py new file mode 100644 index 00000000..0bec87f7 --- /dev/null +++ b/test/test_key_derivation.py @@ -0,0 +1,281 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Tests for key derivation specification compliance annotations. + +Each test in this module corresponds to a MUST requirement from +specification/s3-encryption/key-derivation.md and carries a type=test annotation +that mirrors the type=implementation annotation in the source code. +""" + +import hmac +import os + +import pytest +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.hashes import SHA512 +from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand + +from s3_encryption.key_derivation import ( + derive_keys, +) +from s3_encryption.materials.materials import AlgorithmSuite + +_KC_SUITE = AlgorithmSuite.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY +SUITE_ID_BYTES = _KC_SUITE.suite_id_bytes +ENCRYPTION_KEY_LENGTH = _KC_SUITE.data_key_length_bytes +COMMIT_KEY_LENGTH = _KC_SUITE.commitment_length_bytes +MESSAGE_ID_LENGTH = _KC_SUITE.commitment_nonce_length_bytes +KC_GCM_IV = _KC_SUITE.kc_gcm_iv + + +# --------------------------------------------------------------------------- +# HKDF Extract / Expand +# --------------------------------------------------------------------------- + + +class TestHkdfOperation: + """Tests for specification/s3-encryption/key-derivation.md#hkdf-operation.""" + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The hash function MUST be specified by the algorithm suite commitment settings. + def test_hash_function_is_sha512(self): + """HKDF extract MUST use the hash function specified by the algorithm suite.""" + pdk = os.urandom(_KC_SUITE.data_key_length_bytes) + msg_id = os.urandom(MESSAGE_ID_LENGTH) + + # Manual extract using the algorithm suite's configured hash + hash_alg = _KC_SUITE.kdf_hash_algorithm + prk = hmac.new(msg_id, pdk, hash_alg).digest() + + # Expand with the same hash to get expected DEK + expected_dek = HKDFExpand( + algorithm=SHA512(), + length=_KC_SUITE.data_key_length_bytes, + info=SUITE_ID_BYTES + b"DERIVEKEY", + ).derive(prk) + + # derive_keys using the suite must match + actual_dek, _ = derive_keys(pdk, msg_id, _KC_SUITE) + assert actual_dek == expected_dek + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The input keying material MUST be the plaintext data key (PDK) generated by the key provider. + def test_ikm_is_plaintext_data_key(self): + """Different plaintext data keys MUST produce different derived keys.""" + msg_id = os.urandom(MESSAGE_ID_LENGTH) + pdk_a = os.urandom(_KC_SUITE.data_key_length_bytes) + pdk_b = os.urandom(_KC_SUITE.data_key_length_bytes) + + key_a, _ = derive_keys(pdk_a, msg_id, _KC_SUITE) + key_b, _ = derive_keys(pdk_b, msg_id, _KC_SUITE) + assert key_a != key_b + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The length of the input keying material MUST equal the key derivation input length specified by the algorithm suite commit key derivation setting. + def test_ikm_length_is_32_bytes(self): + """The plaintext data key (IKM) length MUST equal the algorithm suite's data key length.""" + pdk = os.urandom(_KC_SUITE.data_key_length_bytes) + msg_id = os.urandom(MESSAGE_ID_LENGTH) + assert len(pdk) == _KC_SUITE.data_key_length_bytes + # Should succeed with correct-length key + key, ck = derive_keys(pdk, msg_id, _KC_SUITE) + assert len(key) == ENCRYPTION_KEY_LENGTH + assert len(ck) == COMMIT_KEY_LENGTH + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The length of the input keying material MUST equal the key derivation input length specified by the algorithm suite commit key derivation setting. + def test_ikm_wrong_length_raises(self): + """derive_keys MUST raise when the plaintext data key length doesn't match the suite.""" + from s3_encryption.exceptions import S3EncryptionClientError + + msg_id = os.urandom(MESSAGE_ID_LENGTH) + # Too short + with pytest.raises(S3EncryptionClientError): + derive_keys(os.urandom(16), msg_id, _KC_SUITE) + # Too long + with pytest.raises(S3EncryptionClientError): + derive_keys(os.urandom(64), msg_id, _KC_SUITE) + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The salt MUST be the Message ID with the length defined in the algorithm suite. + def test_salt_is_message_id(self): + """Different Message IDs (salts) MUST produce different derived keys.""" + pdk = os.urandom(_KC_SUITE.data_key_length_bytes) + msg_id_a = os.urandom(MESSAGE_ID_LENGTH) + msg_id_b = os.urandom(MESSAGE_ID_LENGTH) + + key_a, _ = derive_keys(pdk, msg_id_a, _KC_SUITE) + key_b, _ = derive_keys(pdk, msg_id_b, _KC_SUITE) + assert key_a != key_b + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The DEK input pseudorandom key MUST be the output from the extract step. + def test_dek_uses_prk_from_extract(self): + """The DEK expand step MUST use the PRK from the extract step.""" + pdk = os.urandom(_KC_SUITE.data_key_length_bytes) + msg_id = os.urandom(MESSAGE_ID_LENGTH) + + # Manual extract + prk = hmac.new(msg_id, pdk, _KC_SUITE.kdf_hash_algorithm).digest() + # Manual expand for DEK + expected_dek = HKDFExpand( + algorithm=SHA512(), + length=ENCRYPTION_KEY_LENGTH, + info=SUITE_ID_BYTES + b"DERIVEKEY", + ).derive(prk) + + actual_dek, _ = derive_keys(pdk, msg_id, _KC_SUITE) + assert actual_dek == expected_dek + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The length of the output keying material MUST equal the encryption key length specified by the algorithm suite encryption settings. + def test_dek_output_length(self): + """The derived encryption key MUST match the encryption key length from the algorithm suite.""" + key, _ = derive_keys( + os.urandom(_KC_SUITE.data_key_length_bytes), os.urandom(MESSAGE_ID_LENGTH), _KC_SUITE + ) + assert len(key) == _KC_SUITE.data_key_length_bytes + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The input info MUST be a concatenation of the algorithm suite ID as bytes followed by the string DERIVEKEY as UTF8 encoded bytes. + def test_dek_info_is_suite_id_plus_derivekey(self): + """DEK expand info MUST be suite_id_bytes + b'DERIVEKEY'.""" + pdk = os.urandom(_KC_SUITE.data_key_length_bytes) + msg_id = os.urandom(MESSAGE_ID_LENGTH) + + prk = hmac.new(msg_id, pdk, _KC_SUITE.kdf_hash_algorithm).digest() + + # Correct info + correct_dek = HKDFExpand( + algorithm=SHA512(), + length=ENCRYPTION_KEY_LENGTH, + info=SUITE_ID_BYTES + b"DERIVEKEY", + ).derive(prk) + + # Wrong info should produce different output + wrong_dek = HKDFExpand( + algorithm=SHA512(), + length=ENCRYPTION_KEY_LENGTH, + info=SUITE_ID_BYTES + b"WRONGKEY", + ).derive(prk) + + actual_dek, _ = derive_keys(pdk, msg_id, _KC_SUITE) + assert actual_dek == correct_dek + assert actual_dek != wrong_dek + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The CK input pseudorandom key MUST be the output from the extract step. + def test_ck_uses_prk_from_extract(self): + """The CK expand step MUST use the PRK from the extract step.""" + pdk = os.urandom(_KC_SUITE.data_key_length_bytes) + msg_id = os.urandom(MESSAGE_ID_LENGTH) + + prk = hmac.new(msg_id, pdk, _KC_SUITE.kdf_hash_algorithm).digest() + expected_ck = HKDFExpand( + algorithm=SHA512(), + length=COMMIT_KEY_LENGTH, + info=SUITE_ID_BYTES + b"COMMITKEY", + ).derive(prk) + + _, actual_ck = derive_keys(pdk, msg_id, _KC_SUITE) + assert actual_ck == expected_ck + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The length of the output keying material MUST equal the commit key length specified by the supported algorithm suites. + def test_ck_output_length(self): + """The commit key length MUST match the algorithm suite's commitment length.""" + _, ck = derive_keys( + os.urandom(_KC_SUITE.data_key_length_bytes), os.urandom(MESSAGE_ID_LENGTH), _KC_SUITE + ) + assert len(ck) == _KC_SUITE.commitment_length_bytes + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% - The input info MUST be a concatenation of the algorithm suite ID as bytes followed by the string COMMITKEY as UTF8 encoded bytes. + def test_ck_info_is_suite_id_plus_commitkey(self): + """CK expand info MUST be suite_id_bytes + b'COMMITKEY'.""" + pdk = os.urandom(_KC_SUITE.data_key_length_bytes) + msg_id = os.urandom(MESSAGE_ID_LENGTH) + + prk = hmac.new(msg_id, pdk, _KC_SUITE.kdf_hash_algorithm).digest() + + correct_ck = HKDFExpand( + algorithm=SHA512(), + length=COMMIT_KEY_LENGTH, + info=SUITE_ID_BYTES + b"COMMITKEY", + ).derive(prk) + + wrong_ck = HKDFExpand( + algorithm=SHA512(), + length=COMMIT_KEY_LENGTH, + info=SUITE_ID_BYTES + b"WRONGKEY", + ).derive(prk) + + _, actual_ck = derive_keys(pdk, msg_id, _KC_SUITE) + assert actual_ck == correct_ck + assert actual_ck != wrong_ck + + +# --------------------------------------------------------------------------- +# IV and AAD for KC-GCM +# --------------------------------------------------------------------------- + + +class TestKcGcmCipherParams: + """Tests for KC-GCM cipher initialization parameters.""" + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% When encrypting or decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, + ##% the IV used in the AES-GCM content encryption/decryption MUST consist entirely of bytes with the value 0x01. + def test_kc_gcm_iv_is_all_0x01(self): + """The KC-GCM IV MUST consist entirely of 0x01 bytes.""" + assert all(b == 0x01 for b in KC_GCM_IV) + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% The IV's total length MUST match the IV length defined by the algorithm suite. + def test_kc_gcm_iv_length_is_12(self): + """The KC-GCM IV length MUST match the IV length defined by the algorithm suite.""" + assert len(KC_GCM_IV) == _KC_SUITE.cipher_iv_length_bytes + + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% The client MUST initialize the cipher, or call an AES-GCM encryption API, with the derived encryption key, an IV containing only bytes with the value 0x01, + ##% and the tag length defined in the Algorithm Suite when encrypting or decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY. + ##= specification/s3-encryption/key-derivation.md#hkdf-operation + ##= type=test + ##% The client MUST set the AAD to the Algorithm Suite ID represented as bytes. + def test_kc_gcm_roundtrip_with_derived_key_iv_aad(self): + """KC-GCM MUST encrypt/decrypt with derived key, 0x01 IV, and suite ID as AAD.""" + pdk = os.urandom(_KC_SUITE.data_key_length_bytes) + msg_id = os.urandom(MESSAGE_ID_LENGTH) + plaintext = b"key derivation roundtrip test" + + derived_key, _ = derive_keys(pdk, msg_id, _KC_SUITE) + + # Encrypt with derived key, KC_GCM_IV, and SUITE_ID_BYTES as AAD + aesgcm = AESGCM(derived_key) + ciphertext = aesgcm.encrypt(KC_GCM_IV, plaintext, SUITE_ID_BYTES) + + # Decrypt with same parameters + decrypted = aesgcm.decrypt(KC_GCM_IV, ciphertext, SUITE_ID_BYTES) + assert decrypted == plaintext + + # Decrypting with wrong AAD must fail + with pytest.raises(Exception): + aesgcm.decrypt(KC_GCM_IV, ciphertext, b"\x00\x00") + + # Decrypting with wrong IV must fail + with pytest.raises(Exception): + aesgcm.decrypt(b"\x00" * _KC_SUITE.cipher_iv_length_bytes, ciphertext, SUITE_ID_BYTES) diff --git a/test/test_kms_keyring.py b/test/test_kms_keyring.py index d613cbf9..0a5d66de 100644 --- a/test/test_kms_keyring.py +++ b/test/test_kms_keyring.py @@ -128,7 +128,7 @@ def test_on_encrypt_adds_kms_context_algorithm(self): result = keyring.on_encrypt(enc_materials) call_args = mock_kms_client.generate_data_key.call_args - assert call_args.kwargs["EncryptionContext"]["aws:x-amz-cek-alg"] == "AES/GCM/NoPadding" + assert call_args.kwargs["EncryptionContext"]["aws:x-amz-cek-alg"] == "115" def test_on_encrypt_sets_encrypted_data_key(self): """Test that on_encrypt sets the encrypted data key from KMS response.""" diff --git a/test/test_metadata.py b/test/test_metadata.py index ba783bf5..55c1f0b2 100644 --- a/test/test_metadata.py +++ b/test/test_metadata.py @@ -56,7 +56,7 @@ def test_to_dict(self): # Verify that fields that are None are not included in the dictionary assert "x-amz-key" not in metadata_dict assert "x-amz-matdesc" not in metadata_dict - # Note: content_cipher_tag_length has a default value of "128" + # content_cipher_tag_length defaults to "128" for V1/V2 assert metadata_dict.get("x-amz-tag-len") == "128" assert "x-amz-crypto-instr-file" not in metadata_dict @@ -124,6 +124,9 @@ def test_to_dict_v3_fields(self): assert metadata_dict["x-amz-m"] == "mat-desc" assert metadata_dict["x-amz-t"] == "encryption-context" + # V3 metadata must NOT include V1/V2-only keys like x-amz-tag-len + assert "x-amz-tag-len" not in metadata_dict + def test_is_v1_format(self): metadata = ObjectMetadata( content_iv="iv", diff --git a/test/test_pipelines.py b/test/test_pipelines.py index 9f40cd5c..3d32b8cc 100644 --- a/test/test_pipelines.py +++ b/test/test_pipelines.py @@ -8,8 +8,10 @@ import pytest +from s3_encryption.exceptions import S3EncryptionClientError, S3EncryptionClientSecurityError from s3_encryption.materials.crypto_materials_manager import DefaultCryptoMaterialsManager from s3_encryption.materials.keyring import S3Keyring +from s3_encryption.materials.materials import CommitmentPolicy, DecryptionMaterials from s3_encryption.pipelines import GetEncryptedObjectPipeline @@ -45,7 +47,11 @@ def test_decrypt_v1_from_instruction_file(self): cmm = DefaultCryptoMaterialsManager(mock_keyring) # Create pipeline with mocked S3 client - pipeline = GetEncryptedObjectPipeline(cmm, mock_s3_client) + pipeline = GetEncryptedObjectPipeline( + cmm, + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + s3_client=mock_s3_client, + ) # Create mock response mock_response = { @@ -100,7 +106,11 @@ def test_decrypt_v2_from_instruction_file(self): cmm = DefaultCryptoMaterialsManager(mock_keyring) # Create pipeline with mocked S3 client - pipeline = GetEncryptedObjectPipeline(cmm, mock_s3_client) + pipeline = GetEncryptedObjectPipeline( + cmm, + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + s3_client=mock_s3_client, + ) # Create mock response mock_response = { @@ -127,7 +137,7 @@ def test_decrypt_v2_from_instruction_file(self): ##% In the V3 message format, only the content metadata related to ##% the encrypted data is stored in the Instruction File. def test_decrypt_v3_from_instruction_file(self): - """Test decrypting V3 format with instruction file.""" + """Test decrypting V3 format with instruction file (kms+context wrapping).""" # Object metadata contains V3 content keys only object_metadata = { "x-amz-c": "115", # Compressed algorithm suite @@ -136,11 +146,11 @@ def test_decrypt_v3_from_instruction_file(self): } # Instruction file contains encrypted data key and wrapping algorithm + # Uses "12" (kms+context) with "x-amz-t" for encryption context instruction_file_metadata = { "x-amz-3": base64.b64encode(b"encrypted-key-data").decode("utf-8"), - "x-amz-w": "02", # AES/GCM - "x-amz-m": json.dumps({"test-instruction": "material-desc-instruction"}), - "x-amz-crypto-instr-file": "", + "x-amz-w": "12", # kms+context + "x-amz-t": json.dumps({"aws:x-amz-cek-alg": "AES/GCM/NoPadding"}), } # Create mock S3 client @@ -156,7 +166,11 @@ def test_decrypt_v3_from_instruction_file(self): cmm = DefaultCryptoMaterialsManager(mock_keyring) # Create pipeline with mocked S3 client - pipeline = GetEncryptedObjectPipeline(cmm, mock_s3_client) + pipeline = GetEncryptedObjectPipeline( + cmm, + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + s3_client=mock_s3_client, + ) # Create mock response with encrypted data iv = os.urandom(12) @@ -168,8 +182,6 @@ def test_decrypt_v3_from_instruction_file(self): } # Mock the keyring to return decryption materials - from s3_encryption.materials.materials import DecryptionMaterials - plaintext_data_key = os.urandom(32) mock_dec_materials = DecryptionMaterials( @@ -182,8 +194,11 @@ def test_decrypt_v3_from_instruction_file(self): mock_keyring.on_decrypt.return_value = mock_dec_materials - # This should fail with NotImplementedError since V3 decryption isn't implemented yet - with pytest.raises(NotImplementedError, match="V3 decryption not yet implemented"): + # V3 decryption is now implemented; with fake commitment data, + # key commitment verification will fail. + with pytest.raises( + S3EncryptionClientSecurityError, match="Key commitment verification failed" + ): pipeline.decrypt(mock_response, bucket="test-bucket", key="test-key") # Verify instruction file was fetched @@ -217,7 +232,11 @@ def test_decrypt_with_custom_instruction_file_suffix(self): mock_keyring = Mock(spec=S3Keyring) cmm = DefaultCryptoMaterialsManager(mock_keyring) - pipeline = GetEncryptedObjectPipeline(cmm, mock_s3_client) + pipeline = GetEncryptedObjectPipeline( + cmm, + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + s3_client=mock_s3_client, + ) mock_response = { "Body": BytesIO(b"encrypted-test-data"), @@ -239,3 +258,36 @@ def test_decrypt_with_custom_instruction_file_suffix(self): mock_s3_client.get_object.assert_called_once_with( Bucket="test-bucket", Key="test-key.custom-suffix" ) + + def test_decrypt_v3_unsupported_wrap_alg(self): + """Test that V3 decryption with unsupported wrapping algorithm is rejected by the keyring.""" + # V3 metadata with AES/GCM wrapping (02) — not supported by the KMS keyring + metadata = { + "x-amz-c": "115", + "x-amz-3": base64.b64encode(b"encrypted-key-data").decode("utf-8"), + "x-amz-w": "02", # AES/GCM — unsupported by KMS keyring + "x-amz-m": json.dumps({"some": "material-desc"}), + "x-amz-d": base64.b64encode(b"key-commitment-data").decode("utf-8"), + "x-amz-i": base64.b64encode(b"test-message-id").decode("utf-8"), + } + + mock_keyring = Mock(spec=S3Keyring) + # The keyring rejects wrapping algorithms it doesn't support + mock_keyring.on_decrypt.side_effect = S3EncryptionClientError( + "AES/GCM is not a valid key wrapping algorithm!" + ) + cmm = DefaultCryptoMaterialsManager(mock_keyring) + pipeline = GetEncryptedObjectPipeline( + cmm, + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, + ) + + mock_response = { + "Body": BytesIO(b"encrypted-test-data"), + "Metadata": metadata, + } + + with pytest.raises( + S3EncryptionClientError, match="AES/GCM is not a valid key wrapping algorithm" + ): + pipeline.decrypt(mock_response)