Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Cloud audit logs and what to alert on

After this lesson: I can write alert rules over a cloud audit log.

65 min lesson12 commandsCloud lab: practise S3 buckets, SQS queues and DynamoDB tables with the AWS command line

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can write alert rules over a cloud audit log.

Key words

WordWhat it meansExample
Audit loga record of who did what, and when
CloudTrailthe AWS service that records API calls
Eventone recorded API call
Management eventa call that changes settings
Data eventa call that reads or writes dataGetObject
Alerta 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Every 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

FieldWhat it saysExample
eventNameWhich callDeletePublicAccessBlock
userIdentityWho, and what kind of identitytype Root, or a key id
eventTimeWhen, in UTC2026-11-22T03:04:05Z
sourceIPAddressFrom where203.0.113.7
errorCodeWhy it failed, if it didAccessDenied

The cells students fill in are left blank in this preview.

Try it: read one event

Code: python
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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A 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

Command
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 AWS_ENDPOINT_URL=http://cloud:4566

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the recorder, part 1

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the recorder, part 2

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the recorder, part 3

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the recorder, part 4

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Record your own work on a bucket

Command
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=true

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Record the intern's night

Command
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-logs

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Read the last record

Command
tail -n 1 ~/cs/trail.jsonl

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the alert rules, part 1

Command
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.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the alert rules, part 2

Command
printf '%s\n' '        print("ALERT", who, ":", count, "failed calls")' 'print(len(records), "records read")' >> ~/cs/alerts.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Run the rules, knowing only your key

Command
cd ~/cs && python3 alerts.py trail.jsonl test

Shown 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Undo 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

Command
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.jsonl

Shown 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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.