TExcelTAD
Home › Cloud & Container Security › Encryption at Rest: KMS and Envelope Encryption

Encryption at Rest: KMS and Envelope Encryption

"Is it encrypted?" is on every cloud audit checklist, and the answer is almost always yes: providers now encrypt storage at rest by default. That makes it the wrong question. The useful questions are who can make the provider decrypt it, and would we see them do it. Encryption at rest with a provider-managed key protects against a stolen disk in a data centre; it does nothing against a stolen access key, because the service decrypts transparently for anyone allowed to read. Encryption with a customer-managed key in a key management service (AWS KMS, Azure Key Vault, Google Cloud KMS) adds a second permission check and an audit log entry on every use. This lesson shows the mechanism, envelope encryption, and the security properties that follow from it. The cryptography behind it is in Key Management, Rotation and Envelope Encryption and AEAD.

Envelope encryption

KMS keys never leave the KMS (they live in hardware security modules). Encrypting gigabytes inside KMS would be slow and expensive, so services use two layers:

  1. The service calls GenerateDataKey on a KMS key. KMS returns a fresh data key twice: in plaintext, and encrypted under the KMS key.
  2. The service encrypts the data locally with the plaintext data key (AES-256-GCM), stores the encrypted data key next to the ciphertext, and forgets the plaintext key.
  3. To read, the service sends the encrypted data key to KMS Decrypt. KMS checks the caller's permission on the KMS key, decrypts the data key and returns it; the service decrypts the data.

Every GenerateDataKey and Decrypt call is a CloudTrail event with the caller, the key and the encryption context: non-secret key-value pairs bound to the ciphertext as authenticated data (S3 uses the object's ARN, for example). The wrong context makes decryption fail.

A small KMS, in Python

The model below implements the flow with the cryptography package: a KMS key that only the "KMS" can use, a key policy, data keys, encryption context as AES-GCM associated data, and a log. Keys and nonces are fixed so the output is stable; real KMS keys and data keys come from an HSM's random number generator and nonces are never reused.

python · try it yourself
import hashlib, json
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.exceptions import InvalidTag

class ToyKMS:
    def __init__(self):
        self._keys = {"alias/lab-data": hashlib.sha256(b"lab-only kms key material").digest()}   # never leaves the KMS
        self.policy = {"alias/lab-data": {"kms:GenerateDataKey": {"app-role"}, "kms:Decrypt": {"app-role", "svc-backup"}}}
        self.log, self._n = [], 0

    def _check(self, caller, action, key_id, ctx):
        ok = caller in self.policy[key_id].get(action, set())
        self.log.append({"eventName": action.split(":")[1], "caller": caller, "key": key_id,
                         "encryptionContext": ctx, "errorCode": None if ok else "AccessDeniedException"})
        if not ok:
            raise PermissionError(f"{caller} is not allowed {action} on {key_id}")
        return self.log[-1]

    def generate_data_key(self, caller, key_id, ctx):
        self._check(caller, "kms:GenerateDataKey", key_id, ctx)
        self._n += 1
        data_key = hashlib.sha256(f"data key {self._n}".encode()).digest()          # real KMS: drawn from an HSM generator
        nonce = self._n.to_bytes(12, "big")
        aad = json.dumps(ctx, sort_keys=True).encode()
        return data_key, nonce + AESGCM(self._keys[key_id]).encrypt(nonce, data_key, aad)

    def decrypt(self, caller, key_id, blob, ctx):
        entry = self._check(caller, "kms:Decrypt", key_id, ctx)
        aad = json.dumps(ctx, sort_keys=True).encode()
        try:
            return AESGCM(self._keys[key_id]).decrypt(blob[:12], blob[12:], aad)
        except InvalidTag:
            entry["errorCode"] = "InvalidCiphertextException"
            raise

kms = ToyKMS()

def put_object(caller, name, data):
    ctx = {"aws:s3:arn": f"arn:aws:s3:::lab-app-uploads/{name}"}
    key, wrapped = kms.generate_data_key(caller, "alias/lab-data", ctx)
    nonce = bytes(12)                                   # one object per data key, so a fixed nonce is safe here only
    return {"ciphertext": AESGCM(key).encrypt(nonce, data, None), "wrapped_key": wrapped, "ctx": ctx}

def get_object(caller, obj, ctx=None):
    key = kms.decrypt(caller, "alias/lab-data", obj["wrapped_key"], ctx or obj["ctx"])
    return AESGCM(key).decrypt(bytes(12), obj["ciphertext"], None)

obj = put_object("app-role", "invoices/0001.json", b'{"customer": "c-17", "total": 120}')
print("stored ciphertext:", obj["ciphertext"][:16].hex(), "...", len(obj["ciphertext"]), "bytes")
print("stored wrapped key:", len(obj["wrapped_key"]), "bytes (12 nonce + 32 key + 16 tag)")

for caller, ctx in [("app-role", None), ("svc-backup", None), ("analyst", None),
                    ("app-role", {"aws:s3:arn": "arn:aws:s3:::lab-app-uploads/invoices/0002.json"})]:
    try:
        print(f"{caller:10} reads -> {get_object(caller, obj, ctx).decode()}")
    except PermissionError as e:
        print(f"{caller:10} reads -> denied by key policy ({e})")
    except InvalidTag:
        print(f"{caller:10} reads -> InvalidCiphertext: encryption context does not match")

print()
for e in kms.log:
    print(f"{e['eventName']:16} {e['caller']:10} {e['encryptionContext']['aws:s3:arn'].split('/', 1)[1]:22} {e['errorCode'] or 'ok'}")
stored ciphertext: a6f65a17869fe884196a6ba11004516b ... 50 bytes
stored wrapped key: 60 bytes (12 nonce + 32 key + 16 tag)
app-role   reads -> {"customer": "c-17", "total": 120}
svc-backup reads -> {"customer": "c-17", "total": 120}
analyst    reads -> denied by key policy (analyst is not allowed kms:Decrypt on alias/lab-data)
app-role   reads -> InvalidCiphertext: encryption context does not match

GenerateDataKey  app-role   invoices/0001.json     ok
Decrypt          app-role   invoices/0001.json     ok
Decrypt          svc-backup invoices/0001.json     ok
Decrypt          analyst    invoices/0001.json     AccessDeniedException
Decrypt          app-role   invoices/0002.json     InvalidCiphertextException

What the model shows:

  • The storage holds only ciphertext and a wrapped data key. Whoever copies both (a snapshot shared by mistake, a backup in the wrong bucket) has nothing without kms:Decrypt.
  • analyst might hold s3:GetObject on the bucket, but the key policy doesn't list it, so the read fails, and the failure is logged. With SSE-S3 (provider-managed keys) the same analyst would have read the plaintext without any trace in KMS.
  • Using the wrapped key with another object's context fails the GCM authentication tag (logged as InvalidCiphertextException): the encryption context ties a data key to its object, and it appears in every log line, so investigators can see exactly which object each decryption was for.

Key policies are the real access control

A KMS key's key policy is a resource policy, and for KMS it is required: unlike most services, an IAM identity policy alone grants nothing on a key unless the key policy delegates to the account (the default key policy does, with a statement trusting arn:aws:iam::<account>:root). Review points:

  • Who can use the key (kms:Decrypt, kms:GenerateDataKey*), who can administer it (kms:PutKeyPolicy, kms:ScheduleKeyDeletion, kms:DisableKey), and whether those are different people.
  • Grants (kms:CreateGrant), which give use permissions outside the policy document and are easy to forget in reviews (list-grants).
  • Cross-account statements: a key used by another account can decrypt your data for that account.

How key misuse is detected

CloudTrail event (source kms.amazonaws.com) Why it matters
Decrypt / GenerateDataKey volume spike, or from a new principal bulk reading of encrypted data, a classic exfiltration sign
Decrypt with errorCode AccessDeniedException someone without permission trying; often the first trace of a stolen credential
ScheduleKeyDeletion, DisableKey destroys access to all data under the key (a ransom or sabotage technique); deletion waits 7–30 days, so the alert gives time to CancelKeyDeletion
PutKeyPolicy, CreateGrant to an unknown principal or account opening the key to someone new
re-encryption of objects with a key from another account the cloud form of ransomware: data copied or rewritten under a key the victim doesn't control

How it is fixed

  • Use customer-managed keys for sensitive data stores, one key per data domain, so each key policy names a small set of users.
  • Separate key administrators from key users; nobody needs both in production.
  • Deny kms:ScheduleKeyDeletion and kms:DisableKey organisation-wide except for a break-glass role (SCP), and alert on every attempt.
  • Enable automatic key rotation (for AWS KMS symmetric customer-managed keys every 365 days by default, configurable from 90 to 2,560 days, plus on-demand rotation; rotation keeps old key material so old data still decrypts, and it doesn't re-encrypt data or rotate the data keys).
  • Use the encryption context in your own envelope encryption and require it with the kms:EncryptionContext: condition keys.

Pitfalls

  • Reporting "encrypted at rest: yes" as a control against data theft. With provider-managed keys it is only a control against physical media loss.
  • A key policy with "Principal": {"AWS": "*"} and a weak condition: anyone in AWS can use your key.
  • Caching plaintext data keys for too long, or logging them: the data key is the data.
  • Expecting one KMS event per S3 object everywhere: with S3 Bucket Keys enabled (common, because it cuts KMS cost), S3 asks KMS for a bucket-level key and reuses it, so there are far fewer Decrypt events and their encryption context names the bucket ARN, not each object.

Practice

1. Add "analyst" to the kms:Decrypt set. What changes in the output, and in the log?

The analyst's read returns the invoice JSON, and its log line shows Decrypt analyst invoices/0001.json ok instead of AccessDeniedException. Every future read by the analyst is now visible per object.

2. Why is a fixed nonce acceptable for the object encryption in this model but not in general?

Each object gets its own fresh data key, used exactly once, so the (key, nonce) pair never repeats. AES-GCM breaks badly when a nonce repeats under the same key (Nonce Reuse); with a long-lived key, nonces must be random or counters.

3. An attacker with admin rights schedules deletion of alias/lab-data with a 7-day window. What do you do, in order?

Contain the principal (disable the session or key), CancelKeyDeletion and re-enable the key, review the key policy and grants for changes, check CloudTrail for other destructive calls by the same principal, then add the SCP that denies ScheduleKeyDeletion outside break-glass.

Test yourself

What does encryption at rest with a provider-managed key protect against?

  1. Stolen access keys
  2. Loss or theft of the physical storage media
  3. Public bucket policies
  4. SSRF

In envelope encryption, what is stored next to the ciphertext?

  1. The KMS key
  2. The plaintext data key
  3. The data key encrypted under the KMS key
  4. Nothing

Why did the read with another object's encryption context fail?

  1. Wrong key policy
  2. The context is authenticated data, so the GCM tag check fails
  3. The object was deleted
  4. KMS was offline

Which KMS event most urgently needs an alert because it destroys access to data?

  1. DescribeKey
  2. ScheduleKeyDeletion (and DisableKey)
  3. ListAliases
  4. GenerateRandom