It was in the log for six weeks
At three in the morning, an intern's key switched off block public access on a bucket. The audit log recorded it within minutes.
Nobody noticed for six weeks, because nobody read the log and nothing read it for them.
The one rule
Warning
Everything in this module happens in the practice cloud of your own lab. Reading another account's logs or using its keys needs the owner's written permission. In the UK, without it, it can break the Computer Misuse Act 1990.
Quick check: the rule
Have a go
Quick check: the rule
3 questionsBy the end of this lesson
Note
I can write alert rules over a cloud audit log.
Key words
| Word | What it means | Example |
|---|---|---|
| Audit log | a record of who did what, and when | |
| CloudTrail | the AWS service that records API calls | |
| Event | one recorded API call | |
| Management event | a call that changes settings | |
| Data event | a call that reads or writes data | GetObject |
| Alert | a message sent to a person when a rule matches |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsEvery call leaves a record
CloudTrail writes one event for each API call in an account. It says who called, what, when, from which address and whether it failed.
Management events, such as changing a bucket policy, are recorded by default. Data events, such as reading an object, are recorded only if you turn them on, and they cost more.
The fields you alert on
| Field | What it says | Example |
|---|---|---|
| eventName | Which call | DeletePublicAccessBlock |
| userIdentity | Who, and what kind of identity | type Root, or a key id |
| eventTime | When, in UTC | 2026-11-22T03:04:05Z |
| sourceIPAddress | From where | 203.0.113.7 |
| errorCode | Why it failed, if it did | AccessDenied |
The cells students fill in are left blank in this preview.
Try it: read one event
import json
line = '{"eventName": "DeleteBucketPolicy", "userIdentity": {"type": "IAMUser", "userName": "sam"}, "sourceIPAddress": "203.0.113.7"}'
record = json.loads(line)
print(record["userIdentity"]["userName"], "did", record["eventName"])
print("from", record["sourceIPAddress"])
print("identity type:", record["userIdentity"]["type"])
# Change the type to "Root". Should that worry you?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsA recorder in front of your stack
The lab runs S3, SQS and DynamoDB only, so there is no CloudTrail to switch on. trail.py stands in for it. It runs one aws command through a small recorder that passes each request to your stack.
For every request it writes one line in CloudTrail's shape to trail.jsonl. The key name intern stands for a second person.
Point the aws command at your stack
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 AWS_ENDPOINT_URL=http://cloud:4566Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the recorder, part 1
mkdir -p ~/cs && printf '%s\n' 'import datetime' 'import json' 'import os' 'import subprocess' 'import sys' 'import threading' 'import urllib.error' 'import urllib.parse' 'import urllib.request' 'from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer' '' 'S3 = {"PUT policy": "PutBucketPolicy", "GET policy": "GetBucketPolicy", "DELETE policy": "DeleteBucketPolicy",' ' "PUT publicAccessBlock": "PutPublicAccessBlock", "DELETE publicAccessBlock": "DeletePublicAccessBlock",' ' "GET publicAccessBlock": "GetPublicAccessBlock", "PUT encryption": "PutBucketEncryption",' ' "PUT versioning": "PutBucketVersioning", "PUT bucket": "CreateBucket", "GET bucket": "ListObjects",' ' "DELETE bucket": "DeleteBucket", "PUT object": "PutObject", "GET object": "GetObject",' ' "DELETE object": "DeleteObject", "HEAD object": "HeadObject", "HEAD bucket": "HeadBucket",' ' "GET list": "ListBuckets"}' 'SOURCES = {"DynamoDB": "dynamodb", "AmazonSQS": "sqs"}' > ~/cs/trail.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the recorder, part 2
printf '%s\n' '' '' 'def event_name(method, path, query, target):' ' if target:' ' return target.split(".")[-1]' ' parts = [p for p in path.split("/") if p]' ' sub = next((key for key in urllib.parse.parse_qs(query, keep_blank_values=True)), "")' ' what = sub if sub in ["policy", "publicAccessBlock", "encryption", "versioning"] else ["list", "bucket", "object"][min(len(parts), 2)]' ' return S3.get(method + " " + what, method + " " + what)' '' '' 'class Recorder(BaseHTTPRequestHandler):' ' def log_message(self, *args):' ' pass' '' ' def relay(self):' ' body = self.rfile.read(int(self.headers.get("Content-Length", 0)))' ' ask = urllib.request.Request("http://cloud:4566" + self.path, data=body or None, method=self.command)' ' for key, value in self.headers.items():' ' if not key.lower() in ["host", "content-length"]:' ' ask.add_header(key, value)' ' try:' >> ~/cs/trail.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the recorder, part 3
printf '%s\n' ' reply = urllib.request.urlopen(ask)' ' code, data = reply.status, reply.read()' ' except urllib.error.HTTPError as error:' ' code, data = error.code, error.read()' ' url = urllib.parse.urlparse(self.path)' ' target = self.headers.get("X-Amz-Target", "")' ' key = self.headers.get("Authorization", "Credential=unknown/").split("Credential=")[1].split("/")[0]' ' record = {"eventTime": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),' ' "eventSource": SOURCES.get(target.split("_")[0].split(".")[0], "s3") + ".amazonaws.com",' ' "eventName": event_name(self.command, url.path, url.query, target),' ' "userIdentity": {"accessKeyId": key}, "sourceIPAddress": self.client_address[0],' ' "requestParameters": {"path": url.path}}' ' if code >= 400:' ' text = data.decode(errors="replace")' >> ~/cs/trail.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the recorder, part 4
printf '%s\n' ' record["errorCode"] = text.split("<Code>")[1].split("</Code>")[0] if "<Code>" in text else str(code)' ' with open("trail.jsonl", "a") as log:' ' print(json.dumps(record), file=log)' ' self.send_response(code)' ' self.send_header("Content-Length", str(len(data)))' ' self.end_headers()' ' self.wfile.write(data)' '' ' do_GET = do_PUT = do_POST = do_DELETE = do_HEAD = relay' '' '' 'server = ThreadingHTTPServer(("127.0.0.1", 4567), Recorder)' 'threading.Thread(target=server.serve_forever, daemon=True).start()' 'env = dict(os.environ, AWS_ENDPOINT_URL="http://127.0.0.1:4567")' 'done = subprocess.run(["aws", *sys.argv[1:]], env=env)' 'server.shutdown()' 'sys.exit(done.returncode)' >> ~/cs/trail.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Record your own work on a bucket
cd ~/cs && rm -f trail.jsonl && python3 trail.py s3 mb s3://shop-logs && python3 trail.py s3api put-public-access-block --bucket shop-logs --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=trueShown here, not run. Press Start lab to type it into your own lab’s terminal.
Record the intern's night
cd ~/cs && for n in 1 2 3; do AWS_ACCESS_KEY_ID=intern python3 trail.py s3api get-bucket-policy --bucket shop-payroll; done; AWS_ACCESS_KEY_ID=intern python3 trail.py s3api delete-public-access-block --bucket shop-logsShown here, not run. Press Start lab to type it into your own lab’s terminal.
Read the last record
tail -n 1 ~/cs/trail.jsonlShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the alert rules, part 1
mkdir -p ~/cs && printf '%s\n' 'import json' 'import sys' '' 'WATCH = {"PutBucketPolicy": "who can reach a bucket changed",' ' "DeleteBucketPolicy": "a bucket lost its policy",' ' "DeletePublicAccessBlock": "block public access was removed",' ' "StopLogging": "the trail was stopped",' ' "DeleteTrail": "the trail was deleted"}' 'known = sys.argv[2].split(",")' 'failures = {}' 'seen = set()' 'records = [json.loads(line) for line in open(sys.argv[1])]' 'for record in records:' ' who = record["userIdentity"].get("accessKeyId", "?")' ' name = record["eventName"]' ' if name in WATCH:' ' print("ALERT", who, name, ":", WATCH[name])' ' if who not in known and who not in seen:' ' print("ALERT", who, name, ": a key nobody listed")' ' seen.add(who)' ' if "errorCode" in record:' ' failures[who] = failures.get(who, 0) + 1' 'for who, count in failures.items():' ' if count >= 3:' > ~/cs/alerts.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the alert rules, part 2
printf '%s\n' ' print("ALERT", who, ":", count, "failed calls")' 'print(len(records), "records read")' >> ~/cs/alerts.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Run the rules, knowing only your key
cd ~/cs && python3 alerts.py trail.jsonl testShown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think turning logging on is enough. A log nobody reads catches nothing. Write each question down as a rule, run the rules all the time and send every match to a person.
Check
Have a go
Check
3 questionsUndo the change, keep the record
Put the block back, through the recorder so the fix is recorded too. The log is history, so the alerts about the intern stay true. Next, a person asks the intern why, and the key is taken away until there is an answer.
Put block public access back, recorded
cd ~/cs && python3 trail.py s3api put-public-access-block --bucket shop-logs --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true && tail -n 1 trail.jsonlShown here, not run. Press Start lab to type it into your own lab’s terminal.
A trail worth having
On AWS, record every region in one trail and deliver it to a bucket in a separate log account, with log file validation on. Alert when logging stops.
Common rules alert on the root account being used, a console sign-in without MFA, and changes to policies, trails and block public access.
Assignment: alert rules for a trail
Write alert rules over CloudTrail records, given as dictionaries.
is_root(record) is True when userIdentity has type "Root". no_mfa_sign_in(record) is True for a ConsoleLogin whose additionalEventData has MFAUsed "No". alerts(records) gives one line per finding in record order ("root <event>", "no-mfa <user>", "watch <event>" for a name in WATCH), then "failures <key>" for each key with three or more errors.
WATCH = ["PutBucketPolicy", "DeleteBucketPolicy", "DeletePublicAccessBlock",
"StopLogging", "DeleteTrail"]
def is_root(record):
# True when userIdentity has type "Root".
return False
def no_mfa_sign_in(record):
# True for a ConsoleLogin whose additionalEventData has MFAUsed "No".
return False
def alerts(records):
# One line per finding, in record order: "root <event>", "no-mfa <user>",
# "watch <event>", then "failures <key>" for each key with 3 or more errorCode.
return []
Make a free account to save your work and track your progress.
Exit quiz
Have a go