Cloud & Container Security Exercises
Sixteen exercises across the whole course, in the order of its sections. Each is the kind of judgement a cloud security reviewer makes every week: read a policy, a configuration, an event or a manifest, decide what it allows, and say how to detect and fix it. Try each before opening the answer. Exercise 10's answer includes a program you can edit and run.
| # | Exercise | Practises |
|---|---|---|
| 1 | Whose fix is it? | Shared Responsibility |
| 2 | Allowed or denied? | Policy Evaluator |
| 3 | The capped administrator | Boundaries and SCPs |
| 4 | Spot the escalation | Over-Broad Policies |
| 5 | Read the trust policy | Role Assumption, Workload Identity |
| 6 | Is it exposed? | VPC Exposure Review, Egress |
| 7 | Public or not? | Object Storage |
| 8 | Who can decrypt? | KMS and Envelope Encryption, Secrets |
| 9 | A key on GitHub | Leaked Keys |
| 10 | Write the detection | Audit Logs, Cloud Detections, Managed Detection |
| 11 | The SSRF finding | IMDS, Metadata Credential Theft |
| 12 | Decode and judge the container | Isolation, seccomp and LSMs, Escapes |
| 13 | Review the Dockerfile and the rule | Image Hardening, Runtime Detection |
| 14 | Who can read the Secrets? | RBAC Review, K8s Audit |
| 15 | Harden the namespace | Attack Surface, Pod Security, NetworkPolicies, Admission |
| 16 | From finding to guardrail | IaC Scanning, Policy as Code, Posture |
Exercise 1: Whose fix is it?
For each finding, say customer, provider or shared, and what the customer does: (a) the Lambda runtime's language version reaches end of support; (b) an Azure SQL database allows connections from all Azure services; (c) a GKE Autopilot node runs an old kernel; (d) the SaaS ticketing system lets any user create public share links.
Answer
(a) Shared: the provider stops patching the deprecated runtime, the customer must move the function to a supported one. (b) Customer: a configuration setting ("allow Azure services") that opens the server to every tenant's resources; restrict to private endpoints. (c) Provider: Autopilot nodes are managed; check the provider's bulletins and the cluster's release channel. (d) Customer: sharing settings in SaaS are the customer's configuration.
Exercise 2: Allowed or denied?
Bucket policy on lab-reports (account 123456789012): Allow s3:GetObject to {"AWS": "arn:aws:iam::210987654321:root"} on arn:aws:s3:::lab-reports/*, and Deny s3:* to * when aws:SecureTransport is false. Decide for: (a) role analytics in 210987654321 with an identity policy allowing s3:GetObject on *, over HTTPS; (b) the same over HTTP; (c) role intern in 210987654321 with no S3 permissions, over HTTPS; (d) user alice in 123456789012 with no S3 permissions, over HTTPS.
Answer
(a) Allowed: cross-account, both sides allow. (b) Denied: explicit deny wins. (c) Denied: the bucket trusts the account, but cross-account access also needs the caller's identity policy. (d) Denied: same account, but neither her identity policy nor the bucket policy names her (the bucket grants only to the other account).
Exercise 3: The capped administrator
A role has AdministratorAccess, a permission boundary allowing ec2:*, s3:* and iam:PassRole on arn:aws:iam::123456789012:role/app-*, and its account is under an SCP denying s3:DeleteBucket. Can it (a) delete a bucket, (b) launch an instance passing role/app-worker, (c) launch one passing role/admin-role, (d) create an IAM user?
Answer
(a) No (SCP explicit deny). (b) Yes: EC2 is in the boundary, PassRole on app-* matches. (c) No: the boundary doesn't allow passing admin-role. (d) No: not in the boundary (implicit deny). Check also that the role can't change its own boundary.
Exercise 4: Spot the escalation
Which of these grants is an escalation path, and which is merely broad? (a) iam:AttachUserPolicy on arn:aws:iam::123456789012:user/${aws:username}; (b) ec2:* on *; (c) iam:PassRole on * plus cloudformation:CreateStack; (d) secretsmanager:GetSecretValue on *.
Answer
(a) Escalation: the user can attach any managed policy (including AdministratorAccess) to themselves; the ${aws:username} scope makes it self-escalation, not safe. (b) Broad, not IAM escalation, but it includes RunInstances (with an existing instance profile only if PassRole exists) and destructive actions. (c) Escalation: a stack can be created with any passable role as its service role, which then creates resources with that role's power. (d) Broad data access: every secret, often including other credentials, which makes it an indirect escalation.
Exercise 5: Read the trust policy
{"Effect": "Allow",
"Principal": {"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {"StringLike": {"token.actions.githubusercontent.com:sub": "repo:lab-org/*"},
"StringEquals": {"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"}}}Who can assume the role, what is the risk, and what would you change? For a Kubernetes IRSA role, what is the equivalent mistake?
Answer
Any workflow run in any repository of lab-org, on any branch, tag, pull request or environment. A pull request from a contributor's branch, or any team's repository, gets the role. Pin sub with StringEquals to repo:lab-org/shop:environment:production (with environment protection rules) or the protected branch. For IRSA: system:serviceaccount:*:name or system:serviceaccount:ns:*.
Exercise 6: Is it exposed?
An RDS instance has publicly_accessible = false, sits in a private subnet (route only to a NAT gateway), and its security group allows 5432 from 0.0.0.0/0. A Lambda function in the same VPC has no VPC endpoints and a NAT route. (a) Is the database reachable from the Internet? (b) What is still wrong? (c) Where can the Lambda send data?
Answer
(a) No: no public address and no Internet gateway route. (b) The security group is a latent finding: anything in the VPC (or peered networks) can reach it, and one change (publicly_accessible, a route) exposes it; reference the app's security group instead. (c) Anywhere on the Internet through the NAT gateway: add VPC endpoints for the AWS services it uses and an egress allow-list.
Exercise 7: Public or not?
Account-level Block Public Access: all four settings on. A bucket policy grants s3:GetObject to "*" with condition {"StringEquals": {"aws:SourceVpce": "vpce-0a1b2c3d"}}. Is the bucket public? Can the policy even be saved? Who can read?
Answer
Not public: aws:SourceVpce with a fixed value pins the caller to that endpoint, so S3 doesn't classify the policy as public, and BlockPublicPolicy accepts it. Anyone whose request arrives through that VPC endpoint can read, including any principal using the endpoint; combine with aws:PrincipalOrgID and an endpoint policy to make it "our principals, through our network".
Exercise 8: Who can decrypt?
A KMS key policy contains only the default statement (arn:aws:iam::123456789012:root with kms:*). Role reports has an identity policy allowing kms:Decrypt on *. A bucket uses SSE-KMS with this key. (a) Can reports decrypt objects? (b) What changes if the key policy is replaced by one naming only app-role? (c) How would you see each decryption?
Answer
(a) Yes: the default statement delegates to IAM policies in the account, and reports has one (it also needs s3:GetObject). (b) reports can no longer decrypt, whatever its identity policy says: without the delegation statement, the key policy is the only grant. (c) CloudTrail Decrypt events from kms.amazonaws.com with the caller and the encryption context (the object ARN, or only the bucket ARN, with far fewer events, if S3 Bucket Keys are enabled).
Exercise 9: A key on GitHub
At 09:00 a scanner reports AKIA… for user deploy-bot in a public commit pushed at 08:20. List your first five actions in order.
Answer
- Deactivate the key. 2. Search CloudTrail (all regions) for the key ID from 08:20 to now. 3. List and undo what it created: users, keys, login profiles, roles, policy changes, instances, functions, shared snapshots. 4. Replace
deploy-bot's key with CI OIDC federation (no long-lived key), then delete the key. 5. Rotate any secret it could read, and add pre-commit and CI secret scanning to the repository. (Removing the commit comes after revocation, and doesn't undo the leak.)
Exercise 10: Write the detection
Write predicates over CloudTrail-style events for: (a) an access key created for a user by someone else; (b) a trail stopped by anyone except role/logging-pipeline; (c) a GuardDuty-style "instance credentials used outside the instance" using a table of instance IPs. Test (a) on two events.
Answer
def key_for_other(e):
return e["eventName"] == "CreateAccessKey" and e["requestParameters"].get("userName") not in (None, e["userIdentity"].get("userName"))
def trail_stopped(e):
return e["eventName"] in ("StopLogging", "DeleteTrail") and not e["userIdentity"]["arn"].endswith("role/logging-pipeline")
INSTANCE_IPS = {"i-0a1b2c3d4e5f60001": {"10.10.0.70", "198.51.100.5"}}
def instance_creds_outside(e):
session = e["userIdentity"]["arn"].split("/")[-1]
return session.startswith("i-") and e.get("sourceIPAddress") not in INSTANCE_IPS.get(session, set())
events = [
{"eventName": "CreateAccessKey", "requestParameters": {"userName": "bob"}, "userIdentity": {"userName": "bob", "arn": "arn:aws:iam::123456789012:user/bob"}},
{"eventName": "CreateAccessKey", "requestParameters": {"userName": "alice"}, "userIdentity": {"userName": "mallory", "arn": "arn:aws:iam::123456789012:user/mallory"}},
{"eventName": "StopLogging", "requestParameters": {}, "userIdentity": {"arn": "arn:aws:iam::123456789012:role/logging-pipeline"}},
{"eventName": "GetObject", "requestParameters": {}, "sourceIPAddress": "203.0.113.66",
"userIdentity": {"arn": "arn:aws:sts::123456789012:assumed-role/app-role/i-0a1b2c3d4e5f60001"}},
]
for e in events:
hits = [f.__name__ for f in (key_for_other, trail_stopped, instance_creds_outside) if f(e)]
print(f"{e['eventName']:16} by {e['userIdentity']['arn'].split(':')[-1]:52} {hits or '-'}")CreateAccessKey by user/bob -
CreateAccessKey by user/mallory ['key_for_other']
StopLogging by role/logging-pipeline -
GetObject by assumed-role/app-role/i-0a1b2c3d4e5f60001 ['instance_creds_outside']
Only Mallory's key for Alice and the instance credentials from an outside address fire; Bob's own key and the pipeline's planned trail change don't.
Exercise 11: The SSRF finding
A penetration test reports: "the image proxy at /fetch?url= retrieved http://169.254.169.254/latest/meta-data/ in scope". The instance has HttpTokens=optional, hop limit 1, and role img-role with s3:GetObject on lab-*. Rate it, and give the fix in order of speed.
Answer
Critical: an unauthenticated SSRF reaches IMDSv1, so the role's credentials (reading every lab-* bucket, possibly including lab-trail-… and exports) are one request away. Fixes: (1) modify-instance-metadata-options --http-tokens required (minutes; also in the launch template); (2) narrow img-role to the one bucket it needs and add a network-perimeter condition; (3) fix the proxy with an allow-list and no redirects; (4) add the metadata-credential detection. Check CloudTrail for prior use of img-role sessions from outside.
Exercise 12: Decode and judge the container
A container's /proc/1/status shows CapBnd: 00000000a82425fb, Seccomp: 0, and docker inspect shows a bind of /var/log:/host/log. Which capability was added, what is off, and what is the overall verdict?
Answer
0xa82425fb − 0xa80425fb = 0x200000 = bit 21, CAP_SYS_ADMIN. Seccomp: 0 means no filter (unconfined). With a host log mount that is a combination behind known escape classes (mount operations, symlink tricks in host paths): HIGH to CRITICAL. Fix: drop SYS_ADMIN, restore RuntimeDefault seccomp, ship logs with an agent designed for it rather than a host mount in an application container.
Exercise 13: Review the Dockerfile and the rule
FROM node:22
COPY . /srv
RUN npm ci && npm run build
ENV NPM_TOKEN=npm_lab_not_real_0000
CMD ["node", "/srv/dist/server.js"]List the findings, then write a Falco-style condition that would catch an attacker installing tools in this container at run time.
Answer
Mutable tag (pin by digest), runs as root (add USER node or a numeric UID), full base image with build tools (multi-stage to a slim or distroless runtime), COPY . without .dockerignore (may include .env, .git), a token in ENV (in every layer; use a build secret mount and revoke the token). Rule: spawned_process and container and proc.name in (apt, apt-get, apk, npm, curl, wget) and k8s.ns.name = shop (with npm only flagged at run time, not during builds, which don't run in the cluster).
Exercise 14: Who can read the Secrets?
In namespace pay: Role ops allows get, list on secrets; Role deployer allows create, update on deployments; RoleBindings: ops → Group pay-oncall, deployer → ServiceAccount ci/deployer. A ClusterRoleBinding gives Group auditors the ClusterRole view. Who can read Secrets in pay, directly or indirectly?
Answer
Directly: pay-oncall. Indirectly: ci/deployer, because it can update a deployment to run under any service account in pay and mount any Secret there (and its pods can print them). auditors with view cannot (the built-in view excludes Secrets). Confirm with kubectl auth can-i list secrets -n pay --as=… and watch audit logs for Secret reads.
Exercise 15: Harden the namespace
A new namespace pay gets its first workloads tomorrow. Write the five objects or settings you create today, and one check each.
Answer
- Labels
pod-security.kubernetes.io/enforce: restricted(+warn,audit, pinned version); check: a dry-run server-side label on existing namespaces,kubectl runof a privileged test pod fails. 2. A default-deny NetworkPolicy for ingress and egress plus DNS egress; check: a test pod can resolve names but not reach other namespaces or169.254.169.254. 3. Admission policies: images from the internal registry, digests, signatures; check: a public image is rejected, including as an init container. 4. RBAC: groups bound to narrow Roles, nolist secretsfor humans, CI deploys only; check:kubectl auth can-i --listper identity. 5. Audit-log detections for exec, Secret listing and privileged pod attempts inpay; check: replay recorded events.
Exercise 16: From finding to guardrail
The posture checker keeps reporting "instance allows IMDSv1" for new instances every week. Turn the recurring finding into guardrails at three stages.
Answer
Code: a custom check (Rego in Trivy or Conftest on plans) failing aws_instance and aws_launch_template without metadata_options { http_tokens = "required" } (Trivy's built-in AWS-0028 already flags instances). Deployment: an SCP denying ec2:RunInstances unless ec2:MetadataHttpTokens is required, plus the account-level IMDS default set to v2-only. Running: the posture rule stays, now as a regression alarm, with an owner and an SLA; and a CloudWatch alarm on MetadataNoToken for the remaining old instances.
Test yourself
Exercise 2: why is the intern in the trusted account denied?
- HTTP was used
- Cross-account access needs an allow in the caller's identity policy as well as the bucket policy
- Interns can't use S3
- The bucket is in another region
Exercise 12: which capability does CapBnd 00000000a82425fb add to Docker's default set?
- NET_ADMIN
- SYS_PTRACE
- SYS_ADMIN
- SYS_MODULE
Exercise 14: why can ci/deployer read Secrets in pay without any Secret permission?
- It can't
- It can change a deployment to run as any service account in pay and mount any Secret there
- CI is always admin
- view includes Secrets