Notes
The problem
Here is how encryption usually fails in practice. The key is in the source code, or a config file, or an environment variable on the same host. Or it sits in the same database as the encrypted column, or in the same backup. Then one breach gives the attacker both the data and the key, and the encryption did nothing. It may still pass a checklist that asks, is the data encrypted. Your job is to ask the better question: where is the key?
- in source code or a config file in the repo
- in an environment variable on the same host
- in the same database as the encrypted column
- in the same bucket or backup
- result: one breach gives the attacker data and key
- auditors call this "encrypted"
Two kinds of key
The solution uses two kinds of key. A data encryption key, or DEK, encrypts the actual data. There are many of them: one per file, per record or per tenant. A key encryption key, or KEK, also called the master key, does only one thing: it encrypts data keys. Encrypting a key with another key is called wrapping. There are few master keys, and they are guarded far more tightly than any data.
- DEK: data encryption key encrypts the actual data many of them, short-lived
- KEK: key encryption key (master key, KMS key) only ever encrypts DEKs few, tightly guarded
- encrypting a key with another key is called "wrapping"
Envelope encryption
Here is the full flow. The application asks the key management service for a data key, and receives it twice: once in plain form, and once wrapped by the master key. It encrypts the data locally with the plain key, using AES in GCM mode. It stores the ciphertext together with the wrapped key. Then it erases the plain key from memory. The data and its key now travel together, but the key is locked, and the master key never left the service.
- 1. ask KMS for a data key: you get it in plain form AND wrapped by the master
- 2. encrypt the data locally with the plain key
- 3. store the ciphertext and the WRAPPED key together
- 4. erase the plain key from memory
- the master key never left
Decrypt
To decrypt, the application reads the ciphertext and the wrapped key, and sends only the wrapped key to the key management service. The service checks who is asking, checks the policy, writes an audit log entry, and returns the plain data key. The application decrypts locally. Notice two things. The data itself never goes to the service, so size and speed are not a problem. And every single decryption passes through an access check and a log.
- 1. read the ciphertext and the wrapped key
- 2. send only the wrapped key to KMS: "unwrap this"
- 3. KMS checks identity and policy, logs the call, returns the plain key
- 4. decrypt locally, erase the key
- the data never goes to KMS
Run it locally
Here is the pattern run locally, with an ordinary key standing in for the master. A thirty two byte data key wraps to forty bytes. Unwrapping with a different master key raises an error, so a wrapped key is useless without the right master. And here is what we store beside the ciphertext: a key version, the wrapped key and the nonce, about a hundred bytes. That key version field matters, and the next episode on rotation depends on it.
kek = AESGCM.generate_key(256)
dek = AESGCM.generate_key(256)
wrapped = aes_key_wrap(kek, dek)
len(dek), len(wrapped) # (32, 40)
aes_key_unwrap(other_kek, wrapped)
# raises InvalidUnwrap
# stored beside the ciphertext:
# {"kv": 1, "wk": "3s31k5f6...",
# "n": "Zm6mNhwS..."} Why it works
Why is this better? An attacker who steals the disk, the bucket or the backup has ciphertext and wrapped keys, both useless without the key service. Access to decryption is controlled by one policy in one place, and can be revoked in seconds. Every decryption is logged. If one data key leaks, it exposes one object and not the whole dataset. And rotation becomes cheap, because you rewrap small keys instead of re-encrypting all the data.
- stolen storage: ciphertext and wrapped keys, both useless without KMS
- access is one policy, in one place, and can be revoked
- every decrypt is logged
- a leaked data key exposes one object, not everything
- rotation is cheap: rewrap the small keys
HSM
Under the key service sits a hardware security module. An HSM is a tamper-resistant device that generates keys and holds them so that they cannot be exported. You send it data, it performs the operation inside, and results come out. Even its administrators cannot read the keys. They are certified to a standard called FIPS one forty, usually level three. A cloud key management service is a fleet of HSMs with an API in front.
- a tamper-resistant device that generates and holds keys
- keys are non-exportable: you send data in, results come out certified: FIPS 140-2 / 140-3 level 3 is typical
- cloud KMS: an HSM fleet with an API in front
- CloudHSM: a dedicated one
KMS in the cloud
Every provider has the same design: AWS KMS, Azure Key Vault, Google Cloud KMS, and Vault's transit engine for self-hosting. You choose between provider-managed keys, which are easy but give little control, and customer-managed keys, where you own the policy, the rotation and the logs. The key policy decides who may encrypt and who may decrypt. A core rule: the people who administer a key should not be the ones who can use it to decrypt.
- AWS KMS, Azure Key Vault, Google Cloud KMS, Vault Transit
- provider-managed keys: easy, little control
- customer-managed keys: your policy, rotation and logs
- key policy + IAM decide who may encrypt and decrypt
- separate key admins from key users
How attackers abuse KMS
Attackers do not steal a master key from an HSM. They borrow the right to use it. A compromised role with decrypt permission on every key is as good as having the keys. Policies that trust a whole account are common. Attackers add grants for persistence. In cloud ransom attacks, they re-encrypt your data under a key they control, or schedule your key for deletion. And plain data keys sometimes leak into logs or memory dumps.
- a compromised role that has kms:Decrypt on *
- key policies open to the whole account or to "*"
- grants created quietly for persistence
- ransom: re-encrypt your data under THEIR key, or schedule your key deletion
- plain data keys in logs or crash dumps
Defend and detect
Defenses. Grant decrypt only to the roles that need it, on specific keys, never on everything. Use an encryption context, which is associated data for the key service: a decrypt call must present the same tenant or resource identifier used at encryption. Alert on key disabling, scheduled deletion, policy changes and unusual spikes in decrypt calls. Keep the deletion waiting period. And use separate keys for production and for each data classification.
- least privilege: decrypt only for the roles that need it, on specific keys
- encryption context: bind a key use to a tenant or resource
- alert on: DisableKey, ScheduleKeyDeletion, policy changes, decrypt spikes
- keep a deletion waiting period
- separate keys per environment
Common mistakes
Mistakes. The key stored beside the data. Sending bulk data to the key service for encryption instead of using data keys, which is slow, costly and size-limited. Wildcard key permissions. One master key shared by every environment and every tenant. Caching plain data keys forever, or writing them to logs. No alerts on key policy changes. And no tested plan for what happens if a key is deleted or a region is lost.
- the key beside the data
- sending bulk data to KMS instead of using data keys
- kms:* or Decrypt on *
- one master key for all environments and tenants
- caching plain data keys forever, or logging them
- no alerts on key changes
- no tested key recovery
Say it like this
In the interview: data is encrypted locally with a data key, using AES in GCM mode. The data key is wrapped by a master key that never leaves the key management service or its HSM, and the wrapped key is stored with the data. To read, the application asks the service to unwrap the key, which enforces the access policy and logs the call. Stolen storage is useless by itself, access is centrally controlled, and rotation only rewraps keys.
- "Data is encrypted locally
- with a data key. That key is wrapped by a master key that never leaves the KMS or HSM, and the wrapped key is stored
- with the data. To read, the app asks KMS to unwrap, which enforces policy and logs it.
- Rotation only rewraps keys."