Chapter 46: Cloud & Container Red Teaming¶
Overview¶
As organizations migrate workloads to cloud environments and adopt container orchestration, the attack surface shifts from on-premises infrastructure to identity-centric, API-driven architectures. Cloud red teaming requires a fundamentally different mindset: the perimeter is IAM, the infrastructure is ephemeral, and misconfigurations are often more dangerous than vulnerabilities. This chapter covers cloud attack methodology across AWS, Azure, and GCP, container escape concepts, Kubernetes cluster security, and serverless attack surfaces. Every technique is mapped to the MITRE ATT&CK Cloud and Containers matrices with corresponding detection and prevention controls.
Educational Content Only
All techniques in this chapter are presented for defensive understanding only. All cloud account IDs, resource names, IP addresses, and scenarios are 100% synthetic. IP addresses use RFC 5737 (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24) and RFC 1918 ranges. Never execute these techniques without explicit written authorization against accounts you own or have written permission to test.
Learning Objectives¶
By the end of this chapter, students SHALL be able to:
- Map the cloud attack lifecycle from initial access through data exfiltration
- Identify and explain IAM privilege escalation paths in AWS, Azure, and GCP
- Describe metadata service abuse and the security controls that mitigate it
- Explain container escape concepts and their prerequisites
- Analyze Kubernetes RBAC misconfigurations and their security implications
- Evaluate cloud security posture using CSPM tools and frameworks
- Design detection strategies for cloud-native attacks
Prerequisites¶
- Completion of Chapter 17 (Red Team Operations) and Chapter 45 (AD Red Teaming)
- Foundational knowledge of at least one cloud provider (AWS, Azure, or GCP)
- Understanding of containerization concepts (Docker fundamentals)
- Familiarity with Kubernetes architecture (pods, services, RBAC)
Why This Matters
Cloud misconfigurations were the leading cause of data breaches in cloud environments in 2024, accounting for 65% of cloud security incidents (CSA Cloud Threats Report). A single over-permissioned IAM role, an exposed metadata service, or a misconfigured S3 bucket can expose millions of records. Unlike on-premises environments where physical access provides a natural boundary, cloud environments are accessible from anywhere — making identity and configuration the only perimeter.
MITRE ATT&CK Cloud & Container Mapping¶
| Technique ID | Technique Name | Cloud/Container Context | Tactic |
|---|---|---|---|
| T1078.004 | Valid Accounts: Cloud Accounts | Compromised IAM credentials | Initial Access (TA0001) |
| T1552.005 | Unsecured Credentials: Cloud Instance Metadata | IMDS credential theft | Credential Access (TA0006) |
| T1098.001 | Account Manipulation: Additional Cloud Credentials | IAM key creation for persistence | Persistence (TA0003) |
| T1078.001 | Valid Accounts: Default Accounts | Default K8s service accounts | Privilege Escalation (TA0004) |
| T1610 | Deploy Container | Malicious container deployment | Execution (TA0002) |
| T1611 | Escape to Host | Container escape to node | Privilege Escalation (TA0004) |
| T1613 | Container and Resource Discovery | K8s API enumeration | Discovery (TA0007) |
| T1609 | Container Administration Command | kubectl exec abuse | Execution (TA0002) |
| T1537 | Transfer Data to Cloud Account | Exfil to attacker-owned account | Exfiltration (TA0010) |
| T1580 | Cloud Infrastructure Discovery | API-based enumeration | Discovery (TA0007) |
46.1 Cloud Attack Lifecycle¶
46.1.1 The Cloud Kill Chain¶
graph TD
A[Initial Access\nPhished credentials\nExposed keys\nSSRF to IMDS] --> B[Enumeration\nIAM policies\nCloud resources\nNetwork topology]
B --> C[Privilege Escalation\nIAM policy abuse\nRole chaining\nService exploitation]
C --> D[Lateral Movement\nCross-account roles\nVPC peering\nShared services]
D --> E[Persistence\nAdditional keys\nBackdoor roles\nLambda triggers]
E --> F[Data Access\nS3/Blob/GCS\nDatabase snapshots\nSecrets managers]
F --> G[Exfiltration\nCross-account copy\nPublic snapshot\nDNS tunneling]
style A fill:#e63946,color:#fff
style B fill:#457b9d,color:#fff
style C fill:#e9c46a,color:#000
style D fill:#f4a261,color:#000
style E fill:#2a9d8f,color:#fff
style F fill:#264653,color:#fff
style G fill:#780000,color:#fff 46.1.2 Initial Access Vectors¶
| Vector | Description | Prevalence |
|---|---|---|
| Exposed credentials in code | API keys committed to public repos | Very High |
| SSRF to metadata service | Application vulnerability → IMDS credential theft | High |
| Phished cloud console credentials | Social engineering targeting cloud admins | High |
| Misconfigured storage | Public S3 buckets, Azure Blob containers | Medium |
| CI/CD pipeline compromise | Build system credentials lead to cloud access | Medium |
| Supply chain attack | Compromised dependency with cloud credential access | Low (high impact) |
46.2 IAM Privilege Escalation¶
46.2.1 AWS IAM Escalation Paths¶
IAM is the single most critical security domain in AWS. Over-permissioned policies are the cloud equivalent of misconfigured AD ACLs.
graph LR
A[Low-priv IAM User\nsynth-dev-user] -->|iam:PassRole +\nlambda:CreateFunction| B[Create Lambda\nwith admin role]
B -->|lambda:InvokeFunction| C[Execute as\nadmin role]
C -->|Full AWS\nAccess| D[Account\nCompromise]
style A fill:#1d3557,color:#fff
style B fill:#e9c46a,color:#000
style C fill:#e63946,color:#fff
style D fill:#780000,color:#fff Common AWS Escalation Paths (Conceptual)¶
// SYNTHETIC POLICY — Demonstrates dangerous permission combination
// Account: 111122223333 (SYNTHETIC)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iam:PassRole",
"lambda:CreateFunction",
"lambda:InvokeFunction"
],
"Resource": "*"
}
]
}
// CONCEPTUAL ESCALATION:
// 1. User creates Lambda function
// 2. Assigns existing admin role via iam:PassRole
// 3. Lambda executes with admin privileges
// 4. Lambda can create new IAM user with full admin access
// REMEDIATION:
// - Restrict iam:PassRole to specific role ARNs
// - Restrict lambda:CreateFunction with condition keys
// - Use permission boundaries on all IAM entities
// SYNTHETIC — User can create and attach arbitrary policies
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iam:CreatePolicy",
"iam:AttachUserPolicy"
],
"Resource": "*"
}
]
}
// CONCEPTUAL ESCALATION:
// 1. Create a new policy granting AdministratorAccess
// 2. Attach that policy to own IAM user
// 3. Now has full admin access
// REMEDIATION:
// - Never grant iam:CreatePolicy + iam:Attach* together
// - Use Permission Boundaries to cap maximum permissions
// - SCPs to deny privilege escalation actions
SYNTHETIC SCENARIO — Role Chain Escalation
═══════════════════════════════════════════
Account: 111122223333 (SYNTHETIC)
1. User "synth-dev" can assume role "SynthDevRole"
2. SynthDevRole can assume role "SynthStagingRole"
3. SynthStagingRole can assume role "SynthProdAdminRole"
4. SynthProdAdminRole has AdministratorAccess in production
Result: Developer → Production Admin via role chaining
Each hop is individually "reasonable" but the chain is dangerous
DETECTION:
- CloudTrail: sts:AssumeRole events
- Alert on: Unusual role chaining patterns
- Implement: Maximum session duration limits
AWS Defense: Permission Boundaries
Permission Boundaries define the maximum permissions an IAM entity can receive, regardless of identity-based policies. Even if a user creates a policy granting *:*, the permission boundary limits what they can actually do. Every IAM user and role should have a permission boundary attached.
46.2.2 Azure IAM Escalation¶
Azure uses a different RBAC model but shares similar escalation patterns.
| Dangerous Azure Permission | Escalation Concept | Defense |
|---|---|---|
| Microsoft.Authorization/roleAssignments/write | Self-assign Owner/Contributor | Restrict role assignment scope |
| Microsoft.Compute/virtualMachines/runCommand | Execute commands on any VM | Conditional Access + PIM |
| Microsoft.KeyVault/vaults/secrets/read | Access all Key Vault secrets | Key Vault access policies + RBAC |
| Microsoft.ManagedIdentity/userAssignedIdentities | Impersonate managed identities | Restrict managed identity assignment |
| Microsoft.Resources/subscriptions/providers/register | Register malicious resource providers | Lock provider registration |
46.2.3 GCP Service Account Impersonation¶
Concept: GCP's service account impersonation allows principals with iam.serviceAccounts.getAccessToken to generate access tokens as a service account. If a low-privilege service account can impersonate a high-privilege one, this creates an escalation chain.
SYNTHETIC SCENARIO — GCP Impersonation Chain
═════════════════════════════════════════════════
Project: synth-project-12345 (SYNTHETIC)
1. Compromised: compute-sa@synth-project-12345.iam.gserviceaccount.com
2. compute-sa has iam.serviceAccounts.getAccessToken on data-sa
3. data-sa has roles/bigquery.admin
4. data-sa has iam.serviceAccounts.getAccessToken on admin-sa
5. admin-sa has roles/owner
RESULT: Compute workload → Project Owner via impersonation chain
REMEDIATION:
- Audit iam.serviceAccounts.getAccessToken grants
- Use IAM Recommender to rightsize permissions
- Enable VPC Service Controls for data exfiltration prevention
- Monitor: Admin Activity audit logs for impersonation events
46.3 Metadata Service Abuse¶
46.3.1 IMDS Credential Theft Concept¶
Cloud instances use Instance Metadata Services (IMDS) to provide configuration and credentials to applications. IMDSv1 uses simple HTTP GET requests without session tokens, making it vulnerable to SSRF attacks.
CONCEPTUAL FLOW — IMDSv1 SSRF Credential Theft
════════════════════════════════════════════════
1. Application has SSRF vulnerability
2. Attacker crafts request to: http://169.254.169.254/latest/meta-data/
3. Retrieves IAM role name from:
/latest/meta-data/iam/security-credentials/
4. Retrieves temporary credentials (AccessKeyId, SecretAccessKey, Token)
5. Uses credentials from outside the instance
NOTE: 169.254.169.254 is the link-local IMDS address (RFC 3927)
This is NOT an RFC 5737 address — it is the actual IMDS endpoint
used by AWS, Azure (also), and GCP.
CONCEPTUAL FLOW — IMDSv2 Session Tokens
════════════════════════════════════════════════
IMDSv2 requires a PUT request to obtain a session token:
PUT /latest/api/token
X-aws-ec2-metadata-token-ttl-seconds: 21600
The token must be included in subsequent GET requests:
GET /latest/meta-data/iam/security-credentials/SynthRole
X-aws-ec2-metadata-token: <token>
WHY THIS BLOCKS SSRF:
- Most SSRF vulnerabilities only allow GET requests
- The PUT request for token acquisition is blocked
- Even if PUT is possible, the token header must be forwarded
- Response hop limit of 1 prevents container-to-host IMDS access
ENFORCEMENT:
- Set HttpTokens=required on all EC2 instances
- Use SCP to enforce IMDSv2 org-wide
- Monitor CloudTrail for IMDSv1 usage (MetadataNoToken events)
46.3.2 Azure IMDS and Managed Identity¶
Azure's IMDS operates on the same link-local address but uses managed identities. The token endpoint requires an additional Metadata: true header.
SYNTHETIC — Azure Managed Identity Token Request
═══════════════════════════════════════════════════
GET http://169.254.169.254/metadata/identity/oauth2/token
?api-version=2018-02-01
&resource=https://management.azure.com/
Header: Metadata: true
Response includes:
- access_token (JWT for Azure Resource Manager)
- expires_in
- resource
DEFENSE:
- The Metadata:true header blocks some SSRF attacks
- But advanced SSRF (full header control) can bypass this
- Use Private Link/Service Endpoints to reduce SSRF targets
- Apply Conditional Access policies requiring compliant devices
- Network segmentation between application and management planes
46.4 Container Security Concepts¶
46.4.1 Container Threat Model¶
graph TD
subgraph Host OS
subgraph Container Runtime
A[Container A\nCompromised] -->|Escape Vector| B[Host Kernel]
C[Container B\nNormal]
end
B -->|Full Access| D[Host Filesystem]
B -->|Full Access| E[Other Containers]
B -->|Full Access| F[Network\nNo Isolation]
end
style A fill:#e63946,color:#fff
style B fill:#780000,color:#fff
style C fill:#2d6a4f,color:#fff
style D fill:#e9c46a,color:#000
style E fill:#e9c46a,color:#000
style F fill:#e9c46a,color:#000 46.4.2 Container Escape Concepts¶
Container escapes allow an attacker inside a container to gain access to the underlying host. These are among the most impactful cloud/container vulnerabilities.
| Escape Vector | Concept | Prerequisites | Detection |
|---|---|---|---|
| Docker socket mount | /var/run/docker.sock exposed inside container | Socket mounted as volume | Monitor for socket mounts in pod specs |
| Privileged container | --privileged flag disables all isolation | Container launched as privileged | Admission controller: deny privileged |
| Writable hostPath | Container mounts host filesystem | hostPath volume with write access | OPA/Gatekeeper policy enforcement |
| Kernel exploit | Exploit vulnerability in shared kernel | Vulnerable host kernel | Keep host kernel patched; use gVisor/Kata |
| CAP_SYS_ADMIN | Linux capability enables mount namespace escape | Capability granted to container | Drop all capabilities; add only needed |
| procfs/sysfs abuse | Write to host proc/sys via mount | These filesystems mounted writable | Read-only mount; seccomp profiles |
Docker Socket Exposure (Conceptual)¶
# SYNTHETIC — Vulnerable pod specification
# This mounts the Docker socket into the container
apiVersion: v1
kind: Pod
metadata:
name: synth-vulnerable-pod
namespace: synth-namespace
spec:
containers:
- name: synth-app
image: synth-registry.example.com/app:1.0
volumeMounts:
- name: docker-socket
mountPath: /var/run/docker.sock
volumes:
- name: docker-socket
hostPath:
path: /var/run/docker.sock
# CONCEPTUAL IMPACT:
# Any process in this container can communicate with
# the Docker daemon on the host, effectively granting
# full host access. The attacker can:
# - Launch a new privileged container
# - Mount the host filesystem
# - Access all other containers on the host
# OPA Gatekeeper constraint to block Docker socket mounts
# SYNTHETIC — Policy enforcement concept
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDenyDockerSocket
metadata:
name: deny-docker-socket
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
blockedPaths:
- "/var/run/docker.sock"
- "/run/docker.sock"
- "/var/run/containerd/containerd.sock"
46.4.3 Container Image Security¶
CONTAINER IMAGE SECURITY CHECKLIST
══════════════════════════════════════════════════
□ Use minimal base images (distroless, Alpine, scratch)
□ Scan images with Trivy, Grype, or Snyk before deployment
□ Sign images with cosign/Notary and enforce signature verification
□ Never run containers as root (USER directive in Dockerfile)
□ Pin image versions by SHA256 digest, not tag
□ Implement registry allowlisting (only approved registries)
□ Scan for secrets in image layers (truffleHog, GitLeaks)
□ Rebuild images regularly to incorporate security patches
□ Use multi-stage builds to exclude build tools from runtime image
46.5 Kubernetes Cluster Attacks¶
46.5.1 Kubernetes Attack Surface¶
graph TD
A[External Attacker] -->|Exposed API Server\nor Ingress Vuln| B[K8s API Server\n198.51.100.10]
B -->|Weak RBAC| C[Pod Compromise]
C -->|Service Account\nToken| D[API Server\nAccess]
D -->|Secrets Access| E[Cluster Secrets]
C -->|Node Access| F[etcd\n198.51.100.20]
F -->|Unencrypted| G[All Cluster\nSecrets]
C -->|Lateral Move| H[Other Pods\nvia Network]
style A fill:#1d3557,color:#fff
style B fill:#e63946,color:#fff
style C fill:#e9c46a,color:#000
style F fill:#780000,color:#fff
style G fill:#780000,color:#fff 46.5.2 RBAC Misconfiguration Exploitation¶
Kubernetes RBAC controls who can perform what actions on which resources. Common misconfigurations create escalation paths.
| Misconfiguration | Risk | Impact |
|---|---|---|
cluster-admin ClusterRoleBinding to default SA | Any pod can control the cluster | CRITICAL |
Wildcard verbs (*) on secrets | Read all secrets including service account tokens | HIGH |
create on pods + any service account | Create pod with privileged SA | HIGH |
list on secrets cluster-wide | Enumerate all secrets across namespaces | HIGH |
escalate verb on roles | Create roles with higher privileges | CRITICAL |
bind verb on clusterrolebindings | Bind cluster-admin to any subject | CRITICAL |
# SYNTHETIC — Overly permissive ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: synth-dev-role
rules:
- apiGroups: [""]
resources: ["pods", "pods/exec"]
verbs: ["*"] # Can create, exec into any pod
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "list"] # Can read all secrets
- apiGroups: [""]
resources: ["serviceaccounts"]
verbs: ["get", "list"]
# RISK: Developer with this role can:
# 1. List all secrets (including admin tokens)
# 2. Create a pod with a privileged service account
# 3. Exec into the pod and use the SA token
# 4. Escalate to cluster-admin
# SYNTHETIC — Namespace-scoped, least-privilege Role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: synth-dev-role
namespace: synth-dev-ns # Scoped to namespace
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"] # Read-only for pods
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "update"] # Specific verbs
# NO access to secrets, service accounts, or pods/exec
46.5.3 etcd Access and Secrets Extraction¶
Concept: etcd is the key-value store backing all Kubernetes cluster state, including Secrets. If an attacker gains access to etcd directly (port 2379), they can read all cluster data, including Secrets stored in plaintext (unless encryption at rest is configured).
SYNTHETIC SCENARIO — etcd Exposure
═══════════════════════════════════════════════
Cluster: synth-cluster (198.51.100.0/24)
etcd endpoint: https://198.51.100.20:2379
ATTACK CONCEPT:
1. Attacker compromises a node in the cluster network
2. etcd is accessible without mutual TLS authentication
3. Attacker queries etcd for all secrets:
etcdctl get /registry/secrets --prefix (conceptual)
4. Retrieves: database passwords, API keys, TLS certificates
PREVENTION:
□ Enable mutual TLS (mTLS) for all etcd communication
□ Restrict etcd port (2379) to API server nodes only
□ Enable encryption at rest for Kubernetes Secrets
□ Use external secrets management (Vault, AWS Secrets Manager)
□ Network policy: isolate etcd to dedicated subnet
□ Regular rotation of etcd peer and client certificates
46.5.4 Kubelet API Exploitation¶
Concept: The kubelet runs on every node and exposes an API (port 10250) that allows pod management. If the kubelet API is exposed without authentication, attackers can execute commands in any pod on that node.
Default Risk
In some Kubernetes distributions, the kubelet API's --anonymous-auth defaults to true. This means unauthenticated requests are allowed. Always set --anonymous-auth=false and configure webhook authentication.
46.6 Serverless Attack Concepts¶
46.6.1 Serverless Threat Model¶
Serverless functions (AWS Lambda, Azure Functions, GCP Cloud Functions) introduce unique attack surfaces:
| Attack Vector | Concept | Defense |
|---|---|---|
| Event injection | Malicious data in triggers (S3, SQS, API Gateway) | Input validation in function code |
| Environment variable exposure | Secrets stored in env vars accessible to function | Use Secrets Manager with IAM policies |
| Over-permissioned execution role | Lambda role with *:* permissions | Least-privilege IAM for each function |
| Dependency vulnerability | Vulnerable library in deployment package | SCA scanning in CI/CD pipeline |
| Cold start timing attack | Information leakage through execution timing | Not typically exploitable — theoretical |
| Cross-function data flow | Shared resources (S3, DynamoDB) between functions | Resource-level IAM policies |
46.6.2 Lambda Privilege Escalation (Conceptual)¶
SYNTHETIC SCENARIO — Lambda Escalation
═══════════════════════════════════════════
Account: 111122223333 (SYNTHETIC)
Region: us-east-1
Vulnerable Configuration:
- User "synth-dev" has: lambda:CreateFunction, iam:PassRole
- Existing role "SynthAdminRole" has AdministratorAccess
- No permission boundary on SynthAdminRole
ESCALATION CONCEPT:
1. Create Lambda function with SynthAdminRole as execution role
2. Function code creates new IAM user with AdministratorAccess
3. Invoke the function
4. New admin credentials are created
PREVENTION:
□ Permission boundaries on all roles (cap maximum permissions)
□ Restrict iam:PassRole with condition keys (specific roles only)
□ SCPs to prevent creation of users without permission boundaries
□ CloudTrail monitoring for lambda:CreateFunction + iam:PassRole
46.7 Cloud Security Assessment Tools (Theory)¶
46.7.1 Tool Landscape¶
| Tool | Type | Coverage | Key Capability |
|---|---|---|---|
| Pacu | Offensive | AWS | IAM escalation, enumeration, exploitation framework |
| ScoutSuite | Assessment | Multi-cloud | Configuration audit against security best practices |
| Prowler | CSPM | AWS/Azure/GCP | CIS benchmark compliance, 300+ security checks |
| Trivy | Scanner | Containers/IaC | Image vulnerability + misconfiguration scanning |
| kube-bench | Audit | Kubernetes | CIS Kubernetes benchmark compliance |
| Checkov | IaC Scanner | Multi-cloud | Terraform/CloudFormation policy enforcement |
| CloudSploit | CSPM | Multi-cloud | Automated cloud security monitoring |
46.7.2 CSPM Coverage Model¶
graph TD
A[Cloud Security Posture\nManagement - CSPM] --> B[Identity & Access]
A --> C[Network Security]
A --> D[Data Protection]
A --> E[Logging & Monitoring]
A --> F[Compute Security]
A --> G[Container Security]
B --> B1[IAM policies audit]
B --> B2[MFA enforcement]
B --> B3[Key rotation]
C --> C1[Security groups]
C --> C2[Public exposure]
C --> C3[VPC flow logs]
D --> D1[Encryption at rest]
D --> D2[Encryption in transit]
D --> D3[Bucket policies]
E --> E1[CloudTrail enabled]
E --> E2[Log integrity]
E --> E3[SIEM integration]
style A fill:#1d3557,color:#fff
style B fill:#457b9d,color:#fff
style C fill:#457b9d,color:#fff
style D fill:#457b9d,color:#fff
style E fill:#457b9d,color:#fff
style F fill:#457b9d,color:#fff
style G fill:#457b9d,color:#fff 46.8 Blue Team Detection Correlation¶
46.8.1 Cloud Detection Matrix¶
| Attack Technique | AWS Detection | Azure Detection | GCP Detection |
|---|---|---|---|
| IAM credential theft | CloudTrail: GetSessionToken from unusual IP | Sign-in logs: unfamiliar location | Admin Activity: CreateServiceAccountKey |
| Privilege escalation | CloudTrail: AttachUserPolicy, CreatePolicy | Activity log: role assignment changes | IAM audit: SetIamPolicy |
| Metadata abuse | VPC Flow Logs: 169.254.169.254 access patterns | NSG flow logs + Defender alerts | VPC flow logs + metadata access |
| S3/Blob exfiltration | CloudTrail data events: unusual GetObject volume | Storage analytics: bulk download | Data Access audit: unusual reads |
| Container escape | GuardDuty: PrivilegeEscalation:Runtime | Defender for Containers alerts | Security Command Center findings |
| K8s API abuse | EKS audit logs: unusual API calls | AKS diagnostic logs | GKE audit logs |
46.8.2 Cloud-Native Detection Rules (Conceptual)¶
-- CONCEPTUAL — CloudTrail query for IAM escalation
-- Platform: Amazon Athena / SIEM
SELECT
eventTime,
userIdentity.arn,
eventName,
requestParameters,
sourceIPAddress
FROM cloudtrail_logs
WHERE eventName IN (
'CreateUser', 'CreateAccessKey',
'AttachUserPolicy', 'AttachRolePolicy',
'PutUserPolicy', 'PutRolePolicy',
'CreateRole', 'UpdateAssumeRolePolicy'
)
AND sourceIPAddress NOT IN ('198.51.100.0/24') -- Known admin IPs
AND eventTime > current_timestamp - interval '24' hour
ORDER BY eventTime DESC
-- CONCEPTUAL — K8s audit log query
-- Detect: secrets enumeration, exec into pods, privilege escalation
SELECT
requestReceivedTimestamp,
user.username,
verb,
objectRef.resource,
objectRef.namespace,
sourceIPs
FROM k8s_audit_logs
WHERE
(verb = 'list' AND objectRef.resource = 'secrets')
OR (verb = 'create' AND objectRef.resource = 'pods/exec')
OR (verb IN ('create','update') AND objectRef.resource = 'clusterrolebindings')
ORDER BY requestReceivedTimestamp DESC
46.8.3 Cloud Security Controls Checklist¶
CLOUD RED TEAM DEFENSE VALIDATION CHECKLIST
══════════════════════════════════════════════════════
IAM:
□ MFA enforced for all human users (console + CLI)
□ No long-lived access keys (use temporary credentials)
□ Permission boundaries on all IAM entities
□ Regular access reviews (IAM Access Analyzer / Recommender)
□ SCPs/Organization Policies to prevent privilege escalation
Network:
□ IMDSv2 enforced (HttpTokens=required)
□ No public-facing management interfaces
□ VPC Flow Logs enabled and monitored
□ Security groups follow least-privilege (no 0.0.0.0/0 ingress)
Containers:
□ No privileged containers in production
□ Pod Security Standards enforced (Restricted profile)
□ Network policies implemented for pod-to-pod traffic
□ Image scanning in CI/CD pipeline with vulnerability thresholds
□ Admission controllers: OPA Gatekeeper or Kyverno
Kubernetes:
□ RBAC follows least-privilege (namespace-scoped roles)
□ Default service account tokens disabled (automountServiceAccountToken: false)
□ etcd encrypted at rest and access restricted
□ Kubelet authentication enabled (--anonymous-auth=false)
□ Audit logging enabled and forwarded to SIEM
Monitoring:
□ CloudTrail/Activity Log/Audit Log enabled in all regions
□ GuardDuty/Defender/Security Command Center active
□ Alerts for IAM changes, unusual API calls, data access
□ Automated response (Lambda/Function) for critical findings
Exam Prep & Certifications¶
Relevant Certifications
The topics in this chapter align with the following certifications:
Review Questions¶
1. Explain how an SSRF vulnerability leads to cloud credential theft via IMDSv1, and how IMDSv2 mitigates this.
With IMDSv1, any HTTP GET request to http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name> returns temporary IAM credentials. An SSRF vulnerability allows an attacker to make the application issue this request, leaking the credentials. IMDSv2 mitigates this by requiring a session token obtained via a PUT request — most SSRF vulnerabilities only allow GET requests and cannot forge the PUT + header combination. Additionally, IMDSv2 uses a TTL of 1 for the IP hop count, preventing token requests from containers reaching the host's IMDS.
2. Why is iam:PassRole combined with lambda:CreateFunction a dangerous permission pair?
iam:PassRole allows a user to assign an IAM role to an AWS service. lambda:CreateFunction allows creating Lambda functions. Combined, a user can create a Lambda function that executes with the permissions of a highly-privileged role (e.g., AdministratorAccess), effectively escalating their own privileges through the function's execution role. This is mitigated by restricting iam:PassRole to specific role ARNs and applying permission boundaries.
3. What is the primary risk of mounting the Docker socket inside a container?
Mounting /var/run/docker.sock inside a container gives that container direct access to the Docker daemon on the host. The Docker daemon runs as root, so any process in the container can use the socket to create new containers with host filesystem access, execute commands on other containers, or launch a privileged container — effectively achieving full host compromise. This is equivalent to root access on the host.
4. Describe three Kubernetes RBAC misconfigurations that lead to cluster compromise.
(1) Binding cluster-admin to a default service account — any pod using that SA gets full cluster control. (2) Granting wildcard verbs (*) on secrets — allows reading all secrets including service account tokens for privilege escalation. (3) Granting create on pods with get on service accounts — an attacker can create a pod using a privileged service account and exec into it to use those privileges.
5. How does encryption at rest for Kubernetes Secrets protect against etcd compromise?
Without encryption at rest, Kubernetes Secrets are stored as base64-encoded plaintext in etcd. If an attacker gains direct access to etcd, they can read all secrets immediately. With encryption at rest configured (using an EncryptionConfiguration with AES-CBC or AES-GCM), Secrets are encrypted before being written to etcd. An attacker with etcd access would only see encrypted data and would need the encryption key (stored separately) to decrypt them.
6. What is a Permission Boundary in AWS and why is it critical for preventing IAM escalation?
A Permission Boundary is an advanced IAM feature that defines the maximum permissions an IAM entity (user or role) can have. It acts as a guardrail: even if an identity-based policy grants *:*, the effective permissions are the intersection of the identity policy and the permission boundary. This prevents IAM escalation because even if an attacker creates a new policy granting full access, they cannot exceed the boundary. All IAM entities created by non-admin users should have permission boundaries enforced.
Key Takeaways¶
Chapter Summary
- IAM is the cloud perimeter — privilege escalation paths in cloud environments stem from over-permissioned IAM policies, not network misconfigurations. Audit IAM continuously.
- Metadata services are high-value targets — enforce IMDSv2 in AWS, restrict managed identity token endpoints in Azure, and limit service account impersonation in GCP.
- Container escapes bridge the container-to-host boundary — never run privileged containers, never mount the Docker socket, and enforce Pod Security Standards.
- Kubernetes RBAC requires least-privilege discipline — use namespace-scoped Roles instead of ClusterRoles, disable default service account token mounting, and protect etcd with mTLS and encryption at rest.
- Serverless functions inherit their execution role's permissions — apply least-privilege to every function role and use permission boundaries.
- Cloud detection requires cloud-native logging — CloudTrail, Azure Activity Logs, GCP Audit Logs, and Kubernetes audit logs are the foundation of cloud security monitoring.
- CSPM tools automate baseline validation — deploy Prowler, ScoutSuite, or equivalent tooling for continuous compliance monitoring.
- The shared responsibility model defines your defensive boundary — understand what the cloud provider secures versus what you must secure.