Audit Trails, Threat Detection and Guardrails
Generate CloudTrail-format audit records with five suspicious actions and benign activity, write detections that flag each attack while staying quiet on normal events, learn the commands that enable an organisation trail and managed threat detection, then add a Service Control Policy guardrail evaluated locally, and an EventBridge rule pattern tested against a matching and a non-matching event.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Generate the audit records
- Step 2: Write the detections
- Step 3: Test the benign case
- Organisation trail and managed threat detection
- Step 4: A guardrail that prevents the action
- Step 5: An alert rule for the highest-risk action
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Cloud Security
- Shared Responsibility and the Cloud Control Plane Concept · 15 min
- Cloud IAM: Policies, Roles and Escalation Paths Worked example · 25 min
- Posture Scanning and Fixing Misconfigurations in IaC Lab · 30 min
- Audit Trails, Threat Detection and Guardrails Lab · 25 min
- Securing the SaaS Tenants Everyone Forgets Worked example · 20 min
- Cloud Security Check Knowledge check · 10 questions
What you will learn
- Enable organisation-wide audit logging, managed threat detection and preventive guardrails, and alert on a high-risk control-plane action.
Prerequisites: Cloud Basics
01. Goal and setup
Every control-plane call in an AWS account can be recorded in an audit log. AWS calls its service CloudTrail, and each record is a JSON object with fields such as eventName, eventSource, userIdentity and sourceIPAddress. Azure has Activity logs and Microsoft Entra audit logs; Google Cloud has Cloud Audit Logs. The log is only useful if someone reads it for signs of an attacker, if the attacker cannot quietly switch it off, and if the riskiest actions raise an alert in minutes rather than being found weeks later.
In this lab you generate CloudTrail-format records that hide five suspicious actions among benign activity, write detections for each, and confirm they stay quiet on the benign events. Then you add four controls: an organisation-wide trail and managed threat detection (their commands need a real AWS organisation, so they are shown from the AWS documentation), and a guardrail policy and an alert rule pattern that you test locally. You need only Python 3.12. The records are synthetic, with the field names of the CloudTrail record reference. Work in a folder called trail-lab; the first command creates it.
02. Step 1: Generate the audit records
Save the generator as make_events.py and run it. It writes nine records in JSON Lines format (one JSON object per line). Four are benign: a user reading resources, a GetObject, an MFA sign-in, and a user creating an access key for herself. Five are suspicious and all come from one user, mallory, an administrator in a member account, from one address late at night.
"""Writes events.jsonl: CloudTrail-format records with a fixed set of actions."""
import json
ACCT = "111122223333"
def rec(t, src, name, user, ip, extra=None, error=None, mfa=None):
identity = {"type": "IAMUser", "arn": f"arn:aws:iam::{ACCT}:user/{user}",
"accountId": ACCT, "userName": user}
r = {"eventTime": t, "eventSource": src, "eventName": name,
"awsRegion": "eu-west-1", "sourceIPAddress": ip, "userIdentity": identity,
"recipientAccountId": ACCT,
"readOnly": name.startswith(("Describe", "List", "Get"))}
if mfa is not None: # ConsoleLogin records MFA use here
r["additionalEventData"] = {"MFAUsed": "Yes" if mfa else "No"}
if extra:
r["requestParameters"] = extra
if error:
r["errorCode"] = error
return r
EVENTS = [
# benign activity, must not alert
rec("2026-11-15T08:01:00Z", "ec2.amazonaws.com", "DescribeInstances", "ana",
"198.51.100.10"),
rec("2026-11-15T08:05:00Z", "s3.amazonaws.com", "GetObject", "ana",
"198.51.100.10"),
rec("2026-11-15T08:12:00Z", "signin.amazonaws.com", "ConsoleLogin", "ana",
"198.51.100.10", extra=None, error=None, mfa=True),
rec("2026-11-15T09:30:00Z", "iam.amazonaws.com", "CreateAccessKey", "ana",
"198.51.100.10", extra={"userName": "ana"}), # own key: benign
# 1. logging turned off
rec("2026-11-15T23:02:00Z", "cloudtrail.amazonaws.com", "StopLogging", "mallory",
"203.0.113.9", extra={"name": "acct-trail"}),
# 2. trail deleted
rec("2026-11-15T23:03:30Z", "cloudtrail.amazonaws.com", "DeleteTrail", "mallory",
"203.0.113.9", extra={"name": "acct-trail"}),
# 3. bucket made public
rec("2026-11-15T23:10:00Z", "s3.amazonaws.com", "PutBucketPolicy", "mallory",
"203.0.113.9", extra={"bucketName": "shop-exports",
"bucketPolicy": {"Statement": [{"Effect": "Allow",
"Principal": "*", "Action": "s3:GetObject"}]}}),
# 4. console login without MFA
rec("2026-11-15T23:15:00Z", "signin.amazonaws.com", "ConsoleLogin", "mallory",
"203.0.113.9", mfa=False),
# 5. access key created for another user
rec("2026-11-15T23:20:00Z", "iam.amazonaws.com", "CreateAccessKey", "mallory",
"203.0.113.9", extra={"userName": "ana"}),
]
with open("events.jsonl", "w") as fh:
fh.writelines(json.dumps(e) + "\n" for e in EVENTS)
print(len(EVENTS), "events written to events.jsonl")mkdir -p trail-lab && cd trail-lab # save make_events.py here
python3 make_events.py9 events written to events.jsonlOne record looks like the following. The eventName is the API action, eventSource is the service, userIdentity says who called, and a console sign-in records whether MFA was used under additionalEventData.MFAUsed.
{
"eventTime": "2026-11-15T23:02:00Z",
"eventSource": "cloudtrail.amazonaws.com",
"eventName": "StopLogging",
"awsRegion": "eu-west-1",
"sourceIPAddress": "203.0.113.9",
"userIdentity": {
"type": "IAMUser",
"arn": "arn:aws:iam::111122223333:user/mallory",
"accountId": "111122223333",
"userName": "mallory"
},
"recipientAccountId": "111122223333",
"readOnly": false,
"requestParameters": {
"name": "acct-trail"
}
}03. Step 2: Write the detections
The five suspicious actions are: turning off the trail (StopLogging), deleting the trail (DeleteTrail), a PutBucketPolicy that makes a bucket readable by everyone, a console sign-in without MFA, and creating an access key for another user. Each is a recognised step in cloud intrusions. detect.py has one rule per pattern.
"""Detections over CloudTrail-format events. Each rule prints the records it flags."""
import json
def load(path):
return [json.loads(line) for line in open(path)]
def user_of(e):
return e["userIdentity"].get("userName", "?")
def mfa_used(e):
return e.get("additionalEventData", {}).get("MFAUsed") == "Yes"
def principal_is_public(policy):
for stmt in policy.get("Statement", []):
principal = stmt.get("Principal")
if stmt.get("Effect") == "Allow" and principal in ("*", {"AWS": "*"}):
return True
return False
def detect(events):
alerts = []
for e in events:
name, src = e["eventName"], e["eventSource"]
user, ip = user_of(e), e["sourceIPAddress"]
if src == "cloudtrail.amazonaws.com" and name in ("StopLogging", "DeleteTrail"):
alerts.append(("logging-tampered", user, ip,
f"{name} on {e['requestParameters'].get('name')}"))
elif name == "PutBucketPolicy":
policy = e.get("requestParameters", {}).get("bucketPolicy", {})
if principal_is_public(policy):
bucket = e["requestParameters"].get("bucketName")
alerts.append(("bucket-made-public", user, ip, f"bucket {bucket}"))
elif name == "ConsoleLogin" and not mfa_used(e):
alerts.append(("login-without-mfa", user, ip, "console sign-in, no MFA"))
elif name == "CreateAccessKey":
target = e.get("requestParameters", {}).get("userName")
if target and target != user:
alerts.append(("key-for-other-user", user, ip,
f"created a key for {target}"))
return alerts
if __name__ == "__main__":
events = load("events.jsonl")
alerts = detect(events)
for rule, user, ip, detail in alerts:
print(f"ALERT {rule:20} {user:9} {ip:14} {detail}")
print(f"benign events: {len(events) - len(alerts)}; alerts: {len(alerts)}")python3 detect.pyALERT logging-tampered mallory 203.0.113.9 StopLogging on acct-trail
ALERT logging-tampered mallory 203.0.113.9 DeleteTrail on acct-trail
ALERT bucket-made-public mallory 203.0.113.9 bucket shop-exports
ALERT login-without-mfa mallory 203.0.113.9 console sign-in, no MFA
ALERT key-for-other-user mallory 203.0.113.9 created a key for ana
benign events: 4; alerts: 5Two rules need care to avoid false positives. The bucket rule does not fire on every PutBucketPolicy; it reads the policy and fires only when a statement allows "Principal": "*", because setting a private policy is normal. The access-key rule fires only when the target user differs from the caller: creating your own key is routine, creating a key for someone else is a way to take over their identity, so ana's own key is left alone.
04. Step 3: Test the benign case
A detection that alerts on everything is worthless, so the test asserts that exactly the five attacks fire and that nothing by ana is flagged. It fails if a benign event ever triggers a rule.
"""Negative tests: benign events must not alert, and only the five attacks must."""
from detect import detect, load
events = load("events.jsonl")
alerts = detect(events)
rules = sorted(a[0] for a in alerts)
expected = sorted(["logging-tampered", "logging-tampered", "bucket-made-public",
"login-without-mfa", "key-for-other-user"])
assert rules == expected, f"unexpected alerts: {rules}"
# ana's own CreateAccessKey and her MFA login must not be flagged.
assert all(a[1] != "ana" for a in alerts), "a benign event by ana was flagged"
print("ok: 5 expected alerts, no benign event flagged")python3 test_detect.pyok: 5 expected alerts, no benign event flagged05. Organisation trail and managed threat detection
Detections are only as good as the log they read. Two organisation-wide settings protect the log itself.
First, an organisation trail: one trail, created in the management account (or a CloudTrail delegated administrator account), that logs every member account into a separate log-archive bucket. A forgotten new account is covered automatically, and member accounts cannot stop, change or delete it. That is why mallory's StopLogging on her account's own acct-trail still reached you: the organisation trail recorded it.
Second, managed threat detection: Amazon GuardDuty (or Microsoft Defender for Cloud, or Google Security Command Center). They read the audit and network logs and raise findings with named types. For example, GuardDuty raises Stealth:IAMUser/CloudTrailLoggingDisabled when a trail is disabled, which is exactly the StopLogging event your first rule caught, and Policy:S3/BucketAnonymousAccessGranted when a bucket is opened to everyone. Managed detection is broad and needs no rules from you, but you still write detections for patterns specific to your account.
Enabling both needs an AWS Organizations management account, so this lab cannot run the commands below; they follow the CloudTrail and GuardDuty guides. The log-archive bucket must already exist with the bucket policy from the CloudTrail guide. GuardDuty is regional: repeat steps 3 and 4 in each Region you use. In the console, the same options are "Enable for all accounts in my organization" when you create a trail, and GuardDuty Settings, Delegated administrator.
# 1. Management account: let CloudTrail work across the organisation.
aws organizations enable-aws-service-access \
--service-principal cloudtrail.amazonaws.com
# 2. Create a multi-Region organisation trail into the log-archive bucket.
aws cloudtrail create-trail --name org-trail --s3-bucket-name shop-log-archive \
--is-organization-trail --is-multi-region-trail --enable-log-file-validation
aws cloudtrail start-logging --name org-trail
# 3. Management account: make the security account GuardDuty administrator.
aws guardduty enable-organization-admin-account --admin-account-id 444455556666
# 4. Security account, same Region: enable GuardDuty in every member account.
aws guardduty list-detectors
aws guardduty update-organization-configuration --detector-id DETECTOR_ID \
--auto-enable-organization-members=ALL{
"IncludeGlobalServiceEvents": true,
"Name": "org-trail",
"TrailARN": "arn:aws:cloudtrail:eu-west-1:111122223333:trail/org-trail",
"LogFileValidationEnabled": true,
"IsMultiRegionTrail": true,
"IsOrganizationTrail": true,
"S3BucketName": "shop-log-archive"
}Check that IsOrganizationTrail and IsMultiRegionTrail are both true, and run start-logging, because a new trail does not log until you do. Log file validation lets you prove later that no log file was changed. With ALL, GuardDuty is enabled in existing member accounts as well as new ones.
06. Step 4: A guardrail that prevents the action
Detection tells you after the fact. A guardrail stops the action from succeeding at all. In AWS Organizations, a Service Control Policy (SCP) sets the maximum permissions for IAM users and roles, root users included, in the member accounts it is attached to. It never grants permissions; an SCP can be an allow list of permitted services or, as here, a list of denies. It does not affect the management account or service-linked roles, so keep workloads and people out of the management account. Save the guardrail below as scp.json. Its first statement denies cloudtrail:StopLogging, DeleteTrail and UpdateTrail to everyone except a named break-glass role (an emergency role for when normal access fails); its second denies any action outside two EU regions, with an exemption for global services such as IAM. The aws:RequestedRegion key carries the region of the request.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyTrailTampering",
"Effect": "Deny",
"Action": ["cloudtrail:StopLogging", "cloudtrail:DeleteTrail",
"cloudtrail:UpdateTrail"],
"Resource": "*",
"Condition": {
"ArnNotLike": {
"aws:PrincipalArn": "arn:aws:iam::*:role/OrgSecurityAdmin"
}
}
},
{
"Sid": "DenyOutsideEU",
"Effect": "Deny",
"NotAction": ["iam:*", "sts:*", "cloudfront:*", "route53:*", "support:*",
"organizations:*"],
"Resource": "*",
"Condition": {
"StringNotEquals": {
"aws:RequestedRegion": ["eu-west-1", "eu-central-1"]
}
}
}
]
}You can evaluate the guardrail locally, the same idea as the IAM evaluator in the IAM lesson but only for Deny statements. scp_check.py tests that a denied action is blocked and an allowed action passes, including the exemptions.
"""Evaluates whether the Deny statements of an SCP guardrail block a request."""
import fnmatch
import json
import sys
def as_list(v):
return v if isinstance(v, list) else [v]
def act_match(stmt, action):
low = action.lower()
if "Action" in stmt:
pats = as_list(stmt["Action"])
return any(fnmatch.fnmatchcase(low, p.lower()) for p in pats)
pats = as_list(stmt["NotAction"])
return not any(fnmatch.fnmatchcase(low, p.lower()) for p in pats)
def cond_triggers_deny(cond, ctx):
for op, keys in cond.items():
for key, vals in keys.items():
have = ctx.get(key, "")
vals = as_list(vals)
if op == "StringNotEquals":
ok = have not in vals
elif op == "ArnNotLike":
ok = not any(fnmatch.fnmatchcase(have, v) for v in vals)
elif op == "StringEquals":
ok = have in vals
else:
raise ValueError(f"operator {op} not modelled")
if not ok:
return False # a condition failed, so this Deny does not apply
return True
def denied(scp, action, ctx):
for stmt in scp["Statement"]:
if stmt["Effect"] != "Deny" or not act_match(stmt, action):
continue
if cond_triggers_deny(stmt.get("Condition", {}), ctx):
return stmt["Sid"]
return None
if __name__ == "__main__":
scp = json.load(open("scp.json"))
ADMIN = "arn:aws:iam::111122223333:role/OrgSecurityAdmin"
DEV = "arn:aws:iam::111122223333:role/Developer"
CASES = [
("cloudtrail:StopLogging", {"aws:PrincipalArn": DEV,
"aws:RequestedRegion": "eu-west-1"}, "StopLogging by a developer"),
("cloudtrail:StopLogging", {"aws:PrincipalArn": ADMIN,
"aws:RequestedRegion": "eu-west-1"}, "StopLogging by the security admin"),
("ec2:RunInstances", {"aws:PrincipalArn": DEV,
"aws:RequestedRegion": "us-east-1"}, "launch a VM in us-east-1"),
("ec2:RunInstances", {"aws:PrincipalArn": DEV,
"aws:RequestedRegion": "eu-west-1"}, "launch a VM in eu-west-1"),
("iam:CreateUser", {"aws:PrincipalArn": DEV,
"aws:RequestedRegion": "us-east-1"}, "create an IAM user (global)"),
]
for action, ctx, label in CASES:
sid = denied(scp, action, ctx)
verdict = f"DENIED by {sid}" if sid else "allowed by the guardrail"
print(f"{verdict:24} {label}")python3 scp_check.pyDENIED by DenyTrailTampering StopLogging by a developer
allowed by the guardrail StopLogging by the security admin
DENIED by DenyOutsideEU launch a VM in us-east-1
allowed by the guardrail launch a VM in eu-west-1
allowed by the guardrail create an IAM user (global)The developer is denied StopLogging and denied a VM launch in us-east-1, but the break-glass role may stop logging and anyone may launch a VM in eu-west-1. The IAM call is allowed because the region restriction exempts global services, whose requests always go to one region. A guardrail written without that exemption would break IAM across the whole organisation. The NotAction list here is shortened for the lab: AWS's example SCP "Deny access to AWS based on the requested AWS Region" also exempts services such as budgets, ce, globalaccelerator, health, kms and waf, and a real version should exempt the break-glass role too.
07. Step 5: An alert rule for the highest-risk action
The few actions that must page someone at once, such as logging being turned off, go to an alert. On AWS this is an EventBridge rule: an event pattern that, when it matches a delivered event, triggers a target such as a notification. A pattern lists only the fields that must match; any field it does not name is ignored, and a list of values means "any of these". EventBridge receives these events only while a trail is logging, and a rule in the default ENABLED state matches write events only; read-only events such as DescribeTrails need the state ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS. Save the pattern below as eventpattern.json; it matches StopLogging and DeleteTrail calls.
{
"source": ["aws.cloudtrail"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventSource": ["cloudtrail.amazonaws.com"],
"eventName": ["StopLogging", "DeleteTrail"]
}
}match.py is a small matcher for the subset of pattern rules used here, so you can test the pattern without any cloud service. It checks a matching event (a StopLogging call, which should alert) and a non-matching one (a read-only DescribeTrails, which should not).
"""A small matcher for the subset of EventBridge pattern rules this lesson uses."""
import json
def matches(pattern, event):
for key, want in pattern.items():
if key not in event:
return False # every field named in the pattern must be present
have = event[key]
if isinstance(want, dict):
if not isinstance(have, dict) or not matches(want, have):
return False
elif isinstance(want, list):
if have not in want: # a list of values is a logical OR
return False
return True # fields not named in the pattern are ignored
MATCH = {"source": "aws.cloudtrail", "detail-type": "AWS API Call via CloudTrail",
"region": "eu-west-1",
"detail": {"eventSource": "cloudtrail.amazonaws.com",
"eventName": "StopLogging",
"userIdentity": {"userName": "mallory"}}}
NON_MATCH = {"source": "aws.cloudtrail", "detail-type": "AWS API Call via CloudTrail",
"detail": {"eventSource": "cloudtrail.amazonaws.com",
"eventName": "DescribeTrails"}}
if __name__ == "__main__":
pattern = json.load(open("eventpattern.json"))
print("StopLogging event ->", matches(pattern, MATCH))
print("DescribeTrails event ->", matches(pattern, NON_MATCH))
assert matches(pattern, MATCH) and not matches(pattern, NON_MATCH)
print("ok: high-risk action matches, read-only action does not")python3 match.pyStopLogging event -> True
DescribeTrails event -> False
ok: high-risk action matches, read-only action does notThe matching event alerts and the read-only event does not: paging on DescribeTrails would train people to ignore the alert. Together these controls form a layered design. The guardrail prevents the action, the organisation trail and GuardDuty record and detect it, and the EventBridge rule turns the highest-risk event into an immediate alert.
08. Troubleshooting
09. Check your understanding
10. Apply it
For the skill project, extend this into an alerting pipeline:
- Add one more suspicious action (for example
AuthorizeSecurityGroupIngressopening0.0.0.0/0), a detection for it and a benign near-miss that must not alert. - Add it to the EventBridge pattern and show the matcher firing on it but not on the near-miss.
- Extend the SCP to deny disabling GuardDuty, and test that the break-glass role is still exempt.
- Write a runbook entry per alert: the fields that identify it, the overlapping GuardDuty finding type and the first containment step.
11. Review prompt
Without looking back, explain: which CloudTrail fields a detection reads to identify an action and its caller; why the bucket and access-key rules need a guard to avoid false positives; how you enable an organisation trail and GuardDuty for every account, and what the organisation trail protects; which accounts and roles an SCP does not affect; why an SCP guardrail prevents an action that a detection only reports; and why an EventBridge alert pattern should list only the highest-risk actions.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.