Security Notes
Cloud

AWS Data Protection — Keys, Secrets, Immutability & Encryption in Transit

Protecting data in AWS comes down to four questions: who holds the keys, where secrets live and how they rotate, can anyone delete or change the data, and is it encrypted on the wire. The KMS basics (envelope encryption, key policies, grants) and S3 basics are in AWS fundamentals; this file covers the harder choices. For the cryptography underneath, see cryptography.

15 min read 6 sections 8 model answers verified 2026-10

Last verified2026-10 — KMS, CloudHSM and Backup features evolve; check current service documentation for limits and supported key types.


Choosing Where Keys Live — KMS, Imported Material, Custom Key Stores, CloudHSM

What is this?

AWS offers a ladder of key-custody options. At the bottom, AWS creates and holds the key for you. At the top, the key never leaves hardware you control, possibly outside AWS. Each step up gives more control and more operational burden.

Why it matters

Regulators and customers ask "who can decrypt our data?" The answer depends on this choice. The exam tests whether you can pick the least operationally heavy option that still meets a stated requirement, such as "keys must be in a single-tenant HSM" or "we must be able to delete key material instantly."

How it works

More AWS-managed ◄───────────────────────────────────────────────► More customer control

AWS owned   AWS managed    Customer managed    Imported key     CloudHSM       External key
keys        keys (aws/s3)  KMS key             material (BYOK)  key store      store (XKS)
  │            │               │                   │                │               │
 invisible   per service,   you own the key     you generate     KMS API, keys   KMS API, keys in
 to you      auto-rotated   policy, rotation,   material, upload  in YOUR         YOUR HSM outside
             yearly         grants, deletion    it into KMS       single-tenant   AWS via a proxy
                                                                  CloudHSM
  • Customer managed KMS key — the default right answer. You control the key policy, can enable automatic rotation (period configurable from 90 days to about 7 years) or rotate on demand, and CloudTrail logs every use. Key material never leaves KMS's FIPS 140-validated HSMs (hardware security modules) in plaintext.
  • Imported key material (BYOK, "bring your own key") — you generate the key material in your own HSM and import it into a KMS key whose origin is EXTERNAL. Differences from AWS-generated material:
    • You can set an expiration, and you can delete the material immediately, making data unreadable at once (AWS-generated keys only support scheduled deletion after a 7–30 day wait).
    • You are responsible for durability: keep a secure copy, because AWS cannot regenerate it.
    • Automatic rotation is not available. Since June 2025 you can rotate on demand: import new material (it waits in a PENDING_ROTATION state, unused), then call RotateKeyOnDemand; the key ID and ARN stay the same and old ciphertext still decrypts. On-demand rotation is limited to 10 per key; the older alternative is a new key plus moving the alias.
  • CloudHSM key store — a KMS custom key store backed by your own CloudHSM cluster. Services still use the normal KMS API, but key material lives in single-tenant HSMs you control.
  • External key store (XKS) — keys stay in your HSM outside AWS, reached through an XKS proxy you run. Every encrypt and decrypt call goes out to your infrastructure, so if your proxy is down, AWS services cannot read the data. This is "hold your own key": maximum control, maximum availability risk.
  • Multi-Region keys — related KMS keys in several regions sharing the same key ID and key material (IDs start with mrk-). Data encrypted in one region can be decrypted in another without re-encryption, which helps disaster recovery and global tables. Each replica has its own key policy, so access must be managed per region.

AWS CloudHSM directly

CloudHSM gives you dedicated HSMs in your VPC (FIPS 140-3 Level 3 validated on current hardware). You manage the HSM users and keys; AWS cannot access or recover your keys. You need it when an application uses standard HSM interfaces directly (PKCS #11, Java JCE, Microsoft CNG), for Oracle or SQL Server transparent database encryption, for SSL/TLS offload, or when a rule demands single-tenant HSMs. Run at least two HSMs in different Availability Zones; if all are lost and you have no backup, the keys are gone.

Encryption types

Server-side encryption

AWS encrypts after receiving the data (S3 SSE-S3, SSE-KMS, DSSE-KMS for dual-layer). Simple; AWS handles keys at use time.

Client-side encryption

you encrypt before sending (the AWS Encryption SDK or S3 encryption client). AWS only ever sees ciphertext; useful when even the storage service must not see plaintext.

In practiceThe part of a key policy that decides who can use the key, and how to see what kind of key it is:

json
{ "Sid": "AllowUseOnlyViaS3InThisAccount", "Effect": "Allow",
  "Principal": { "AWS": "arn:aws:iam::123456789012:role/app-orders" },
  "Action": ["kms:Decrypt", "kms:GenerateDataKey"], "Resource": "*",
  "Condition": { "StringEquals": { "kms:ViaService": "s3.eu-west-1.amazonaws.com",
                                    "kms:EncryptionContext:aws:s3:arn": "arn:aws:s3:::acme-orders/*" } } }
console
$ aws kms describe-key --key-id alias/orders --query "KeyMetadata.{Origin:Origin,Manager:KeyManager,Spec:KeySpec,MultiRegion:MultiRegion}"
{ "Origin": "EXTERNAL", "Manager": "CUSTOMER", "Spec": "SYMMETRIC_DEFAULT", "MultiRegion": false }   ← imported (BYOK) key
📰

Real incident — Codefinger (2025). Attackers used stolen AWS access keys with S3 read and write rights to re-encrypt victims' objects with server-side encryption using customer-provided keys (SSE-C) — keys only the attacker held, which AWS never stores. They then set lifecycle rules to delete the data in seven days and demanded payment. No AWS vulnerability was involved: legitimate encryption, attacker-controlled key. Defences: deny SSE-C by bucket policy or SCP where you don't use it, require KMS, and remove long-lived keys.

Security angle

  • The key policy is the real gate. If it doesn't allow the account (arn:aws:iam::<acct>:root), IAM policies alone cannot grant use of the key. Use kms:ViaService and encryption-context conditions to limit where and why a key is used.
  • Crypto-shredding: deleting or expiring key material makes every object encrypted under it unreadable. This is a legitimate destruction method, and also a ransomware technique if an attacker gains kms:ScheduleKeyDeletion or kms:DeleteImportedKeyMaterial. Alert on both, and deny them by SCP outside a break-glass role.
  • An attacker who can edit a key policy can lock you out of your own data; protect kms:PutKeyPolicy.

Secrets, Certificates and Data Masking

What is this?

Secrets are passwords, API keys and database credentials that applications need at runtime. Certificates prove identity for TLS. Masking hides sensitive values in logs and messages from people who don't need them.

Why it matters

Hard-coded and never-rotated secrets are behind a large share of cloud breaches. A secrets manager with automatic rotation shrinks the useful life of any leak.

How it works

AWS Secrets Manager

  • Stores secrets encrypted with KMS and returns them through an IAM-authorised API call; applications fetch at runtime instead of reading a config file.
  • Rotation runs on a schedule through a Lambda function (or managed rotation for RDS, Aurora and Redshift):
1. createSecret  → generate a new password, store as version AWSPENDING
2. setSecret     → set that password on the database
3. testSecret    → log in with AWSPENDING to prove it works
4. finishSecret  → move the AWSCURRENT label to the new version
  • Single-user rotation changes one user's password (brief window where old connections fail); alternating-users rotation switches between two database users, so one is always valid.
  • Resource policies allow cross-account access; secrets can be replicated to other regions for disaster recovery.
  • Systems Manager Parameter Store SecureString is the cheaper option for configuration values but has no built-in rotation.

Certificates — ACM and AWS Private CA

AWS Certificate Manager (ACM)

issues and auto-renews public TLS certificates for load balancers, CloudFront and API Gateway.

AWS Private CA

runs a managed private certificate authority for internal TLS, mutual TLS, device identity and IAM Roles Anywhere. It can be shared across accounts with AWS RAM. A short-lived certificate mode (validity up to 7 days) avoids the need for revocation checking. Root CA keys should sit in a separate, tightly controlled account.

See certificates and PKI for how chains and revocation work.

Masking sensitive data

CloudWatch Logs data protection policies

detect sensitive data in log events using managed identifiers (credit card numbers, AWS secret keys, national IDs), mask it on display, and optionally send audit findings. Only principals with logs:Unmask see the original.

Amazon SNS message data protection

audit, de-identify (mask or redact) or deny messages containing sensitive data as they pass through a topic.

Amazon Macie

finds sensitive data already sitting in S3.

In practiceThe difference between a secret in the code and a secret fetched at runtime:

python
DB_PASSWORD = "Pr0d-Passw0rd!"                          # ✗ in git history forever

import boto3, json
secret = json.loads(boto3.client("secretsmanager").get_secret_value(SecretId="prod/orders/db")["SecretString"])
DB_PASSWORD = secret["password"]                        # ✓ IAM-controlled, logged, rotatable
📰

Real incident — Uber (2016). Attackers found AWS access keys in a private GitHub repository used by Uber engineers, used them to read an S3 backup, and took data on 57 million riders and drivers. The keys gave direct access to production data from a code repository. Secrets in code are a matter of when, not if.

📰

Real incident — Toyota T-Connect (2022). A contractor published part of Toyota's source code to a public GitHub repository, including an access key to a customer data server. It stayed public for nearly five years and exposed email addresses and customer IDs of about 296,000 customers.

🎯

On the job. Turn on secret scanning with push protection for every repository, and when a secret leaks: revoke first, investigate its use in logs second, and only then clean the history.

Security angle

  • Secrets Manager moves the risk to IAM: secretsmanager:GetSecretValue on * is a high-value permission. Scope by secret ARN or tag.
  • Watch for GetSecretValue from unusual principals or IPs; it is a common post-compromise step.
  • A private CA that issues for anything is a skeleton key; restrict who can call IssueCertificate and what templates they can use.

Integrity, Retention and Immutability

What is this?

Controls that prove data has not changed and stop anyone, including an administrator or an attacker with admin rights, from deleting it before a set date.

Why it matters

Ransomware operators delete backups before encrypting production. Regulators require records to be kept unaltered for years. Immutability is the control that survives a full account compromise.

How it works

  • S3 Versioning — every overwrite or delete keeps the old version; a delete only adds a "delete marker." It is required for Object Lock and replication.
  • S3 Object Lock — write-once-read-many (WORM) protection per object version:
    Governance mode

    blocks deletion unless the caller has s3:BypassGovernanceRetention.

    Compliance mode

    nobody, including the root user, can delete or shorten retention until the date passes.

    Legal hold

    an indefinite lock independent of retention, removed explicitly.

  • S3 Glacier Vault Lock — a vault lock policy (for example "deny delete for 7 years") that, once confirmed within a 24-hour test window, can never be changed.
  • S3 Lifecycle rules — move objects to cheaper storage classes and expire them on schedule; deletion at the right time is also a data-protection requirement. EFS lifecycle policies and FSx backup policies do the same for file systems.
  • Integrity checks — S3 checksums (CRC or SHA) on upload, CloudTrail log file validation, and code signing (AWS Signer for Lambda, which rejects unsigned deployment packages).

In practice

console
$ aws s3api put-object-retention --bucket acme-records --key 2026/ledger.csv \
    --retention '{"Mode":"COMPLIANCE","RetainUntilDate":"2033-10-11T00:00:00Z"}'
$ aws s3api delete-object --bucket acme-records --key 2026/ledger.csv --version-id 3HL4kqtJ…
An error occurred (AccessDenied) … object is WORM protected and cannot be overwritten   ← even for root

Security angle

  • Compliance mode with a long retention on a misconfigured bucket means paying to store data you cannot delete; test retention settings on a small scope first.
  • MFA Delete on versioned buckets is a weaker, older control; Object Lock is the modern answer.

Backups and Ransomware Resilience

What is this?

Copies of data that can be restored after deletion, corruption or encryption by an attacker, kept somewhere the attacker cannot reach.

Why it matters

The difference between a ransomware incident and a ransomware crisis is whether clean, untouched backups exist. See also business continuity and disaster recovery.

How it works

AWS Backup

central backup plans (schedule, retention, copy rules) across EBS, EC2, RDS, Aurora, DynamoDB, EFS, FSx, S3 and more, applied by tag and enforced organisation-wide through backup policies.

Backup Vault Lock

WORM protection for a backup vault. In compliance mode, after a short grace period, nobody can delete recovery points or change the lock.

Logically air-gapped vaults

vaults owned by an AWS service account and shared to yours, so even a compromised account cannot delete the copies.

Cross-account and cross-region copies

the classic pattern is copying to a separate backup account whose credentials production never holds.

Restore testing

scheduled automatic restores to prove recovery points actually work.

Amazon Data Lifecycle Manager

automates EBS snapshot and AMI creation and expiry.

AWS DataSync

moves data between on-prem storage and AWS (and between AWS storage services) with encryption in transit and integrity verification.

Ransomware-resilient pattern
Prod account ──backup plan──► local vault ──copy──► Backup account vault (Vault Lock: compliance)
                                                      │  separate credentials, SCP denies
                                                      │  backup:DeleteRecoveryPoint
                                                      └► restore testing monthly

Security angle

Backups inherit the encryption key: if the key is in the compromised account and the attacker deletes it, the backups are unreadable. Use a key owned by the backup account for the copied recovery points.


Encryption in Transit

What is this?

Making sure data moving between clients, load balancers, services and networks is encrypted and authenticated, and that unencrypted connections are refused rather than merely discouraged.

Why it matters

"Encrypt in transit" is only true if plaintext is impossible. Most failures are a single listener or bucket that still accepts HTTP.

How it works

Load balancers

HTTPS and TLS listeners use an ELB security policy that sets the allowed TLS versions and ciphers; choose a TLS 1.3/1.2 forward-secrecy policy and redirect port 80 to 443. ALB supports mutual TLS (verify client certificates against a trust store). NLB can terminate TLS or pass it through.

Requiring TLS on services

an S3 bucket policy (or an RCP) denying requests where aws:SecureTransport is false; rds.force_ssl for PostgreSQL, require_secure_transport for MySQL.

Private paths

VPC endpoints and AWS PrivateLink keep traffic to AWS services and partner services off the internet; endpoint policies limit what can be reached. See VPC endpoint policies.

Between instances

Nitro-based instance types automatically encrypt traffic between supported instances in the same or peered VPCs at the hardware level.

Inside clusters

EKS has no built-in pod-to-pod encryption, so use a service mesh with mutual TLS or encrypted CNI options; EMR enables in-transit encryption through a security configuration with TLS certificates; SageMaker AI can encrypt inter-container traffic for distributed training.

Remote and hybrid

Client VPN, Site-to-Site VPN and MACsec; see hybrid connectivity.

Security angle

TLS termination at a load balancer means traffic from the load balancer to the target may be plaintext; re-encrypt to the target if the data class requires end-to-end encryption.


Interview Questions

Q
When would you choose CloudHSM over KMS?
Model answer

Only when a requirement forces it, because KMS is far less work. Typical triggers are a rule demanding single-tenant HSMs under your exclusive control, applications that talk PKCS #11, JCE or CNG directly, database transparent encryption for Oracle or SQL Server, or TLS offload. The catch is that AWS can't recover CloudHSM keys, so you own clustering across Availability Zones and backups — lose them and the data is gone.

Q
What's the difference between imported key material and AWS-generated key material in KMS?
Model answer

With imported material you generate the key yourself and upload it, so you can set an expiry and delete the material instantly, making the data unreadable at once — whereas AWS-generated keys only support scheduled deletion after a 7 to 30 day wait. The trade-off is durability: you must keep a secure copy, and there's no automatic rotation — you import new material and trigger an on-demand rotation, which keeps the same key ARN. People choose it to prove key provenance or to have an instant kill switch.

Q
What is an external key store and what's the risk?
Model answer

An external key store keeps KMS keys in your own HSM outside AWS, reached through a proxy you run, so AWS services still use the KMS API but every encrypt and decrypt goes out to your hardware. It gives you a hard technical guarantee that AWS can't decrypt without you. The risk is availability and latency: if your proxy or HSM is down, every service using that key stops being able to read its data.

Q
How do you make backups survive a full account compromise?
Model answer

Copy recovery points to a separate backup account whose credentials production never holds, put that vault under AWS Backup Vault Lock in compliance mode so nobody, root included, can delete them early, and encrypt copies with a key owned by the backup account. Logically air-gapped vaults go further by keeping ownership with an AWS service account. Then run scheduled restore tests, because an untested backup is a hope, not a control.

Q
Explain S3 Object Lock governance mode versus compliance mode.
Model answer

Both are write-once-read-many locks on object versions until a retention date. In governance mode, principals with the bypass-governance permission can still delete or shorten retention, which is useful for testing or internal policy. In compliance mode nobody can, not even the root user, until the date passes, which is what regulators and ransomware resilience need. Legal hold is separate: an indefinite lock you remove explicitly.

Q
How does Secrets Manager rotate a database password without an outage?
Model answer

A rotation Lambda creates a new password as a pending version, sets it on the database, tests a login with it, and only then moves the current label to the new version. Using the alternating-users strategy, it switches between two database users so one valid credential always exists while applications pick up the new value. Applications fetch the secret at runtime rather than caching it forever, which is what makes rotation safe.

Q
How do you enforce encryption in transit for an S3 bucket and a load balancer?
Model answer

For S3, a bucket policy — or organisation-wide, an RCP — that denies any request where aws:SecureTransport is false, so plain HTTP is refused, not just discouraged. For the load balancer, only HTTPS or TLS listeners with a modern TLS 1.3/1.2 security policy, and an HTTP listener that does nothing but redirect to HTTPS. If the data class needs end-to-end encryption I'd also re-encrypt from the load balancer to the targets.

Q
Why is kms:ScheduleKeyDeletion a high-risk permission?
Model answer

Because deleting a key crypto-shreds every object, volume and backup encrypted under it, so it's a destruction and ransomware primitive. I'd deny it and DeleteImportedKeyMaterial by SCP outside a break-glass role, alert on any attempt through CloudTrail, and keep the 30-day maximum waiting period so there's time to cancel. The same applies to PutKeyPolicy, which an attacker can use to lock you out of your own key.