Intermediate

AWS Security and Compliance Fundamentals

IAM in depth, Shield and WAF, threat detection, encryption, audit tooling and layered security.

Table of Contents

  1. Module 1 — Security Concepts and Terminology
  2. Module 2 — AWS IAM In Depth
  3. Module 3 — AWS Shield and WAF
  4. Module 4 — Threat Detection Services
  5. Module 5 — Encryption and Secrets Management
  6. Module 6 — Audit and Monitoring Tools
  7. Module 7 — Demo: CloudTrail and S3 Access Logs
  8. Module 8 — AWS Compliance
  9. Module 9 — Layered Security Architecture
  10. Module 10 — Summary and Key Takeaways

Module 1 — Security Concepts and Terminology

Cloud security is not fundamentally different from physical security: the goal is to protect your assets as effectively as possible. AWS provides a comprehensive set of tools to help you secure your environment.

Before diving into the toolset, it is important to become familiar with the fundamental acronyms used across the cloud security domain.


1.1 Essential Security Acronyms

MFA  → Multi-Factor Authentication
IAM  → Identity Access Management
VPN  → Virtual Private Network
DDoS → Distributed Denial of Service
SSO  → Single Sign-On
GRC  → Governance, Risk and Compliance

1.2 MFA — Multi-Factor Authentication

MFA is a security mechanism that strengthens the authentication process: even a strong password alone may not provide sufficient protection.

With MFA, the user must supply a second verification step in addition to their password.

TypeExampleSecurity Level
TOTP codeGoogle Authenticator, Authy (rotating code)High
Passkey / Security key (FIDO2)YubiKey — phishing-resistantVery High
BiometricFingerprint, Face IDHigh
Secret questionMemorized answerLow
Physical cardCAC (Common Access Card)High

AWS Best Practice: Enable MFA on the root account and all privileged IAM accounts. AWS recommends FIDO2 passkeys as the top priority (phishing-resistant).


1.3 IAM — Identity Access Management

IAM is the service that lets you control who can access what within your AWS environment. It manages users, groups, roles, and policies.

flowchart LR
    User["User / Application"]
    IAM["IAM\n(Identity Access Management)"]
    S3["Amazon S3"]
    EC2["Amazon EC2"]
    RDS["Amazon RDS"]

    User -->|"Authentication\n+ Authorization"| IAM
    IAM -->|"Allow / Deny"| S3
    IAM -->|"Allow / Deny"| EC2
    IAM -->|"Allow / Deny"| RDS

1.4 VPN — Virtual Private Network

A VPN creates an encrypted tunnel between a device and a private network, protecting communications over public connections.

Concrete example: Alex works at a coffee shop and uses their employer’s VPN to connect to internal resources — no one on the public Wi-Fi can intercept the data.

Related AWS services:

  • AWS Site-to-Site VPN: connects an on-premises network to a VPC
  • AWS Client VPN: secure individual access for remote users
  • AWS Direct Connect: dedicated physical connection (non-VPN) between on-premises and AWS

1.5 DDoS — Distributed Denial of Service

A DDoS attack aims to make your resources unavailable by flooding them with inbound traffic.

OSI LayerNumberAttack TypeExample
NetworkLayer 3VolumetricUDP Flood, ICMP Flood
TransportLayer 4ProtocolSYN Flood, TCP exhaustion
ApplicationLayer 7Application-levelHTTP Flood, DNS query flood

The machines in a botnet participating in an attack are typically unaware they are doing so.


1.6 SSO — Single Sign-On

SSO allows a user to authenticate once and gain access to multiple applications.

flowchart TD
    User["User"]
    SSO["SSO Provider\n(AWS IAM Identity Center)"]
    MFA_Check{"MFA\nVerified?"}
    App1["AWS Console"]
    App2["Salesforce"]
    App3["Slack"]
    Denied["Access Denied"]

    User -->|"Single login"| SSO
    SSO --> MFA_Check
    MFA_Check -->|"Yes"| App1
    MFA_Check -->|"Yes"| App2
    MFA_Check -->|"Yes"| App3
    MFA_Check -->|"No"| Denied

Warning: Always pair SSO with MFA. A single compromised set of credentials gives access to every connected application.


1.7 GRC — Governance, Risk and Compliance

GRC: “an integrated set of capabilities that enable an organization to achieve its objectives, manage uncertainty, and act with integrity.”

PillarDescription
GovernanceExecutive leadership (C-suite) that drives direction through hierarchical structures
Risk ManagementIdentifying, analyzing, and responding to business risks
ComplianceInternal and external standards that must be met to avoid penalties

Module 2 — AWS IAM In Depth

2.1 IAM Components

ComponentDescriptionUse Case
IAM UserPermanent identity with credentialsA developer’s personal account
IAM GroupCollection of users sharing the same policies”Developers” or “Admins” group
IAM RoleTemporary identity assumed by an entityEC2 accessing S3, Lambda accessing DynamoDB
IAM PolicyJSON document defining permissionsAllow s3:GetObject on a bucket
flowchart TD
    subgraph IAM["AWS IAM"]
        UserA["IAM User\n(Bob)"]
        Group["IAM Group\n(Developers)"]
        Role["IAM Role\n(EC2-S3-ReadRole)"]
        PolicyGroup["Customer Managed Policy\n(attached to group)"]
        PolicyRole["Role Policy"]
    end

    UserA -->|"member of"| Group
    Group --> PolicyGroup
    Role --> PolicyRole

    EC2["Amazon EC2"] -->|"assumes"| Role
    Lambda["AWS Lambda"] -->|"assumes"| Role

2.2 IAM Policy Types

TypeManaged ByUse Case
AWS Managed PolicyAWSStarting point (AdministratorAccess, ReadOnlyAccess)
Customer Managed PolicyYouReusable, custom-built policies
Inline PolicyEmbedded in 1 entityEntity-specific, non-shareable policy
Service Control Policy (SCP)AWS OrganizationsGuardrails at account/OU level
Resource Control Policy (RCP)AWS OrganizationsResource-level control across the org
Permissions BoundaryDelegated adminLimit the maximum permissions of a role
Session PolicyTemporary (STS)Restrict permissions during AssumeRole

2.3 IAM Policy JSON Structure

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OptionalStatementIdentifier",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:role/MyRole"
      },
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::my-data-bucket/*"
      ],
      "Condition": {
        "StringEquals": {
          "s3:prefix": ["uploads/", "reports/"]
        },
        "Bool": {
          "aws:SecureTransport": "true"
        }
      }
    }
  ]
}

Key elements:

ElementRequiredDescription
VersionYesAlways "2012-10-17"
StatementYesArray of statements
EffectYes"Allow" or "Deny"
PrincipalFor resource policiesWho benefits from the policy
ActionYesAWS action(s) allowed or denied
ResourceYesARN of the targeted resource(s)
ConditionNoOptional contextual conditions

Evaluation rule: An explicit Deny always overrides an Allow. Without an Allow, everything is implicitly Denied.


2.4 IAM Policy Examples

Read-only policy on a specific S3 bucket

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "S3ReadOnlyAccess",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:GetObjectVersion",
        "s3:ListBucket",
        "s3:GetBucketLocation"
      ],
      "Resource": [
        "arn:aws:s3:::my-analytics-bucket",
        "arn:aws:s3:::my-analytics-bucket/*"
      ]
    }
  ]
}

Conditional policy — enforce MFA and HTTPS

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyWithoutMFA",
      "Effect": "Deny",
      "Action": "*",
      "Resource": "*",
      "Condition": {
        "BoolIfExists": {
          "aws:MultiFactorAuthPresent": "false"
        }
      }
    },
    {
      "Sid": "DenyHTTP",
      "Effect": "Deny",
      "Action": "*",
      "Resource": "*",
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      }
    }
  ]
}

EC2 role policy for Secrets Manager + CloudWatch access

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "SecretsManagerAccess",
      "Effect": "Allow",
      "Action": [
        "secretsmanager:GetSecretValue",
        "secretsmanager:DescribeSecret"
      ],
      "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/*"
    },
    {
      "Sid": "KMSDecryptForSecrets",
      "Effect": "Allow",
      "Action": "kms:Decrypt",
      "Resource": "arn:aws:kms:us-east-1:123456789012:key/mrk-xyz789"
    },
    {
      "Sid": "CloudWatchLogs",
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    }
  ]
}

Service Control Policy (SCP) — protect CloudTrail and Organizations

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyLeaveOrganization",
      "Effect": "Deny",
      "Action": ["organizations:LeaveOrganization"],
      "Resource": "*"
    },
    {
      "Sid": "DenyDisableCloudTrail",
      "Effect": "Deny",
      "Action": [
        "cloudtrail:StopLogging",
        "cloudtrail:DeleteTrail",
        "cloudtrail:UpdateTrail"
      ],
      "Resource": "*"
    }
  ]
}

2.5 IAM Best Practices

According to the official AWS documentation:

  1. Use federation for human users — AWS IAM Identity Center with temporary credentials; do not create IAM Users for humans.
  2. IAM Roles for workloads — EC2, Lambda, ECS should use roles (auto-rotating temporary credentials), never hardcoded access keys.
  3. Mandatory MFA — Prioritize passkeys/FIDO2 security keys (phishing-resistant).
  4. Principle of least privilege — Grant only the minimum necessary. Refine permissions incrementally.
  5. Protect the root account — Never use root for day-to-day tasks. Enable MFA. No root access keys.
  6. Regular review — Remove unused users, roles, policies, and credentials using the “last accessed” report.
  7. Conditions in policies — Restrict by IP, time, tag, region, or MFA status.
  8. SCPs and RCPs for multi-account — Use AWS Organizations to enforce organizational guardrails.
  9. Permissions Boundaries — Delegate permission management while capping the maximum allowed scope.
flowchart TB
    BP1["Federation\nIAM Identity Center"]
    BP2["IAM Roles\nfor workloads"]
    BP3["Mandatory\nFIDO2 MFA"]
    BP4["Least Privilege\nPrinciple"]
    BP5["Protected\nRoot Account"]
    BP6["Regular\nReview"]
    BP7["Conditions\nin Policies"]
    BP8["SCPs/RCPs\nMulti-account"]

    Security["Optimal IAM\nSecurity Posture"]

    BP1 & BP2 & BP3 & BP4 --> Security
    BP5 & BP6 & BP7 & BP8 --> Security

2.6 IAM Access Analyzer

FeatureDescription
External access findingsResources accessible from outside the organization
Unused access findingsUsers, roles, and permissions that are not being used
Policy validationSyntax and best practice checks (100+ rules)
Policy generationLeast-privilege policy based on CloudTrail activity
# Create an analyzer
aws accessanalyzer create-analyzer \
  --analyzer-name my-org-analyzer \
  --type ORGANIZATION

# List findings
aws accessanalyzer list-findings \
  --analyzer-arn arn:aws:access-analyzer:us-east-1:123456789012:analyzer/my-org-analyzer

Module 3 — AWS Shield and WAF

3.1 AWS Shield Standard vs Advanced

AWS Shield is AWS’s DDoS protection service.

FeatureStandardAdvanced
CostFree~$3,000/month + data transfer
ActivationAutomaticManual (opt-in)
L3/L4 Protection
L7 Protection✅ (via integrated WAF)
Custom detection
Zero-day protectionPartial
Shield Response Team (SRT) access
Financial protections (DDoS credits)
Visibility and reportingLimitedFull
flowchart LR
    Internet["Internet\n(Malicious Traffic)"]
    Shield_Std["Shield Standard\n(Layer 3/4 — Free)"]
    Shield_Adv["Shield Advanced\n(Layer 3/4/7 — $3000/mo)"]
    WAF_node["AWS WAF\n(Layer 7)"]
    Resources["AWS Resources\n(EC2, ALB, CloudFront)"]

    Internet --> Shield_Std
    Shield_Std -->|"Filtered traffic"| Resources
    Internet --> Shield_Adv
    Shield_Adv -->|"+ Integrated WAF"| WAF_node
    WAF_node --> Resources

3.2 AWS WAF — Web Application Firewall

AWS WAF is an application firewall (Layer 7) that protects against common web attacks.

ThreatWAF Mechanism
SQL InjectionRules detecting malicious SQL patterns
Cross-Site Scripting (XSS)Filtering injected scripts
Malicious botBot Control managed rule group
Bad IPsIP sets and geo-restriction
Rate limitingRate-based rules (requests per IP)
OWASP Top 10AWS Managed Rules for OWASP
flowchart LR
    Client["HTTP/HTTPS Client"]
    CF["CloudFront / ALB\n/ API Gateway"]
    WAF_acl["AWS WAF\nWeb ACL"]
    Rules["Rule Groups:\n- AWS Managed Rules\n- Custom Rules\n- IP Sets"]
    Actions["Actions:\n- Allow\n- Block\n- Count\n- CAPTCHA"]
    Origin["Web Application"]

    Client --> CF
    CF --> WAF_acl
    WAF_acl --> Rules
    Rules --> Actions
    WAF_acl -->|"Allowed traffic"| Origin
# Create a WAF Web ACL with OWASP managed rules
aws wafv2 create-web-acl \
  --name "ProdWebACL" \
  --scope REGIONAL \
  --default-action Allow={} \
  --rules '[{
    "Name": "AWSManagedRulesCommonRuleSet",
    "Priority": 1,
    "OverrideAction": {"None": {}},
    "Statement": {
      "ManagedRuleGroupStatement": {
        "VendorName": "AWS",
        "Name": "AWSManagedRulesCommonRuleSet"
      }
    },
    "VisibilityConfig": {
      "SampledRequestsEnabled": true,
      "CloudWatchMetricsEnabled": true,
      "MetricName": "CommonRuleSetMetric"
    }
  }]' \
  --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=ProdWebACLMetric \
  --region us-east-1

3.3 Shield vs WAF — When to Use Which

CriteriaAWS ShieldAWS WAF
Protection typeVolumetric DDoS protectionL7 application filtering
OSI LayersL3/L4 (Standard), L3/L4/L7 (Advanced)L7 only
Targeted threatsTraffic floods, botnetsSQLi, XSS, bots, OWASP
ActivationAutomatic (Standard)Manual configuration
ComplementarityShield Advanced includes WAFWAF alone or with Shield

Recommendation: For comprehensive protection, use Shield Advanced + WAF together.


Module 4 — Threat Detection Services

4.1 Amazon GuardDuty

Amazon GuardDuty is an AI/ML-powered threat detection service that continuously monitors for malicious behavior.

flowchart TD
    GD["Amazon GuardDuty\n(Threat Detection — AI/ML)"]

    subgraph Sources["Data Sources"]
        CT_src["CloudTrail Events\n(API calls, console)"]
        VPC_src["VPC Flow Logs\n(network traffic)"]
        DNS_src["DNS Query Logs"]
        EKS_src["EKS Audit Logs"]
        RDS_src["RDS Login Activity"]
        Lambda_src["Lambda Network Activity"]
        S3Events_src["CloudTrail S3 Data Events"]
        Runtime_src["Runtime Monitoring\n(EC2, ECS, EKS)"]
    end

    CT_src & VPC_src & DNS_src & EKS_src --> GD
    RDS_src & Lambda_src & S3Events_src & Runtime_src --> GD

    GD -->|"Findings"| Detective["Amazon Detective\n(Root Cause Analysis)"]
    GD -->|"Alerts"| EB["Amazon EventBridge"]
    EB --> SNS_gd["SNS Notification"]
    EB --> LambdaResp["Lambda (auto-remediation)"]
    EB --> SH_Hub["AWS Security Hub"]
# Enable GuardDuty
aws guardduty create-detector --enable --region us-east-1

# List HIGH+ findings
aws guardduty list-findings \
  --detector-id abc123def456 \
  --finding-criteria '{"Criterion":{"severity":{"Gte":7}}}'

4.2 GuardDuty Finding Types

Format: ThreatPurpose:ResourceType/ThreatFamilyName.DetectionMechanism

Severity levels:

  • Critical (9.0): Multi-step AttackSequence
  • High (7.0–8.9): Likely active compromise
  • Medium (4.0–6.9): Suspicious activity
  • Low (1.0–3.9): Atypical behavior

Main Categories

CategoryFinding ExampleSeverityData Source
AttackSequenceAttackSequence:IAM/CompromisedCredentialsCriticalCloudTrail
AttackSequenceAttackSequence:S3/CompromisedDataCriticalCloudTrail + S3
BackdoorBackdoor:EC2/C&CActivity.BHighVPC Flow Logs
CryptoCurrencyCryptoCurrency:EC2/BitcoinTool.BHighDNS / VPC Flow
CredentialAccessCredentialAccess:IAMUser/AnomalousBehaviorMediumCloudTrail
DefenseEvasionDefenseEvasion:IAMUser/AnomalousBehaviorMediumCloudTrail
DiscoveryDiscovery:S3/AnomalousBehaviorLowCloudTrail S3
ExfiltrationExfiltration:S3/MaliciousIPCallerHighCloudTrail S3
ImpactImpact:S3/AnomalousBehavior.DeleteHighCloudTrail S3
PenTestPenTest:IAMUser/KaliLinuxMediumCloudTrail
PersistencePersistence:IAMUser/AnomalousBehaviorMediumCloudTrail
PolicyPolicy:S3/BucketPublicAccessGrantedHighCloudTrail
PrivilegeEscalationPrivilegeEscalation:IAMUser/AnomalousBehaviorMediumCloudTrail
ReconRecon:EC2/PortscanMediumVPC Flow Logs
StealthStealth:IAMUser/CloudTrailLoggingDisabledLowCloudTrail
TrojanTrojan:EC2/DNSDataExfiltrationHighDNS Logs
UnauthorizedAccessUnauthorizedAccess:EC2/SSHBruteForceLowVPC Flow Logs
UnauthorizedAccessUnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWSHighCloudTrail

Critical IAM Findings to Monitor

FindingDescriptionRecommended Action
Stealth:IAMUser/CloudTrailLoggingDisabledCloudTrail was disabledRe-enable, investigate immediately
Policy:IAMUser/RootCredentialUsageRoot credentials were usedAlert, verify whether legitimate
UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWSEC2 credentials used outside AWSRevoke immediately
AttackSequence:IAM/CompromisedCredentialsMulti-step attack sequenceImmediate incident response
PrivilegeEscalation:IAMUser/AnomalousBehaviorPrivilege escalation attemptBlock access, investigate
DefenseEvasion:IAMUser/BedrockLoggingDisabledBedrock logging was disabledRe-enable, investigate

4.3 Amazon Macie

Amazon Macie is an ML-powered service for discovering and protecting sensitive data in Amazon S3.

CategoryExamples of Detected Data
PIINames, addresses, phone numbers, emails
Financial dataCredit card numbers, bank accounts
CredentialsAPI keys, passwords, AWS tokens
Health dataMedical information (PHI/HIPAA)
Legal dataSocial security numbers, driver’s licenses
flowchart LR
    S3_mac["Amazon S3\n(Buckets)"]
    Macie_svc["Amazon Macie\n(ML scanning)"]
    Findings_mac["Findings\n(sensitive data)"]
    EB_mac["EventBridge"]
    SH_mac["Security Hub"]
    SNS_mac["SNS / Lambda\n(Alerts & remediation)"]

    S3_mac -->|"Inventory\n+ Scan"| Macie_svc
    Macie_svc --> Findings_mac
    Findings_mac --> EB_mac
    EB_mac --> SH_mac
    EB_mac --> SNS_mac

Key features:

  • Automatic S3 inventory: classifies the sensitivity level of each bucket
  • Sensitive data discovery jobs: scheduled or on-demand scans
  • Bucket security posture: detects public, unencrypted, or unlogged buckets
  • Security Hub integration: centralizes findings
# Enable Macie
aws macie2 enable-macie --region us-east-1

# Create a discovery job
aws macie2 create-classification-job \
  --job-type ONE_TIME \
  --name "SensitiveDataScan" \
  --s3-job-definition '{
    "bucketDefinitions": [{"accountId": "123456789012", "buckets": ["my-data-bucket"]}]
  }'

4.4 Amazon Inspector

Amazon Inspector is a service for automated CVE vulnerability assessment of your AWS workloads.

ResourceAnalysis Type
Amazon EC2OS and package CVEs, network exposure
Containers (ECR)CVE vulnerabilities in Docker images
AWS LambdaCVEs in dependencies (layers and packages)

Severity levels (CVSS):

SeverityCVSS ScoreAction
Critical9.0 – 10.0Remediate immediately
High7.0 – 8.9Remediate quickly
Medium4.0 – 6.9Schedule remediation
Low0.1 – 3.9Next maintenance window
Informational0.0No action required
# Enable Inspector v2
aws inspector2 enable \
  --resource-types EC2 ECR LAMBDA \
  --region us-east-1

# List critical findings
aws inspector2 list-findings \
  --filter-criteria '{"severity":[{"comparison":"EQUALS","value":"CRITICAL"}]}' \
  --sort-criteria '{"field":"SEVERITY","sortOrder":"DESC"}'

4.5 AWS Security Hub

AWS Security Hub is a centralized security dashboard that aggregates findings from multiple services.

flowchart TB
    subgraph Sources_sh["Finding Sources"]
        GD_sh["GuardDuty"]
        Inspector_sh["Inspector"]
        Macie_sh["Macie"]
        Config_sh["AWS Config"]
        IAM_AA_sh["IAM Access Analyzer"]
        ThirdParty_sh["Third-party tools\n(CrowdStrike, Splunk...)"]
    end

    SH_main["AWS Security Hub\n(Centralization + CSPM + Scoring)"]

    GD_sh & Inspector_sh & Macie_sh --> SH_main
    Config_sh & IAM_AA_sh & ThirdParty_sh --> SH_main

    SH_main --> Dashboards_sh["Dashboards\n& Security Score"]
    SH_main --> EB_sh["EventBridge\n(automation)"]
    SH_main --> SIEM_sh["External SIEM\n(OpenSearch, Splunk)"]

Supported security standards:

StandardDescription
AWS FSBPAWS Foundational Security Best Practices
CIS AWS Foundations BenchmarkCIS Benchmark for AWS
PCI DSSPayment Card Industry Data Security Standard
NIST SP 800-53NIST Cybersecurity Framework
# Enable Security Hub with default standards
aws securityhub enable-security-hub \
  --enable-default-standards \
  --region us-east-1

# List CRITICAL and HIGH findings
aws securityhub get-findings \
  --filters '{"SeverityLabel":[
    {"Value":"CRITICAL","Comparison":"EQUALS"},
    {"Value":"HIGH","Comparison":"EQUALS"}
  ]}'

Module 5 — Encryption and Secrets Management

5.1 AWS KMS — Key Management Service

AWS KMS is the centralized service for managing encryption keys. Nearly every AWS service uses KMS for encryption at rest.

Main features:

  • Create, rotate, disable, and delete keys
  • Cryptographic operations via API (Encrypt, Decrypt, Sign)
  • Full audit trail via CloudTrail
  • Native integration: S3, EBS, RDS, Secrets Manager, CloudTrail, and more

5.2 KMS Key Types

TypeDescriptionManaged ByUse Case
AWS Managed KeyAutomatically created by AWS for a serviceAWSDefault encryption (e.g., aws/s3)
Customer Managed Key (CMK)Created and managed by youYouFull control: rotation, policies, audit
AWS Owned KeyExclusively AWS-owned, sharedAWS (invisible)Internal AWS services
Multi-Region Key (MRK)Key replicated across regionsYouMulti-region workloads, DR
Asymmetric KeyRSA/ECC public/private pairYouDigital signatures, asymmetric encryption
HMAC KeyMessage authentication codesYouIntegrity verification

Key rotation:

TypeFrequencyTrigger
Automatic (symmetric CMK)Every 365 daysAWS manages automatically
ManualAt your discretionaws kms rotate-key-on-demand
# Create a CMK with automatic rotation
aws kms create-key \
  --description "Prod RDS encryption key" \
  --key-usage ENCRYPT_DECRYPT \
  --key-spec SYMMETRIC_DEFAULT \
  --enable-key-rotation

# List keys
aws kms list-keys
aws kms describe-key --key-id alias/my-kms-key

Key Policy — example:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowRootFullAccess",
      "Effect": "Allow",
      "Principal": {"AWS": "arn:aws:iam::123456789012:root"},
      "Action": "kms:*",
      "Resource": "*"
    },
    {
      "Sid": "AllowEC2RoleDecryptOnly",
      "Effect": "Allow",
      "Principal": {"AWS": "arn:aws:iam::123456789012:role/AppServerRole"},
      "Action": ["kms:Decrypt", "kms:DescribeKey"],
      "Resource": "*"
    }
  ]
}

5.3 AWS Secrets Manager

AWS Secrets Manager is the service for securely managing secrets (credentials, passwords, API keys).

Main features:

  • Automatic encryption with AWS KMS
  • Automatic rotation via Lambda (RDS, Redshift, DocumentDB)
  • Programmatic access via API/SDK — no more hardcoded credentials in code
  • Full audit trail in CloudTrail
  • Versioning for rollback
sequenceDiagram
    participant App as Application (EC2/Lambda)
    participant IAM_sm as IAM Role
    participant SM_seq as Secrets Manager
    participant KMS_seq as AWS KMS
    participant CT_sm as CloudTrail

    App->>IAM_sm: Assume Role (instance profile)
    IAM_sm-->>App: Temporary credentials (STS)
    App->>SM_seq: GetSecretValue("prod/db/password")
    SM_seq->>CT_sm: Log the API call
    SM_seq->>KMS_seq: Decrypt secret material
    KMS_seq-->>SM_seq: Decrypted value
    SM_seq-->>App: Secret value (in memory only)
    Note over App: Never in source code<br/>Never on disk<br/>Never in env variables
# Create a secret
aws secretsmanager create-secret \
  --name "prod/db/password" \
  --description "Production database password" \
  --secret-string '{"username":"dbadmin","password":"SecurePass456!"}' \
  --kms-key-id alias/my-kms-key

# Retrieve a secret
aws secretsmanager get-secret-value \
  --secret-id prod/db/password \
  --query SecretString --output text

# Enable automatic rotation (30 days)
aws secretsmanager rotate-secret \
  --secret-id prod/db/password \
  --rotation-lambda-arn arn:aws:lambda:us-east-1:123456789012:function:SecretsManagerRotation \
  --rotation-rules AutomaticallyAfterDays=30

Secrets Manager vs SSM Parameter Store:

CriteriaSecrets ManagerSSM Parameter Store
Cost~$0.40/secret/monthFree (Standard)
Automatic rotation✅ Native with Lambda❌ Manual
EncryptionKMS requiredKMS optional
Primary use caseDB credentials, API keysConfig, feature flags

Module 6 — Audit and Monitoring Tools

6.1 Amazon CloudWatch

Amazon CloudWatch is the primary monitoring tool for AWS resources and applications.

FeatureDescriptionTier
MetricsStandard AWS metrics (CPU, network, I/O)Free
Custom MetricsCustom application metricsPaid
AlarmsTrigger actions on threshold breachFree (10)
LogsLog collection and storagePaid (per GB)
Log InsightsAnalytical queries on logsPaid (per GB scanned)
DashboardsVisual dashboardsFree (3) / Paid
Database InsightsAdvanced database monitoringPaid
Cross-account observationCentralized multi-account monitoringPaid
# Create a CPU alarm
aws cloudwatch put-metric-alarm \
  --alarm-name "HighCPUAlert" \
  --metric-name CPUUtilization \
  --namespace AWS/EC2 \
  --statistic Average \
  --period 300 \
  --threshold 80 \
  --comparison-operator GreaterThanThreshold \
  --dimensions Name=InstanceId,Value=i-0987654321abcdef0 \
  --evaluation-periods 1 \
  --alarm-actions arn:aws:sns:us-east-1:123456789012:AlertTopic

6.2 AWS CloudTrail

AWS CloudTrail records all user actions and API calls in your AWS environment.

The three event types:

TypeDescriptionExamplesCost
Management EventsControl plane operationsCreateBucket, RunInstancesFree (90 days)
Data EventsData plane operationsS3 GetObject, Lambda InvokePaid
Insights EventsAPI activity anomaliesSudden spike in API callsPaid
flowchart TD
    Console_ct["AWS Console"]
    CLI_ct["AWS CLI"]
    SDK_ct["AWS SDK / API"]

    Console_ct & CLI_ct & SDK_ct --> CT_main["AWS CloudTrail"]

    CT_main --> S3_ct["S3\n(.json.gz encrypted)"]
    CT_main --> CW_ct["CloudWatch Logs\n(real-time)"]
    CT_main --> SNS_ct["SNS\n(notifications)"]

    S3_ct --> Athena_ct["Athena\n(SQL queries)"]
    CW_ct --> CW_Alarms_ct["CloudWatch Alarms"]
# Create a secure multi-region trail
aws cloudtrail create-trail \
  --name prod-audit-trail \
  --s3-bucket-name aws-cloudtrail-logs-prod-123456789012 \
  --is-multi-region-trail \
  --enable-log-file-validation \
  --kms-key-id arn:aws:kms:us-east-1:123456789012:key/mrk-xyz789

# Start logging
aws cloudtrail start-logging --name prod-audit-trail

# Search for console sign-in events
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin \
  --start-time 2024-01-01T00:00:00Z

6.3 CloudTrail Log Format

CloudTrail logs are compressed JSON files (.json.gz) stored in S3.

{
  "Records": [
    {
      "eventVersion": "1.08",
      "userIdentity": {
        "type": "IAMUser",
        "principalId": "AIDIODR4TAW7CSEXAMPLE",
        "arn": "arn:aws:iam::123456789012:user/bob",
        "accountId": "123456789012",
        "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
        "userName": "bob"
      },
      "eventTime": "2024-03-10T09:15:30Z",
      "eventSource": "s3.amazonaws.com",
      "eventName": "GetObject",
      "awsRegion": "us-east-1",
      "sourceIPAddress": "198.51.100.42",
      "userAgent": "aws-cli/2.15.0 Python/3.11",
      "requestParameters": {
        "bucketName": "my-sensitive-data-bucket",
        "key": "reports/internal-review.pdf"
      },
      "responseElements": null,
      "requestID": "57A5B9EXAMPLE",
      "eventID": "1234567890abcdef",
      "readOnly": true,
      "eventType": "AwsApiCall",
      "managementEvent": false,
      "recipientAccountId": "123456789012"
    }
  ]
}

Key fields for auditing:

FieldPurpose
userIdentityWho performed the action
eventTimeWhen
eventNameWhat action (CreateUser, DeleteBucket…)
sourceIPAddressFrom which IP
awsRegionIn which region
requestParametersRequest details
errorCodeIf present, the action failed (AccessDenied, etc.)

6.4 AWS Audit Manager

AWS Audit Manager automates evidence collection to prepare for compliance audits.

Supported prebuilt frameworks: SOC 2, PCI DSS, HIPAA, GDPR, FedRAMP, NIST 800-53, ISO 27001

flowchart LR
    Framework_am["Framework\n(SOC2 / PCI-DSS / HIPAA...)"]
    AM_main["AWS Audit Manager"]
    subgraph Collecte["Automated Evidence Collection"]
        Config_am["AWS Config"]
        CT_am["CloudTrail"]
        SH_am["Security Hub"]
        CW_am["CloudWatch"]
    end
    Review_am["Team Review"]
    Report_am["Audit Report"]
    Auditor_am["External Auditor"]

    Framework_am --> AM_main
    AM_main --> Config_am & CT_am & SH_am & CW_am
    Config_am & CT_am & SH_am & CW_am --> Review_am
    Review_am --> Report_am --> Auditor_am

6.5 AWS Config

AWS Config continuously records the configuration state of resources and evaluates their compliance.

Config Rules — essential examples:

RuleDescriptionSeverity
restricted-sshSecurity groups do not allow SSH from 0.0.0.0/0High
s3-bucket-public-read-prohibitedS3 buckets are not publicly readableHigh
s3-bucket-ssl-requests-onlyS3 buckets enforce HTTPSMedium
iam-root-access-key-checkRoot account has no active access keysCritical
mfa-enabled-for-iam-console-accessMFA enabled for all IAM console usersHigh
cloudtrail-enabledCloudTrail enabled in each regionHigh
encrypted-volumesEBS volumes are encryptedMedium
rds-storage-encryptedRDS storage is encryptedMedium
guardduty-enabled-centralizedGuardDuty is enabledHigh
access-keys-rotatedAccess keys are less than 90 days oldMedium
# Enable a managed Config rule
aws configservice put-config-rule \
  --config-rule '{
    "ConfigRuleName": "restricted-ssh",
    "Source": {
      "Owner": "AWS",
      "SourceIdentifier": "INCOMING_SSH_DISABLED"
    },
    "Scope": {
      "ComplianceResourceTypes": ["AWS::EC2::SecurityGroup"]
    }
  }'

# List non-compliant resources
aws configservice describe-compliance-by-config-rule \
  --compliance-types NON_COMPLIANT
flowchart LR
    Resource_cfg["AWS Resource\n(configuration change)"]
    Config_main["AWS Config\n(continuous evaluation)"]
    Rule_cfg["Config Rule"]
    NonCompliant_cfg{"Compliant?"}
    Remediation_cfg["Auto-remediation\n(SSM Automation)"]
    SH_cfg["Security Hub\n(finding)"]

    Resource_cfg -->|"Change"| Config_main
    Config_main --> Rule_cfg --> NonCompliant_cfg
    NonCompliant_cfg -->|"No"| Remediation_cfg
    NonCompliant_cfg -->|"No"| SH_cfg
    Remediation_cfg -->|"Fixes"| Resource_cfg

Module 7 — Demo: CloudTrail and S3 Access Logs

7.1 Creating a CloudTrail Trail

Steps in the AWS Console

1. Navigate to CloudTrail — Search for “CloudTrail” in the search bar

2. Create a new trail — Trails → Create trail

3. Configure the trail:

ParameterRecommended Value
Trail namemanagement-events
S3 bucketaws-cloudtrail-logs-<account-id>-<random> (new)
Log file SSE-KMS encryptionRecommended
Log file validation✅ Enable
Multi-region trail✅ Recommended
Management Events✅ Read + Write

Generated S3 structure:

s3://aws-cloudtrail-logs-<account-id>/
  └── AWSLogs/<account-id>/CloudTrail/<region>/<YYYY>/<MM>/<DD>/
      └── <account>_CloudTrail_<region>_<timestamp>.json.gz

4. Integrity validation: A digitally signed digest file is created every hour to detect any log tampering.

# Create and start the trail
aws cloudtrail create-trail \
  --name management-events \
  --s3-bucket-name aws-cloudtrail-logs-123456789012 \
  --is-multi-region-trail \
  --enable-log-file-validation

aws cloudtrail start-logging --name management-events

# Validate log integrity
aws cloudtrail validate-logs \
  --trail-arn arn:aws:cloudtrail:us-east-1:123456789012:trail/management-events \
  --start-time 2024-01-01T00:00:00Z

7.2 Configuring S3 Access Logs

S3 Access Logs record all HTTP access to an S3 bucket (GET, PUT, DELETE, etc.).

S3 Access Logs vs CloudTrail Data Events: S3 Access Logs capture HTTP details (headers, response time, bytes transferred). CloudTrail Data Events capture the IAM context (who, from which API).

# Enable S3 Access Logs
aws s3api put-bucket-logging \
  --bucket my-sensitive-data-bucket \
  --bucket-logging-status '{
    "LoggingEnabled": {
      "TargetBucket": "my-access-logs-bucket",
      "TargetPrefix": "logs/my-sensitive-data-bucket/"
    }
  }'

Destination bucket policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "S3ServerAccessLogsPolicy",
      "Effect": "Allow",
      "Principal": {"Service": "logging.s3.amazonaws.com"},
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::my-access-logs-bucket/*",
      "Condition": {
        "ArnLike": {
          "aws:SourceArn": "arn:aws:s3:::my-sensitive-data-bucket"
        },
        "StringEquals": {
          "aws:SourceAccount": "123456789012"
        }
      }
    }
  ]
}

Best practice: Always use a dedicated bucket for logs, separate from the source bucket.


Module 8 — AWS Compliance

8.1 Shared Responsibility Model

The Shared Responsibility Model defines what AWS secures versus what the customer must secure.

flowchart TB
    subgraph AWS_resp["AWS — Security OF the cloud infrastructure"]
        HW_resp["Physical hardware\n(Servers, network, storage)"]
        DC_resp["Data Centers\n(Physical access, environmental controls)"]
        HV_resp["Hypervisor\n(Virtualization)"]
        GlobalInfra_resp["Global infrastructure\n(Regions, AZs, Edge)"]
    end

    subgraph Customer_resp["Customer — Security IN the cloud"]
        Data_resp["Data & Encryption"]
        IAM_resp2["Identity management\n(IAM, MFA, policies)"]
        OS_resp["EC2 instance OS\n(patches, hardening)"]
        Network_resp["Network configuration\n(Security Groups, NACLs)"]
        AppCode_resp["Application code\n(vulnerabilities, secrets)"]
    end
LayerAWSCustomer
Hardware / Data Center
Virtualization
EC2 OS
Application patches
Data encryptionTools provided✅ Configuration
IAM and accessService provided✅ Configuration
Security Groups / NACLsService provided✅ Configuration
Customer data

Note on managed services: For RDS, Lambda, ECS Fargate, AWS manages the OS/runtime — the customer’s responsibility boundary moves up accordingly.


8.2 AWS Compliance Programs

Standard / ProgramDomainApplicability
SOC 1 / SOC 2 / SOC 3Service controls (AICPA)Global
PCI DSS Level 1Payment data securityGlobal
HIPAAPatient data (US)US
FedRAMPFederal government servicesUS Gov
ISO 27001Information security managementGlobal
ISO 27017Cloud securityGlobal
ISO 27018PII protection in the cloudGlobal
GDPRPersonal data protectionEU
PIPEDAPersonal information protectionCanada
NIST SP 800-171Unclassified informationUS
CSA STARCloud Security AllianceGlobal

AWS Artifact: a service that allows you to download compliance reports and agreements directly from the console (HIPAA BAA, etc.).


Module 9 — Layered Security Architecture

flowchart TB
    subgraph External_arch["External World"]
        Internet_arch["Internet"]
        Attackers_arch["Attackers\n(DDoS, hackers, bots)"]
    end

    subgraph Layer1_arch["Layer 1 — DDoS Protection & Perimeter"]
        Shield_arch["AWS Shield\n(Standard + Advanced)"]
        WAF_arch["AWS WAF\n(SQLi, XSS, OWASP)"]
        CF_arch["CloudFront + Route53"]
    end

    subgraph Layer2_arch["Layer 2 — Network"]
        VPC_arch["Amazon VPC"]
        SG_arch["Security Groups\n(stateful)"]
        NACL_arch["NACLs\n(stateless)"]
    end

    subgraph Layer3_arch["Layer 3 — Identity & Access"]
        IAM_arch["AWS IAM\n(Policies, Roles)"]
        IIC_arch["IAM Identity Center\n(SSO + MFA)"]
        Org_arch["Organizations\n(SCPs / RCPs)"]
    end

    subgraph Layer4_arch["Layer 4 — Data & Secrets"]
        KMS_arch["AWS KMS\n(encryption)"]
        SM_arch["Secrets Manager"]
        Macie_arch["Macie\n(PII detection)"]
    end

    subgraph Layer5_arch["Layer 5 — Detection & Response"]
        GD_arch["GuardDuty\n(threat detection)"]
        Inspector_arch["Inspector\n(CVE)"]
        SH_arch["Security Hub\n(dashboard)"]
    end

    subgraph Layer6_arch["Layer 6 — Audit & Compliance"]
        CT_arch["CloudTrail\n(audit trail)"]
        Config_arch["AWS Config\n(compliance)"]
        AM_arch["Audit Manager"]
        CW_arch["CloudWatch\n(monitoring)"]
    end

    Internet_arch & Attackers_arch --> Layer1_arch
    Layer1_arch --> Layer2_arch --> Layer3_arch
    Layer3_arch --> Layer4_arch --> Layer5_arch --> Layer6_arch

Audit and Compliance Workflow

sequenceDiagram
    participant User_seq as User/Service
    participant GD_seq2 as GuardDuty
    participant CT_seq2 as CloudTrail
    participant Config_seq2 as AWS Config
    participant SH_seq2 as Security Hub
    participant AM_seq2 as Audit Manager
    participant SOC_seq as SOC Team / Auditor

    User_seq->>CT_seq2: AWS Action (API Call)
    CT_seq2-->>GD_seq2: Analyzed event
    CT_seq2-->>Config_seq2: Configuration change

    GD_seq2->>GD_seq2: AI/ML analysis
    GD_seq2-->>SH_seq2: Finding (if threat detected)

    Config_seq2->>Config_seq2: Compliance evaluation
    Config_seq2-->>SH_seq2: Finding (if non-compliant)

    SH_seq2->>SH_seq2: Aggregation + scoring
    SH_seq2-->>SOC_seq: Dashboard + alerts

    AM_seq2->>CT_seq2: Collect evidence
    AM_seq2->>Config_seq2: Collect evidence
    AM_seq2-->>SOC_seq: Report (SOC2, PCI-DSS, HIPAA)

Module 10 — Summary and Key Takeaways

Service Summary Table

ServiceCategoryPrimary FunctionCost
MFAAuthenticationSecond factor (TOTP, FIDO2)Free
AWS IAMAccess controlUsers, Groups, Roles, PoliciesFree
IAM Identity CenterSSOCentralized multi-account accessFree
Organizations (SCPs/RCPs)GovernanceMulti-account guardrailsFree
IAM Access AnalyzerPolicy analysisExternal access + policy generationFree (basic)
AWS Shield StandardDDoS protectionAutomatic L3/L4 protectionFree
AWS Shield AdvancedDDoS protectionL3/L4/L7 + Shield Response Team~$3,000/month
AWS WAFL7 firewallSQLi, XSS, bots, OWASPPaid (Web ACL)
Amazon GuardDutyThreat detectionAI/ML on CloudTrail, VPC Flow, DNSPaid (usage)
Amazon MacieData protectionPII discovery in S3Paid (usage)
Amazon InspectorVulnerabilitiesCVE scanning EC2, ECR, LambdaPaid (usage)
AWS Security HubCentralizationSecurity posture dashboard + scoringPaid (findings)
AWS KMSEncryptionKey management (CMK, MRK, HMAC…)Paid (key + calls)
AWS Secrets ManagerSecretsCredential storage + rotation~$0.40/secret/month
Amazon CloudWatchMonitoringMetrics, logs, alarms, dashboardsFree (basic) / Paid
AWS CloudTrailAuditAPI and console action traceabilityFree (90d) / Paid
AWS Audit ManagerComplianceAutomated audit evidence collectionPaid (per assessment)
AWS ConfigComplianceResource inventory + rulesPaid (per rule evaluated)
AWS ArtifactComplianceReports and agreements (BAA, PCI…)Free

Detection and Monitoring Services Comparison

CriteriaGuardDutyMacieInspectorSecurity HubConfig
FocusActive threatsPII in S3Workload CVEsOverall postureConfig compliance
SourcesCloudTrail, VPC, DNS, EKS…S3 objectsEC2 OS, ECR, LambdaAll servicesAWS resources
TechnologyAI/MLMLCVE DB (CVSS)Rules + standardsRules engine
Security Hub integration

Key Takeaways

  1. MFA is essential — Enable it everywhere, especially on root and privileged accounts. Prioritize FIDO2 (phishing-resistant).

  2. IAM Roles > IAM Users — AWS workloads should use roles (temporary credentials), never hardcoded access keys.

  3. Principle of least privilege — Grant only what is strictly necessary. IAM Access Analyzer can generate least-privilege policies from CloudTrail activity.

  4. Shield Standard is automatic — All AWS accounts benefit from it without any configuration.

  5. WAF for L7, Shield for L3/L4 — They complement each other. Shield Advanced includes WAF.

  6. GuardDuty = proactive detection — Continuously analyzes CloudTrail, VPC Flow Logs, and DNS. Disabling it is itself a critical finding (Stealth:IAMUser/CloudTrailLoggingDisabled).

  7. Security Hub = unified view — Aggregates GuardDuty, Macie, Inspector, Config, and IAM Access Analyzer with a compliance score.

  8. KMS for all encryption — Customer Managed Keys (CMK) for full control with automatic rotation.

  9. Secrets Manager > Environment variables — Never store credentials in plaintext. Enable automatic rotation.

  10. CloudTrail + CloudWatch = complete visibility — CloudTrail tracks who did what, CloudWatch monitors what is happening. Always enable log file validation.

  11. Shared Responsibility Model — AWS secures the infrastructure; the customer secures their data, IAM configurations, and access settings.

  12. AWS Config rules = automated compliance — Define rules and enable automatic remediation via SSM to correct configuration drift.


CLI Reference Commands

# === IAM ===
# Enable MFA on a user
aws iam enable-mfa-device \
  --user-name bob \
  --serial-number arn:aws:iam::123456789012:mfa/bob \
  --authentication-code1 654321 \
  --authentication-code2 987012

# Generate IAM credential report
aws iam generate-credential-report
aws iam get-credential-report --query Content --output text | base64 -d

# Create an IAM Role for EC2
aws iam create-role \
  --role-name AppServer-S3-ReadRole \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": {"Service": "ec2.amazonaws.com"},
      "Action": "sts:AssumeRole"
    }]
  }'

# === GuardDuty ===
aws guardduty create-detector --enable --region us-east-1
aws guardduty list-findings \
  --detector-id abc123 \
  --finding-criteria '{"Criterion":{"severity":{"Gte":7}}}'

# === CloudTrail ===
aws cloudtrail describe-trails
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin
aws cloudtrail validate-logs \
  --trail-arn arn:aws:cloudtrail:us-east-1:123456789012:trail/management-events \
  --start-time 2024-01-01T00:00:00Z

# === KMS ===
aws kms list-keys
aws kms create-key --description "Prod encryption key" --enable-key-rotation
aws kms enable-key-rotation --key-id alias/my-kms-key

# === Secrets Manager ===
aws secretsmanager get-secret-value \
  --secret-id prod/db/password \
  --query SecretString --output text
aws secretsmanager list-secrets \
  --query "SecretList[*].{Name:Name,LastChanged:LastChangedDate}"

# === Config ===
aws configservice describe-compliance-by-config-rule \
  --compliance-types NON_COMPLIANT

# === Security Hub ===
aws securityhub enable-security-hub --enable-default-standards --region us-east-1
aws securityhub get-findings \
  --filters '{"SeverityLabel":[{"Value":"CRITICAL","Comparison":"EQUALS"}]}'

# === S3 Access Logs ===
aws s3api put-bucket-logging \
  --bucket my-sensitive-data-bucket \
  --bucket-logging-status '{
    "LoggingEnabled": {
      "TargetBucket": "my-access-logs-bucket",
      "TargetPrefix": "logs/"
    }
  }'

Search Terms

aws · security · compliance · fundamentals · core · services · amazon · web · iam · policy · access · cloudtrail · service · audit · management · manager · secrets · shield · types · waf · cloudwatch · detection · guardduty · kms

Interested in this course?

Contact us to book it or get a custom training plan for your team.