Lesson 01 · 50 minutes
Map a cloud account and say who is responsible for what
- Explain the shared responsibility model and the two planes of a cloud service
- Read the name of a cloud resource and say which account, region and service it belongs to
- Find resources that are in the wrong region or that nobody owns
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
Larkfield Books is an invented online bookshop. All its systems run in one account at Amazon Web Services (AWS). You start there as a junior security analyst, and your lead gives you an export of the account, a snapshot, with one request: "Before you look for holes, tell me what we have. What is in this account, in which regions, and who owns it? And is there anything that should not be there?" You cannot protect what you cannot list, so the first job in any cloud is a map.
The idea
Cloud computing means that you rent computers, storage and networks from a provider and control them over the network, on demand. The NIST definition of cloud computing (SP 800-145) is the text that most other documents build on. For a defender, three things change.
1. The responsibility is shared. AWS calls its part "security of the cloud" and the customer's part "security in the cloud". The provider protects the buildings, the hardware and the software that runs the services. The customer protects what they put there and how they set it up. Where the line runs depends on the service.
| You use | The provider looks after | You look after |
|---|---|---|
| A virtual machine (Amazon EC2) | The building, the hardware, the layer that separates customers | The operating system and its patches, the firewall rules, your programs, your data |
| A managed database (Amazon RDS) | All of the above, and the database software | Who may connect, the network rules, encryption settings, backups that you choose, your data |
| Object storage (Amazon S3) | All of the above, and the storage software | Who may read and write, encryption settings, your data |
Three things are always yours: your data, your identities (who may do what) and your configuration. Almost every cloud breach that reaches the news is a mistake in one of these three, on the customer's side of the line.
2. Everything is an API call. An API (application programming interface) is a set of requests that a program can send to a service. Nobody walks into a data centre: a person or a program sends a signed request such as "create a machine" or "give me this file". Each service has two sides. The control plane is the API that creates, changes and deletes resources (make a bucket, open a port). The data plane is the resource doing its work (serve a file, answer a database query). AWS uses these words for its logs too: calls to the control plane are management events, and calls to the data plane are data events (lesson 7).
3. Identity is the perimeter. In an office, the firewall decided who came in. In a cloud, the control plane is on the internet for everyone, and the only thing between a stranger and your account is the question "who signed this request, and are they allowed?". Lessons 2 to 4 are about that question.
A cloud estate has five levels.
An account is the strongest wall that AWS gives you: by default, nothing in one account can touch another. Companies use many accounts (one for production, one for development) and join them in an organisation. A region is a group of data centres in one area. Most resources live in one region, and a few services are global: IAM (Identity and Access Management), the service for users and rights, is one.
Every resource has a unique name, the ARN (Amazon Resource Name), with six parts separated by colons:
arn:aws:iam::111122223333:user/alice.morgan
arn:aws:s3:::larkfield-ordersNot every ARN fills all six parts. The first of these two has an empty region, because IAM is global. The second has no region and no account: the name of an S3 bucket (a container for files, which S3 calls objects) is unique in the whole partition in the default namespace. Since March 2026 a new bucket can instead use a namespace of your own account and region. Existing buckets are not changed.
| Same idea, other names | AWS | Microsoft Azure | Google Cloud |
|---|---|---|---|
| The wall around resources | Account | Subscription | Project |
| Many of them under one company | Organisation (AWS Organizations) | Management groups in a tenant | Organisation and folders |
| The name of one resource | ARN | Resource ID | Full resource name |
Worked example
1. Make the snapshot
gen_account.py writes the snapshot of the Larkfield account into the folder account: ten JSON files that the next lessons use one by one. It prints the size and a short SHA-256 hash of each file (a hash is a fingerprint of a file, from "Security fundamentals", lesson 5). You do not need to read the program now. Open the block, save the file in your lab folder and run it. In a real account you make such files with the AWS CLI: the cheat sheet lists the calls. This course does not run those calls.
The finished file: gen_account.py
gen_account.py
"""gen_account.py: write the snapshot of an invented cloud account (Larkfield Books) into a folder.
python3 gen_account.py [seed] [folder] default: seed 1, folder account
The same seed gives the same files on every machine. Nothing here is a real account, key or address.
"""
import hashlib
import json
import random
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
SEED = int(sys.argv[1]) if len(sys.argv) > 1 else 1
OUT = Path(sys.argv[2] if len(sys.argv) > 2 else "account")
r = random.Random(SEED) # only random() is used: the files are the same on every Python version
ACCOUNT, DEV_ACCOUNT = "111122223333", "444455556666"
IAM = f"arn:aws:iam::{ACCOUNT}:"
V = "2012-10-17"
UPPER = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
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": V, "Statement": list(statements)}
def trust(principal, **more):
return doc({"Effect": "Allow", "Principal": principal, "Action": "sts:AssumeRole", **more})
# What changes with the seed: the intruder of lesson 7 and the size of the account.
ROGUE_REGION = ["ap-southeast-2", "sa-east-1"][(SEED - 1) % 2]
ROGUE_COUNT = 3 if SEED == 1 else 2 + int(r.random() * 3)
ROGUE_IP = ["203.0.113.77", "198.51.100.23"][(SEED - 1) % 2]
ROGUE_USER = ["svc-monitor", "svc-backup2"][(SEED - 1) % 2]
ROGUE_KEY = "AKIA" + rid(9, UPPER) + "EXAMPLE"
T0 = datetime(2026, 11, 18, 2, 41, 7, tzinfo=timezone.utc) + timedelta(minutes=(SEED - 1) * 37)
T_START = datetime(2026, 11, 18, 8, 15, 30, tzinfo=timezone.utc) + timedelta(minutes=(SEED - 1) * 23)
CI_KEY = "AKIAQ7XJ2MPLWEXAMPLE"
# ---------------------------------------------------------------- identity
POLICIES = {
"AdminAll": doc(allow("*", "*")),
"DevCompute": doc(
allow(["ec2:Describe*", "ec2:StartInstances", "ec2:StopInstances"], "*"),
allow(["s3:GetObject", "s3:ListBucket"], ["arn:aws:s3:::larkfield-dev-scratch", "arn:aws:s3:::larkfield-dev-scratch/*"])),
"GuardRails": doc({"Effect": "Deny", "Action": ["s3:DeleteBucket", "cloudtrail:StopLogging", "cloudtrail:DeleteTrail"],
"Resource": "*"}),
"ReadOnlyAudit": doc(allow(["s3:Get*", "s3:List*", "iam:Get*", "iam:List*", "ec2:Describe*", "cloudtrail:LookupEvents"], "*")),
"HelpdeskKeys": doc(allow(["iam:CreateAccessKey", "iam:UpdateLoginProfile"], IAM + "user/*")),
"DeployFull": doc(allow(["s3:*", "ec2:*", "lambda:*"], "*"), allow("iam:PassRole", "*")),
"BackupWrite": doc(allow("s3:PutObject", "arn:aws:s3:::larkfield-backups/*",
Condition={"IpAddress": {"aws:SourceIp": "192.0.2.0/24"}})),
"WebAppData": doc(
allow(["s3:GetObject", "s3:PutObject"], "arn:aws:s3:::larkfield-orders/*"),
allow(["kms:Decrypt", "kms:GenerateDataKey"], f"arn:aws:kms:eu-west-1:{ACCOUNT}:key/1a2b3c4d-0000-4000-8000-larkfield001")),
"ReportsRead": doc(allow("s3:GetObject", "arn:aws:s3:::larkfield-orders/reports/*"), allow("logs:*", "*")),
"SupportRead": doc(allow(["s3:Get*", "s3:List*"], "*")),
}
GROUPS = [{"name": "Admins", "policies": ["AdminAll"]},
{"name": "Developers", "policies": ["DevCompute", "GuardRails"]},
{"name": "Auditors", "policies": ["ReadOnlyAudit"]}]
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("alice.morgan", ["Admins"], [], True, True, "2026-11-20", []),
user("ben.okafor", ["Developers"], ["HelpdeskKeys"], True, False, "2026-11-20",
[("AKIAT4HN8RZKDEXAMPLE", "Active", "2025-03-02", "2026-11-19")]),
user("chloe.tan", ["Developers", "Admins"], [], True, True, "2026-11-19", []),
user("dmitri.volkov", ["Auditors"], [], True, True, "2026-11-12", []),
user("nadia.temp", [], ["AdminAll"], True, False, "2025-08-14", []),
user("ci-deploy", [], ["DeployFull"], False, False, None,
[(CI_KEY, "Active", "2026-05-10", "2026-11-20"), ("AKIAL9SD3FQUAEXAMPLE", "Inactive", "2025-01-15", "2025-06-30")]),
user("backup-bot", [], ["BackupWrite"], False, False, None, [("AKIAW2CV6BYGFEXAMPLE", "Active", "2024-11-20", "2026-11-20")]),
user(ROGUE_USER, [], ["AdminAll"], False, False, None, [(ROGUE_KEY, "Active", "2026-11-18", "2026-11-19")]),
]
def role(name, trust_doc, policies):
return {"name": name, "arn": IAM + "role/" + name, "trust": trust_doc, "policies": policies}
ROLES = [
role("web-app-role", trust({"Service": "ec2.amazonaws.com"}), ["WebAppData"]),
role("report-lambda-role", trust({"Service": "lambda.amazonaws.com"}), ["ReportsRead"]),
role("ec2-maintenance", trust({"Service": "ec2.amazonaws.com"}), ["AdminAll"]),
role("dev-cross-account", trust({"AWS": f"arn:aws:iam::{DEV_ACCOUNT}:root"}), ["DevCompute"]),
role("support-partner", trust({"AWS": "*"}), ["SupportRead"]),
role("ops-admin", trust({"AWS": IAM + "root"}, Condition={"Bool": {"aws:MultiFactorAuthPresent": "true"}}), ["AdminAll"]),
]
# ---------------------------------------------------------------- requests for the evaluator
ORDERS, BACKUPS, SCRATCH = "arn:aws:s3:::larkfield-orders", "arn:aws:s3:::larkfield-backups", "arn:aws:s3:::larkfield-dev-scratch"
WEB1 = f"arn:aws:ec2:eu-west-1:{ACCOUNT}:instance/i-0a11b22c33d44e551"
TRAIL = f"arn:aws:cloudtrail:eu-west-1:{ACCOUNT}:trail/larkfield-trail"
OFFICE, ELSEWHERE = "192.0.2.21", "203.0.113.9"
def req(n, who, action, resource, **context):
return {"id": f"R{n:02d}", "principal": IAM + who, "action": action, "resource": resource,
"context": {k.replace("_", ":", 1): v for k, v in context.items()}}
def requests():
out = [
req(1, "user/alice.morgan", "s3:DeleteBucket", ORDERS, aws_SourceIp=OFFICE),
req(2, "user/ben.okafor", "ec2:StopInstances", WEB1, aws_SourceIp=OFFICE),
req(3, "user/chloe.tan", "cloudtrail:StopLogging", TRAIL, aws_SourceIp=OFFICE),
req(4, "user/dmitri.volkov", "s3:PutObject", ORDERS + "/2026/11/orders.csv", aws_SourceIp=OFFICE),
req(5, "user/backup-bot", "s3:PutObject", BACKUPS + "/db/2026-11-20.dump", aws_SourceIp=OFFICE),
req(6, "user/backup-bot", "s3:PutObject", BACKUPS + "/db/2026-11-20.dump", aws_SourceIp=ELSEWHERE),
]
who = ["user/" + u["name"] for u in USERS[:7]] + ["role/" + x["name"] for x in ROLES[:3]]
what = [("s3:GetObject", ORDERS + "/reports/q3.pdf"), ("s3:GetObject", SCRATCH + "/notes.txt"),
("s3:PutObject", ORDERS + "/2026/11/orders.csv"), ("s3:PutObject", BACKUPS + "/db/full.dump"),
("s3:DeleteBucket", BACKUPS), ("s3:ListBucket", SCRATCH), ("ec2:DescribeInstances", "*"),
("ec2:StopInstances", WEB1), ("ec2:TerminateInstances", WEB1), ("iam:CreateAccessKey", IAM + "user/alice.morgan"),
("iam:ListUsers", "*"), ("cloudtrail:StopLogging", TRAIL), ("cloudtrail:LookupEvents", "*"),
("logs:CreateLogGroup", f"arn:aws:logs:eu-west-1:{ACCOUNT}:log-group:reports"),
("iam:PassRole", IAM + "role/ec2-maintenance"), ("kms:Decrypt", POLICIES["WebAppData"]["Statement"][1]["Resource"])]
for n in range(7, 41):
action, resource = pick(what)
out.append(req(n, pick(who), action, resource, aws_SourceIp=pick([OFFICE, OFFICE, ELSEWHERE])))
return out
# Requests where the resource has a policy of its own (lesson 2, "Your turn").
PARTNER_POLICY = doc({"Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{DEV_ACCOUNT}:role/build"},
"Action": "s3:GetObject", "Resource": "arn:aws:s3:::larkfield-partner/*"},
{"Effect": "Allow", "Principal": {"AWS": IAM + "user/dmitri.volkov"},
"Action": "s3:PutObject", "Resource": "arn:aws:s3:::larkfield-partner/inbox/*"},
{"Effect": "Deny", "Principal": "*", "Action": "s3:DeleteObject", "Resource": "arn:aws:s3:::larkfield-partner/*"})
BUILD_IDENTITY = doc(allow("s3:GetObject", "arn:aws:s3:::larkfield-partner/*"))
def cross():
partner = "arn:aws:s3:::larkfield-partner"
build, other = f"arn:aws:iam::{DEV_ACCOUNT}:role/build", f"arn:aws:iam::{DEV_ACCOUNT}:role/test"
def case(n, principal, account, identity, action, key):
return {"id": f"X{n}", "principal": principal, "principal_account": account, "identity_policies": identity,
"action": action, "resource": f"{partner}/{key}", "context": {}}
return {"resource_account": ACCOUNT, "resource_policy": PARTNER_POLICY, "requests": [
case(1, IAM + "user/dmitri.volkov", ACCOUNT, [POLICIES["ReadOnlyAudit"]], "s3:PutObject", "inbox/a.csv"),
case(2, IAM + "user/dmitri.volkov", ACCOUNT, [POLICIES["ReadOnlyAudit"]], "s3:PutObject", "public/a.csv"),
case(3, IAM + "user/dmitri.volkov", ACCOUNT, [POLICIES["ReadOnlyAudit"]], "s3:GetObject", "inbox/a.csv"),
case(4, IAM + "user/alice.morgan", ACCOUNT, [POLICIES["AdminAll"]], "s3:DeleteObject", "inbox/a.csv"),
case(5, build, DEV_ACCOUNT, [BUILD_IDENTITY], "s3:GetObject", "inbox/a.csv"),
case(6, build, DEV_ACCOUNT, [], "s3:GetObject", "inbox/a.csv"),
case(7, other, DEV_ACCOUNT, [BUILD_IDENTITY], "s3:GetObject", "inbox/a.csv"),
case(8, build, DEV_ACCOUNT, [BUILD_IDENTITY], "s3:PutObject", "inbox/a.csv"),
case(9, IAM + "user/ben.okafor", ACCOUNT, [POLICIES["DevCompute"], POLICIES["GuardRails"]], "s3:GetObject", "inbox/a.csv"),
case(10, build, DEV_ACCOUNT, [POLICIES["AdminAll"]], "s3:DeleteObject", "inbox/a.csv"),
]}
# What the deploy user really did in 90 days, and the tests for a smaller policy (lesson 3, "Your turn").
ORDERS_API = f"arn:aws:lambda:eu-west-1:{ACCOUNT}:function:orders-api"
CI_USAGE = [{"action": "s3:ListBucket", "resource": "arn:aws:s3:::larkfield-site", "calls": 212},
{"action": "s3:PutObject", "resource": "arn:aws:s3:::larkfield-site/*", "calls": 4410},
{"action": "s3:DeleteObject", "resource": "arn:aws:s3:::larkfield-site/*", "calls": 388},
{"action": "lambda:UpdateFunctionCode", "resource": ORDERS_API, "calls": 57},
{"action": "ec2:DescribeInstances", "resource": "*", "calls": 212},
{"action": "iam:PassRole", "resource": IAM + "role/report-lambda-role", "calls": 3}]
def ci_tests():
def t(action, resource):
return {"action": action, "resource": resource, "context": {}}
return {"must_allow": [t("s3:ListBucket", "arn:aws:s3:::larkfield-site"), t("s3:PutObject", "arn:aws:s3:::larkfield-site/index.html"),
t("s3:DeleteObject", "arn:aws:s3:::larkfield-site/old/a.css"), t("lambda:UpdateFunctionCode", ORDERS_API),
t("ec2:DescribeInstances", "*"), t("iam:PassRole", IAM + "role/report-lambda-role")],
"must_not_allow": [t("s3:GetObject", ORDERS + "/2026/11/orders.csv"), t("s3:PutObject", BACKUPS + "/x"),
t("s3:DeleteBucket", "arn:aws:s3:::larkfield-site"), t("ec2:RunInstances", "*"),
t("ec2:TerminateInstances", WEB1), t("iam:PassRole", IAM + "role/ec2-maintenance"),
t("lambda:UpdateFunctionCode", ORDERS_API.replace("orders-api", "report-job")),
t("iam:CreateAccessKey", IAM + "user/alice.morgan")]}
# ---------------------------------------------------------------- storage
EVERYONE = "http://acs.amazonaws.com/groups/global/AllUsers"
SIGNED_IN = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
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, versioning=False):
return {"name": name, "region": "eu-west-1", "public_access_block": block, "policy": policy,
"acl": [{"Grantee": {"Type": "Group", "URI": g}, "Permission": p} for g, p in grants],
"encryption": {"SSEAlgorithm": sse}, "versioning": versioning, "intended_public": intended_public}
TLS_ONLY = {"Effect": "Deny", "Principal": "*", "Action": "s3:*",
"Resource": ["arn:aws:s3:::larkfield-logs", "arn:aws:s3:::larkfield-logs/*"],
"Condition": {"Bool": {"aws:SecureTransport": "false"}}}
BUCKETS = {"account_public_access_block": pab(acls=True), "buckets": [
bucket("larkfield-orders", pab(True, True, True, True), sse="aws:kms", versioning=True,
policy=doc({"Effect": "Allow", "Principal": {"AWS": IAM + "role/web-app-role"}, "Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::larkfield-orders/*"})),
bucket("larkfield-site", pab(), policy=doc(anyone("larkfield-site", "s3:GetObject")), intended_public=True),
bucket("larkfield-backups", pab(), policy=doc(anyone("larkfield-backups", ["s3:GetObject", "s3:ListBucket"]))),
bucket("larkfield-reports", pab(restrict=True), policy=doc(anyone("larkfield-reports", "s3:GetObject"))),
bucket("larkfield-uploads", pab(), grants=[(EVERYONE, "READ")]),
bucket("larkfield-logs", pab(True, True, True, True), versioning=True,
policy=doc({"Effect": "Allow", "Principal": {"Service": "cloudtrail.amazonaws.com"}, "Action": "s3:PutObject",
"Resource": f"arn:aws:s3:::larkfield-logs/AWSLogs/{ACCOUNT}/*"}, TLS_ONLY)),
bucket("larkfield-partner", pab(), policy=doc(anyone("larkfield-partner", "s3:GetObject",
Condition={"IpAddress": {"aws:SourceIp": "198.51.100.0/24"}}))),
bucket("larkfield-dev-scratch", pab(ignore=True), grants=[(SIGNED_IN, "WRITE")]),
bucket("larkfield-media", pab(), policy=doc(anyone("larkfield-media", "s3:GetObject",
Condition={"IpAddress": {"aws:SourceIp": "0.0.0.0/0"}}))),
]}
# ---------------------------------------------------------------- network
ANY = "0.0.0.0/0"
def rule(port, cidr=None, group=None, to=None):
return {"protocol": "tcp", "from_port": port, "to_port": to or port, **({"cidr": cidr} if cidr else {"source_group": group})}
def entry(number, action, cidr=ANY, port=None, to=None, egress=False):
return {"rule_number": number, "egress": egress, "action": action, "cidr": cidr,
"protocol": "tcp" if port else "all", "from_port": port, "to_port": to or port}
NETWORK = {
"vpc": {"id": "vpc-0larkfield", "cidr": "10.20.0.0/16"}, "expected_public": [["web-1", 443], ["web-1", 80]],
"subnets": [{"id": "subnet-public-a", "cidr": "10.20.1.0/24", "route_table": "rt-public", "nacl": "nacl-main"},
{"id": "subnet-app-a", "cidr": "10.20.11.0/24", "route_table": "rt-private", "nacl": "nacl-main"},
{"id": "subnet-db-a", "cidr": "10.20.21.0/24", "route_table": "rt-db", "nacl": "nacl-main"},
{"id": "subnet-legacy", "cidr": "10.20.31.0/24", "route_table": "rt-public", "nacl": "nacl-legacy"}],
"route_tables": [{"id": "rt-public", "routes": [{"destination": "10.20.0.0/16", "target": "local"}, {"destination": ANY, "target": "igw-0a1"}]},
{"id": "rt-private", "routes": [{"destination": "10.20.0.0/16", "target": "local"}, {"destination": ANY, "target": "nat-0b2"}]},
{"id": "rt-db", "routes": [{"destination": "10.20.0.0/16", "target": "local"}]}],
"security_groups": [
{"id": "sg-web", "ingress": [rule(443, ANY), rule(80, ANY)]},
{"id": "sg-bastion", "ingress": [rule(22, ANY)]},
{"id": "sg-app", "ingress": [rule(8080, group="sg-web"), rule(22, group="sg-bastion")]},
{"id": "sg-db", "ingress": [rule(5432, group="sg-app"), rule(5432, ANY)]},
{"id": "sg-legacy", "ingress": [rule(3306, ANY), rule(3389, "203.0.113.0/24")]}],
"nacls": [{"id": "nacl-main", "entries": [entry(100, "allow"), entry(100, "allow", egress=True)]},
{"id": "nacl-legacy", "entries": [entry(90, "deny", port=3389), entry(100, "allow"), entry(100, "allow", egress=True)]}],
"instances": [{"id": "i-0a11b22c33d44e551", "name": "web-1", "subnet": "subnet-public-a", "private_ip": "10.20.1.10",
"public_ip": "192.0.2.10", "security_groups": ["sg-web"]},
{"id": "i-0a11b22c33d44e552", "name": "bastion-1", "subnet": "subnet-public-a", "private_ip": "10.20.1.11",
"public_ip": "192.0.2.11", "security_groups": ["sg-bastion"]},
{"id": "i-0a11b22c33d44e553", "name": "app-1", "subnet": "subnet-app-a", "private_ip": "10.20.11.10",
"public_ip": None, "security_groups": ["sg-app"]},
{"id": "i-0a11b22c33d44e554", "name": "db-1", "subnet": "subnet-db-a", "private_ip": "10.20.21.10",
"public_ip": None, "security_groups": ["sg-db"]},
{"id": "i-0a11b22c33d44e555", "name": "legacy-db", "subnet": "subnet-legacy", "private_ip": "10.20.31.10",
"public_ip": "192.0.2.40", "security_groups": ["sg-legacy"]}],
}
# ---------------------------------------------------------------- logging
TRAILS = [{"Name": "larkfield-trail", "S3BucketName": "larkfield-logs", "HomeRegion": "eu-west-1", "IsMultiRegionTrail": False,
"LogFileValidationEnabled": False, "KmsKeyId": None, "IsLogging": True, "DataEvents": []}]
OFFICE_IPS = {"alice.morgan": "192.0.2.51", "ben.okafor": "192.0.2.52", "chloe.tan": "192.0.2.53", "dmitri.volkov": "192.0.2.54",
"ci-deploy": "192.0.2.20", "backup-bot": "192.0.2.21"}
PRINCIPAL_IDS = {u["name"]: "AIDA" + rid(10, UPPER) + "EXAMPLE" for u in USERS}
READS = [("ec2.amazonaws.com", "DescribeInstances"), ("ec2.amazonaws.com", "DescribeSecurityGroups"), ("ec2.amazonaws.com", "DescribeVolumes"),
("s3.amazonaws.com", "ListBuckets"), ("s3.amazonaws.com", "GetBucketLocation"), ("s3.amazonaws.com", "GetBucketPolicy"),
("iam.amazonaws.com", "ListUsers"), ("iam.amazonaws.com", "GetUser"), ("iam.amazonaws.com", "ListRoles"),
("cloudtrail.amazonaws.com", "DescribeTrails"), ("kms.amazonaws.com", "ListKeys"), ("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"
def stamp(t):
return t.strftime("%Y-%m-%dT%H:%M:%SZ")
def guid():
return f"{rid(8)}-{rid(4)}-{rid(4)}-{rid(4)}-{rid(12)}"
def user_identity(name, key=None, mfa=None):
ident = {"type": "IAMUser", "principalId": PRINCIPAL_IDS[name], "arn": IAM + "user/" + name, "accountId": ACCOUNT, "userName": name}
if key:
ident["accessKeyId"] = key
if mfa is not None:
ident["sessionContext"] = {"attributes": {"mfaAuthenticated": "true" if mfa else "false"}}
return ident
def role_identity(name, session, key, created):
arn = f"arn:aws:sts::{ACCOUNT}:assumed-role/{name}/{session}"
return {"type": "AssumedRole", "principalId": f"AROAEC2MAINT77EXAMPLE:{session}", "arn": arn, "accountId": ACCOUNT, "accessKeyId": key,
"sessionContext": {"sessionIssuer": {"type": "Role", "principalId": "AROAEC2MAINT77EXAMPLE", "arn": IAM + "role/" + name,
"accountId": ACCOUNT, "userName": name},
"attributes": {"creationDate": stamp(created), "mfaAuthenticated": "false"}}}
def event(t, ident, source, name, ip, agent=CLI, region="eu-west-1", params=None, response=None, error=None, read=True, **more):
ev = {"eventVersion": "1.11", "userIdentity": ident, "eventTime": stamp(t), "eventSource": source, "eventName": name,
"awsRegion": "us-east-1" if source in GLOBAL else region, "sourceIPAddress": ip, "userAgent": agent}
if error:
ev["errorCode"], ev["errorMessage"] = "AccessDenied", error
ev.update({"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, mfa):
ident = user_identity(name)
return event(t, ident, "signin.amazonaws.com", "ConsoleLogin", OFFICE_IPS[name], 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 denied(name, action):
return f"User: {IAM}user/{name} is not authorized to perform: {action} because no identity-based policy allows the {action} action"
def events():
out, mfa = [], {u["name"]: u["mfa"] for u in USERS}
for day in range(16, 21):
base = datetime(2026, 11, day, tzinfo=timezone.utc)
for name in ("alice.morgan", "ben.okafor", "chloe.tan", "dmitri.volkov"):
if r.random() < 0.8 or (day == 18 and name == "alice.morgan"):
t = base + timedelta(hours=8, minutes=int(r.random() * 90), seconds=int(r.random() * 60))
if day == 18 and name == "alice.morgan": # she signs in, sees that the trail is off, and starts it
t = T_START - timedelta(minutes=9, seconds=12)
out.append(login(t, name, mfa[name]))
for _ in range(4 + int(r.random() * 6)):
t += timedelta(seconds=30 + int(r.random() * 2400))
source, call = pick(READS[:11])
out.append(event(t, user_identity(name, "ASIA" + rid(9, UPPER) + "EXAMPLE", mfa[name]), source, call, OFFICE_IPS[name], BROWSER,
sessionCredentialFromConsole="true"))
for name, key in (("ci-deploy", CI_KEY), ("backup-bot", "AKIAW2CV6BYGFEXAMPLE")):
for _ in range(6 + int(r.random() * 5)):
t = base + timedelta(seconds=int(r.random() * 86400))
source, call = pick([READS[11], READS[0], READS[1], READS[3], READS[4]])
out.append(event(t, user_identity(name, key), source, call, OFFICE_IPS[name]))
# two approved changes
t = datetime(2026, 11, 17, 10, 22, 41, tzinfo=timezone.utc)
out.append(event(t, user_identity("chloe.tan", "ASIA" + rid(9, UPPER) + "EXAMPLE", True), "ec2.amazonaws.com", "AuthorizeSecurityGroupIngress",
OFFICE_IPS["chloe.tan"], BROWSER, read=False, response={"_return": True}, sessionCredentialFromConsole="true",
params={"groupId": "sg-web", "ipPermissions": {"items": [{"ipProtocol": "tcp", "fromPort": 443, "toPort": 443,
"ipRanges": {"items": [{"cidrIp": ANY}]}}]}}))
t = datetime(2026, 11, 19, 14, 5, 12, tzinfo=timezone.utc)
out.append(event(t, user_identity("alice.morgan", "ASIA" + rid(9, UPPER) + "EXAMPLE", True), "s3.amazonaws.com", "PutBucketPolicy",
OFFICE_IPS["alice.morgan"], BROWSER, read=False, sessionCredentialFromConsole="true",
params={"bucketName": "larkfield-partner", "policy": ""}))
# the intruder: the key of ci-deploy, used from a new address
ci = user_identity("ci-deploy", CI_KEY)
t = T0
steps = [(0, "sts.amazonaws.com", "GetCallerIdentity", None), (21, "iam.amazonaws.com", "ListUsers", "iam:ListUsers"),
(19, "iam.amazonaws.com", "ListAttachedUserPolicies", "iam:ListAttachedUserPolicies"), (25, "s3.amazonaws.com", "ListBuckets", None),
(35, "ec2.amazonaws.com", "DescribeInstances", None), (50, "iam.amazonaws.com", "ListRoles", "iam:ListRoles")]
for wait, source, call, action in steps:
t += timedelta(seconds=wait)
out.append(event(t, ci, source, call, ROGUE_IP, error=denied("ci-deploy", action) if action else None))
rogue_ids = []
for n in range(ROGUE_COUNT):
t += timedelta(seconds=50 if n == 0 else 4)
iid = "i-0" + rid(16)
rogue_ids.append(iid)
params = {"instanceType": "c5.4xlarge", "instancesSet": {"items": [{"imageId": "ami-0abcdef1234567890", "minCount": 1, "maxCount": 1}]}}
if n == 0:
params["iamInstanceProfile"] = {"name": "ec2-maintenance"}
out.append(event(t, ci, "ec2.amazonaws.com", "RunInstances", ROGUE_IP, region=ROGUE_REGION, params=params, read=False,
response={"instancesSet": {"items": [{"instanceId": iid}]}}))
created = t + timedelta(minutes=4)
box = role_identity("ec2-maintenance", rogue_ids[0], "ASIA" + rid(9, UPPER) + "EXAMPLE", created)
box_ip = "203.0.113.140"
t = T0 + timedelta(minutes=9)
out.append(event(t, box, "iam.amazonaws.com", "CreateUser", box_ip, params={"userName": ROGUE_USER}, read=False,
response={"user": {"userName": ROGUE_USER, "arn": IAM + "user/" + ROGUE_USER}}))
t += timedelta(seconds=20)
out.append(event(t, box, "iam.amazonaws.com", "AttachUserPolicy", box_ip, read=False,
params={"userName": ROGUE_USER, "policyArn": IAM + "policy/AdminAll"}))
t += timedelta(seconds=25)
out.append(event(t, box, "iam.amazonaws.com", "CreateAccessKey", box_ip, params={"userName": ROGUE_USER}, read=False,
response={"accessKey": {"userName": ROGUE_USER, "accessKeyId": ROGUE_KEY, "status": "Active"}}))
t += timedelta(seconds=75)
stop = t
out.append(event(t, box, "cloudtrail.amazonaws.com", "StopLogging", box_ip, params={"name": TRAIL}, read=False))
# the morning after: an administrator finds the trail off and starts it again
alice = user_identity("alice.morgan", "ASIA" + rid(9, UPPER) + "EXAMPLE", True)
out.append(event(T_START, alice, "cloudtrail.amazonaws.com", "StartLogging", OFFICE_IPS["alice.morgan"], BROWSER, params={"name": TRAIL},
read=False, sessionCredentialFromConsole="true"))
# the new user is used after the trail is on again
rogue = user_identity(ROGUE_USER, ROGUE_KEY)
t = T_START + timedelta(hours=1, minutes=14)
out.append(event(t, rogue, "sts.amazonaws.com", "GetCallerIdentity", ROGUE_IP))
t = datetime(2026, 11, 19, 3, 10, 2, tzinfo=timezone.utc) + timedelta(minutes=(SEED - 1) * 11)
out.append(event(t, rogue, "s3.amazonaws.com", "ListBuckets", ROGUE_IP))
t += timedelta(seconds=95)
out.append(event(t, rogue, "s3.amazonaws.com", "DeleteBucketPublicAccessBlock", ROGUE_IP, params={"bucketName": "larkfield-uploads"}, read=False))
t += timedelta(seconds=31)
out.append(event(t, rogue, "s3.amazonaws.com", "PutBucketAcl", ROGUE_IP, read=False,
params={"bucketName": "larkfield-uploads", "x-amz-acl": "public-read"}))
# nothing was written while the trail was off
out = [e for e in out if not stop < datetime.strptime(e["eventTime"], "%Y-%m-%dT%H:%M:%S%z") < T_START]
out.sort(key=lambda e: e["eventTime"])
return out, rogue_ids
# ---------------------------------------------------------------- inventory
def inventory(rogue_ids):
rows = []
def add(arn, service, kind, region, name, created, owner="platform", env="prod"):
tags = {"owner": owner, "env": env} if owner else {}
rows.append({"arn": arn, "service": service, "type": kind, "region": region, "name": name, "created": created, "tags": tags})
for n, i in enumerate(NETWORK["instances"]):
add(f"arn:aws:ec2:eu-west-1:{ACCOUNT}:instance/{i['id']}", "ec2", "instance", "eu-west-1", i["name"], f"2025-0{n + 2}-11",
"shop" if n < 3 else "data")
for g in NETWORK["security_groups"]:
add(f"arn:aws:ec2:eu-west-1:{ACCOUNT}:security-group/{g['id']}", "ec2", "security-group", "eu-west-1", g["id"], "2025-02-10")
for b in BUCKETS["buckets"]:
add(f"arn:aws:s3:::{b['name']}", "s3", "bucket", "eu-west-1", b["name"], "2025-01-20", pick(["shop", "data", "platform"]))
for u in USERS:
add(u["arn"], "iam", "user", "", u["name"], u["access_keys"][0]["created"] if u["name"] == ROGUE_USER else "2025-01-15",
None if u["name"] == ROGUE_USER else "platform")
for x in ROLES:
add(x["arn"], "iam", "role", "", x["name"], "2025-01-15")
add(POLICIES["WebAppData"]["Statement"][1]["Resource"], "kms", "key", "eu-west-1", "orders-key", "2025-01-20", "data")
add(TRAIL, "cloudtrail", "trail", "eu-west-1", "larkfield-trail", "2025-01-15")
add(f"arn:aws:rds:eu-west-1:{ACCOUNT}:db:orders-db", "rds", "db", "eu-west-1", "orders-db", "2025-03-01", "data")
for name in ("orders-api", "report-job"):
add(f"arn:aws:lambda:eu-west-1:{ACCOUNT}:function:{name}", "lambda", "function", "eu-west-1", name, "2025-06-02", "shop")
for n in range(10 + int(r.random() * 8)): # volumes and snapshots; some have no tags
region, kind = pick(["eu-west-1", "eu-west-1", "eu-central-1"]), pick(["volume", "volume", "snapshot"])
rid_ = ("vol-0" if kind == "volume" else "snap-0") + rid(16)
add(f"arn:aws:ec2:{region}:{ACCOUNT}:{kind}/{rid_}", "ec2", kind, region, rid_, f"2026-{1 + int(r.random() * 10):02d}-{1 + int(r.random() * 28):02d}",
None if r.random() < 0.4 else pick(["shop", "data"]), pick(["prod", "dev"]))
for n in range(3 + int(r.random() * 4)): # the backup site
iid = "i-0" + rid(16)
add(f"arn:aws:ec2:eu-central-1:{ACCOUNT}:instance/{iid}", "ec2", "instance", "eu-central-1", f"standby-{n + 1}", "2025-09-30", "platform")
for iid in rogue_ids:
add(f"arn:aws:ec2:{ROGUE_REGION}:{ACCOUNT}:instance/{iid}", "ec2", "instance", ROGUE_REGION, iid, "2026-11-18", None)
return {"organisation": {"id": "o-exampleorgid", "accounts": [{"id": "999999999999", "name": "larkfield-management"},
{"id": ACCOUNT, "name": "larkfield-prod"},
{"id": DEV_ACCOUNT, "name": "larkfield-dev"}]},
"account": ACCOUNT, "approved_regions": ["eu-west-1", "eu-central-1"], "known_networks": ["192.0.2.0/24"], "resources": rows}
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(parents=True, 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("requests.json", requests())
write("cross.json", cross())
write("ci-usage.json", CI_USAGE)
write("ci-tests.json", ci_tests())
write("buckets.json", BUCKETS)
write("network.json", NETWORK)
write("trails.json", TRAILS)
write("events.json", {"Records": recs})cd ~/krlab/cloud-security-basics
python3 gen_account.pyinventory.json 15891 bytes sha256 7b482d6eb552
iam.json 7978 bytes sha256 1d14a4051d51
requests.json 9102 bytes sha256 14c29087c8d4
cross.json 5855 bytes sha256 afc926974b14
ci-usage.json 627 bytes sha256 a8d360ab5cca
ci-tests.json 1672 bytes sha256 0ff9b46e501e
buckets.json 6201 bytes sha256 4432d84c25a5
network.json 4410 bytes sha256 0f43431acacd
trails.json 232 bytes sha256 9672cf20c252
events.json 199406 bytes sha256 631802a29c18If your hashes differ, your copy of the program differs.
2. Read one record and one ARN
This lesson uses account/inventory.json. Its shape is our own: a real export has more fields, but the same ideas. The file names the account, the regions that Larkfield has approved for its systems, and a list of resources. python3 -c runs a short program from the command line, and json.load reads a JSON file (from "Python for security work", lesson 4).
python3 -c "
import json
inv = json.load(open('account/inventory.json'))
print(inv['account'], inv['approved_regions'])
print(json.dumps(inv['resources'][0], indent=1))"111122223333 ['eu-west-1', 'eu-central-1']
{
"arn": "arn:aws:ec2:eu-west-1:111122223333:instance/i-0a11b22c33d44e551",
"service": "ec2",
"type": "instance",
"region": "eu-west-1",
"name": "web-1",
"created": "2025-02-11",
"tags": {
"owner": "shop",
"env": "prod"
}
}Read the ARN from left to right: the service is ec2, the region is eu-west-1, the account is 111122223333, and the resource is an instance (a virtual machine). A tag is a label that the owner puts on a resource. Larkfield's rule is that every resource carries an owner tag.
3. Save the mapping program
account_map.py counts the resources by service and by region and lists two kinds of trouble: resources in a region that is not approved, and resources with no owner tag. The key function is parse_arn. It splits the ARN at the first five colons only (split(":", 5)), because the last part may hold colons of its own. Counter (from "Python for security work", lesson 2) counts how often each value appears.
account_map.py
"""account_map.py: draw a map of an account from its inventory.
python3 account_map.py [folder] default folder: account
"""
import json
import sys
from collections import Counter
def parse_arn(arn):
"""Split an ARN into its six parts. The resource part may itself hold colons, so split five times only."""
prefix, partition, service, region, account, resource = arn.split(":", 5)
return {"partition": partition, "service": service, "region": region, "account": account, "resource": resource}
def load(folder="account"):
with open(f"{folder}/inventory.json") as src:
return json.load(src)
def outside(inv):
"""Resources in a region that the company has not approved. Global resources have an empty region."""
return [x for x in inv["resources"] if x["region"] and x["region"] not in inv["approved_regions"]]
def untagged(inv):
return [x for x in inv["resources"] if "owner" not in x["tags"]]
if __name__ == "__main__":
inv = load(sys.argv[1] if len(sys.argv) > 1 else "account")
rows = inv["resources"]
print(f"account {inv['account']}: {len(rows)} resources")
for title, key in (("by service", "service"), ("by region", "region")):
counts = Counter(x[key] or "(global)" for x in rows)
print(title + ": " + ", ".join(f"{name} {n}" for name, n in sorted(counts.items())))
for x in outside(inv):
print(f"OUTSIDE {x['region']:15s} {x['type']:9s} {x['name']} created {x['created']}")
print(f"{len(outside(inv))} outside the approved regions, {len(untagged(inv))} with no owner tag")parse_arn is not used by the report itself: the inventory already gives the region as a field. Check that both agree, because an inventory is made by a program that can be wrong.
python3 -c "
import account_map
inv = account_map.load()
bad = [x for x in inv['resources'] if account_map.parse_arn(x['arn'])['region'] not in ('', x['region'])]
print(account_map.parse_arn(inv['resources'][0]['arn']))
print(len(bad), 'records where the ARN and the region field disagree')"{'partition': 'aws', 'service': 'ec2', 'region': 'eu-west-1', 'account': '111122223333', 'resource': 'instance/i-0a11b22c33d44e551'}
0 records where the ARN and the region field disagree4. Draw the map
python3 account_map.pyaccount 111122223333: 61 resources
by service: cloudtrail 1, ec2 33, iam 14, kms 1, lambda 2, rds 1, s3 9
by region: (global) 14, ap-southeast-2 3, eu-central-1 9, eu-west-1 35
OUTSIDE ap-southeast-2 instance i-00371135fa847ca27 created 2026-11-18
OUTSIDE ap-southeast-2 instance i-0602dadb72a889788 created 2026-11-18
OUTSIDE ap-southeast-2 instance i-0c767544ace4967f3 created 2026-11-18
3 outside the approved regions, 9 with no owner tagSome names are new. lambda runs a function with no server of your own, and kms keeps encryption keys (lesson 9). A volume is the disk of a machine, and a snapshot is a copy of a volume.
Most of the account is in eu-west-1 (Ireland), a few resources are in eu-central-1 (Frankfurt, the standby site), and 14 are global: the users and roles of IAM. Then the surprise: three machines in ap-southeast-2 (Sydney). Larkfield has no customers and no staff there. All three were created on the same day, 18 November, and none has an owner tag.
A machine in a region that nobody uses is a classic sign of a stolen key: the intruder starts machines where the owner never looks. It can also be a developer's test. A map does not tell you which. It tells you where to ask, and lesson 7 finds the answer in the audit log.
5. Find what nobody owns
A resource with no owner cannot be reviewed, patched or switched off with confidence. List the kinds of resource that have no tag.
python3 -c "
import account_map
from collections import Counter
inv = account_map.load()
print(Counter(x['type'] for x in account_map.untagged(inv)))"Counter({'volume': 4, 'instance': 3, 'user': 1, 'snapshot': 1})The three machines are the ones in Sydney. The one user is worth a note for lesson 3: a new identity that nobody claims.
Your turn
Larkfield's sister company keeps a similar account. Make its snapshot with seed 2 in the folder account2, and map it. Then answer one question that the program does not answer yet: how many virtual machines (resources of type instance) run in the approved regions? Write the few lines of Python that count them.
python3 gen_account.py 2 account2inventory.json 15422 bytes sha256 ef3799cca7f1
iam.json 7978 bytes sha256 692ceabfb857
requests.json 9022 bytes sha256 fbdca59ea057
cross.json 5855 bytes sha256 afc926974b14
ci-usage.json 627 bytes sha256 a8d360ab5cca
ci-tests.json 1672 bytes sha256 0ff9b46e501e
buckets.json 6201 bytes sha256 4432d84c25a5
network.json 4410 bytes sha256 0f43431acacd
trails.json 232 bytes sha256 9672cf20c252
events.json 243178 bytes sha256 30a06f5a284bCheck yourself
A company runs its shop on virtual machines at a cloud provider. An attacker gets in through a web server that was not patched for a year. Whose part of the shared responsibility failed?
The customer's. On a virtual machine, the provider looks after the hardware and the layer below the machine, and the customer looks after the operating system, the programs and their patches. With a managed service, more of that work moves to the provider, but the data, the identities and the configuration stay with the customer.
Is "create a bucket" a call to the control plane or to the data plane? And "download a file from that bucket"?
Creating a bucket changes a resource, so it goes to the control plane. Downloading a file is the bucket doing its work: the data plane. The difference matters for logs: by default the audit log of AWS records the first kind and not the second (lesson 7).
What does the ARN arn:aws:iam::444455556666:role/build tell you, and why is one part empty?
It is a role named build in the IAM service of account 444455556666, in the standard partition. The region is empty because IAM is a global service: a role exists once for the whole account, not once in each region.
Why do companies split their systems over several accounts and not over folders inside one account?
Because the account is the strongest wall. A mistake in a policy of the development account cannot give access to production data that lives in another account. With one account, every policy mistake can reach everything. An organisation joins the accounts again for billing and for rules that apply to all of them.
Field notes
- Keep an inventory that a program makes every day, and compare it with the day before. New resources in an unused region, new users and new public addresses are the changes to look at first. AWS Config and AWS Resource Explorer are the provider's own tools for this.
- Switch off the regions that you do not use, or deny them with a rule of the organisation (a service control policy, lesson 2). A region that nobody can use needs no monitoring.
- Enforce the
ownertag when a resource is created, not afterwards. A tag policy or a check in the deployment pipeline (lesson 10) is cheaper than a hunt for owners. - The CIS AWS Foundations Benchmark and the CSA Security Guidance are the public texts that auditors use for a cloud account. Read the current version of each at its source: both change.
- In a real case, a machine in a strange region is evidence. Do not delete it before you have a copy of what it holds (lesson 12).