Sub topic 6
Binding ciphertext to its use with encryption context
This chapter assumes you have created a symmetric KMS key and called Encrypt and Decrypt directly, as in the previous chapters. It also assumes you can read an IAM policy statement. Here you will add encryption context to those calls, see how a mismatch fails, and use it as a policy condition and an audit field.
What encryption context is
Encryption context is a set of key-value pairs of plain text that you pass with a KMS cryptographic request. KMS cryptographically binds the pairs to the ciphertext. To decrypt, you must supply exactly the same pairs. If any pair is missing, changed or extra, the call fails.
KMS treats the context as additional authenticated data (AAD) in an authenticated cipher. The context is not encrypted and is not stored inside the ciphertext. You must supply it again on every decrypt, so your application has to know it or be able to rebuild it.
Encryption context gives you three things:
- Integrity of purpose. A ciphertext made for one record or tenant cannot be decrypted as if it belonged to another.
- Policy conditions. Key policies, IAM policies and grants can allow or deny requests based on the context values.
- Audit detail. KMS writes the context into CloudTrail, so each log entry shows what the key was used for.
Encryption context is supported only for symmetric encryption KMS keys. Asymmetric Encrypt calls and HMAC operations do not accept it.
Using it with the CLI
The earlier chapter already used --encryption-context purpose=demo. This sequence shows what happens when the context does not match:
echo -n "my secret" > secret.txt
aws kms encrypt \
--key-id alias/tutorial-key \
--plaintext fileb://secret.txt \
--encryption-context purpose=demo,tenant=acme \
--query CiphertextBlob \
--output text | base64 --decode > secret.enc
# Same pairs in a different order: succeeds
aws kms decrypt \
--ciphertext-blob fileb://secret.enc \
--encryption-context tenant=acme,purpose=demo \
--query Plaintext --output text | base64 --decode
# Missing pair: fails
aws kms decrypt \
--ciphertext-blob fileb://secret.enc \
--encryption-context purpose=demoThe last command returns an InvalidCiphertextException. KMS gives the same error for a wrong context as it does for a corrupted ciphertext. When a decrypt fails with that error, check the context before you suspect the data.
The matching rules are strict:
| Situation on decrypt | Result |
|---|---|
| Same pairs, same order | Succeeds |
| Same pairs, different order | Succeeds. The pairs are matched as a set. |
| A key or value differs in case (`Demo` vs `demo`) | Fails. Matching is case-sensitive. |
| One pair missing | Fails |
| One extra pair | Fails |
| No context, but one was used to encrypt | Fails |
What to put in the context
Choose values that identify the thing the ciphertext belongs to, and that your application already knows when it decrypts. Good examples:
- A tenant or customer ID, such as
tenant=acme. - A record identifier, such as
table=orders,orderId=8841. - A purpose label, such as
purpose=payment-token. - The ARN of the resource the data lives in. AWS services do this themselves. For example, S3 uses the object or bucket ARN as context.
Do not put secrets in the context. It appears in plain text in CloudTrail logs and in API requests. Do not use values that change over time, such as a timestamp, unless you store them next to the ciphertext. If you cannot reproduce the context, you cannot decrypt.
The size of the context is limited, so use short identifiers instead of whole documents.
The context protects the data key, not your data
In envelope encryption, KMS sees only the data key. If you pass a context to GenerateDataKey, KMS binds it to the encrypted data key. Your local AES-GCM call that encrypts the actual payload knows nothing about it. The earlier envelope example passed None as the AAD argument, so the payload ciphertext was not bound to the context.
For many designs this is acceptable, because an attacker cannot obtain the plaintext data key without a valid context. But an attacker could still swap the whole record (data key and payload) for another one that was encrypted under the same context. To close that gap, also pass the context to AES-GCM as AAD. Serialize it the same way on both sides:
import json
import os
import boto3
from botocore.exceptions import ClientError
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
kms = boto3.client("kms")
KEY_ID = "alias/tutorial-key"
def aad(context: dict) -> bytes:
# Sorted keys and fixed separators give identical bytes every time.
return json.dumps(context, sort_keys=True, separators=(",", ":")).encode()
def encrypt(plaintext: bytes, context: dict) -> dict:
resp = kms.generate_data_key(
KeyId=KEY_ID, KeySpec="AES_256", EncryptionContext=context
)
nonce = os.urandom(12)
ciphertext = AESGCM(resp["Plaintext"]).encrypt(nonce, plaintext, aad(context))
return {
"encrypted_key": resp["CiphertextBlob"],
"nonce": nonce,
"ciphertext": ciphertext,
}
def decrypt(blob: dict, context: dict) -> bytes:
resp = kms.decrypt(
CiphertextBlob=blob["encrypted_key"], EncryptionContext=context
)
return AESGCM(resp["Plaintext"]).decrypt(
blob["nonce"], blob["ciphertext"], aad(context)
)
if __name__ == "__main__":
ctx = {"tenant": "acme", "orderId": "8841"}
blob = encrypt(b"card token 4242", ctx)
print(decrypt(blob, ctx))
try:
decrypt(blob, {"tenant": "globex", "orderId": "8841"})
except ClientError as err:
print("KMS refused:", err.response["Error"]["Code"])The last call fails at KMS with InvalidCiphertextException, before any local decryption happens. If someone passes the correct context to KMS but the payload was tampered with or came from another record, AES-GCM raises InvalidTag (imported above if you want to catch it).
Using context in policies
Because KMS evaluates the context before it allows an operation, you can require it. The key policy from the earlier chapter used kms:EncryptionContext:purpose. Two condition keys are available:
kms:EncryptionContext:<name>checks the value of one named pair. Use it withStringEquals.kms:EncryptionContextKeyschecks which names appear in the request, regardless of value. Use it withForAnyValue:StringEqualsorForAllValues:StringEquals.
This statement allows an application role to decrypt only when the request includes tenant=acme, and denies any request with no tenant pair at all:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowAcmeDecrypt",
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::111122223333:role/acme-app" },
"Action": ["kms:Decrypt", "kms:GenerateDataKey"],
"Resource": "*",
"Condition": {
"StringEquals": { "kms:EncryptionContext:tenant": "acme" }
}
},
{
"Sid": "DenyMissingTenant",
"Effect": "Deny",
"Principal": { "AWS": "*" },
"Action": ["kms:Decrypt", "kms:GenerateDataKey"],
"Resource": "*",
"Condition": {
"Null": { "kms:EncryptionContext:tenant": "true" }
}
}
]
}Conditions only restrict who can ask. They cannot make a wrong context succeed. A caller who passes the right context and has permission still gets a valid decrypt.
Grants can also carry constraints, EncryptionContextEquals and EncryptionContextSubset. A grant with these constraints lets its grantee use the key only for requests whose context matches. The next chapters cover grants in detail.
Context in CloudTrail
Every KMS call that carries a context logs it in the requestParameters.encryptionContext field of the CloudTrail event. This lets you answer questions such as which tenant's data a role decrypted, or whether anything decrypted with an unexpected context. Failed calls are logged too, with the error code. A burst of InvalidCiphertextException events for one principal can indicate a bug or an attempt to replay ciphertext in the wrong place. Because the log keeps the values in plain text, this is one more reason never to put secrets in a context.
Common mistakes
- Building the context from data that changes between encrypt and decrypt, such as a display name or a timestamp.
- Not storing the context, or the information needed to rebuild it, with the ciphertext record.
- Treating the context as secret or as access control by itself. It is a binding and a policy hook, not encryption.
- Forgetting that re-encrypting with
ReEncrypttakes separate source and destination contexts. Set each one deliberately. - Passing the context to KMS but not to the local cipher, which leaves the payload unbound.
Exercise
A service encrypts customer notes with GenerateDataKey and AES-GCM, using the context {"customerId": "42"} for KMS and None as the AES-GCM AAD. An attacker with database write access copies customer 99's encrypted record (data key and payload, both created under {"customerId": "99"}) into customer 42's row. When the service decrypts customer 42's row using {"customerId": "42"}, what happens, and what change to the code would make the swap detectable in the way you intended?
Show answer
KMS rejects the decrypt with InvalidCiphertextException, because the encrypted data key was bound to customerId=99 and the request supplies customerId=42. So this particular swap is caught at KMS. The gap is a different one: if the attacker swaps only the payload and nonce with another record encrypted under the same data key and context, the local AES-GCM call succeeds, because its AAD is None. Passing the serialized context as AAD to AESGCM on both encrypt and decrypt binds the payload to the context as well, so such a swap fails with InvalidTag.