TExcelTAD
Home › Cloud & Container Security › Mini Project: Security Review of a Synthetic Cloud Account

Mini Project: Security Review of a Synthetic Cloud Account

You have been engaged to review the lab account 123456789012 before the shop application goes live. The review is read-only and configuration-based: you receive an export of IAM, storage, network, audit-log and Kubernetes configuration, plus the repository with the Terraform, the Dockerfile and the manifests. Nothing is tested against live systems; every name, ID and address is synthetic. In a real engagement the same work needs written authorization naming the accounts, the access you get (a read-only audit role), the time window and who receives the report (Authorization, Scope and Rules of Engagement).

The brief

Scope: account 123456789012 (production), region eu-west-1 plus global services; the EKS cluster shop; the shop repository. Out of scope: the development account, the vendor account 999988887777, any active testing.

Deliverables:

  1. A findings list: ID, severity, affected resource, evidence, impact, fix, and how to detect abuse.
  2. The top attack paths, each as a chain of findings.
  3. Pre-deployment checks for the repository, with results.
  4. A report for the account owner, using the template in step 4.

Step 1: review the account export

The program holds the export and runs one check family per section of the course, each a compact version of a lesson's tool. Read the checks and the export side by side; then change the export (fix a finding) and run it again.

python · try it yourself
import json, ipaddress
from fnmatch import fnmatchcase

export = json.loads("""{
 "iam": {
  "policies": {
   "app-role": [{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": "arn:aws:s3:::lab-*"},
                {"Effect": "Allow", "Action": "iam:PassRole", "Resource": "*"},
                {"Effect": "Allow", "Action": "lambda:CreateFunction", "Resource": "*"}],
   "ci-deploy": [{"Effect": "Allow", "Action": "*", "Resource": "*"}],
   "support": [{"Effect": "Allow", "Action": ["iam:UpdateLoginProfile", "iam:ListUsers"], "Resource": "arn:aws:iam::123456789012:user/*"}],
   "reports": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::lab-reports/*"}]},
  "trust": {
   "ci-deploy": {"Principal": {"Federated": "token.actions.githubusercontent.com"},
                 "Condition": {"StringEquals": {"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"}}},
   "vendor-read": {"Principal": {"AWS": "arn:aws:iam::999988887777:root"}, "Condition": {}}},
  "users": [{"name": "legacy-sync", "keys": [{"age_days": 520, "last_used_days": 3}], "mfa": false, "console": false}]},
 "buckets": {
  "lab-customer-exports": {"data": "confidential", "bpa_restrict": false,
     "policy": [{"Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Condition": {"StringEquals": {"aws:UserAgent": "partner-sync"}}}]},
  "lab-reports": {"data": "internal", "bpa_restrict": true, "policy": []},
  "lab-trail-123456789012": {"data": "audit", "bpa_restrict": true, "policy": [], "object_lock": false}},
 "network": {
  "sgs": {"sg-web": [[443, "0.0.0.0/0"]], "sg-admin": [[22, "0.0.0.0/0"], [5432, "10.10.0.0/24"]]},
  "instances": [{"id": "i-0a1b2c3d4e5f60001", "public_ip": "203.0.113.20", "subnet_igw": true, "sgs": ["sg-web"],
                 "imds": "optional", "hop_limit": 1, "role": "app-role"},
                {"id": "i-0a1b2c3d4e5f60002", "public_ip": "203.0.113.21", "subnet_igw": true, "sgs": ["sg-admin"],
                 "imds": "required", "hop_limit": 1, "role": null}]},
 "trail": {"multi_region": true, "log_validation": false, "data_events": []},
 "events": [
  {"t": "2026-06-01T02:14:09Z", "name": "ConsoleLogin", "who": "Root", "ip": "198.51.100.23", "mfa": "No"},
  {"t": "2026-06-01T02:20:31Z", "name": "PutBucketPolicy", "who": "Root", "ip": "198.51.100.23", "target": "lab-customer-exports"},
  {"t": "2026-06-02T10:00:00Z", "name": "GetObject", "who": "assumed-role/app-role/i-0a1b2c3d4e5f60001", "ip": "10.10.0.70"}],
 "pod": {"name": "web", "ns": "shop", "privileged": false, "runAsNonRoot": false, "hostPath": ["/var/run/docker.sock"],
         "image": "registry.lab.test/shop/web:latest", "serviceAccount": "default", "automountToken": true}
}""")

findings = []
def add(sev, area, resource, issue, fix, detect):
    findings.append({"sev": sev, "area": area, "res": resource, "issue": issue, "fix": fix, "detect": detect})

# --- Identity (policy evaluator, escalation finder, trust checker, key hygiene)
L = lambda x: x if isinstance(x, list) else [x]
def grants(stmts, action):
    return [r for s in stmts if s["Effect"] == "Allow" and any(fnmatchcase(action.lower(), a.lower()) for a in L(s["Action"])) for r in L(s["Resource"])]
for role, stmts in export["iam"]["policies"].items():
    if "*" in grants(stmts, "iam:DeleteRole") and "*" in grants(stmts, "s3:DeleteBucket"):
        add("CRITICAL", "Identity", role, "Action * on Resource * (administrator)", "scope to the services and ARNs the pipeline deploys", "CloudTrail IAM writes by this principal")
    elif "*" in grants(stmts, "iam:PassRole") and grants(stmts, "lambda:CreateFunction"):
        add("CRITICAL", "Identity", role, "iam:PassRole on * + lambda:CreateFunction: can run code as any role", "exact role ARNs + iam:PassedToService", "CreateFunction with a role other than the expected one")
    for r in grants(stmts, "iam:UpdateLoginProfile"):
        if r.endswith("/*"):
            add("HIGH", "Identity", role, f"iam:UpdateLoginProfile on {r}: can take over any user", "remove; use the identity provider's reset flow", "UpdateLoginProfile for another userName")
for role, t in export["iam"]["trust"].items():
    keys = {k for tests in t["Condition"].values() for k in tests}
    if "Federated" in t["Principal"] and not any(k.endswith(":sub") for k in keys):
        add("CRITICAL", "Identity", role, "OIDC trust without sub: any repository on the CI service can assume it", "pin sub to repo and environment", "AssumeRoleWithWebIdentity with unknown sub")
    if "AWS" in t["Principal"] and ":root" in t["Principal"]["AWS"] and "sts:ExternalId" not in keys:
        add("HIGH", "Identity", role, "foreign account trusted without external ID", "require sts:ExternalId", "AssumeRole from that account")
for u in export["iam"]["users"]:
    for k in u["keys"]:
        if k["age_days"] > 90:
            add("MEDIUM", "Identity", u["name"], f"long-lived access key, {k['age_days']} days old, in use", "replace with a role / federation", "key used from new IPs")
# --- Data (bucket evaluator)
PINNING = {"aws:SourceVpce", "aws:PrincipalOrgID", "aws:SourceIp", "aws:PrincipalAccount"}
for name, b in export["buckets"].items():
    public = [s for s in b["policy"] if s["Principal"] == "*" and not ({k for v in s.get("Condition", {}).values() for k in v} & PINNING)]
    if public and not b["bpa_restrict"]:
        add("CRITICAL", "Data", name, f"public read ({b['data']} data); the UserAgent condition doesn't pin the caller", "remove the statement, enable all BPA settings", "GetObject by anonymous principals")
    if b["data"] == "audit" and not b.get("object_lock"):
        add("MEDIUM", "Logging", name, "audit bucket without object lock", "object lock / separate log-archive account", "PutBucketPolicy, DeleteObject on it")
# --- Network and IMDS (exposure review)
for i in export["network"]["instances"]:
    for port, cidr in [r for sg in i["sgs"] for r in export["network"]["sgs"][sg]]:
        if cidr == "0.0.0.0/0" and i["public_ip"] and i["subnet_igw"] and port in (22, 3389):
            add("HIGH", "Network", i["id"], f"port {port} reachable from the Internet", "session manager instead of SSH", "flow logs, auth logs")
    if i["imds"] != "required":
        add("HIGH", "Compute", i["id"], "IMDSv1 allowed on an Internet-facing instance", "http-tokens required, in the launch template too", "MetadataNoToken metric; role use outside the instance")
# --- Logging and detection (rules over events)
if not export["trail"]["log_validation"]:
    add("MEDIUM", "Logging", "org-trail", "log file validation off", "enable validation", "-")
if not export["trail"]["data_events"]:
    add("MEDIUM", "Logging", "org-trail", "no S3 data events: object reads of confidential data are invisible", "data events for confidential buckets", "-")
for e in export["events"]:
    if e["who"] == "Root":
        add("HIGH", "Detection", e["name"], f"root activity at {e['t']} from {e['ip']} (MFA {e.get('mfa', '-')})", "investigate; root MFA; alert on root use", "this event")
# --- Kubernetes (pod review)
p = export["pod"]
if p["hostPath"]:
    add("CRITICAL", "Kubernetes", f"{p['ns']}/{p['name']}", f"hostPath {p['hostPath']}: runtime socket = node root", "remove; enforce Pod Security baseline+", "runtime rule: socket opened in container")
if not p["runAsNonRoot"]:
    add("MEDIUM", "Kubernetes", f"{p['ns']}/{p['name']}", "may run as root", "runAsNonRoot, drop ALL, RuntimeDefault seccomp", "-")
if p["serviceAccount"] == "default" and p["automountToken"]:
    add("LOW", "Kubernetes", f"{p['ns']}/{p['name']}", "default service account token mounted", "own SA, automount false", "-")
if p["image"].endswith(":latest"):
    add("LOW", "Kubernetes", f"{p['ns']}/{p['name']}", "image by mutable tag", "pin by digest, admission check", "-")

ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"]
findings.sort(key=lambda f: (ORDER.index(f["sev"]), f["area"]))
for n, f in enumerate(findings, 1):
    print(f"F{n:02d} {f['sev']:8} {f['area']:10} {f['res']:24} {f['issue']}")
print("\n" + ", ".join(f"{sum(f['sev'] == s for f in findings)} {s}" for s in ORDER))
F01 CRITICAL Data       lab-customer-exports     public read (confidential data); the UserAgent condition doesn't pin the caller
F02 CRITICAL Identity   app-role                 iam:PassRole on * + lambda:CreateFunction: can run code as any role
F03 CRITICAL Identity   ci-deploy                Action * on Resource * (administrator)
F04 CRITICAL Identity   ci-deploy                OIDC trust without sub: any repository on the CI service can assume it
F05 CRITICAL Kubernetes shop/web                 hostPath ['/var/run/docker.sock']: runtime socket = node root
F06 HIGH     Compute    i-0a1b2c3d4e5f60001      IMDSv1 allowed on an Internet-facing instance
F07 HIGH     Detection  ConsoleLogin             root activity at 2026-06-01T02:14:09Z from 198.51.100.23 (MFA No)
F08 HIGH     Detection  PutBucketPolicy          root activity at 2026-06-01T02:20:31Z from 198.51.100.23 (MFA -)
F09 HIGH     Identity   support                  iam:UpdateLoginProfile on arn:aws:iam::123456789012:user/*: can take over any user
F10 HIGH     Identity   vendor-read              foreign account trusted without external ID
F11 HIGH     Network    i-0a1b2c3d4e5f60002      port 22 reachable from the Internet
F12 MEDIUM   Identity   legacy-sync              long-lived access key, 520 days old, in use
F13 MEDIUM   Kubernetes shop/web                 may run as root
F14 MEDIUM   Logging    lab-trail-123456789012   audit bucket without object lock
F15 MEDIUM   Logging    org-trail                log file validation off
F16 MEDIUM   Logging    org-trail                no S3 data events: object reads of confidential data are invisible
F17 LOW      Kubernetes shop/web                 default service account token mounted
F18 LOW      Kubernetes shop/web                 image by mutable tag

5 CRITICAL, 6 HIGH, 5 MEDIUM, 2 LOW

Step 2: the repository, before deployment

The same weaknesses exist in the repository as code. The session writes the relevant parts of the shop repository (Terraform for the web instance and the exports bucket, the Dockerfile, the pod manifest) and runs Trivy's misconfiguration and secret scanners as the CI pipeline would. It runs in your sandbox on local files only.

bash · try it yourself
mkdir -p shop/infra shop/k8s && cd shop
cat > infra/main.tf <<'TF'
resource "aws_instance" "web" {
  ami           = "ami-0123456789abcdef0"
  instance_type = "t3.small"
  root_block_device { encrypted = true }
}
resource "aws_s3_bucket" "exports" {
  bucket = "lab-customer-exports"
}
TF
cat > Dockerfile <<'DF'
FROM node:22
COPY . /srv
RUN npm ci --omit=dev
ENV EXPORT_API_KEY=lab-not-a-real-key
CMD ["node", "/srv/server.js"]
DF
cat > k8s/web.yaml <<'Y'
apiVersion: v1
kind: Pod
metadata: {name: web, namespace: shop}
spec:
  containers:
    - name: web
      image: registry.lab.test/shop/web:latest
      volumeMounts: [{name: sock, mountPath: /var/run/docker.sock}]
  volumes:
    - name: sock
      hostPath: {path: /var/run/docker.sock}
Y
trivy config -q -f json . | jq -r '[.Results[] | .Target as $t | .Misconfigurations[]? | select(.Severity == "HIGH" or .Severity == "CRITICAL") | "\(.Severity) \(.ID) \($t): \(.Title)"] | unique[]'
echo "--- totals per file (all severities)"
trivy config -q -f json . | jq -r '.Results[] | select((.Misconfigurations // []) | length > 0) | "\(.Target): \(.Misconfigurations | length)"' | sort
CRITICAL DS-0031 Dockerfile: Secrets passed via `build-args` or envs or copied secret files
HIGH AWS-0028 infra/main.tf: aws_instance should activate session tokens for Instance Metadata Service.
HIGH AWS-0086 infra/main.tf: S3 Access block should block public ACL
HIGH AWS-0087 infra/main.tf: S3 Access block should block public policy
HIGH AWS-0091 infra/main.tf: S3 Access Block should Ignore Public ACL
HIGH AWS-0093 infra/main.tf: S3 Access block should restrict public bucket to limit access
HIGH AWS-0132 infra/main.tf: S3 encryption should use Customer Managed Keys
HIGH DS-0002 Dockerfile: Image user should not be 'root'
HIGH KSV-0006 k8s/web.yaml: hostPath volume mounted with docker.sock
HIGH KSV-0014 k8s/web.yaml: Root file system is not read-only
HIGH KSV-0118 k8s/web.yaml: Default security context configured
--- totals per file (all severities)
Dockerfile: 3
infra/main.tf: 9
k8s/web.yaml: 20

The repository scan shows the code side of several account findings (the IMDS setting, the bucket without Block Public Access, the Docker socket in the pod, root in the container), adds hardening items (read-only root filesystem, customer-managed keys), and finds one thing the export couldn't show: an API key baked into the image, which must be revoked. The account review also found things no repository scan can: the root sign-in, the bucket policy added by hand (drift), the trust policy and the long-lived key. Both views are needed.

Step 3: attack paths

Group the findings into chains an attacker could follow, and fix the cheapest link of each first:

  1. SSRF to customer data: Internet → the web instance (public, IMDSv1) → app-role credentials → s3:GetObject on lab-*, which includes lab-customer-exports. Cheapest link: http-tokens required (minutes). Then scope the role to its own bucket, and add a network perimeter.
  2. CI supply-chain takeover: any repository on the CI service → ci-deploy (OIDC trust without sub) → Action: *. Cheapest link: pin sub. Then reduce the policy.
  3. Escalation from the application: app-role → iam:PassRole * + lambda:CreateFunction → code running as any role whose trust policy accepts lambda.amazonaws.com (not ci-deploy itself, which trusts only the OIDC provider, but every function and automation role in the account). Cheapest link: remove CreateFunction from the app role.
  4. Already in progress? Root signed in without MFA at 02:14 from an unknown address and changed the exports bucket policy six minutes later; the bucket is public through a condition that doesn't pin the caller. This is an incident, not a finding: escalate to incident response before the report is finished (Incident Handling in the SOC), and note that without S3 data events nobody can tell what was read.

Step 4: the report

Use this structure; keep the executive summary to what the account owner must decide.

markdown
# Cloud Security Review: account 123456789012 (shop), <date>

## 1. Executive summary
- Overall: <one sentence>. Urgent: <the incident lead, if any>.
- Top risks: 1) <path 1 in one line> 2) <path 2> 3) <path 3>.
- Decisions needed: <e.g. approve emergency IMDS change; fund log archive account>.

## 2. Scope and method
- In scope: <accounts, regions, cluster, repository>; out of scope: <...>.
- Access: read-only audit role <ARN>, <dates>. Method: configuration export, IaC scan (Trivy 0.76.1), event review.
- Limits: no S3 data events available; no active testing; benchmark used: <name and version>.

## 3. Attack paths
| Path | Chain (finding IDs) | Impact | Cheapest fix | Owner | Due |
|---|---|---|---|---|---|

## 4. Findings
| ID | Severity | Area | Resource | Issue and evidence | Fix | Detection | Owner | Due |
|---|---|---|---|---|---|---|---|---|

## 5. Detections to add
<rule name, data source, condition, response>

## 6. Guardrails to prevent recurrence
<SCPs, admission policies, IaC checks, posture rules, each tied to findings>

## 7. Appendix
<raw exports, tool versions, accepted risks with expiry>

A sample executive summary, written from this review:

The account is not ready for go-live. Three independent paths lead from the Internet or from the CI service to customer data or administrator rights; each can be closed with a configuration change of under an hour (IMDSv2 on the web instance, pinning the CI trust policy, removing Lambda creation from the application role). Separately, the root user signed in without MFA on 1 June at 02:14 UTC from an unknown address and made the customer-exports bucket publicly readable; this has been handed to incident response, and object-level logging must be enabled to determine what was accessed.

Test yourself

Why is the lab-customer-exports bucket treated as public although its policy has a condition?

  1. It is encrypted
  2. aws:UserAgent is set by the caller, so it doesn't restrict who the caller is
  3. BPA is fully on
  4. The condition uses StringEquals

Which item should leave the review process and go to incident response immediately?

  1. The latest tag
  2. Root sign-in without MFA from an unknown IP followed by a bucket policy change on confidential data
  3. The default service account token
  4. Missing log validation

What is the cheapest link to break in the SSRF-to-customer-data path?

  1. Rewriting the application
  2. Requiring IMDSv2 on the web instance
  3. Deleting the bucket
  4. Moving regions

What could the account review find that the repository scan could not?

  1. The IMDS setting
  2. Manual changes and live state: the root sign-in, the hand-added bucket policy, trust policies and old keys
  3. The Docker socket mount
  4. The secret in the Dockerfile