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

Lesson 07 · 55 minutes

Read the audit log of an account and find the risky calls

After this lesson you can
  • Name the fields of an audit-log record and say what the log does not hold
  • Find the calls that change identity, logging, storage and network settings
  • Build the timeline of one source address and measure a gap in the log
Lab files of this lesson (12)

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

You have a list of weak points: a deploy key in a repository, a role with too many rights, three machines in Sydney, a new user that nobody owns. Your lead asks the question that matters: "Did someone use these, or are they only possible? The account has an audit trail. Read it and tell me what happened, in order, and tell me what the trail cannot show us." The audit log of the control plane is the best evidence a cloud gives you, if it was switched on and nobody switched it off.

Recall

Lesson 1: what is the difference between the control plane and the data plane?

The control plane is the API that creates, changes and deletes resources. The data plane is the resource doing its work, such as serving a file. AWS calls the calls to the first management events and the calls to the second data events.

Lesson 3: which chain let the deploy user reach administrator rights?

Its policy allowed iam:PassRole on every role and ec2:*. So it could start a machine and hand it the role ec2-maintenance, which holds an administrator policy.

The idea

AWS CloudTrail is the service that records the API calls of an account. One call gives one record, a JSON object. You read the method for logs in "Security operations basics", lessons 1 to 4: find the fields, make events, write rules, triage. This lesson gives you the fields of this one log and what is special about it.

One record of the audit log
eventTime 02:52:07Zwhen, in UTCuserIdentitywho made the calleventSourcewhich serviceeventName StopLoggingwhich API callsourceIPAddressfrom whereerrorCodeonly when it failedeventTime 02:52:07Zwhen, in UTCuserIdentitywho made the calleventSourcewhich serviceeventName StopLoggingwhich API callsourceIPAddressfrom whereerrorCodeonly when it failed
FieldRead it for
userIdentity.typeIAMUser, AssumedRole (a role session), Root, AWSService. For a role session, sessionContext.sessionIssuer names the role.
userIdentity.accessKeyIdThe key that signed the call: AKIA... for a long-lived key, ASIA... for a temporary one
eventSource, eventNameThe service and the call, for example iam.amazonaws.com and CreateAccessKey
sourceIPAddress, userAgentWhere the call came from and with which tool. The caller chooses the user agent, so it proves nothing alone.
errorCode, errorMessageA refused call, for example AccessDenied. A row of refused calls is someone testing what a key can do.
requestParameters, responseElementsWhat was asked for and what was made: the name of a new user, the ID of a new key
readOnly, eventCategoryfalse for a call that changes something. Management or Data.

A console sign-in is a record too, with the eventName ConsoleLogin. Its responseElements say Success or Failure, and additionalEventData.MFAUsed says Yes or No.

What the log holds depends on what was set up.

What you getWhat you do not get
Event history (always on)The management events of the last 90 days, per regionData events. Anything older.
A trail (you create it)Records delivered as files to an S3 bucket, kept as long as you keep the bucketData events, unless you ask for them. Other regions, unless the trail covers all regions.
Data events (extra, at a cost)Who read or wrote which objectNothing by default: reads of a public bucket leave no record in the audit log

So the audit log shows that a bucket was made public and not who downloaded from it. That needs data events or the access log of the bucket.

Two controls protect the log. Log file validation makes CloudTrail write a signed digest file every hour with the hash of each log file, so that a deleted or changed file can be proved (hashes and signatures: "Security fundamentals", lesson 5). And the bucket of the log belongs in another account, where an administrator of this one cannot delete it.

Same idea, other namesAWSMicrosoft AzureGoogle Cloud
Audit log of the control planeCloudTrail management eventsAzure Activity logCloud Audit Logs, Admin Activity
Kept without set-up90 days in the event history90 daysAdmin Activity logs are always written
Log of data accessData events, off by defaultResource logs, by diagnostic settingsData Access audit logs, off by default for most services

Worked example

1. Look at the file and one record

account/events.json has the shape of a CloudTrail log file: one object with a list named Records. A real trail delivers many small compressed files. The generator wrote five days into one file, and it simplifies one thing: every sign-in carries the region us-east-1. It also puts the records of every region into one file. The trail of Larkfield covers one region only (trails.json, lesson 13), and a real one-region trail would not hold the Sydney calls: they would be in the event history only. The field names are the real ones.

python3 -c "
import json
recs = json.load(open('account/events.json'))['Records']
print(len(recs), 'records from', min(e['eventTime'] for e in recs), 'to', max(e['eventTime'] for e in recs))
e = next(e for e in recs if e['eventName'] == 'CreateAccessKey')
print(json.dumps({k: e[k] for k in ('eventTime', 'eventSource', 'eventName', 'sourceIPAddress', 'requestParameters', 'responseElements')}, indent=1))
print(json.dumps(e['userIdentity'], indent=1))" | head -n 34
202 records from 2026-11-16T00:16:15Z to 2026-11-20T23:19:53Z
{
 "eventTime": "2026-11-18T02:50:52Z",
 "eventSource": "iam.amazonaws.com",
 "eventName": "CreateAccessKey",
 "sourceIPAddress": "203.0.113.140",
 "requestParameters": {
  "userName": "svc-monitor"
 },
 "responseElements": {
  "accessKey": {
   "userName": "svc-monitor",
   "accessKeyId": "AKIAE52JRQW3DEXAMPLE",
   "status": "Active"
  }
 }
}
{
 "type": "AssumedRole",
 "principalId": "AROAEC2MAINT77EXAMPLE:i-00371135fa847ca27",
 "arn": "arn:aws:sts::111122223333:assumed-role/ec2-maintenance/i-00371135fa847ca27",
 "accountId": "111122223333",
 "accessKeyId": "ASIAVPAG95Z7FEXAMPLE",
 "sessionContext": {
  "sessionIssuer": {
   "type": "Role",
   "principalId": "AROAEC2MAINT77EXAMPLE",
   "arn": "arn:aws:iam::111122223333:role/ec2-maintenance",
   "accountId": "111122223333",
   "userName": "ec2-maintenance"
  },
  "attributes": {
   "creationDate": "2026-11-18T02:48:35Z",
   "mfaAuthenticated": "false"

Somebody made an access key for the user svc-monitor. The caller was not a person: it was a session of the role ec2-maintenance, and the session name is the ID of a machine. A machine with that role made a key for a user.

2. Save the reader

trail.py loads the records in time order and judges each one. The table RISKY at the top of the file maps the names of sensitive calls to a severity and a reason. The function risk adds the cases that need more than a name.

def risk(e, approved_regions=()):
    """Return (severity, reason) for an event that needs a look, or None."""
    name = e["eventName"]
    if e["userIdentity"]["type"] == "Root":
        return "high", "the root user was used"
    if name == "ConsoleLogin":
        if e.get("additionalEventData", {}).get("MFAUsed") == "No" and e["responseElements"] == {"ConsoleLogin": "Success"}:
            return "medium", "console sign-in without MFA"
        return None
    if e.get("errorCode") == "AccessDenied":
        return "low", "a call was refused"
    if name in RISKY:
        severity, why = RISKY[name]
        if name == "RunInstances" and approved_regions and e["awsRegion"] not in approved_regions:
            return "high", f"new machines in {e['awsRegion']}, a region that is not approved"
        return severity, why
    return None

A sign-in counts when it succeeded without MFA. A refused call is low. New machines are low, unless the region is not on the approved list of lesson 1. The function gaps pairs each StopLogging with the next StartLogging and measures the time between them. Open the block and save the file.

The finished file: trail.py

trail.py

"""trail.py: read the audit log of a cloud account and find the calls that matter.

    python3 trail.py [folder]                       the risky calls and the gaps (default folder: account)
    python3 trail.py folder --ip ADDRESS            the timeline of one source address
    python3 trail.py folder --key ACCESS_KEY_ID     the timeline of one access key
"""
import ipaddress
import json
import sys
from collections import Counter
from datetime import datetime

# eventName: (severity, why it matters)
RISKY = {
    "StopLogging": ("critical", "the audit log was switched off"),
    "DeleteTrail": ("critical", "the audit log was deleted"),
    "UpdateTrail": ("high", "the audit log was changed"),
    "CreateUser": ("high", "a new identity"),
    "CreateAccessKey": ("high", "a new long-lived key"),
    "CreateLoginProfile": ("high", "a new console password"),
    "UpdateLoginProfile": ("high", "a console password was reset"),
    "CreatePolicyVersion": ("high", "a shared policy was rewritten"),
    "PutRolePolicy": ("high", "more rights for a role"),
    "AttachUserPolicy": ("high", "more rights for a user"),
    "AttachRolePolicy": ("high", "more rights for a role"),
    "PutUserPolicy": ("high", "more rights for a user"),
    "UpdateAssumeRolePolicy": ("high", "the trust of a role was changed"),
    "PutBucketPolicy": ("medium", "the policy of a bucket was changed"),
    "PutBucketAcl": ("high", "the ACL of a bucket was changed"),
    "DeleteBucketPublicAccessBlock": ("high", "the public-access block of a bucket was removed"),
    "PutBucketPublicAccessBlock": ("medium", "the public-access block of a bucket was changed"),
    "AuthorizeSecurityGroupIngress": ("medium", "a security group was opened"),
    "RunInstances": ("low", "new machines"),
}


def load(folder="account"):
    """The records of folder/events.json in time order. A real trail does not promise any order."""
    with open(f"{folder}/events.json") as src:
        return sorted(json.load(src)["Records"], key=lambda e: e["eventTime"])


def who(e):
    """A short name for the caller: the user name, or the word role and the name of the role."""
    ident = e["userIdentity"]
    if ident["type"] == "AssumedRole":
        return "role " + ident["arn"].split("/")[1]
    return ident.get("userName", ident["type"])


def risk(e, approved_regions=()):
    """Return (severity, reason) for an event that needs a look, or None."""
    name = e["eventName"]
    if e["userIdentity"]["type"] == "Root":
        return "high", "the root user was used"
    if name == "ConsoleLogin":
        if e.get("additionalEventData", {}).get("MFAUsed") == "No" and e["responseElements"] == {"ConsoleLogin": "Success"}:
            return "medium", "console sign-in without MFA"
        return None
    if e.get("errorCode") == "AccessDenied":
        return "low", "a call was refused"
    if name in RISKY:
        severity, why = RISKY[name]
        if name == "RunInstances" and approved_regions and e["awsRegion"] not in approved_regions:
            return "high", f"new machines in {e['awsRegion']}, a region that is not approved"
        return severity, why
    return None


def gaps(records):
    """Each time the trail was off: (stop, start, whole minutes). start is None when it was never started again."""
    out, stop = [], None
    for e in records:
        if e["eventName"] == "StopLogging" and not e.get("errorCode"):
            stop = e["eventTime"]
        elif e["eventName"] == "StartLogging" and stop:
            minutes = int((datetime.fromisoformat(e["eventTime"].replace("Z", "+00:00"))
                           - datetime.fromisoformat(stop.replace("Z", "+00:00"))).total_seconds() // 60)
            out.append((stop, e["eventTime"], minutes))
            stop = None
    return out + ([(stop, None, None)] if stop else [])


def outside(e, known_networks):
    """True when the source is an address that is not in one of the known networks."""
    try:
        address = ipaddress.ip_address(e["sourceIPAddress"])
    except ValueError:
        return False  # a service name, not an address
    return not any(address in ipaddress.ip_network(n) for n in known_networks)


def line(e):
    error = " " + e["errorCode"] if e.get("errorCode") else ""
    return f"{e['eventTime']} {e['sourceIPAddress']:15s} {who(e):20s} {e['eventName']}{error} ({e['awsRegion']})"


if __name__ == "__main__":
    folder = sys.argv[1] if len(sys.argv) > 1 else "account"
    records = load(folder)
    if len(sys.argv) > 3:
        field = {"--ip": lambda e: e["sourceIPAddress"], "--key": lambda e: e["userIdentity"].get("accessKeyId")}[sys.argv[2]]
        picked = [e for e in records if field(e) == sys.argv[3]]
        for e in picked:
            print(line(e))
        print(f"{len(picked)} events")
        sys.exit(0)
    with open(f"{folder}/inventory.json") as src:
        inv = json.load(src)
    count = Counter()
    for e in records:
        found = risk(e, inv["approved_regions"])
        if found and found[0] != "low":
            count[found[0]] += 1
            print(f"{found[0]:8s} {line(e)}  <- {found[1]}")
    for stop, start, minutes in gaps(records):
        print(f"GAP      the trail was off from {stop} to {start}: {minutes} minutes")
    refused = sum(1 for e in records if e.get("errorCode") == "AccessDenied")
    print(f"{len(records)} events, {sum(count.values())} to look at ({', '.join(f'{k} {v}' for k, v in sorted(count.items()))}), {refused} refused calls")

3. Find the calls that matter

cut -c1-118 keeps the first 118 characters of each line, so that a long line fits the page. It cuts the reason at the end of a line on purpose.

python3 trail.py | cut -c1-118
medium   2026-11-17T09:22:42Z 192.0.2.52      ben.okafor           ConsoleLogin (us-east-1)  <- console sign-in withou
medium   2026-11-17T10:22:41Z 192.0.2.53      chloe.tan            AuthorizeSecurityGroupIngress (eu-west-1)  <- a sec
high     2026-11-18T02:44:27Z 203.0.113.77    ci-deploy            RunInstances (ap-southeast-2)  <- new machines in a
high     2026-11-18T02:44:31Z 203.0.113.77    ci-deploy            RunInstances (ap-southeast-2)  <- new machines in a
high     2026-11-18T02:44:35Z 203.0.113.77    ci-deploy            RunInstances (ap-southeast-2)  <- new machines in a
high     2026-11-18T02:50:07Z 203.0.113.140   role ec2-maintenance CreateUser (us-east-1)  <- a new identity
high     2026-11-18T02:50:27Z 203.0.113.140   role ec2-maintenance AttachUserPolicy (us-east-1)  <- more rights for a 
high     2026-11-18T02:50:52Z 203.0.113.140   role ec2-maintenance CreateAccessKey (us-east-1)  <- a new long-lived ke
critical 2026-11-18T02:52:07Z 203.0.113.140   role ec2-maintenance StopLogging (eu-west-1)  <- the audit log was switc
high     2026-11-19T03:11:37Z 203.0.113.77    svc-monitor          DeleteBucketPublicAccessBlock (eu-west-1)  <- the p
high     2026-11-19T03:12:08Z 203.0.113.77    svc-monitor          PutBucketAcl (eu-west-1)  <- the ACL of a bucket wa
medium   2026-11-19T08:39:05Z 192.0.2.52      ben.okafor           ConsoleLogin (us-east-1)  <- console sign-in withou
medium   2026-11-19T14:05:12Z 192.0.2.51      alice.morgan         PutBucketPolicy (eu-west-1)  <- the policy of a buc
medium   2026-11-20T08:23:01Z 192.0.2.52      ben.okafor           ConsoleLogin (us-east-1)  <- console sign-in withou
GAP      the trail was off from 2026-11-18T02:52:07Z to 2026-11-18T08:15:30Z: 323 minutes
202 events, 14 to look at (critical 1, high 8, medium 5), 3 refused calls

Of 202 records, 14 need a look. Some are routine: Ben signs in without MFA (a finding of lesson 3, not an attack), and two changes were made by administrators from the office range 192.0.2.0/24. The night of 18 November is not routine.

4. Build the timeline of one address

The machines in Sydney were started from 203.0.113.77. Ask for everything from that address.

python3 trail.py account --ip 203.0.113.77 | cut -c1-100
2026-11-18T02:41:07Z 203.0.113.77    ci-deploy            GetCallerIdentity (us-east-1)
2026-11-18T02:41:28Z 203.0.113.77    ci-deploy            ListUsers AccessDenied (us-east-1)
2026-11-18T02:41:47Z 203.0.113.77    ci-deploy            ListAttachedUserPolicies AccessDenied (us-
2026-11-18T02:42:12Z 203.0.113.77    ci-deploy            ListBuckets (eu-west-1)
2026-11-18T02:42:47Z 203.0.113.77    ci-deploy            DescribeInstances (eu-west-1)
2026-11-18T02:43:37Z 203.0.113.77    ci-deploy            ListRoles AccessDenied (us-east-1)
2026-11-18T02:44:27Z 203.0.113.77    ci-deploy            RunInstances (ap-southeast-2)
2026-11-18T02:44:31Z 203.0.113.77    ci-deploy            RunInstances (ap-southeast-2)
2026-11-18T02:44:35Z 203.0.113.77    ci-deploy            RunInstances (ap-southeast-2)
2026-11-18T09:29:30Z 203.0.113.77    svc-monitor          GetCallerIdentity (us-east-1)
2026-11-19T03:10:02Z 203.0.113.77    svc-monitor          ListBuckets (eu-west-1)
2026-11-19T03:11:37Z 203.0.113.77    svc-monitor          DeleteBucketPublicAccessBlock (eu-west-1)
2026-11-19T03:12:08Z 203.0.113.77    svc-monitor          PutBucketAcl (eu-west-1)
13 events
The night of 18 November, in UTC
02:41the key of ci-deploy is used from 203.0.113.7702:41 to 02:43three calls to IAM are refused: it tests what the key can do02:44three machines start in ap-southeast-2, one with a stronger role02:50from a machine: a new user svc-monitor, an admin policy, a key02:52from a machine: StopLogging. The trail is off08:15an administrator starts the trail again02:41the key of ci-deploy is used from203.0.113.7702:41 to 02:43three calls to IAM are refused: it testswhat the key can do02:44three machines start in ap-southeast-2, onewith a stronger role02:50from a machine: a new user svc-monitor, anadmin policy, a key02:52from a machine: StopLogging. The trail isoff08:15an administrator starts the trail again

This is the escalation path of lesson 3, used. The key from the repository of lesson 4 could not create a user, so it started machines with a stronger role, and the role did the rest. The last three lines of the output are the new user at work a day later (its first call, GetCallerIdentity, is the line before them), on the bucket larkfield-uploads: that is how the ACL of lesson 5 became public.

5. Measure the gap

python3 trail.py | grep GAP
python3 -c "
import trail
recs = trail.load()
print(sum(1 for e in recs if '2026-11-18T02:52:07Z' < e['eventTime'] < '2026-11-18T08:15:30Z'), 'records inside the gap')"
GAP      the trail was off from 2026-11-18T02:52:07Z to 2026-11-18T08:15:30Z: 323 minutes
0 records inside the gap

For more than five hours the trail delivered nothing. An honest report says so: "we do not know what was done between 02:52 and 08:15 from this file". The event history of the provider still holds the management events of that time, because StopLogging stops a trail and not the event history. In a real case you would read it there before the 90 days end.

Your turn

The sister company had the same kind of night. Its snapshot is in account2 (you made it in lesson 1). Run the reader, find the address that the company does not know, build its timeline, and read the records themselves where the program does not print what you need. The office range of the company is 192.0.2.0/24.

Check yourself

A bucket was public for two days. Can the management events tell you which objects were downloaded?

No. Downloads are data events, and a trail does not record them unless they were switched on for that bucket before the incident. The management events show when the bucket became public and who did it. For the downloads you need data events or the server access log of the bucket, and if neither existed, the honest answer is "unknown, assume all".

The userIdentity of a record has the type AssumedRole and an ARN that ends in ec2-maintenance/i-00371135fa847ca27. Who made the call?

A session of the role ec2-maintenance. The last part is the session name, and for a role that a machine uses, it is the ID of the machine. So a program on that machine made the call with the temporary credentials of the role.

Why is the userAgent field weak evidence?

The caller sets it. An intruder can send the text of a browser or of the official command-line tool. Use it to group events and to spot a change, and build the case on the fields that the service sets: the time, the identity, the access key and the source address.

An intruder with administrator rights calls StopLogging. Which two controls limit the damage?

An alert on the call itself, so that someone knows within minutes, and a log bucket in another account with log file validation, so that the records before the stop cannot be deleted or changed. A service control policy that denies cloudtrail:StopLogging for everyone but one role stops the call in the first place.

Field notes

  • Use one trail for all regions, for the whole organisation, delivered to a bucket in a separate logging account. A trail for one region misses the region that the intruder chooses.
  • Alert on a short list first: StopLogging, DeleteTrail, any use of the root user, ConsoleLogin without MFA, CreateAccessKey, CreateUser, AttachUserPolicy, and changes to Block Public Access. Amazon GuardDuty is the provider's detection service on top of these logs.
  • Write these as detection rules in the format of your log system. "Security operations basics" teaches rules as data in lessons 3, 7 and 8, and Sigma has a logsource for this log.
  • Always join AssumedRole records to the AssumeRole or RunInstances event that started the session. The session is who acted, and the earlier event is who is responsible.
  • MITRE ATT&CK has a matrix for cloud platforms. Its technique names for what you saw here include Valid Accounts and Impair Defenses. Take the current names and numbers from the ATT&CK site.