Overview and What You Will Learn
Encryption keys and secrets are where many AWS breaches begin, because whoever controls a key or a credential controls the data. This topic covers the services AWS gives you to protect data and detect threats: KMS for keys, Secrets Manager and Parameter Store for secrets, CloudHSM for dedicated hardware, ACM for certificates, WAF and Shield for edge protection, and GuardDuty, Inspector and Macie for detection. In the lab you create a customer managed key, store secrets, and turn on GuardDuty from the CLI.
By the end you will be able to:
- Explain how KMS keys, envelope encryption and key policies work
- Choose between AWS owned, AWS managed and customer managed keys
- Pick Parameter Store or Secrets Manager for a given secret
- Decide when CloudHSM is worth its cost
- Use ACM certificates correctly, including the us-east-1 rule
- Place WAF and Shield in a layered defense
- Explain what GuardDuty, Inspector and Macie each detect, and what none of them blocks
Why This Matters in Production
In early 2025, a ransomware campaign tracked as Codefinger targeted AWS accounts without malware. Using stolen access keys, attackers re-encrypted victims' S3 objects with SSE-C, where the caller supplies the key and AWS keeps only verification data, so the victim could not decrypt the objects. The attackers also set lifecycle rules to delete the data in about a week to pressure victims into paying.
No AWS flaw was exploited. The attack used a valid credential and a legitimate encryption feature, which shows that "we use encryption" means little on its own: who controls the key is the real security boundary. AWS has since changed S3 defaults so SSE-C is disabled on new buckets and on existing buckets that did not use it, but verify the current behaviour in the S3 documentation and block SSE-C yourself unless you need it.
Core Principles
How Does AWS KMS Work?
KMS creates, stores and controls the cryptographic keys that other services use to encrypt your data. It does not store your data. Every encrypted S3 object, EBS volume, RDS database and secret ultimately depends on a KMS key, so a misconfigured or compromised key is a shortcut for an attacker.
The deciding policy lives in the key policy, which controls who can use and administer a key, combined with IAM policies and grants.
What Are the KMS Key Types?
KMS has three ownership models, and the question that decides between them is whether you need to share the key or control its policy.
| Key type | Who manages it | Use when |
|---|---|---|
| AWS owned key | AWS, hidden from you | Default encryption some services apply |
| AWS managed key | AWS, in your account | Zero-setup encryption, for example aws/s3 |
| Customer managed key | You | Cross-account sharing, your own key policy, audit control |
AWS managed keys rotate automatically and you can view but not edit their policy. Customer managed keys cost a small monthly fee plus requests, so use them where their control is needed. Encrypted snapshots can only be shared across accounts if they use a customer managed key.
RememberKMS also offers asymmetric keys, HMAC keys, multi-Region keys and external key stores. Most workloads use symmetric keys.
What Is Envelope Encryption?
Envelope encryption encrypts your data with a data key, then encrypts that data key with a KMS key, so large data never has to travel to KMS. Direct KMS Encrypt calls are limited to 4 KB. For anything larger, services and SDKs call GenerateDataKey, encrypt locally, and store the encrypted data key beside the data. This is what happens when you turn on SSE-KMS for S3.
How Should You Rotate KMS Keys?
Turn on automatic rotation for every customer managed symmetric key. Rotation creates new key material for future encryption while KMS keeps older material so existing data still decrypts, and it does not re-encrypt your data. The default period is one year, and you can choose a different period and also rotate on demand.
SecurityA KMS key scheduled for deletion that you did not schedule, or S3 objects encrypted with an algorithm your team does not use, is a sign of credential compromise. Treat it as an incident, not drift.
How Do You Block SSE-C Ransomware Paths?
Deny the SSE-C request header on buckets that have no legitimate SSE-C use, and enforce it with a service control policy across accounts. Also protect the credentials, because the attack starts with a stolen key. The deny rule has these elements:
| Policy element | Value |
|---|---|
| Effect | Deny |
| Principal | * |
| Action | s3:PutObject |
| Resource | arn:aws:s3:::YOUR-BUCKET/* |
| Condition | Null on s3:x-amz-server-side-encryption-customer-algorithm equals false |
Save it as policy.json and apply it:
aws s3api put-bucket-policy \ --bucket devops-prod-data \ --policy file://policy.jsonAlso use least-privilege IAM, short-lived credentials from roles instead of long-lived access keys, MFA, and S3 Versioning and Object Lock for recoverability.
Should You Use Parameter Store or Secrets Manager?
Use Secrets Manager for credentials that must rotate, and Parameter Store for configuration and simple secrets that do not. The deciding question is whether the value needs automatic rotation.
| Parameter Store | Secrets Manager | |
|---|---|---|
| Cost | Standard tier free | Paid per secret and per call |
| Rotation | No built-in | Built-in with Lambda |
| Best for | Config, flags, simple secrets | Database passwords, API keys |
- Parameter Store types: String, StringList and SecureString, where SecureString is encrypted with KMS
- Tiers: Standard allows 10,000 parameters up to 4 KB each, and Advanced allows more parameters, 8 KB values and parameter policies for expiry notifications, for a fee
- Secrets Manager: Always encrypted with KMS, supports multi-Region replicas, and rotates secrets on a schedule through a Lambda function, with managed rotation for some RDS setups
- Rotation strategy: Single-user rotation can briefly break connections, so the alternating-users strategy keeps one valid user while the other changes
Without rotation, a stolen database password works forever. With rotation, it stops working on the next cycle, and the application keeps fetching the current value from Secrets Manager.
Common MistakePutting passwords in Lambda environment variables or code. Store them in Secrets Manager or Parameter Store and fetch them at startup, with caching to limit API calls.
When Do You Need AWS CloudHSM?
CloudHSM gives you dedicated, single-tenant hardware security modules in your VPC where you alone control the keys. Choose it when a regulation or contract demands exclusive control of key material or a dedicated device, because it has hourly cost and operational overhead. KMS is multi-tenant and managed by AWS, and AWS publishes FIPS 140-2 Level 3 validation for both services at the time of writing, so check the compliance pages for what your auditor needs. A custom key store lets KMS use keys held in your CloudHSM cluster.
| KMS | CloudHSM | |
|---|---|---|
| Tenancy | Multi-tenant, managed | Single-tenant, dedicated |
| Key control | IAM and key policy | You manage HSM users |
| Cost | Pay per key and request | Hourly per HSM |
How Does AWS Certificate Manager Work?
ACM provisions public TLS certificates for free and renews them automatically when you use DNS validation. Certificates can be attached to Elastic Load Balancers, CloudFront and API Gateway, and some other integrated services.
- Standard public ACM certificates cannot be exported, so they cannot be installed directly on an EC2 instance. AWS has added a paid exportable option, so check current docs.
- Keep the DNS validation CNAME record, because deleting it breaks renewal
- ACM does not auto-renew imported certificates. EventBridge sends a daily expiry event starting 45 days before, and the AWS Config rule acm-certificate-expiration-check flags them
- CloudFront and Edge-Optimized API Gateway need the certificate in us-east-1, and Regional endpoints need it in the same Region as the API
What Does AWS WAF Protect?
WAF filters HTTP and HTTPS requests at Layer 7 using a web ACL of rules that allow, block, count or challenge. It attaches to CloudFront, Application Load Balancers, API Gateway REST APIs, AppSync, Cognito user pools and some other services. It cannot attach to a Network Load Balancer, which works at Layer 4. For CloudFront, create the web ACL in us-east-1, and otherwise in the same Region as the resource.
- Managed rule groups: AWS and partner rule sets for common attacks, known bad inputs, SQL injection and bots
- Rate-based rules: Limit requests per IP in a time window against brute force and floods
- IP sets, geo match and size constraints: Block or allow by address, country or payload size
- Count mode first: Test new rules in count mode to avoid blocking real users, then switch to block
- Logging: Send WAF logs to S3, CloudWatch Logs or Firehose to tune rules
ALB addresses can change, so when a client needs a fixed IP to allow-list, put Global Accelerator in front of the ALB and keep WAF on the ALB.
What Does AWS Shield Do?
Shield protects against DDoS attacks. Shield Standard is free and automatic for all customers and covers common network and transport layer attacks such as SYN floods and reflection attacks. Shield Advanced is a paid subscription with a monthly fee and a term commitment, so check current pricing. It adds tuned detection for protected resources, access to the AWS Shield Response Team during attacks, cost protection for scaling caused by an attack, and automatic Layer 7 mitigation using WAF rules.
Shield Advanced is worth considering when downtime is very costly, you have SLA penalties, or you want expert help during attacks.
What Do GuardDuty, Inspector, and Macie Each Detect?
They answer three different questions: GuardDuty asks what suspicious activity is happening, Inspector asks what weaknesses exist, and Macie asks where sensitive data is stored.
| Service | Question it answers |
|---|---|
| GuardDuty | Is something suspicious happening now? |
| Inspector | Which vulnerabilities could be exploited? |
| Macie | Where is sensitive data in S3? |
- GuardDuty: Analyses CloudTrail events, VPC Flow Logs and DNS logs by default, with optional protection for S3, EKS, runtime activity, malware and RDS logins. It finds things like compromised instances, unusual API use and crypto mining. No agent is needed for the foundational sources.
- Inspector: Continuously scans EC2 instances, ECR images and Lambda functions for software vulnerabilities and unintended network exposure, with a risk score per finding.
- Macie: Uses managed data identifiers and your own custom identifiers to find sensitive data such as card numbers or national IDs in S3. Add custom identifiers for formats not covered, for example Indian PAN numbers.
GuardDuty and Macie produce findings that go to EventBridge and Security Hub. None of these services blocks anything, so you must wire findings to a response.
SecurityDetection without response is incomplete. Send high-severity GuardDuty findings through EventBridge to a Lambda that isolates the instance, revokes the credential, or updates a WAF block list.
Detailed Step-by-Step Practical Lab
This lab runs in ap-south-1. It generates random values so no real secret is written into your shell history.
Step 1: Create a customer managed key with rotation
KEY_ID=$(aws kms create-key \ --description "Key for production secrets" \ --query 'KeyMetadata.KeyId' --output text --region ap-south-1) aws kms create-alias --alias-name alias/devops-prod-key \ --target-key-id $KEY_ID --region ap-south-1 aws kms enable-key-rotation --key-id $KEY_ID --region ap-south-1Step 2: Encrypt and decrypt a small value directly
echo -n "hello kms" > hello.txt aws kms encrypt --key-id alias/devops-prod-key \ --plaintext fileb://hello.txt --region ap-south-1 \ --query CiphertextBlob --output text | base64 --decode > cipher.bin aws kms decrypt --ciphertext-blob fileb://cipher.bin --region ap-south-1 \ --query Plaintext --output text | base64 --decodeThe last command prints hello kms. This direct method works only for data up to 4 KB.
Step 3: Store a secret in Secrets Manager
DB_PASSWORD=$(aws secretsmanager get-random-password \ --password-length 24 --exclude-punctuation \ --query RandomPassword --output text --region ap-south-1) aws secretsmanager create-secret \ --name prod/devops-app/rds-password \ --description "RDS password for the production app" \ --secret-string "$DB_PASSWORD" \ --kms-key-id alias/devops-prod-key \ --region ap-south-1 aws secretsmanager get-secret-value \ --secret-id prod/devops-app/rds-password \ --query SecretString --output text --region ap-south-1For database credentials that rotate, store them in the JSON structure Secrets Manager expects, which the RDS integration creates for you.
Step 4: Store configuration in Parameter Store
aws ssm put-parameter --name /devops-app/prod/db-host \ --value "devops-prod-db.abc123.ap-south-1.rds.amazonaws.com" \ --type String --region ap-south-1 API_KEY=$(aws secretsmanager get-random-password \ --password-length 32 --exclude-punctuation \ --query RandomPassword --output text --region ap-south-1) aws ssm put-parameter --name /devops-app/prod/api-key \ --value "$API_KEY" --type SecureString \ --key-id alias/devops-prod-key --region ap-south-1 aws ssm get-parameters-by-path --path /devops-app/prod/ \ --with-decryption --region ap-south-1 \ --query 'Parameters[].Name' --output textStep 5: Enable GuardDuty
aws guardduty create-detector --enable \ --finding-publishing-frequency FIFTEEN_MINUTES --region ap-south-1 DETECTOR_ID=$(aws guardduty list-detectors \ --query 'DetectorIds[0]' --output text --region ap-south-1) aws guardduty list-findings --detector-id $DETECTOR_ID --region ap-south-1A new account usually has no findings. GuardDuty has a free trial, and it bills after that, so disable it in cleanup if you do not want to keep it.
Step 6: Clean up
aws secretsmanager delete-secret --secret-id prod/devops-app/rds-password \ --force-delete-without-recovery --region ap-south-1 aws ssm delete-parameters --region ap-south-1 \ --names /devops-app/prod/db-host /devops-app/prod/api-key aws guardduty delete-detector --detector-id $DETECTOR_ID --region ap-south-1 aws kms delete-alias --alias-name alias/devops-prod-key --region ap-south-1aws kms schedule-key-deletion --key-id $KEY_ID \ --pending-window-in-days 7 --region ap-south-1Production Best Practices & Common Pitfalls
- Turn on GuardDuty everywhere: Enable it in every account and Region, and manage it centrally through AWS Organizations.
- Rotate secrets automatically: Use Secrets Manager for credentials and enable rotation on customer managed keys.
- Use customer managed keys where you need control: Cross-account sharing and custom policies need them.
- Block SSE-C unless needed: Use bucket policies and SCPs, and protect access keys.
- Prefer roles over long-lived keys: Short-lived credentials limit what a leak can do.
- Use rate-based WAF rules on public APIs: Start in count mode, then block.
- Alert on ACM expiry for imported certificates: They do not renew automatically.
- Run Macie on buckets that may hold personal data: The first scan often finds surprises.
- Automate response: Findings are only useful if something acts on them.
Common MistakeUsing Parameter Store Standard for passwords that must rotate. It has no rotation, so you would build and maintain your own Lambda and update the database yourself.
Common MistakeScheduling KMS key deletion while secrets, snapshots or volumes still use the key. Anything encrypted with it becomes unrecoverable when the key is deleted.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Create KMS key | aws kms create-key --description "<text>" |
| Enable rotation | aws kms enable-key-rotation --key-id <id> |
| Create secret | aws secretsmanager create-secret --name <name> --secret-string "<value>" |
| Get secret | aws secretsmanager get-secret-value --secret-id <name> --query SecretString --output text |
| Put parameter | aws ssm put-parameter --name /path --value "<value>" --type SecureString |
| Get parameter | aws ssm get-parameter --name /path --with-decryption |
| Enable GuardDuty | aws guardduty create-detector --enable |
| List certificates | aws acm list-certificates --region ap-south-1 |
| Problem | Likely cause and fix |
|---|---|
| KMS throttling on S3 | High SSE-KMS request rate. Enable S3 Bucket Keys or request a quota increase. |
| Cannot share encrypted snapshot | Encrypted with an AWS managed key. Re-encrypt with a customer managed key. |
| Secret rotation fails | Rotation Lambda cannot reach the database. Place it in the VPC with the right security groups. |
| ACM certificate not renewing | DNS validation record deleted. Re-add the CNAME. |
| Certificate not offered for CloudFront | Certificate not in us-east-1. |
| GuardDuty finding raised no alert | No EventBridge rule. Create one to SNS or Lambda. |
| Access denied using a key | Key policy or grant missing for the caller. Check the key policy first. |