KMS Encryption
Claves maestras, cifrado en reposo, key policies y encryption contexts
KMS (Key Management Service) gestiona claves criptográficas para cifrar datos en reposo. Una CMK (Customer Master Key) es la clave de nivel superior: nunca sale de KMS, nunca la ves en texto plano, pero puedes pedir a KMS que cifre/descifre datos con ella. Los servicios de AWS (S3, RDS, DynamoDB, CloudWatch Logs, Secrets Manager) se integran nativamente con KMS para cifrado transparente.
El modelo es un envelope encryption: KMS genera una Data Key con GenerateDataKey(), la Data Key cifra tus datos, y KMS cifra la Data Key con la CMK. Para descifrar, envías la Data Key cifrada a KMS, KMS la descifra con la CMK, y usas la Data Key en texto plano para descifrar tus datos. La CMK nunca toca los datos directamente. Esto permite que los datos sean enormes (la Data Key siempre es pequeña) y que KMS sea el único lugar que conoce la clave maestra.
Las Key Policies determinan quién puede usar la CMK: administradores (pueden gestionar la clave pero no usarla para cifrado), usuarios (pueden cifrar/descifrar con la clave), y la cuenta root (acceso de emergencia). A diferencia de las políticas IAM que controlan desde el lado del principal, las Key Policies controlan desde el lado de la clave. Una llave sin Key Policy que incluya la cuenta root es irrecuperable si los administradores son eliminados.
El Encryption Context es metadata opcional que se debe proveer al cifrar y descifrar. KMS valida que el contexto sea idéntico en ambas operaciones: si cifras con context={service: 'payments'}, debes proveer el mismo context para descifrar. Si alguien roba el ciphertext y lo usa en otro contexto, KMS rechaza el descifrado. Úsalo para vincular datos cifrados a su contexto de uso.
import boto3
import json
import base64
kms = boto3.client('kms')
# === Create CMK with key policy ===
key_policy = {
'Version': '2012-10-17',
'Statement': [
{
# Root account: emergency access + ability to manage key policies
'Sid': 'Allow root account management',
'Effect': 'Allow',
'Principal': {'AWS': 'arn:aws:iam::ACCOUNT_ID:root'},
'Action': 'kms:*',
'Resource': '*'
},
{
# Admin role: manage key (but not use for crypto)
'Sid': 'Allow key administration',
'Effect': 'Allow',
'Principal': {'AWS': 'arn:aws:iam::ACCOUNT_ID:role/KeyAdminRole'},
'Action': ['kms:Create*', 'kms:Describe*', 'kms:Enable*',
'kms:List*', 'kms:Put*', 'kms:Update*',
'kms:Revoke*', 'kms:Disable*', 'kms:GetKeyPolicy',
'kms:DeleteImportedKeyMaterial', 'kms:ScheduleKeyDeletion'],
'Resource': '*'
},
{
# Lambda role: encrypt/decrypt only
'Sid': 'Allow use by lambda',
'Effect': 'Allow',
'Principal': {'AWS': 'arn:aws:iam::ACCOUNT_ID:role/lambda-ml-processor'},
'Action': ['kms:Encrypt', 'kms:Decrypt', 'kms:GenerateDataKey*',
'kms:DescribeKey'],
'Resource': '*'
}
]
}
cmk = kms.create_key(
Description='Master key for ML model weights encryption',
KeyUsage='ENCRYPT_DECRYPT',
KeySpec='SYMMETRIC_DEFAULT',
Policy=json.dumps(key_policy),
Tags=[{'TagKey': 'Service', 'TagValue': 'MLPipeline'}]
)
key_id = cmk['KeyMetadata']['KeyId']
# Create a human-readable alias
kms.create_alias(
AliasName='alias/ml-pipeline-key',
TargetKeyId=key_id
)
# === Envelope encryption with context ===
def encrypt_data(plaintext: bytes, service_name: str, environment: str) -> dict:
encryption_context = {
'service': service_name, # must provide same context to decrypt
'environment': environment
}
# GenerateDataKey: get both encrypted and plaintext data key
response = kms.generate_data_key(
KeyId='alias/ml-pipeline-key',
KeySpec='AES_256',
EncryptionContext=encryption_context
)
encrypted_key = response['CiphertextBlob']
plaintext_key = response['Plaintext']
# Encrypt data with plaintext data key (locally, fast)
from cryptography.fernet import Fernet
import base64
fernet_key = base64.urlsafe_b64encode(plaintext_key[:32])
f = Fernet(fernet_key)
encrypted_data = f.encrypt(plaintext)
return {
'encrypted_key': base64.b64encode(encrypted_key).decode(),
'encrypted_data': base64.b64encode(encrypted_data).decode(),
'context': encryption_context
}
def decrypt_data(encrypted_payload: dict) -> bytes:
import base64
encrypted_key = base64.b64decode(encrypted_payload['encrypted_key'])
context = encrypted_payload['context']
# Decrypt data key (KMS validates context matches)
response = kms.decrypt(
CiphertextBlob=encrypted_key,
EncryptionContext=context # must match what was used during encrypt
)
plaintext_key = response['Plaintext']
from cryptography.fernet import Fernet
fernet_key = base64.urlsafe_b64encode(plaintext_key[:32])
f = Fernet(fernet_key)
return f.decrypt(base64.b64decode(encrypted_payload['encrypted_data']))
# === Enable KMS encryption on S3 bucket ===
s3 = boto3.client('s3')
s3.put_bucket_encryption(
Bucket='ml-data-bucket',
ServerSideEncryptionConfiguration={
'Rules': [{'ApplyServerSideEncryptionByDefault': {
'SSEAlgorithm': 'aws:kms',
'KMSMasterKeyID': 'alias/ml-pipeline-key'
}}]
}
)Debugging lab
Detecta y corrige el error en el código.
- 01
# KMS key without root account in key policy key_policy = { 'Statement': [{ 'Effect': 'Allow', 'Principal': {'AWS': 'arn:aws:iam::ACCOUNT:role/AdminRole'}, 'Action': 'kms:*', 'Resource': '*' }] } # If AdminRole is deleted, key is unrecoverable!
- 02
# Encrypting sensitive data without encryption context response = kms.generate_data_key( KeyId='alias/my-key', KeySpec='AES_256' # No EncryptionContext ) # Ciphertext can be decrypted in any context
- 03
# Using one KMS key for everything # Same key for: user PII, ML model weights, audit logs, backups alias = 'alias/everything-key' # If this key is compromised, ALL data is at risk