🛡️ Security & Compliance#

Learning Objectives#

  • Implement encryption with KMS and CloudHSM
  • Protect applications with WAF, Shield, and GuardDuty
  • Audit with CloudTrail, Config, and Inspector
  • Manage secrets with Secrets Manager and Parameter Store

1. AWS KMS (Key Management Service)#

1.1 KMS Overview#

KMS is a managed service for creating and controlling encryption keys.

                    ┌────────────────────────────┐
                    │        AWS KMS              │
                    │                            │
                    │  Customer Master Keys (CMK) │
                    │  ┌──────────────────────┐  │
                    │  │ AWS Managed Keys     │  │
                    │  │ (aws/s3, aws/ebs)    │  │
                    │  └──────────────────────┘  │
                    │  ┌──────────────────────┐  │
                    │  │ Customer Managed Keys│  │
                    │  │ (automatic rotation) │  │
                    │  └──────────────────────┘  │
                    │  ┌──────────────────────┐  │
                    │  │ Custom Key Store     │  │
                    │  │ (CloudHSM backed)    │  │
                    │  └──────────────────────┘  │
                    └────────────────────────────┘

1.2 KMS Key Types#

Key Type Managed By Auto Rotation Use Case
AWS Managed AWS Yes (every 3 years) Default encryption (S3, RDS, EBS)
Customer Managed You Optional (1 year) Control over keys and policies
Custom Key Store You (via CloudHSM) No FIPS 140-2 Level 3 compliance

1.3 KMS Operations#

# Create a customer managed key
aws kms create-key \
  --description "EBS encryption key for production" \
  --key-usage ENCRYPT_DECRYPT \
  --origin AWS_KMS

# Create key alias
aws kms create-alias \
  --alias-name alias/ebs-production \
  --target-key-id abcdef01-1234-5678-9abc-def012345678

# Encrypt data (up to 1 MB directly — use envelope encryption for larger)
aws kms encrypt \
  --key-id alias/ebs-production \
  --plaintext fileb://my-secret.txt \
  --output text \
  --query CiphertextBlob | base64 --decode > my-secret-encrypted.txt

# Decrypt data
aws kms decrypt \
  --ciphertext-blob fileb://my-secret-encrypted.txt \
  --output text \
  --query Plaintext | base64 --decode > my-secret-decrypted.txt

1.4 Envelope Encryption#

For data larger than 1 MB, KMS uses envelope encryption:

1. Generate a data key (DEK) using KMS
2. Encrypt data with DEK (locally)
3. Store encrypted DEK alongside encrypted data
4. To decrypt: KMS decrypts DEK → use DEK to decrypt data

aws kms generate-data-key \
  --key-id alias/ebs-production \
  --key-spec AES_256 \
  --output text \
  --query 'CiphertextBlob' > encrypted-data-key.bin

# Use plaintext data key to encrypt locally using OpenSSL

Exam Tip: KMS cannot encrypt data > 1 MB directly. Use envelope encryption or S3 client-side encryption for larger data.

1.5 KMS Key Policies vs IAM Policies#

{"Version": "2012-10-17",
  "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:role/Developers" },
      "Action": "kms:Decrypt",
      "Resource": "*",
      "Condition": {"Bool": { "kms:GrantIsForAWSResource": "true" }
      }
    }
  ]
}

IAM policies alone cannot grant KMS access — the key policy must also allow it.


2. AWS Secrets Manager vs Parameter Store#

Feature Secrets Manager Parameter Store (Standard)
Max secret size 64 KB 4 KB (standard) / 8 KB (advanced)
Auto-rotation Yes (with Lambda) No
Cross-account Yes Yes (advanced tier)
Price $0.40/secret/month + rotation Free (standard), $0.05/param/month (advanced)
Use Case DB passwords, API keys App config, feature flags
# Store a secret
aws secretsmanager create-secret \
  --name prod/db-password \
  --secret-string '{"username":"admin","password":"MyP@ssword!"}'

# Store a parameter
aws ssm put-parameter \
  --name /app/prod/db-url \
  --value "postgresql://prod-db.example.com:5432/app" \
  --type SecureString \
  --key-id alias/ssm-key

# Retrieve (auto-decrypts SecureString)
aws ssm get-parameter \
  --name /app/prod/db-url \
  --with-decryption \
  --query 'Parameter.Value' \
  --output text

3. AWS Shield & WAF#

(See also Chapter 09 for WAF details)

3.1 Shield Advanced Features#

  • DDoS cost protection — Get credits for scale events
  • Real-time visibility — CloudWatch metrics for attacks
  • DDoS Response Team (DRT) — 24/7 access to AWS experts
  • Health-based detection — Route53 health check integration

3.2 WAF Rate Limiting#

aws wafv2 create-rule-group \
  --name "rate-limit-rules" \
  --scope CLOUDFRONT \
  --capacity 10 \
  --rules '[
    {"Name": "rate-limit",
      "Priority": 0,
      "Statement": { "RateBasedStatement": { "Limit": 2000, "AggregateKeyType": "IP", "EvaluationWindowSec": 120 }
      },
      "Action": {"Block": {}},
      "VisibilityConfig": {"SampledRequestsEnabled": true, "CloudWatchMetricsEnabled": true, "MetricName": "rateLimitRule" }
    }
  ]'

4. GuardDuty, Inspector & Macie#

4.1 Amazon GuardDuty#

Intelligent threat detection using ML and anomaly detection:

  • Analyzes CloudTrail logs, VPC Flow Logs, DNS logs
  • Detects: Port scanning, crypto mining, unusual API calls
  • Automatically generates findings in Security Hub
# Enable GuardDuty
aws guardduty create-detector --enable

4.2 Amazon Inspector#

Automated vulnerability assessment:

  • Scans EC2 for OS vulnerabilities (CVEs)
  • Scans container images in ECR
  • Continuous scanning with AWS Systems Manager integration

4.3 Amazon Macie#

Data discovery and classification for S3:

  • Uses ML to identify sensitive data (PII, financial data)
  • Generates findings when sensitive data is exposed

5. AWS Config & CloudTrail#

Service Purpose
CloudTrail Audit API calls (who did what, when)
Config Track resource configuration changes

Config Rules Example:

# Enable AWS-managed Config rule
aws configservice put-config-rule \
  --config-rule '{"ConfigRuleName": "s3-bucket-public-read-prohibited", "Source": { "Owner": "AWS", "SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED" },
    "Scope": {"ComplianceResourceTypes": ["AWS::S3::Bucket"] }
  }'

6. Real-World Use Cases#

Use Case 1: Encryption Strategy for a Healthcare Application (HIPAA)#

Scenario: A healthcare SaaS company stores patient records (PII/PHI) and must comply with HIPAA. Data must be encrypted at rest AND in transit. They need to audit who accessed what and when.

Solution: Defense-in-Depth Encryption

graph TD
    Patient["Patient Data"] --> TLS["TLS 1.3 Encryption\nin Transit"]
    TLS --> ALB["ALB (TLS Termination)\nACM Certificate"]
    ALB --> EC2["EC2 App Servers\nIAM Role: kms:Decrypt"]
    
    subgraph Storage["Storage Encryption"]
        EBS["EBS Volumes\nSSE-KMS (Customer Key)"]
        S3["S3 Patient Records\nSSE-KMS + Block Public Access"]
        RDS["RDS Database\nEncrypted at rest (KMS)\nEncrypted in transit (SSL)"]
    end
    
    EC2 --> EBS
    EC2 --> S3
    EC2 --> RDS
    
    subgraph Audit["Auditing"]
        CT["CloudTrail\nLogs all KMS API calls"]
        Config["AWS Config\nMonitors encryption settings"]
    end
    
    KMS["KMS Customer Managed Key\nAuto-rotation: 1 year"] ---> EBS
    KMS ---> S3
    KMS ---> RDS
    
    CT -.->|Who decrypted data?| Config

Key implementation details:

# Step 1: Create a customer managed KMS key with yearly rotation
aws kms create-key --description "HIPAA Patient Data Key"
aws kms enable-key-rotation --key-id alias/hipaa-key

# Step 2: Encrypt RDS with this KMS key
aws rds create-db-instance \
  --db-instance-identifier patient-db \
  --engine aurora-postgresql \
  --storage-encrypted \
  --kms-key-id alias/hipaa-key \
  --enable-iam-database-authentication

# Step 3: Force SSL connections (in-transit encryption)
aws rds modify-db-instance \
  --db-instance-identifier patient-db \
  --cloudwatch-logs-export-configuration '{"EnableLogTypes":["postgresql"]}'

Compliance checklist:

Requirement Implementation
Encryption at rest SSE-KMS for S3, EBS, RDS
Encryption in transit TLS 1.2+ via ALB/CloudFront
Access audit CloudTrail + KMS key usage logging
Key rotation KMS auto-rotation (annual)
Data classification Macie for S3 PII detection

Use Case 2: Incident Response with GuardDuty + Security Hub#

Scenario: A fintech startup needs real-time threat detection and automated response across 5 AWS accounts. When a potential compromise is detected, they want to automatically isolate the affected resource and notify the security team.

Solution: Automated Security Orchestration

graph LR
    subgraph Sources["Threat Detection"]
        GD["GuardDuty\nML-based threat detection"]
        Inspector["Inspector\nVulnerability scanning"]
    end
    
    subgraph Central["Central Security"]
        SH["Security Hub\nAggregate findings"]
        DETECTIVE["Detective\nRoot cause analysis"]
    end
    
    subgraph Response["Automated Response"]
        EB["EventBridge\nMatch finding patterns"]
        Lambda_Resp["Lambda\nIsolate compromised resource"]
        SNS["SNS\nNotify security team"]
    end
    
    Sources --> SH
    SH --> DETECTIVE
    SH --> EB
    EB --> Lambda_Resp
    EB --> SNS

Automated isolation workflow:

# EventBridge rule to catch GuardDuty findings
aws events put-rule \
  --name "guardduty-automation" \
  --event-pattern '{"source": ["aws.guardduty"], "detail-type": ["GuardDuty Finding"], "detail": { "severity": [4.0, 4.1, 4.2, 4.3, 5.0, 7.0, 7.1, 7.2, 7.3, 7.4, 7.5, 8.0, 8.1, 8.2, 8.3, 8.4, 8.5] }
  }'

# Lambda function modifies security group to isolate instance
def lambda_handler(event, context):
    instance_id = event['detail']['resource']['instanceDetails']['instanceId']
    ec2 = boto3.client('ec2')
    
    # Create isolation security group (deny all)
    sg = ec2.create_security_group(
        GroupName=f'isolated-{instance_id}',
        Description='Isolation group for compromised instance'
    )
    
    # Replace instance's security groups
    ec2.modify_instance_attribute(
        InstanceId=instance_id,
        Groups=[sg['GroupId']]
    )

Use Case 3: Secrets Rotation for Database Passwords#

Scenario: A company policy requires database passwords to be rotated every 30 days. The app runs on ECS Fargate and connects to RDS PostgreSQL.

Solution: Secrets Manager + Lambda Rotation

sequenceDiagram
    participant Lambda as Rotation Lambda
    participant SM as Secrets Manager
    participant RDS as RDS PostgreSQL
    participant ECS as ECS Fargate
    
    Note over SM: Rotation schedule: 30 days
    SM->>Lambda: Invoke rotation function
    Lambda->>SM: Create pending secret (new password)
    Lambda->>RDS: ALTER USER app_user PASSWORD 'new_password'
    RDS->>Lambda: Password updated
    Lambda->>SM: Test new password (app login)
    Lambda->>SM: Mark secret as current
    
    Note over ECS,SM: App retrieves latest secret
    ECS->>SM: GetSecretValue (auto-refresh)
    SM->>ECS: Current password
    ECS->>RDS: Connect with new password
# Create secret with automatic rotation
aws secretsmanager create-secret \
  --name prod/rds/password \
  --secret-string '{"username":"app_user","password":"InitialP@ss1"}' \
  --rotation-rules '{"AutomaticallyRotateAfterDays": 30}'

Takeaway: Secrets Manager + Lambda handles the entire rotation lifecycle — creates new password, updates the database, tests connectivity, and marks as current — all without application downtime.


✅ Chapter Quiz#

  1. What is the maximum data size KMS can encrypt directly?

    • A) 64 KB
    • B) 256 KB
    • C) 1 MB
    • D) 5 MB
  2. Which service automatically rotates secrets?

    • A) Parameter Store
    • B) Secrets Manager
    • C) KMS
    • D) Systems Manager
  3. Which service provides intelligent threat detection using ML?

    • A) Inspector
    • B) GuardDuty
    • C) Config
    • D) Macie
  4. Which service would you use to track who deleted an S3 bucket at 3 AM?

    • A) Config
    • B) CloudTrail
    • C) GuardDuty
    • D) CloudWatch
  5. What is required in addition to IAM policies to access a KMS key?

    • A) SCP
    • B) Key policy
    • C) Permission boundary
    • D) Resource tag
  6. Which AWS service automatically discovers and classifies sensitive data stored in S3?

    • A) GuardDuty
    • B) Macie
    • C) Inspector
    • D) Detective
  7. A company needs to enforce that all S3 buckets are encrypted with a specific KMS key. Which AWS Config rule should be used?

    • A) s3-bucket-server-side-encryption-enabled
    • B) s3-bucket-policy-grantee-check
    • C) s3-bucket-ssl-requests-only
    • D) s3-bucket-public-read-prohibited
  8. What is the purpose of AWS Shield Advanced?

    • A) To block SQL injection attacks
    • B) To provide enhanced DDoS protection with 24/7 access to AWS DRT
    • C) To scan EC2 instances for vulnerabilities
    • D) To monitor S3 for sensitive data
  9. Which service provides a managed Microsoft Active Directory in the AWS cloud?

    • A) IAM
    • B) Cognito
    • C) Directory Service for Microsoft AD
    • D) SSO
  10. A company wants to centrally manage access to multiple AWS accounts. Which service should they use?

    • A) IAM
    • B) AWS Organizations with SCPs
    • C) RAM
    • D) Cognito
  11. What is the purpose of AWS Artifact?

    • A) To store encrypted secrets
    • B) To provide on-demand access to AWS compliance reports
    • C) To manage SSL/TLS certificates
    • D) To analyze IAM permissions
  12. Which AWS service allows you to create a private CA for issuing certificates?

    • A) ACM
    • B) ACM Private CA
    • C) KMS
    • D) CloudHSM
  13. A company needs to store database credentials with automatic rotation every 30 days. Which service should they use?

    • A) Parameter Store
    • B) Systems Manager
    • C) Secrets Manager
    • D) KMS
  14. Which feature of CloudTrail detects unusual API activity patterns?

    • A) Management Events
    • B) Data Events
    • C) Insights Events
    • D) CloudWatch Logs
  15. What does AWS WAF use to inspect and filter web traffic?

    • A) Security groups
    • B) Web ACLs
    • C) Network ACLs
    • D) VPC Flow Logs
  16. A company needs to scan container images in ECR for known vulnerabilities. Which service should they use?

    • A) GuardDuty
    • B) Inspector
    • C) Macie
    • D) Security Hub
  17. What is the purpose of a KMS Customer Master Key?

    • A) To encrypt data up to 1 MB directly
    • B) To generate, encrypt, and decrypt data keys
    • C) To store passwords
    • D) To manage SSL certificates
  18. Which AWS service aggregates security findings from GuardDuty, Inspector, and Macie?

    • A) CloudWatch
    • B) EventBridge
    • C) Security Hub
    • D) Config
  19. A company wants to receive alerts when an IAM user is created in their account. Which service should they use?

    • A) CloudWatch
    • B) CloudTrail with CloudWatch Logs
    • C) Config
    • D) GuardDuty
  20. What is the difference between a customer managed key and an AWS managed key in KMS?

    • A) AWS managed keys support automatic rotation, customer managed keys do not
    • B) Customer managed keys support optional yearly rotation and customizable key policies
    • C) AWS managed keys can be deleted, customer managed keys cannot
    • D) Customer managed keys are free, AWS managed keys cost extra
  21. Which AWS service helps you review and refine IAM permissions by identifying unused access?

    • A) IAM Access Analyzer
    • B) Trusted Advisor
    • C) CloudTrail
    • D) Config
  22. What is the purpose of an IAM permissions boundary?

    • A) To grant permissions to a user
    • B) To set the maximum permissions an IAM entity can have
    • C) To deny specific actions
    • D) To enforce MFA
  23. A company needs to encrypt data at rest on an EBS volume. Which KMS key type should be used?

    • A) AWS managed key for EBS
    • B) Customer managed key
    • C) Custom key store backed by CloudHSM
    • D) Any of the above
  24. Which AWS service provides managed threat detection that analyzes VPC Flow Logs, CloudTrail logs, and DNS logs?

    • A) Inspector
    • B) GuardDuty
    • C) Macie
    • D) Detective
  25. A company needs to enforce that MFA is required for all IAM users accessing the AWS console. Which type of policy should be used?

    • A) Identity-based policy
    • B) Resource-based policy
    • C) Service control policy
    • D) IAM policy with a condition for MFA
📝 Answer Key
  1. C — KMS encrypts up to 1 MB directly. Use envelope encryption beyond that.
  2. B — Secrets Manager supports automatic rotation with Lambda.
  3. B — GuardDuty uses ML for intelligent threat detection.
  4. B — CloudTrail records all API calls (who, what, when).
  5. B — Key policy must grant access; IAM alone is insufficient.
  6. B — Macie uses ML to automatically discover and classify sensitive data in S3.
  7. A — The s3-bucket-server-side-encryption-enabled Config rule enforces S3 encryption.
  8. B — Shield Advanced provides enhanced DDoS protection with 24/7 access to the DDoS Response Team.
  9. C — Directory Service for Microsoft AD provides managed Active Directory in AWS.
  10. B — AWS Organizations with SCPs centrally manages permissions across multiple accounts.
  11. B — AWS Artifact provides on-demand access to AWS compliance reports and agreements.
  12. B — ACM Private CA allows creating private certificate authorities for internal use.
  13. C — Secrets Manager supports automatic secret rotation with Lambda integration.
  14. C — CloudTrail Insights uses ML to detect unusual API activity patterns.
  15. B — WAF uses Web ACLs to inspect and filter HTTP/HTTPS traffic.
  16. B — Amazon Inspector scans ECR container images for software vulnerabilities.
  17. B — A CMK is used to generate, encrypt, and decrypt data keys (envelope encryption).
  18. C — Security Hub aggregates and prioritizes security findings from multiple AWS services.
  19. B — CloudTrail sends API events to CloudWatch Logs, which can trigger alarms on IAM user creation.
  20. B — Customer managed keys support customizable key policies and optional annual rotation.
  21. A — IAM Access Analyzer helps identify resources shared with external principals and unused access.
  22. B — A permissions boundary sets the maximum permissions an IAM entity can receive.
  23. D — Any KMS key type can encrypt EBS volumes, including AWS managed or customer managed keys.
  24. B — GuardDuty uses threat intelligence and ML to analyze VPC Flow Logs, CloudTrail, and DNS logs.
  25. D — An IAM policy with a condition key like aws:MultiFactorAuthPresent enforces MFA.

📚 Additional Resources#

Next → Monitoring & Observability