Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 09 · 45 minutes

Encrypt data with a key service and decide who may use the key

After this lesson you can
  • Explain envelope encryption and why a key service never hands out its main key
  • Encrypt and decrypt a file with a data key from a local key service
  • Use a key policy, rotation and the disabling of a key as controls
Lab files of this lesson (19)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

In lesson 5 you saw that the bucket larkfield-orders uses aws:kms and the others use AES256. The data protection officer of Larkfield asks what the difference buys: "If someone copies the files of the order bucket, can they read them? Who decides that? And what do we do when a key must be replaced?" You will build the mechanism on your own machine, with a small stand-in for the key service, and answer with what you measured.

Recall

Lesson 5: does encryption at rest with a key that S3 manages protect a public bucket?

No. S3 decrypts each object for every request that is allowed, and a public bucket allows everyone. With a key of your own in the key service, the reader also needs the right to use the key.

Lesson 2: what is a resource-based policy?

A policy that is attached to a resource and names the principals that may use it. A bucket policy and the trust policy of a role are two examples. The key policy of this lesson is a third.

The idea

AWS Key Management Service (KMS) keeps keys that never leave the service. You cannot download a KMS key. You can only ask the service to do something with it, and every such request is an API call that IAM decides and CloudTrail records.

Sending every file to the service for encryption would be slow, and the service does not take large data. So cloud services use envelope encryption, with two kinds of key.

KeyWhere it livesWhat it encrypts
KMS keyInside the key service, alwaysData keys, never the data itself
Data keyIn the memory of your program, for a momentOne file or one object
Envelope encryption of one file
AppKey serviceStorageGenerateDataKey, with my KMS keythe data key, plain and wrappedencrypt the file with the plain data keyforget the plain data keythe encrypted file and the wrapped keyAppKey serviceStorage12345
  1. App → Key service: GenerateDataKey, with my KMS key
  2. Key service → App: the data key, plain and wrapped
  3. App: encrypt the file with the plain data key
  4. App: forget the plain data key
  5. App → Storage: the encrypted file and the wrapped key

The call GenerateDataKey returns the same data key twice: once in plain form (the field Plaintext) and once encrypted under the KMS key (the field CiphertextBlob). This course calls the second form the wrapped key. The program encrypts the data, throws the plain key away, and stores the wrapped key next to the data. To read the data later, a program sends the wrapped key to the service with Decrypt, gets the plain key back, and decrypts the data.

The result: a copy of the stored file is useless without one successful call to the key service, and that call is where you put the control.

  • The key policy is a resource-based policy on the KMS key, and it is the main way to control the key. The default key policy lets the account use IAM policies for the key. Without such a statement, an Allow in an IAM policy alone does not give access to the key.
  • You can disable a key. Every Decrypt then fails, and with it every read of the data. You can enable it again.
  • Rotation adds new key material for new encryptions. KMS keeps the old material, so old data stays readable. Automatic rotation is optional.
  • Deletion is final: data under a deleted key is lost. AWS therefore makes you wait before a key is deleted. Take the current waiting period and rotation periods from the KMS documentation.

A key that AWS creates for a service in your account is an AWS managed key, and you cannot change its policy. A key that you create is a customer managed key: you write its policy. The order bucket uses a customer managed key, so its key policy decides who may read. The other buckets use SSE-S3, where S3 holds the key and there is no key policy to write.

Same idea, other namesAWSMicrosoft AzureGoogle Cloud
Key serviceAWS KMSAzure Key VaultCloud KMS
A key that you controlCustomer managed keyCustomer-managed keyCustomer-managed encryption key (CMEK)

Worked example

1. Save the box that seals data

sealbox.py is the encryption of this lab. seal encrypts bytes with AES-256 through the openssl program that you used in "Security fundamentals", lesson 5, and then adds a tag: an HMAC, a hash that is computed from the data and a key, so that only a holder of the key can make it. unseal checks the tag first and decrypts only when it fits. So a wrong key and a changed byte give the same clear error. subprocess.run starts another program, hashlib.sha256 makes two separate keys from the one key (one for the cipher, one for the tag), hmac.digest computes the tag, and hmac.compare_digest compares two tags in a way that leaks no timing. A real program would use authenticated encryption from a reviewed library. This file shows the idea with tools that you have.

sealbox.py

"""sealbox.py: encrypt bytes with a key and detect any change. AES-256 from the openssl program, HMAC from Python.

A lab tool that shows the idea. A real program uses authenticated encryption from a reviewed library.
"""
import hashlib
import hmac
import os
import subprocess

TAG = 32  # bytes of an HMAC-SHA256 tag


def _openssl(key, data, *options):
    """Run openssl enc with the key in an environment variable, so that it is not in the list of processes."""
    command = ["openssl", "enc", "-aes-256-cbc", "-pbkdf2", "-pass", "env:KR_SEAL_KEY", *options]
    done = subprocess.run(command, input=data, capture_output=True, env={**os.environ, "KR_SEAL_KEY": key.hex()})
    if done.returncode:
        raise ValueError("openssl failed: " + done.stderr.decode().strip())
    return done.stdout


def subkeys(key):
    """One key for the cipher and another for the tag, so that no key is used for two jobs."""
    return hashlib.sha256(key + b"enc").digest(), hashlib.sha256(key + b"mac").digest()


def seal(key, data):
    """Encrypt, then add a tag over the result. A random salt makes every result different."""
    enc, mac = subkeys(key)
    box = _openssl(enc, data, "-salt")
    return box + hmac.digest(mac, box, hashlib.sha256)


def unseal(key, sealed):
    """Check the tag first. Decrypt only when it is right."""
    enc, mac = subkeys(key)
    box, tag = sealed[:-TAG], sealed[-TAG:]
    if not hmac.compare_digest(tag, hmac.digest(mac, box, hashlib.sha256)):
        raise ValueError("wrong key, or the data was changed")
    return _openssl(enc, box, "-d")

2. Save the stand-in for the key service

kms_mock.py keeps its keys in a file, keystore.json, with mode 600. A real key service keeps them in special hardware. Three functions carry the lesson. authorise reads the key policy. os.urandom(32) returns 32 random bytes from the system: a key.

def authorise(key, principal, action):
    """The key policy decides. No statement for this principal and action: denied."""
    if not key["enabled"]:
        raise Denied("the key is disabled")
    for st in key["policy"]["Statement"]:
        if (st["Effect"] == "Allow" and principal in as_list(st["Principal"]["AWS"])
                and any(like(a, action) for a in as_list(st["Action"]))):
            return
    raise Denied(f"the key policy does not allow {action} for {principal.split(':')[-1]}")
def generate_data_key(name, principal):
    """Return a new data key twice: in plain form, and wrapped (encrypted) with the newest material of the key."""
    key = load()[name]
    authorise(key, principal, "kms:GenerateDataKey")
    plain = os.urandom(32)
    version = len(key["material"])
    wrapped = seal(bytes.fromhex(key["material"][-1]), plain)
    blob = json.dumps({"key": name, "version": version, "wrapped": base64.b64encode(wrapped).decode()})
    return plain, blob

decrypt reads from the wrapped key which KMS key and which version made it, checks the policy for kms:Decrypt, and unwraps. The key policy of the lab, LAB_POLICY, has two statements: web-app-role may generate data keys and decrypt, and report-lambda-role may only decrypt. Open the block and save the file.

The finished file: kms_mock.py

kms_mock.py

"""kms_mock.py: a local stand-in for a cloud key management service. The keys stay in keystore.json.

    python3 kms_mock.py create NAME            make a key with the key policy of this lab
    python3 kms_mock.py rotate NAME            add new key material; the old material stays for old data
    python3 kms_mock.py disable|enable NAME
    python3 kms_mock.py show NAME              the state of a key, without its material
"""
import base64
import json
import os
import sys

from policy_eval import as_list, like
from sealbox import seal, unseal

STORE = "keystore.json"
ROLE = "arn:aws:iam::111122223333:role/"
LAB_POLICY = {"Version": "2012-10-17", "Statement": [
    {"Sid": "AppMayEncryptAndDecrypt", "Effect": "Allow", "Principal": {"AWS": ROLE + "web-app-role"},
     "Action": ["kms:GenerateDataKey", "kms:Decrypt"], "Resource": "*"},
    {"Sid": "ReportsMayOnlyDecrypt", "Effect": "Allow", "Principal": {"AWS": ROLE + "report-lambda-role"},
     "Action": "kms:Decrypt", "Resource": "*"}]}


class Denied(Exception):
    pass


def load():
    if not os.path.exists(STORE):
        return {}
    with open(STORE) as src:
        return json.load(src)


def save(keys):
    with open(os.open(STORE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as out:
        json.dump(keys, out, indent=1)


def create(name, policy=LAB_POLICY):
    keys = load()
    keys[name] = {"enabled": True, "policy": policy, "material": [os.urandom(32).hex()]}
    save(keys)


def rotate(name):
    keys = load()
    keys[name]["material"].append(os.urandom(32).hex())
    save(keys)


def set_enabled(name, flag):
    keys = load()
    keys[name]["enabled"] = flag
    save(keys)


def authorise(key, principal, action):
    """The key policy decides. No statement for this principal and action: denied."""
    if not key["enabled"]:
        raise Denied("the key is disabled")
    for st in key["policy"]["Statement"]:
        if (st["Effect"] == "Allow" and principal in as_list(st["Principal"]["AWS"])
                and any(like(a, action) for a in as_list(st["Action"]))):
            return
    raise Denied(f"the key policy does not allow {action} for {principal.split(':')[-1]}")


def generate_data_key(name, principal):
    """Return a new data key twice: in plain form, and wrapped (encrypted) with the newest material of the key."""
    key = load()[name]
    authorise(key, principal, "kms:GenerateDataKey")
    plain = os.urandom(32)
    version = len(key["material"])
    wrapped = seal(bytes.fromhex(key["material"][-1]), plain)
    blob = json.dumps({"key": name, "version": version, "wrapped": base64.b64encode(wrapped).decode()})
    return plain, blob


def decrypt(blob, principal):
    """Unwrap a data key. The blob itself says which key and which version wrapped it."""
    info = json.loads(blob)
    key = load()[info["key"]]
    authorise(key, principal, "kms:Decrypt")
    return unseal(bytes.fromhex(key["material"][info["version"] - 1]), base64.b64decode(info["wrapped"]))


if __name__ == "__main__":
    verb, name = sys.argv[1], sys.argv[2]
    if verb == "create":
        create(name)
    elif verb == "rotate":
        rotate(name)
    elif verb in ("disable", "enable"):
        set_enabled(name, verb == "enable")
    key = load()[name]
    print(f"{name}: {'enabled' if key['enabled'] else 'disabled'}, {len(key['material'])} versions of key material, "
          f"{len(key['policy']['Statement'])} statements in the key policy")

cut -c1-10 keeps the first ten characters of the line of ls -l: the mode.

python3 kms_mock.py create orders-key
ls -l keystore.json | cut -c1-10
orders-key: enabled, 1 versions of key material, 2 statements in the key policy
-rw-------

3. Encrypt a file as the web application

envelope.py is the application's side. Its function encrypt_file is the diagram in four numbered lines.

envelope.py

"""envelope.py: envelope encryption of a file with a data key from kms_mock.

    python3 envelope.py encrypt FILE ROLE       writes FILE.sealed
    python3 envelope.py decrypt FILE.sealed ROLE
ROLE is the name of a role of the lab account, for example web-app-role.
"""
import base64
import json
import sys

import kms_mock
from sealbox import seal, unseal

KEY_NAME = "orders-key"


def encrypt_file(path, principal):
    plain_key, blob = kms_mock.generate_data_key(KEY_NAME, principal)   # 1. ask for a data key
    with open(path, "rb") as src:
        sealed = seal(plain_key, src.read())                            # 2. encrypt the data with it, here, on this machine
    del plain_key                                                       # 3. forget the plain data key
    with open(path + ".sealed", "w") as out:                            # 4. store the wrapped key next to the data
        json.dump({"data_key": blob, "data": base64.b64encode(sealed).decode()}, out)
    return path + ".sealed"


def decrypt_file(path, principal):
    with open(path) as src:
        envelope = json.load(src)
    plain_key = kms_mock.decrypt(envelope["data_key"], principal)       # only the key service can unwrap the data key
    return unseal(plain_key, base64.b64decode(envelope["data"]))


if __name__ == "__main__":
    verb, path, who = sys.argv[1], sys.argv[2], kms_mock.ROLE + sys.argv[3]
    try:
        if verb == "encrypt":
            print("wrote", encrypt_file(path, who))
        else:
            sys.stdout.write(decrypt_file(path, who).decode())
    except (kms_mock.Denied, ValueError) as err:
        print("refused:", err)
        sys.exit(1)

printf writes a text with line ends into a file.

printf 'order,customer,total\n1001,ada@example.com,42.50\n' > orders.csv
python3 envelope.py encrypt orders.csv web-app-role
python3 -c "
import json
env = json.load(open('orders.csv.sealed'))
key = json.loads(env['data_key'])
print('data key wrapped by', key['key'], 'version', key['version'])
print('file keys:', sorted(env))"
wrote orders.csv.sealed
data key wrapped by orders-key version 1
file keys: ['data', 'data_key']

The sealed file holds the encrypted data and the wrapped data key. Your file differs from every other reader's: the keys are random. It does not hold a key that can open it.

4. Let the key policy decide who reads

python3 envelope.py decrypt orders.csv.sealed report-lambda-role
python3 envelope.py decrypt orders.csv.sealed ec2-maintenance
python3 envelope.py encrypt orders.csv report-lambda-role
order,customer,total
1001,ada@example.com,42.50
refused: the key policy does not allow kms:Decrypt for role/ec2-maintenance
refused: the key policy does not allow kms:GenerateDataKey for role/report-lambda-role

The report job reads the file. The role ec2-maintenance holds an administrator policy in IAM (lesson 3), and in this lab it still gets nothing: the key policy names two roles and gives the account no general right. This is the answer for the data protection officer. Whoever copies the files, or the whole bucket, has ciphertext. The control is one policy on one key. A real default key policy does hand the decision to IAM, so read the key policy of every important key.

5. Rotate the key and read old data

python3 kms_mock.py rotate orders-key
python3 envelope.py decrypt orders.csv.sealed web-app-role
orders-key: enabled, 2 versions of key material, 2 statements in the key policy
order,customer,total
1001,ada@example.com,42.50

The key now has two versions of key material. The old file names version 1 in its wrapped key, so it still opens. Rotation limits how much data one version protects. It does not lock out someone who could already call Decrypt: for that you change the key policy.

Your turn

Work with the key orders-key as it stands after step 5.

  • Make a file invoices.csv with two lines of your own and encrypt it as web-app-role.
  • Rotate the key twice. Make a second file invoices2.csv and encrypt it.
  • Read from both sealed files which version wrapped the data key.
  • Change one letter in the middle of the data value of invoices2.csv.sealed to a different letter, and try to decrypt it. A changed letter is still valid base64, so the text decodes and the tag catches the change. A symbol such as - is not base64 and gives another message.
  • Disable the key (python3 kms_mock.py disable orders-key), try to decrypt invoices.csv.sealed as web-app-role, and enable the key again.

Check yourself

Why does the application throw the plain data key away after it has encrypted the file?

So that the data can be read only through the key service. If the plain key stayed on disk next to the data, a copy of the disk would hold everything. With only the wrapped key stored, every read needs a Decrypt call, which the key policy decides and the audit log records.

An attacker steals a sealed file and the role of the report job. Can they read the data? What stops them next time?

Yes: the role may call Decrypt, so the service unwraps the data key for them. Encryption moves the question from "who has the file" to "who may use the key". The defences are the ones for any role: few rights, short-lived credentials, and an alert when the role is used from an unusual place.

After a rotation, is the old data encrypted with the new key material?

No. Rotation changes what new encryptions use. Old wrapped keys stay as they are, and the service keeps the old material to open them. To move old data to the new material you must wrap its data keys again.

Field notes

  • Use the encryption context of KMS: a set of names and values that the caller must give again for Decrypt, and that appears in the audit log. It ties a wrapped key to its purpose, for example to one bucket.
  • Split the rights on a key: the administrators of a key should not be able to decrypt with it, and its users should not be able to change its policy.
  • Before you schedule a key for deletion, disable it for a time and watch for failures. A disabled key can be enabled again, and a deleted one cannot.
  • KMS calls are management events in the audit log, so Decrypt by an unusual principal is something you can alert on. This is the main reason to prefer a customer managed key for sensitive data.
  • NIST publishes the recommendations for key management that auditors cite (the SP 800-57 series). Read the current parts at the source.