Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Scenario test · 90 minutes

Review the cloud account of a bicycle shop after a night of strange calls

After this lesson you can
  • Review the identity, storage, network and logging of an account with the tools you built
  • Follow an intruder through the audit log, past the point where a tool stops
  • Write a report that separates what is proved, what is concluded and what is unknown
Lab files of this lesson (27)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Marrowby Cycles is an invented company that sells bicycles online. Its systems run in one AWS account, 123456789012, in the region eu-west-2, and its office uses the network 198.51.100.0/24. It is Saturday 21 November 2026. The invoice of the cloud provider for November is five times the usual amount, and the owner asks you, an outside analyst, to review the account. You get a snapshot of the account, taken today, and a copy of the company's tools repository. One more fact from the owner: the developer j.oconnor left the company in the summer.

The snapshot has the same files as the Larkfield account of the lessons, without the lesson files for single exercises: inventory.json, iam.json, buckets.json, network.json, trails.json and events.json, and the folder repo. The generator makes all of it in the folder case. It uses a fixed seed, so your files match the numbers below. Save it in your lab folder and run it. You do not need to read it.

The finished file: gen_case.py (a lab file)

gen_case.py

"""gen_case.py: write the case of the scenario test into the folder case. The company is Marrowby Cycles, an invented firm.

    python3 gen_case.py        The same files every time. Nothing here is a real account, key or address.
"""
import hashlib
import json
import random
from datetime import datetime, timedelta, timezone
from pathlib import Path

OUT = Path("case")
r = random.Random(47)  # only random() is used: the files are the same on every Python version
ACCOUNT = "123456789012"
IAM = f"arn:aws:iam::{ACCOUNT}:"
ANY, OFFICE_NET, INTRUDER, ROGUE_REGION = "0.0.0.0/0", "198.51.100.0/24", "203.0.113.201", "us-west-2"
UPPER = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/+"
ADMIN_KEY, DEV_KEY, NEW_KEY = "AKIAR8HD4YVNC" + "EXAMPLE", "AKIAM3TA9PEQJ" + "EXAMPLE", "AKIAX6JC2ZKWB" + "EXAMPLE"
TRAIL = f"arn:aws:cloudtrail:eu-west-2:{ACCOUNT}:trail/marrowby-trail"


def pick(items):
    return items[int(r.random() * len(items))]


def rid(n, alphabet="0123456789abcdef"):
    return "".join(pick(alphabet) for _ in range(n))


def allow(action, resource, **more):
    return {"Effect": "Allow", "Action": action, "Resource": resource, **more}


def doc(*statements):
    return {"Version": "2012-10-17", "Statement": list(statements)}


def trust(principal, **more):
    return doc({"Effect": "Allow", "Principal": principal, "Action": "sts:AssumeRole", **more})


# ---------------------------------------------------------------- identity
POLICIES = {
    "AdminAll": doc(allow("*", "*")),
    "DevTools": doc(allow(["ec2:Describe*", "ec2:StartInstances", "ec2:StopInstances", "ssm:StartSession"], "*")),
    "NoTrailChanges": doc({"Effect": "Deny", "Action": ["cloudtrail:StopLogging", "cloudtrail:DeleteTrail", "cloudtrail:UpdateTrail"], "Resource": "*"}),
    "ExportWrite": doc(allow("s3:PutObject", "arn:aws:s3:::marrowby-exports/*", Condition={"IpAddress": {"aws:SourceIp": OFFICE_NET}})),
    "DeployBot": doc(allow(["s3:PutObject", "s3:DeleteObject"], "arn:aws:s3:::marrowby-site/*"),
                     allow("s3:ListBucket", "arn:aws:s3:::marrowby-site")),
    "AppData": doc(allow(["s3:GetObject", "s3:PutObject"], "arn:aws:s3:::marrowby-customers/*")),
    "EtlAll": doc(allow(["s3:*", "dynamodb:*"], "*"), allow("iam:PassRole", IAM + "role/*")),
    "AuditRead": doc(allow(["s3:GetBucketPolicy", "s3:GetBucketAcl", "iam:Get*", "iam:List*"], "*")),
}
GROUPS = [{"name": "Admins", "policies": ["AdminAll"]}, {"name": "Developers", "policies": ["DevTools", "NoTrailChanges"]}]


def user(name, groups, policies, console, mfa, last_login, keys):
    return {"name": name, "arn": IAM + "user/" + name, "groups": groups, "policies": policies, "console": console, "mfa": mfa,
            "last_login": last_login, "access_keys": [{"id": k, "status": s, "created": c, "last_used": u} for k, s, c, u in keys]}


USERS = [
    user("r.haddad", ["Admins"], [], True, True, "2026-11-20", [(ADMIN_KEY, "Active", "2026-02-01", "2026-11-12")]),
    user("s.lindqvist", ["Developers"], [], True, True, "2026-11-20", []),
    user("t.adeyemi", ["Developers"], [], True, False, "2026-11-19", [(DEV_KEY, "Active", "2025-04-18", "2026-11-18")]),
    user("j.oconnor", ["Developers"], ["AdminAll"], True, False, "2026-11-12", [(NEW_KEY, "Active", "2026-11-12", "2026-11-13")]),
    user("finance-export", [], ["ExportWrite"], False, False, None, [("AKIAF5NE7XPRT" + "EXAMPLE", "Active", "2026-09-30", "2026-11-20")]),
    user("deploy-bot", [], ["DeployBot"], False, False, None, [("AKIAD2PB8LQYS" + "EXAMPLE", "Active", "2026-10-02", "2026-11-20")]),
]
ROLES = [
    {"name": "app-role", "arn": IAM + "role/app-role", "trust": trust({"Service": "ec2.amazonaws.com"}), "policies": ["AppData"]},
    {"name": "etl-role", "arn": IAM + "role/etl-role", "trust": trust({"Service": "lambda.amazonaws.com"}), "policies": ["EtlAll"]},
    {"name": "partner-audit", "arn": IAM + "role/partner-audit", "policies": ["AuditRead"],
     "trust": trust({"AWS": "*"}, Condition={"StringEquals": {"sts:ExternalId": "marrowby-audit-2026"}})},
    {"name": "break-glass", "arn": IAM + "role/break-glass", "policies": ["AdminAll"],
     "trust": trust({"AWS": IAM + "root"}, Condition={"Bool": {"aws:MultiFactorAuthPresent": "true"}})},
]

# ---------------------------------------------------------------- storage
GROUP_URI = "http://acs.amazonaws.com/groups/global/"


def pab(acls=False, ignore=False, policy=False, restrict=False):
    return {"BlockPublicAcls": acls, "IgnorePublicAcls": ignore, "BlockPublicPolicy": policy, "RestrictPublicBuckets": restrict}


def anyone(name, actions, **more):
    return {"Effect": "Allow", "Principal": "*", "Action": actions, "Resource": [f"arn:aws:s3:::{name}", f"arn:aws:s3:::{name}/*"], **more}


def bucket(name, block, policy=None, grants=(), sse="AES256", intended_public=False):
    return {"name": name, "region": "eu-west-2", "public_access_block": block, "policy": policy,
            "acl": [{"Grantee": {"Type": "Group", "URI": GROUP_URI + g}, "Permission": p} for g, p in grants],
            "encryption": {"SSEAlgorithm": sse}, "versioning": False, "intended_public": intended_public}


BUCKETS = {"account_public_access_block": pab(), "buckets": [
    bucket("marrowby-site", pab(), policy=doc(anyone("marrowby-site", "s3:GetObject")), intended_public=True),
    bucket("marrowby-customers", pab(), policy=doc(anyone("marrowby-customers", ["s3:GetObject", "s3:ListBucket"])), sse="aws:kms"),
    bucket("marrowby-exports", pab(), policy=doc(anyone("marrowby-exports", "s3:GetObject", Condition={"IpAddress": {"aws:SourceIp": OFFICE_NET}}))),
    bucket("marrowby-logs", pab(True, True, True, True),
           policy=doc({"Effect": "Allow", "Principal": {"Service": "cloudtrail.amazonaws.com"}, "Action": "s3:PutObject",
                       "Resource": f"arn:aws:s3:::marrowby-logs/AWSLogs/{ACCOUNT}/*"},
                      {"Effect": "Deny", "Principal": "*", "Action": "s3:*", "Resource": ["arn:aws:s3:::marrowby-logs", "arn:aws:s3:::marrowby-logs/*"],
                       "Condition": {"Bool": {"aws:SecureTransport": "false"}}})),
    bucket("marrowby-backups", pab(ignore=True), grants=[("AuthenticatedUsers", "READ")]),
    bucket("marrowby-media", pab(restrict=True), policy=doc(anyone("marrowby-media", "s3:GetObject"))),
    bucket("marrowby-archive", pab(), grants=[("AllUsers", "READ")]),
    bucket("marrowby-etl-temp", pab(True, True, True, True)),
]}

# ---------------------------------------------------------------- network


def rule(port, cidr=None, group=None):
    return {"protocol": "tcp", "from_port": port, "to_port": port, **({"cidr": cidr} if cidr else {"source_group": group})}


def entry(number, action, port=None, egress=False):
    return {"rule_number": number, "egress": egress, "action": action, "cidr": ANY, "protocol": "tcp" if port else "all",
            "from_port": port, "to_port": port}


def instance(n, name, subnet, ip, public, groups):
    return {"id": f"i-0c44d55e66f77a88{n}", "name": name, "subnet": subnet, "private_ip": ip, "public_ip": public, "security_groups": groups}


NETWORK = {
    "vpc": {"id": "vpc-0marrowby", "cidr": "10.40.0.0/16"}, "expected_public": [["shop-web", 443]],
    "subnets": [{"id": "subnet-public", "cidr": "10.40.1.0/24", "route_table": "rt-public", "nacl": "nacl-main"},
                {"id": "subnet-private", "cidr": "10.40.11.0/24", "route_table": "rt-private", "nacl": "nacl-main"},
                {"id": "subnet-data", "cidr": "10.40.21.0/24", "route_table": "rt-public", "nacl": "nacl-data"}],
    "route_tables": [{"id": "rt-public", "routes": [{"destination": "10.40.0.0/16", "target": "local"}, {"destination": ANY, "target": "igw-0c9"}]},
                     {"id": "rt-private", "routes": [{"destination": "10.40.0.0/16", "target": "local"}, {"destination": ANY, "target": "nat-0d4"}]}],
    "security_groups": [{"id": "sg-web", "ingress": [rule(443, ANY)]},
                        {"id": "sg-jump", "ingress": [rule(22, OFFICE_NET)]},
                        {"id": "sg-app", "ingress": [rule(8080, group="sg-web"), rule(22, group="sg-jump")]},
                        {"id": "sg-db", "ingress": [rule(5432, group="sg-app"), rule(5432, ANY)]},
                        {"id": "sg-reports", "ingress": [rule(3306, ANY), rule(3306, group="sg-app")]},
                        {"id": "sg-cache", "ingress": [rule(6379, ANY)]}],
    "nacls": [{"id": "nacl-main", "entries": [entry(100, "allow"), entry(100, "allow", egress=True)]},
              {"id": "nacl-data", "entries": [entry(80, "deny", port=6379), entry(100, "allow"), entry(100, "allow", egress=True)]}],
    "instances": [instance(1, "shop-web", "subnet-public", "10.40.1.10", "192.0.2.70", ["sg-web"]),
                  instance(2, "admin-jump", "subnet-public", "10.40.1.11", "192.0.2.71", ["sg-jump"]),
                  instance(3, "shop-app", "subnet-private", "10.40.11.10", None, ["sg-app"]),
                  instance(4, "crm-db", "subnet-data", "10.40.21.10", "192.0.2.77", ["sg-db"]),
                  instance(5, "reports-db", "subnet-private", "10.40.11.20", None, ["sg-reports"]),
                  instance(6, "cache-1", "subnet-data", "10.40.21.11", "192.0.2.78", ["sg-cache"])],
}

# ---------------------------------------------------------------- the audit log
OFFICE = {"r.haddad": "198.51.100.11", "s.lindqvist": "198.51.100.12", "t.adeyemi": "198.51.100.13", "j.oconnor": "198.51.100.14",
          "finance-export": "198.51.100.30", "deploy-bot": "198.51.100.31"}
KEYS = {u["name"]: u["access_keys"][0]["id"] for u in USERS if u["access_keys"]}
PRINCIPAL_IDS = {u["name"]: "AIDA" + rid(10, UPPER) + "EXAMPLE" for u in USERS}
READS = [("ec2.amazonaws.com", "DescribeInstances"), ("ec2.amazonaws.com", "DescribeSecurityGroups"), ("s3.amazonaws.com", "ListBuckets"),
         ("s3.amazonaws.com", "GetBucketPolicy"), ("iam.amazonaws.com", "ListUsers"), ("iam.amazonaws.com", "GetUser"),
         ("cloudtrail.amazonaws.com", "DescribeTrails"), ("sts.amazonaws.com", "GetCallerIdentity")]
GLOBAL = {"iam.amazonaws.com", "sts.amazonaws.com", "signin.amazonaws.com"}
CLI = "aws-cli/2.31.4 md/awscrt#0.27.2 ua/2.1 os/linux#6.8 md/arch#x86_64 lang/python#3.13.7"
BROWSER = "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0"
MFA = {u["name"]: u["mfa"] for u in USERS}


def at(day, h, m, s):
    return datetime(2026, 11, day, h, m, s, tzinfo=timezone.utc)


def guid():
    return f"{rid(8)}-{rid(4)}-{rid(4)}-{rid(4)}-{rid(12)}"


def ident(name, key=None, mfa=None):
    out = {"type": "IAMUser", "principalId": PRINCIPAL_IDS[name], "arn": IAM + "user/" + name, "accountId": ACCOUNT, "userName": name}
    if key:
        out["accessKeyId"] = key
    if mfa is not None:
        out["sessionContext"] = {"attributes": {"mfaAuthenticated": "true" if mfa else "false"}}
    return out


def event(t, who, source, name, ip, agent=CLI, region="eu-west-2", params=None, response=None, read=True, **more):
    ev = {"eventVersion": "1.11", "userIdentity": who, "eventTime": t.strftime("%Y-%m-%dT%H:%M:%SZ"), "eventSource": source, "eventName": name,
          "awsRegion": "us-east-1" if source in GLOBAL else region, "sourceIPAddress": ip, "userAgent": agent, "requestParameters": params,
          "responseElements": response, "requestID": guid(), "eventID": guid(), "readOnly": read, "eventType": "AwsApiCall",
          "managementEvent": True, "recipientAccountId": ACCOUNT, "eventCategory": "Management"}
    ev.update(more)
    return ev


def login(t, name, ip, mfa):
    return event(t, ident(name), "signin.amazonaws.com", "ConsoleLogin", ip, BROWSER, response={"ConsoleLogin": "Success"}, read=False,
                 eventType="AwsConsoleSignIn", additionalEventData={"LoginTo": "https://console.aws.amazon.com/console/home",
                                                                    "MobileVersion": "No", "MFAUsed": "Yes" if mfa else "No"})


def console(name):
    return ident(name, "ASIA" + rid(9, UPPER) + "EXAMPLE", MFA[name])


def events():
    out = []
    for day in range(9, 15):
        for name in ("r.haddad", "s.lindqvist", "t.adeyemi"):
            if r.random() < 0.85:
                t = at(day, 8, int(r.random() * 50), int(r.random() * 60))
                out.append(login(t, name, OFFICE[name], MFA[name]))
                for _ in range(3 + int(r.random() * 6)):
                    t += timedelta(seconds=40 + int(r.random() * 2600))
                    source, call = pick(READS[:7])
                    out.append(event(t, console(name), source, call, OFFICE[name], BROWSER, sessionCredentialFromConsole="true"))
        for name in ("r.haddad", "finance-export", "deploy-bot"):
            for _ in range(4 + int(r.random() * 5)):
                t = at(day, 9, 0, 0) + timedelta(seconds=int(r.random() * 32000))
                source, call = pick([READS[7], READS[0], READS[2]])
                out.append(event(t, ident(name, KEYS[name]), source, call, OFFICE[name]))
    # an approved change, by an administrator, from the office
    out.append(event(at(10, 11, 3, 27), console("r.haddad"), "s3.amazonaws.com", "PutBucketPolicy", OFFICE["r.haddad"], BROWSER, read=False,
                     params={"bucketName": "marrowby-exports", "policy": ""}, sessionCredentialFromConsole="true"))
    # night of 12 November: the administrator's key is used from an address that the company does not know
    boss = ident("r.haddad", ADMIN_KEY)
    for t, source, call, params in [
            (at(12, 1, 14, 9), "sts.amazonaws.com", "GetCallerIdentity", None), (at(12, 1, 14, 40), "iam.amazonaws.com", "ListUsers", None),
            (at(12, 1, 15, 22), "s3.amazonaws.com", "ListBuckets", None), (at(12, 1, 16, 5), "cloudtrail.amazonaws.com", "DescribeTrails", None),
            (at(12, 1, 16, 50), "iam.amazonaws.com", "UpdateLoginProfile", {"userName": "j.oconnor"}),
            (at(12, 1, 17, 20), "iam.amazonaws.com", "AttachUserPolicy", {"userName": "j.oconnor", "policyArn": IAM + "policy/AdminAll"}),
            (at(12, 1, 18, 2), "cloudtrail.amazonaws.com", "StopLogging", {"name": TRAIL})]:
        out.append(event(t, boss, source, call, INTRUDER, params=params, read=params is None))
    stop, start = at(12, 1, 18, 2), at(12, 7, 32, 48)
    out.append(login(at(12, 7, 21, 15), "r.haddad", OFFICE["r.haddad"], True))
    out.append(event(start, console("r.haddad"), "cloudtrail.amazonaws.com", "StartLogging", OFFICE["r.haddad"], BROWSER, params={"name": TRAIL},
                     read=False, sessionCredentialFromConsole="true"))
    # evening: the account of a person who left the company signs in to the console from the same address
    out.append(login(at(12, 22, 3, 31), "j.oconnor", INTRUDER, False))
    ghost = console("j.oconnor")
    out.append(event(at(12, 22, 5, 44), ghost, "ec2.amazonaws.com", "AuthorizeSecurityGroupIngress", INTRUDER, BROWSER, read=False,
                     response={"_return": True}, sessionCredentialFromConsole="true",
                     params={"groupId": "sg-db", "ipPermissions": {"items": [{"ipProtocol": "tcp", "fromPort": 5432, "toPort": 5432,
                                                                              "ipRanges": {"items": [{"cidrIp": ANY}]}}]}}))
    out.append(event(at(12, 22, 9, 2), ghost, "iam.amazonaws.com", "CreateAccessKey", INTRUDER, BROWSER, read=False, sessionCredentialFromConsole="true",
                     params={"userName": "j.oconnor"}, response={"accessKey": {"userName": "j.oconnor", "accessKeyId": NEW_KEY, "status": "Active"}}))
    rogue_ids, t = [], at(13, 2, 30, 11)
    for n in range(5):
        iid = "i-0" + rid(16)
        rogue_ids.append(iid)
        out.append(event(t + timedelta(seconds=5 * n), ident("j.oconnor", NEW_KEY), "ec2.amazonaws.com", "RunInstances", INTRUDER, region=ROGUE_REGION,
                         read=False, params={"instanceType": "p3.8xlarge"}, response={"instancesSet": {"items": [{"instanceId": iid}]}}))
    out = [e for e in out if not stop < datetime.strptime(e["eventTime"], "%Y-%m-%dT%H:%M:%S%z") < start]
    out.sort(key=lambda e: e["eventTime"])
    return out, rogue_ids


# ---------------------------------------------------------------- inventory and repository
def inventory(rogue_ids):
    rows = []

    def add(arn, service, kind, region, name, created, owner="platform"):
        rows.append({"arn": arn, "service": service, "type": kind, "region": region, "name": name, "created": created,
                     "tags": {"owner": owner, "env": "prod"} if owner else {}})

    for i in NETWORK["instances"]:
        add(f"arn:aws:ec2:eu-west-2:{ACCOUNT}:instance/{i['id']}", "ec2", "instance", "eu-west-2", i["name"], "2025-04-02", "shop")
    for b in BUCKETS["buckets"]:
        add(f"arn:aws:s3:::{b['name']}", "s3", "bucket", "eu-west-2", b["name"], "2025-02-11", pick(["shop", "data"]))
    for u in USERS:
        add(u["arn"], "iam", "user", "", u["name"], "2025-02-01")
    for x in ROLES:
        add(x["arn"], "iam", "role", "", x["name"], "2025-02-01")
    add(TRAIL, "cloudtrail", "trail", "eu-west-2", "marrowby-trail", "2025-02-01")
    for n in range(14 + int(r.random() * 6)):
        vid = "vol-0" + rid(16)
        add(f"arn:aws:ec2:eu-west-2:{ACCOUNT}:volume/{vid}", "ec2", "volume", pick(["eu-west-2", "eu-west-2", "eu-west-1"]), vid,
            f"2026-{1 + int(r.random() * 10):02d}-{1 + int(r.random() * 28):02d}", None if r.random() < 0.25 else "shop")
    for iid in rogue_ids:
        add(f"arn:aws:ec2:{ROGUE_REGION}:{ACCOUNT}:instance/{iid}", "ec2", "instance", ROGUE_REGION, iid, "2026-11-13", None)
    return {"organisation": {"id": "o-exampleorgid", "accounts": [{"id": ACCOUNT, "name": "marrowby-prod"}]}, "account": ACCOUNT,
            "approved_regions": ["eu-west-2", "eu-west-1"], "known_networks": [OFFICE_NET], "resources": rows}


def repo():
    def secret():
        return "".join(pick(LETTERS) for _ in range(30)) + "EXAMPLE" + "KEY"

    admin_secret, dev_secret = secret(), secret()
    filler = [f"echo \"step {n}: sync {pick(['frames', 'wheels', 'orders', 'stock'])}\"" for n in range(30)]
    files = {
        "README.md": ["# marrowby-tools", "", "Example from the AWS documentation, not a real key:", "",
                      "    aws_access_key_id = AKIAIOSFODNN7" + "EXAMPLE", "    aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCY" + "EXAMPLEKEY"],
        "scripts/backup.sh": ["#!/bin/sh", "# nightly backup of the customer bucket"] + filler[:9]
                             + [f"export AWS_ACCESS_KEY_ID={ADMIN_KEY}", f"export AWS_SECRET_ACCESS_KEY={admin_secret}"] + filler[9:14],
        "scripts/sync.sh": ["#!/bin/sh"] + filler[14:30],
        ".env": ["STAGE=dev", f"AWS_ACCESS_KEY_ID={DEV_KEY}", f"AWS_SECRET_ACCESS_KEY={dev_secret}"],
        "ci/build.log": [f"2026-10-03T07:{n:02d}:10Z {line}" for n, line in enumerate(filler[:12])]
                        + [f"2026-10-03T07:12:44Z + AWS_ACCESS_KEY_ID={ADMIN_KEY} ./scripts/backup.sh"],
        "history/0012-move-key-to-env.patch": ["commit 0012: read the key from the environment", "--- a/scripts/report.sh", "+++ b/scripts/report.sh",
                                                f"-AWS_ACCESS_KEY_ID={ADMIN_KEY}", f"-AWS_SECRET_ACCESS_KEY={admin_secret}",
                                                "+. /etc/marrowby/report.env"],
        "ops/jump.pem": ["-----BEGIN OPENSSH PRIVATE KEY-----", "bm90IGEgcmVhbCBrZXk6IGxhYiBkYXRhIG9ubHk=", "-----END OPENSSH PRIVATE KEY-----"],
        "docs/runbook.md": ["# Runbook", "", "The deploy bot uses a key that starts with AKIA. Ask the platform team for it."],
    }
    for name, lines in files.items():
        path = OUT / "repo" / name
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text("\n".join(lines) + "\n")
    return len(files)


def write(name, data):
    text = json.dumps(data, indent=1) + "\n"
    (OUT / name).write_text(text)
    print(f"{name:15s} {len(text):6d} bytes  sha256 {hashlib.sha256(text.encode()).hexdigest()[:12]}")


if __name__ == "__main__":
    OUT.mkdir(exist_ok=True)
    recs, rogue_ids = events()
    write("inventory.json", inventory(rogue_ids))
    write("iam.json", {"account": ACCOUNT, "users": USERS, "groups": GROUPS, "roles": ROLES, "policies": POLICIES})
    write("buckets.json", BUCKETS)
    write("network.json", NETWORK)
    write("trails.json", [{"Name": "marrowby-trail", "S3BucketName": "marrowby-logs", "HomeRegion": "eu-west-2", "IsMultiRegionTrail": True,
                           "LogFileValidationEnabled": False, "KmsKeyId": None, "IsLogging": True, "DataEvents": []}])
    write("events.json", {"Records": recs})
    print(f"wrote {repo()} files of the repository in case/repo")
cd ~/krlab/cloud-security-basics
python3 gen_case.py
inventory.json   12710 bytes  sha256 d82f8c292312
iam.json          5985 bytes  sha256 5358465e3281
buckets.json      5152 bytes  sha256 c44efaea1905
network.json      4409 bytes  sha256 8b0382b51b3f
trails.json        229 bytes  sha256 1dc3b07cc05a
events.json     217648 bytes  sha256 616829c55269
wrote 8 files of the repository in case/repo

Work in ~/krlab/cloud-security-basics, with the programs of lessons 1 to 13 as the lessons print them: account_map.py, policy_eval.py, iam_audit.py, key_report.py, scan_keys.py, buckets.py, reach.py, trail.py, respond.py and posture.py. If you skipped a lesson, build the lab with sh kr-lab.sh 13-build-a-posture-checker ~/krlab/cloud-security-basics from the zip of the course. The date of the review is 2026-11-21, which is what the programs use.

The tools give the first answer to each task. Two tasks need more than the tools print: read the records and the files yourself.

Your tasks

Do the tasks in this order. Keep your commands and results: the report at the end uses them.

  1. Map. Say what is in the account and what should not be there.
  1. Identity. Audit the users, roles and policies. One policy gives a workload far more than a data job needs: name it and the role that holds it. The audit prints no line for the role partner-audit, whose trust policy names every principal. Read that trust policy and decide whether the audit is right to stay silent.
  1. Keys. Report the access keys of the account, and scan the repository case/repo with the identity file of the case.
  1. Storage. Decide which buckets are public, and why.
  1. Network. Find the ports that the internet can reach and that are not expected. Two more rules allow a database port from everywhere and do no harm today: say what stops each.
  1. Audit log. Find the calls that need a look, the address that the company does not know, and the time for which the trail was off. Build the timeline of that address.
  1. Follow the intruder. Make the response plan for the access key that you found in scripts/backup.sh, for 2026-11-21T10:00:00Z. The planner follows new users and new keys that the leaked key made. Read the three changes that it lists, one by one, and ask what each could be used for. Then go back to the timeline of task 6 and find what the plan does not contain.
  1. Link two findings. One of your findings from task 5 was made by the intruder. Find the call in the audit log that proves it.
  1. Rank. Run the posture checker on the case and write the report file case-report.md.
  1. Repair the network. Copy case/network.json to case-network-fixed.json and change security groups only: no database or cache port (5432, 3306, 6379) may be allowed from 0.0.0.0/0, the rules that name a group stay, and the shop stays reachable on port 443.

Hand in

A written report in your own words, marrowby-report.md, of one to two pages. It is the proof that you can show an employer. The 90 minutes are for the ten tasks. Allow a second sitting for the report. Use these headings:

  • Summary: what happened and what state the account is in, in four sentences that the owner can read.
  • Timeline: the key events in UTC, each with the field values that prove it (eventTime, eventName, the identity, the source address).
  • How the intruder got in and moved: the leaked key, where it was stored, and each step from that key to the machines that caused the invoice.
  • What we do not know: the time for which the trail was off, and every question that the audit log cannot answer (for example, whether customer data was read).
  • What the tools missed: at least two things that a program did not report and that you found by reading, with your decision.
  • Containment plan: the actions in order, with the reason for the order (lesson 12). Include every way back in that you found.
  • Findings to fix: the top findings of the posture report, grouped by area, with the smallest change for each.
  • Why it could happen: the causes, not the people: where the key was kept, which rights it had, which controls were missing.

Review your work

A model solution

The commands, in the order of the tasks. Your own may differ.

python3 account_map.py case
python3 iam_audit.py case
python3 key_report.py case
python3 scan_keys.py case/repo case
python3 buckets.py case/buckets.json
python3 reach.py case/network.json
python3 trail.py case | cut -c1-110
python3 trail.py case --ip 203.0.113.201
python3 respond.py case AKIAR8HD4YVNCEXAMPLE 2026-11-21T10:00:00Z
python3 posture.py case case-report.md

What the files show.

  • The way in. The access key of the administrator r.haddad is in scripts/backup.sh with its secret, in a build log and in a patch file of the history. The key is 293 days old and belongs to a person with every right.
  • Night of 12 November, 01:14 to 01:18 UTC. The key is used from 203.0.113.201: it lists users, buckets and trails, sets a new password for j.oconnor (UpdateLoginProfile), attaches the administrator policy to that user, and stops the trail. The trail is off for 374 minutes, until an administrator starts it at 07:32.
  • Evening of 12 November. j.oconnor signs in to the console from the same address, without MFA. This is the intruder with the new password, not the former employee. At 22:05 the session opens port 5432 of sg-db to 0.0.0.0/0, and at 22:09 it makes a new access key for the user.
  • 13 November, 02:30. That new key starts five machines of a large type in us-west-2. They are the invoice.
  • What the response plan missed. It counts seven events and no new user or key, because the intruder did not create a user: it took over one that existed, by a password reset. The plan follows CreateUser and CreateAccessKey made by the leaked key only. The reader of the log, trail.py, does list the reset as a high event, and the timeline of the source address shows the second half of the incident.
  • What the audit missed. partner-audit is trusted for every principal, with a condition on sts:ExternalId. The audit is silent because a condition is present. An external ID is a shared value, not a secret: the trust policy should name the partner's account. This is a finding to report by hand. The audit also cannot know that j.oconnor left the company: its sign-in dates look current because the intruder used the account.
  • Storage and network. marrowby-customers lets everyone list and read (policy), and marrowby-archive is public by ACL. crm-db has port 5432 open to the internet, in a subnet with a route to an internet gateway and with a public address. reports-db and cache-1 have the same kind of rule and are saved by one other layer each: no public address, and rule 80 of a network ACL.

A containment plan in the right order: make the key of r.haddad inactive, make the new key of j.oconnor inactive, disable the console password of j.oconnor and detach its administrator policy, check that the trail is logging, take snapshots of the five machines and stop them, remove the rule that opens sg-db, and only then issue new credentials. Then fix the causes: no long-lived key for an administrator, no key in a repository, accounts of people who leave are removed, MFA for every console user, an alert on StopLogging.

Mark your report

You mark this yourself, or you ask a colleague or a mentor to mark it. The page checks the numbers above; it cannot read your report.

CriterionNot yetMeets the standardStrong
FindingsThe leaked key, the takeover or the machines missing.Key in backup.sh, j.oconnor taken over, five machines, sg-db open, two public buckets.Also the key's other copies and every way back in.
EvidenceEvents with no field values.Each event in UTC with eventTime, eventName, identity, source address.Each claim names the command that shows it.
JudgementNo ranking; the 374 minutes not named.Ranked with reasons; the 374 minutes and data reads listed as unknown.Says what each unknown could change.
Tool gapsTool output only.The takeover the plan missed; the partner-audit trust policy.Says why each tool missed it.
ContainmentNo order, or new credentials first.Keys and password off, trail checked, machines kept and stopped, sg-db closed, then new credentials.Gives the reason for each step's place.
WritingBlames a person.Eight headings; a summary the owner can act on; dated; causes, not people.Every line is clear without cloud knowledge.

Meets the standard in every row: you can show this report as a work sample. Remove names and data that are not yours to share.

The report proves your work on this scenario, on your own machine, without a proctor. It does not prove work on a live account.

Get a result link

When all 29 answers above are right, the server can check them again and give you a signed link. You can put the link in a CV or send it to a manager: it opens a page that shows the course, the test, the date and the name you give here. No account, and nothing is stored: keep the link.