Secure Secrets Management Strategy
This strategy outlines a comprehensive, zero-trust approach to managing secrets (API keys, passwords, certs) across infrastructure, CI/CD, and runtime. It leverages envelope encryption for data protection, managed KMS/HSM for key custody, automated rotation, least-privilege IAM, dynamic injection, full auditing, and robust IR/recovery. Tools: AWS KMS/Secrets Manager (adaptable to GCP KMS/Vault/Azure Key Vault).
1. Key Custody (KMS/HSM)
Store root keys in FIPS 140-2 Level 3 HSM-backed managed services. Never export keys; perform all ops (encrypt/decrypt) in the service.
Example: AWS KMS Key Creation (Terraform)
hcl Copy code
resource "aws_kms_key" "secrets_key" {
description = "Secrets envelope key"
enable_key_rotation = true # Auto-rotate every year
deletion_window_in_days = 30
policy = jsonencode({
Statement = [{
Effect = "Allow"
Principal = { AWS = "arn:aws:iam::ACCOUNT:role/secrets-role" }
Action = "kms:*"
Resource = "*"
}]
})
}
resource "aws_kms_alias" "secrets_key" {
name = "alias/secrets-key"
target_key_id = aws_kms_key.secrets_key.key_id
}
2. Envelope Encryption
Encrypt secrets with a one-time data key (DEK), encrypt DEK with KMS customer master key (CMK). Store encrypted blob + encrypted DEK.
Example: Python Encryption/Decryption (boto3)
python Copy code
import boto3
kms = boto3.client('kms')
secrets = boto3.client('secretsmanager')
def encrypt_secret(secret_value, key_id):
plaintext = secret_value.encode()
resp = kms.generate_data_key(KeyId=key_id, KeySpec='AES_256')
# Encrypt data with DEK
cipher = AES.new(resp['Plaintext'], AES.MODE_GCM)
ct, tag = cipher.encrypt_and_digest(plaintext)
encrypted_dek = resp['CiphertextBlob']
return {'ct': ct, 'tag': tag, 'iv': cipher.nonce, 'encrypted_dek': encrypted_dek}
def decrypt_secret(envelope):
resp = kms.decrypt(CiphertextBlob=envelope['encrypted_dek'])
cipher = AES.new(resp['Plaintext'], AES.MODE_GCM, envelope['iv'])
return cipher.decrypt_and_verify(envelope['ct'], envelope['tag']).decode()
Store envelope in AWS Secrets Manager for managed rotation/retrieval.
3. Rotation
Automate DEK rotation (e.g., 90 days) via Secrets Manager; CMK rotates annually. Lambda triggers rotation on access patterns or schedule.
Example: AWS Secrets Manager Rotation (JSON Lambda Config)
json Copy code
{
"SecretId": "my-app/db-password",
"RotationLambdaARN": "arn:aws:lambda:region:account:function:rotate-db-password",
"RotationRules": {
"AutomaticallyAfterDays": 90
}
}
Lambda code fetches new secret from DB, encrypts with new DEK, updates envelope.
4. Least-Privilege Access
Use IAM roles/policies with just-in-time (JIT) access. No long-lived creds; temporary tokens only.
Example: IAM Policy for App Role
json Copy code
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": [
"secretsmanager:GetSecretValue",
"kms:Decrypt"
],
"Resource": [
"arn:aws:secretsmanager:region:account:secret:my-app-*",
"arn:aws:kms:region:account:key/KEY-ID"
]
}]
}
Attach to ECS/EKS service roles.
5. CI/CD and Runtime Injection
Never commit secrets. Use OIDC providers for CI (GitHub Actions), inject at deploy/runtime via IRSA/PIM.
CI/CD Example: GitHub Actions + AWS OIDC
yaml Copy code
# .github/workflows/deploy.yaml
name: Deploy
on: push
permissions:
id-token: write # OIDC
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::account:role/github-deploy-role
aws-region: us-east-1
- run: aws secretsmanager get-secret-value --secret-id my-app/db --query SecretString | jq -r .password > .env
- run: docker build --build-arg DB_PASS=$(cat .env) -t app .
- run: aws ecr push ...
Runtime: ECS Task Definition (JSON)
json Copy code
{
"containerDefinitions": [{
"name": "app",
"secrets": [{
"name": "DB_PASS",
"valueFrom": "arn:aws:secretsmanager:region:account:secret:my-app/db:password::"
}]
}]
}
EKS: Use External Secrets Operator to sync to Kubernetes Secrets.
6. Zero-Trust
Verify all access: mTLS for services, SPIFFE/SPIRE for workloads.
Short-lived creds (<15min), no shared secrets.
Network: Encrypt in-transit (TLS 1.3), least-priv SG/NACL.
Assume breach: Segment secrets by app/env, canary deploys.
Example: EKS IRSA Policy Attachment
Bind IAM role to service account for pod-level access.
7. Auditing
Enable CloudTrail + Secrets Manager logs (S3 + CloudWatch). Alert on anomalies (e.g., >5 fetches/hour).
Example: CloudWatch Alarm
hcl Copy code
resource "aws_cloudwatch_metric_alarm" "secrets_access" {
alarm_name = "high-secrets-access"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "2"
metric_name = "GetSecretValue"
namespace = "AWS/SecretsManager"
period = "300"
statistic = "Sum"
threshold = "10"
alarm_actions = [aws_sns_topic.alerts.arn]
}
8. Incident Response
Detect : SIEM (Splunk/GuardDuty) correlates logs; auto-quarantine on breach.
Contain : Revoke IAM roles, rotate all affected keys via KMS ScheduleKeyDeletion.
Eradicate : Scan repos/images (Trivy), force-push clean commits.
Recover : Use versioned secrets history; rollback to prior envelope.
Playbook :
Triage alert.
aws kms disable-key --key-id KEY-ID.
Rotate all DEKs.
Post-mortem: Review audit trails.
Example: CLI Revoke
bash Copy code
aws iam detach-role-policy --role-name app-role --policy-arn arn:aws:iam::aws:policy/SecretsManagerReadWrite
aws kms schedule-key-deletion --key-id alias/secrets-key --pending-window-in-days 7
9. Recovery
Backups: Secrets Manager auto-versions (keep 100); KMS backups via import/export (air-gapped).
DR: Multi-region KMS replicas; cross-account replication.
Test: Quarterly chaos drills (simulate key compromise).
Example: Multi-Region Replication (Terraform)
hcl Copy code
resource "aws_kms_replica_key" "dr_key" {
provider = aws.dr
key_id = aws_kms_key.primary.key_id
region = "us-west-2"
}
This strategy minimizes blast radius, ensures compliance (SOC2/PCI), and scales to production. Audit quarterly; integrate with IAM Access Analyzer for drift detection.