AWS from zero · Part 6: Operating, securing and governing · Lesson 33 of 38 · about 50 minutes

CloudTrail: who did what

Someone opened SSH on Juniper & Rye's network to the whole internet and closed it five seconds later, and someone tried a refused action. Event history found all of it in two minutes, for free. Then a trail kept its own files in S3, and a real puzzle: across eight runs, the trail recorded our reads but never our writes, and how to check a trail that's quietly recording less than you think.

By the end you'll know

  • What CloudTrail records on its own, for free, and what needs a trail
  • How to find who did something, when, from where, and with what settings
  • Why some events are in a different Region's history from the one you work in
  • What management events and data events are, and what each costs
  • How a trail writes its files to S3, and what digest files prove
  • How to check that a trail is recording what you think it is

Before you start

  • You need: the juniper-rye profile, signed in, and Lesson 20's virtual environment. Lesson 3 covers the identities CloudTrail names, and Lesson 9 the security group rule in the story.
  • The script: lab.py from the practice folder's lesson-33. Everything it creates is named jr-lesson33-* and tagged lesson=33, and its delete step removes it.
  • Where you run things: your own machine, labeled (Your machine).
  • Every output below is from real runs on the night of November 15, 2026, in New York, which is early on November 16 in UTC. The lab was run eight times that night; the section "When a trail records less than you think" explains why.

One trail is free; the second one isn't

Event history and a trail's first copy of management events cost nothing. A second trail recording the same management events pays $2.00 per 100,000, and data events, like every file read in a bucket, pay $0.10 per 100,000 from the first one. On a busy bucket that's millions a day. A trail whose bucket it can't write to keeps trying for 30 days, and those attempts are charged too, so delete a trail you've broken. This lab's whole bill is a fraction of a cent.

The short version

  • CloudTrail records API calls: who called what, when, from where, and whether it worked.
  • Event history is always on, free, and keeps 90 days of management events, one Region at a time.
  • Global services like IAM are recorded in us-east-1, whatever Region you work in.
  • A trail writes the records to S3 as files you keep, and can add data events: reads and writes of the data itself.
  • Refused calls are recorded too, with the error.
  • Check what a trail actually delivers, not just that it's logging.

What this lesson costs

PartPriceThis lab
Event historyFree, always onNothing
A trail's first copy of management eventsFreeNothing
Data events$0.10 per 100,000A handful
The trail's files in S3S3 storageAbout 30 small files, deleted the same hour
The network and security groupFreeNothing
This lessonA fraction of a cent

Three places CloudTrail keeps a record

Every change in an AWS account is an API call, whether it came from the console, the CLI, boto3, Terraform or AWS itself. CloudTrail writes each call down as an event: the identity that made it, the time, the address it came from, the settings it asked for, and what came back.

CloudTrail is the bakery's logbook by the back door. Every key handed out, every delivery signed for, every door unlocked goes in it, including the times someone tried a door and it stayed shut. The last 90 days stay on the hook by the door for anyone to read. A trail is the owner's photocopy of every page, filed in a cabinet the owner controls, and it can also note each time someone takes a recipe card out of the drawer, which the book by the door never records.
Event historyA trail
Set upNothing to do: always onYou create it, with an S3 bucket
Keeps90 days, then goneAs long as you keep the files
Management eventsYes: reads and writesYes, and you choose which
Data eventsNeverOnly the ones you select
WhereOne Region at a timeOne Region, or every Region in one place
CostFreeFirst copy of management events free; data events paid

Management events are calls that manage resources: creating a bucket, opening a port, reading a security group's rules. Data events are calls on the data inside a resource: reading a file from a bucket, running a Lambda function. There are far more data events than management events, which is why they're off unless you ask, and why they're paid.

(Your machine)

BASH
cd ~/Apps/aws-practice/lesson-33
source ../lesson-20/.venv/bin/activate
python lab.py fence
OUTPUT
== What's already recording in this account
  trails: 0 (event history still records management events)
  CloudTrail Lake event data stores: 0
== What CloudTrail costs in us-east-2 (from the Price List API)
  data events, per 100,000                         $0.10
  extra copies of management events, per 100,000   $2.00
  event history, 90 days of management events          free, always on
  a trail's first copy of management events            free (S3 storage for the files is not)

No trails, and still every change to this account in the last 90 days is in event history. CloudTrail Lake is a third, SQL-queryable place for events, priced separately; this lesson doesn't use it.

The story

Juniper & Rye's account, an ordinary evening. A recipe bucket is created and tagged, someone makes a network with a security group called ovens, opens SSH to the whole internet "for debugging", and closes it five seconds later. Then someone tries to look at a GitHub sign-in source, the kind Lesson 31 uses for deployments, which this free-plan account isn't allowed to touch.

BASH
python lab.py act
OUTPUT
== 06:18:37 UTC: the story
  1. created bucket jr-lesson33-recipes-0e997169
  2. tagged it
  3. created a network, vpc-0ba23a1d361086d18
  4. created security group jr-lesson33-ovens, sg-0308b57a22173effa
  5. opened port 22 (SSH) to 0.0.0.0/0, the whole internet
     ...and closed it again 5 seconds later
  6. tried to look at the GitHub sign-in source: AccessDenied
== 06:18:45 UTC: done. Event history takes a few minutes to show these; run history next.

Five seconds is long enough. Scanners sweep the whole internet for open SSH ports continuously, and "it was only open for a moment" is how a lot of incidents start. The question CloudTrail answers is the one you'd ask the next morning: did that happen, who did it, and is it closed?

Find it in event history

lookup_events searches event history: by time, and by one attribute such as the event name, the resource, or the user. It returns each event with its full record as a JSON string.

BASH
python lab.py history
OUTPUT
== Looking up events since 06:18:07 UTC in event history (checking every 20 seconds, for up to 15 minutes)
  (IAM is a global service: its events are kept in us-east-1's event history, so look there too)
  7 of 7 actions found, 142 seconds after the story ended
== What happened, oldest first
  UTC      svc    action                         result        from       found in
  06:18:37 s3     CreateBucket                   ok            your IP    us-east-2
  06:18:38 s3     PutBucketTagging               ok            your IP    us-east-2
  06:18:38 ec2    CreateVpc                      ok            your IP    us-east-2
  06:18:39 ec2    CreateSecurityGroup            ok            your IP    us-east-2
  06:18:39 ec2    AuthorizeSecurityGroupIngress  ok            your IP    us-east-2
  06:18:45 ec2    RevokeSecurityGroupIngress     ok            your IP    us-east-2
  06:18:45 iam    GetOpenIDConnectProvider       AccessDenied  your IP    us-east-1
== Who: identity type AssumedRole; the same identity in all 7 events: yes (the name itself is hidden here)
== With: Boto3/1.44.2 in 7 (S3 wraps its userAgent in [brackets]; the script strips them)

All seven, two minutes and 22 seconds after the last one. AWS says CloudTrail delivers events in about five minutes on average, with no guarantee; plan on minutes, not seconds.

The refused call is there, with its error. A call doesn't have to work to be recorded. A run of AccessDenied errors from one identity is one of the first things to look for after a leaked key: someone trying doors.

The IAM call was in us-east-1's history, not us-east-2's. IAM, like a few other services, is global, and CloudTrail records global services' events in us-east-1. The first version of this script only looked in us-east-2, found six of seven, and waited its full 15 minutes for the seventh. If you're hunting for an IAM change and can't find it, check the Region before anything else.

Two events in the same second can come back in either order. In another run of the same story, tagging the bucket was listed before creating it. Sort by time and then by what makes sense, and don't read too much into the order within a second.

"Who" is an identity, not a person. AssumedRole means a role session: here, the session aws login started. The full record names the role and the session; this script hides them, the same way it hides your IP address. In a real account, those two fields, plus the userAgent showing the tool, are how you get from "a role" to "Dami, from her laptop, with Terraform".

The record itself

Each event is a JSON record. Here are the security group rule and the refused call, with some fields left out:

OUTPUT
== The full record of AuthorizeSecurityGroupIngress (some fields left out)
  {
    "eventTime": "2026-11-16T06:18:39Z",
    "eventSource": "ec2.amazonaws.com",
    "eventName": "AuthorizeSecurityGroupIngress",
    "awsRegion": "us-east-2",
    "sourceIPAddress": "your IP",
    "userAgent": "Boto3/1.44.2 md/Botocore#1.44.2 md/awscrt#0.38.0 ua/2.1 os/macos#25.6.0 md/arch#arm64 lang/python#3.13.0 md/pyimpl#CPython m/b,AC,Z,E,
    "requestParameters": {
      "groupId": "sg-0308b57a22173effa",
      "ipPermissions": {
        "items": [
          {
            "ipProtocol": "tcp",
            "fromPort": 22,
            "toPort": 22,
            "groups": {},
            "ipRanges": {
              "items": [
                {
                  "cidrIp": "0.0.0.0/0",
                  "description": "temporary, for debugging"
                }
              ]
            },
            "ipv6Ranges": {},
            "prefixListIds": {}
          }
        ]
      }
    },
    "responseElements": {
      "requestId": "fe2373d1-fd55-43bc-9263-0b97e7c9064a",
      "_return": true,
      "securityGroupRuleSet": {
        "items": [
          {
            "groupOwnerId": "111122223333",
            "groupId": "sg-0308b57a22173effa",
            "securityGroupRuleId": "sgr-0134188421da8219d",
            "description": "temporary, for debugging",
            "isEgress": false,
            "ipProtocol": "tcp",
            "fromPort": 22,
            "toPort": 22,
            "cidrIpv4": "0.0.0.0/0",
            "securityGroupRuleArn": "(an ARN)"
          }
        ]
== The full record of GetOpenIDConnectProvider (some fields left out)
  {
    "eventTime": "2026-11-16T06:18:45Z",
    "eventSource": "iam.amazonaws.com",
    "eventName": "GetOpenIDConnectProvider",
    "awsRegion": "us-east-1",
    "sourceIPAddress": "your IP",
    "userAgent": "Boto3/1.44.2 md/Botocore#1.44.2 md/awscrt#0.38.0 ua/2.1 os/macos#25.6.0 md/arch#arm64 lang/python#3.13.0 md/pyimpl#CPython m/b,AC,Z,E,
    "errorCode": "AccessDenied",
    "errorMessage": "User: (an ARN) is not authorized to perform: iam:GetOpenIDConnectProvider on resource: (an ARN) with an explicit deny in a service
    "requestParameters": null,
    "responseElements": null,
    "readOnly": true,
    "eventType": "AwsApiCall",
    "managementEvent": true,
    "eventCategory": "Management",
    "userIdentity": {
      "type": "AssumedRole",
      "arn": "(an ARN)",
      "accountId": "111122223333"
    }
  }

The script cuts long lines at 150 characters, which is why some end mid-word. Read the first record the way an investigator would:

  • requestParameters is what was asked for: port 22, from 0.0.0.0/0, and even the description someone typed.
  • responseElements is what AWS did about it: it created rule sgr-0134188421da8219d. The matching RevokeSecurityGroupIngress five seconds later names the same rule, so you can prove it's closed.
  • readOnly says whether the call changed anything. Looking at the sign-in source was a read, and it was still recorded, because event history keeps reads as well as writes.
  • errorMessage on the refused call says "explicit deny in a service control policy": the free plan's own block on this kind of sign-in source.

A trail: files you keep

Event history is enough to answer "what happened last Tuesday?" It isn't enough when you need records older than 90 days, when an auditor wants them somewhere the account's own admins can't quietly change, or when the question is about data: who read this file? For those, you create a trail, which writes the events to an S3 bucket as files.

Where CloudTrail sends what it recordsAPI calls from the console, the CLI and boto3 are recorded by CloudTrail. Management events go to event history, which keeps 90 days, one Region at a time, at no cost. A trail receives the management events and data events you select, and writes them to an S3 bucket as log files every few minutes, with a digest file per Region every hour. Global services such as IAM are recorded in us-east-1.Your API callsconsole, CLI, boto3CloudTrailrecords every callmanagementwhat you selectEvent history90 days, per Region, freeYour trailmanagement and data eventsS3 bucketlog files, every few mina digest per Region, hourlyIAM and other global services are recorded in us-east-1, whatever Region you work in.
Event history needs no setup and never holds data events. A trail holds what you select, for as long as you keep its files.

A trail needs a bucket that CloudTrail is allowed to write to, and nobody else is. The script blocks public access and gives the bucket this policy:

PYTHON
{"Sid": "CheckAcl", "Effect": "Allow", "Principal": {"Service": "cloudtrail.amazonaws.com"},
 "Action": "s3:GetBucketAcl", "Resource": "arn:aws:s3:::<bucket>",
 "Condition": {"StringEquals": {"aws:SourceArn": "<this trail's ARN>"}}},
{"Sid": "Write", "Effect": "Allow", "Principal": {"Service": "cloudtrail.amazonaws.com"},
 "Action": "s3:PutObject", "Resource": "arn:aws:s3:::<bucket>/*",
 "Condition": {"StringEquals": {"s3:x-amz-acl": "bucket-owner-full-control",
                                "aws:SourceArn": "<this trail's ARN>"}}}

The aws:SourceArn condition matters. Without it, any trail in any AWS account could write into your bucket by naming it; with it, only this trail can. It's the same condition Lesson 23 put on its queue and topic policies, and it has a name: it stops the confused deputy problem, where a trusted service is tricked into acting for someone else.

BASH
python lab.py trail
OUTPUT
== A bucket for the trail's log files: jr-lesson33-trail-429f84f5
== The trail: every Region, log file validation on
== What it records, with a basic event selector
  management events: yes (All)
  data events: AWS::S3::Object in arn:aws:s3:::jr-lesson33-recipes-0e997169/
== Giving the new trail and its selectors a minute to take effect before anything happens
== jr-lesson33-trail-5e8c7a: logging on; all Regions yes; log file validation on; files go to s3://jr-lesson33-trail-429f84f5/lesson33/AWSLogs/...

Three settings worth knowing:

  • Every Region. A multi-Region trail records events from all Regions into one bucket, including Regions you never use, which is where an attacker with a stolen key likes to start servers. Make every trail multi-Region unless you have a reason not to.
  • Log file validation. CloudTrail also writes digest files: each one lists the log files delivered in the last hour with a hash of each, and is signed. If anyone edits or deletes a log file, aws cloudtrail validate-logs says so.
  • Event selectors decide what the trail records. This one records every management event, plus reads and writes of files in the recipe bucket only.

Basic and advanced event selectors

There are two ways to tell a trail what to record. Basic event selectors are the original form: management events yes or no, all or read-only or write-only, and a list of data resources. Advanced event selectors are newer: lists of fields and values, such as "category is Data, resource type is S3 object, ARN starts with this bucket". They can do more, like excluding a noisy event source, and AWS's documentation leans on them.

PYTHON
# basic: what the lab uses
EventSelectors=[{"ReadWriteType": "All", "IncludeManagementEvents": True,
                 "DataResources": [{"Type": "AWS::S3::Object", "Values": ["arn:aws:s3:::<recipes>/"]}]}]

# advanced: python lab.py trail advanced
AdvancedEventSelectors=[
    {"Name": "Management events that change something",
     "FieldSelectors": [{"Field": "eventCategory", "Equals": ["Management"]},
                        {"Field": "readOnly", "Equals": ["false"]}]},
    {"Name": "Reads and writes of files in the recipe bucket only",
     "FieldSelectors": [{"Field": "eventCategory", "Equals": ["Data"]},
                        {"Field": "resources.type", "Equals": ["AWS::S3::Object"]},
                        {"Field": "resources.ARN", "StartsWith": ["arn:aws:s3:::<recipes>/"]}]}]

The lab was written with the advanced version, and recorded management writes only, to keep the files small. The section after next explains why it now uses the basic one.

Data events

Data events are what event history never has. The script reads and writes a few recipes, and tags the bucket as a management event to compare:

BASH
python lab.py data
OUTPUT
== 06:22:11 UTC: reading and writing recipes in jr-lesson33-recipes-0e997169
  PutObject     sourdough.txt
  PutObject     rye.txt
  PutObject     croissant.txt
  GetObject     sourdough.txt
  GetObject     rye.txt
  DeleteObject  croissant.txt
  PutBucketTagging (a management event, for comparison)
== Event history, 90 seconds later: GetObject events found: 0 (event history keeps management events only)

Zero, and it will stay zero. If a recipe leaks next month and nobody turned on data events for that bucket beforehand, there is no record anywhere of who read it. CloudTrail can't add them after the fact.

The trail's files

A trail doesn't write each event as it happens. It collects them and writes a compressed JSON file every few minutes, per Region, into folders by account, Region and date: under AWSLogs, the account ID, then CloudTrail, the Region, and the year, month and day.

BASH
python lab.py files
OUTPUT
== Waiting for the trail's log files (checking every 30 seconds, for up to 35 minutes)
     1s: log files 2, digest files 3, last delivery 06:23:33 UTC
   182s: log files 2, digest files 18, last delivery 06:23:33 UTC
   364s: log files 3, digest files 18, last delivery 06:28:33 UTC
   546s: log files 3, digest files 18, last delivery 06:28:33 UTC
   728s: log files 4, digest files 18, last delivery 06:33:54 UTC
   910s: log files 4, digest files 18, last delivery 06:33:54 UTC
  1091s: log files 5, digest files 18, last delivery 06:40:44 UTC
  1273s: log files 5, digest files 18, last delivery 06:40:44 UTC
  1454s: log files 6, digest files 18, last delivery 06:46:44 UTC
  1636s: log files 6, digest files 18, last delivery 06:46:44 UTC
  1818s: log files 7, digest files 18, last delivery 06:52:45 UTC
  1999s: log files 7, digest files 18, last delivery 06:52:45 UTC
  6 log files, 37 records, after 2120 seconds
== What CloudTrail says about its own deliveries
  IsLogging                  True
  StartLoggingTime           06:21:10 UTC
  LatestDeliveryTime         06:58:56 UTC
  LatestDeliveryError        (none)
  LatestDigestDeliveryTime   06:24:27 UTC
  LatestDigestDeliveryError  (none)
== Everything in the bucket, by folder
  lesson33/AWSLogs/<account>/CloudTrail-Digest//   1
  lesson33/AWSLogs/<account>/CloudTrail-Digest/ap-northeast-1/ 1
  lesson33/AWSLogs/<account>/CloudTrail-Digest/ap-northeast-2/ 1
  …
  lesson33/AWSLogs/<account>/CloudTrail-Digest/us-west-2/ 1
  lesson33/AWSLogs/<account>/CloudTrail//          1
  lesson33/AWSLogs/<account>/CloudTrail/us-east-2/ 7
== Where they are: s3://jr-lesson33-trail-429f84f5/lesson33/AWSLogs/111122223333/CloudTrail/us-east-2/2026/11/16/...
  one file name: 111122223333_CloudTrail_us-east-2_20261116T0625Z_HkxE0zvZ0fmdGhvj.json.gz
== What's in them
  category     service              action                             kind   count
  Management   cloudtrail           DescribeTrails                     read   1
  Management   cloudtrail           GetTrailStatus                     read   11
  Management   cloudtrail           LookupEvents                       read   1
  Management   s3                   GetBucketAcl                       read   16
  Management   s3                   GetBucketEncryption                read   1
  Management   s3                   GetBucketLogging                   read   1
  Management   signin               CreateOAuth2Token                  read   3
  Management   sts                  AssumeRole                         read   2
  Management   sts                  GetCallerIdentity                  read   1
== Digest files so far: 18 (one per Region, about once an hour: each lists the log files delivered and their hashes)

The list of 18 digest folders is shortened here. What the run shows:

  • Files arrived every five to seven minutes, the first one about two minutes after logging started. The last file arrived after the script's final listing, so it read six of the seven.
  • 18 digest files, one per Region, within a few minutes of starting. They're the starting digests, written when validation is turned on, and each says it covers no log files yet. CloudTrail writes a digest every hour even when nothing happened, so that "no files this hour" can itself be proved.
  • The two empty folder entries (CloudTrail// and CloudTrail-Digest//) are zero-byte objects that appeared as soon as the trail started. The script's first version counted one as a log file.
  • The script's own reading shows up: 11 GetTrailStatus calls from its polling, LookupEvents from the data step, and CreateOAuth2Token and AssumeRole, most likely from the aws login session being refreshed. The 16 GetBucketAcl calls are most likely CloudTrail itself, checking the bucket the way the policy's first statement allows.

And something's missing. There's no PutObject, GetObject or DeleteObject, and no PutBucketTagging: every one of the 37 records is a read. That's the subject of the next section.

When a trail records less than you think

Here is everything that happened that night, because finding it is a real CloudTrail skill: a trail that says it's logging, reports no errors, and delivers less than it should.

RunWhat the trail recordedOther trails runningWhat arrived
1, 2Advanced: management writes, and the recipe bucket's data eventsNoneNo log files in 20 and then 35 minutes, and no error
3Basic: every management eventNone5 files in 22 minutes
4Four trails side by side, each with different selectorsThreeAt least one file from each; the sign-in expired before the report, so their contents weren't seen
5, 6Advanced, as in runs 1 and 2, with a wait, a new trail name, a folder and a wider bucket policyNoneNo log files in 35 minutes
7Advanced, run alone by the same code as run 4NoneNo log files in 30 minutes
8Basic: every management event, and the recipe bucket's data eventsNone7 files; every record a read

Run 8 explains runs 1, 2 and 5 to 7: in this account, our writes and data events weren't delivered, and a trail that records only writes and data events had nothing to deliver. Every change was still in event history within minutes; only the trail missed them. Run 4 is the one that doesn't fit: trails with the same advanced selectors delivered a file each while other trails ran beside them, and we never saw what those files held.

We don't know why. The trail reported no error, AWS's troubleshooting guide doesn't describe it, and the account is a new one on the free plan, which may or may not matter. In an ordinary account, you'd expect run 8's table to include PutObject, GetObject and DeleteObject as data events, and PutBucketTagging as a management write. If yours do, the trail is working as AWS describes. If they don't, you've found the same thing we did, and these checks are how you'd know:

  1. LatestDeliveryTime, not just IsLogging. get_trail_status said "logging" the whole time. A trail with no LatestDeliveryTime after 15 minutes of activity has delivered nothing. LatestDeliveryError only reports problems writing to the bucket; it was empty every time.
  2. Count what arrived, by kind. Group the records by eventCategory and readOnly, the way files does. A trail that should have writes and data events, and has only reads, is quietly incomplete.
  3. Do a known action and look for it in the trail's files, not in event history. A test write that never appears in the files is the signal.
  4. Read a digest file. Each one lists the log files delivered in its hour. A digest listing none, for an hour you know was busy, proves nothing was delivered. python lab.py status prints the newest digest's count.

A trail you haven't checked is a trail you're hoping about

Teams find out their trail was incomplete during an incident, which is the worst time. Check a new trail once with a known action, and again after any change to its selectors.

Take it down

BASH
python lab.py delete
OUTPUT
== Stopping and deleting the trail jr-lesson33-trail-5e8c7a
== What the trail left in jr-lesson33-trail-429f84f5, by folder
  lesson33/AWSLogs/<account>/CloudTrail-Digest//   1
  lesson33/AWSLogs/<account>/CloudTrail-Digest/ap-northeast-1/ 1
  …
  lesson33/AWSLogs/<account>/CloudTrail-Digest/us-west-2/ 1
  lesson33/AWSLogs/<account>/CloudTrail//          1
  lesson33/AWSLogs/<account>/CloudTrail/us-east-2/ 7
== Deleted bucket jr-lesson33-trail-429f84f5 and its 26 files
== Deleted bucket jr-lesson33-recipes-0e997169 and its 2 files
== Deleted security group jr-lesson33-ovens
== Deleted network vpc-0ba23a1d361086d18
== Anything left from Lesson 33
  nothing: all clear
  (event history keeps its record of all of this for 90 days: it can't be edited or deleted)

Deleting the trail is itself recorded. StopLogging and DeleteTrail are management events, in event history for 90 days, which is why a real attacker who turns off a trail still leaves a mark, and why real accounts alarm on exactly those two events.

By hand: the same with the AWS CLI

(Your machine) Search event history, in your Region and in us-east-1 for IAM:

BASH
export AWS_PROFILE=juniper-rye AWS_REGION=us-east-2

aws cloudtrail lookup-events --max-results 5   --lookup-attributes AttributeKey=EventName,AttributeValue=AuthorizeSecurityGroupIngress   --query "Events[].[EventTime,Username,EventName]" --output table

aws cloudtrail lookup-events --region us-east-1 --max-results 5   --lookup-attributes AttributeKey=EventSource,AttributeValue=iam.amazonaws.com   --query "Events[].[EventTime,EventName]" --output table

A trail, with the bucket and its policy already made, and its status:

BASH
aws cloudtrail create-trail --name jr-lesson33-trail --s3-bucket-name $LOGS --s3-key-prefix lesson33   --is-multi-region-trail --enable-log-file-validation

aws cloudtrail put-event-selectors --trail-name jr-lesson33-trail --event-selectors   '[{"ReadWriteType":"All","IncludeManagementEvents":true,"DataResources":[{"Type":"AWS::S3::Object","Values":["arn:aws:s3:::'$RECIPES'/"]}]}]'

aws cloudtrail start-logging --name jr-lesson33-trail
aws cloudtrail get-trail-status --name jr-lesson33-trail

Check the files haven't been changed, once an hour or more has passed:

BASH
TRAIL_ARN=$(aws cloudtrail describe-trails --trail-name-list jr-lesson33-trail --query "trailList[0].TrailARN" --output text)
aws cloudtrail validate-logs --trail-arn $TRAIL_ARN --start-time $(date -u -v-2H +%Y-%m-%dT%H:%M:%SZ)

The date -v-2H form is macOS's; on Linux it's date -u -d '2 hours ago' +%Y-%m-%dT%H:%M:%SZ.

In real systems

  • One organization trail, created in the management account, records every account in the organization. Lesson 36 covers organizations.
  • The trail's bucket lives in a separate log archive account that almost nobody can sign in to, often with S3 Object Lock, so even an admin of the recorded account can't delete the evidence.
  • Alarms on the events that matter: StopLogging, DeleteTrail, root sign-ins, and changes to security groups and IAM, through EventBridge or CloudWatch Logs.
  • Data events only where they're needed, on the buckets that hold sensitive data, scoped by selector, because on a busy bucket they cost more than everything else CloudTrail does.
  • The files are queried, not read: Amazon Athena or a security tool reads them with SQL. GuardDuty, in Lesson 35, reads CloudTrail to spot unusual behavior on its own.
  • Every new trail is tested with a known action, as in the last section.

Spot the problem

Work out what's wrong before you read the explanation.

"Who downloaded the recipe file?" Juniper & Rye's secret croissant recipe turns up on a competitor's website. It lives in an S3 bucket that only three roles can read. The account has a multi-Region trail recording all management events, and event history is on as always. The owner searches both for the file's name and finds the day it was uploaded, and nothing else. What's wrong? Reading a file is a data event, and neither event history nor a trail without data events ever records one: there's no record of who read it, and there never will be. The fix: turn on data events for the buckets that hold sensitive data, scoped to those buckets, before you need them. Then check: read a file yourself and find your GetObject in the trail's files.

Keep this

RememberWhy
Event history is free and always on90 days of management events, no setup
Look in us-east-1 for IAMGlobal services are recorded there
Refused calls are recordedA burst of AccessDenied is someone trying doors
requestParameters and responseElementsWhat was asked for, and what AWS did
Data events need a trail, set up beforehandNobody can find out later who read a file
One trail's management events are freeA second copy is $2.00 per 100,000
Multi-Region, with log file validationNo blind Regions, and tampering shows
Check LatestDeliveryTime and what arrived"Logging" and "no errors" weren't enough here

Where you are now

Juniper & Rye's account answered "who did what" for an evening's changes: event history found all seven actions in a little over two minutes, including a refused one in a different Region, and the records showed exactly what the SSH rule allowed and proved it was closed. A trail kept its own files, with digests to prove they weren't changed, and turned up a real lesson in checking what a trail actually delivers. Next, Lesson 34 protects the data itself, with KMS keys and Secrets Manager, both of which CloudTrail records every use of.

Check yourself

  1. Which needs no setup at all?

  2. The GetOpenIDConnectProvider call was made with us-east-2 set. Where was it?

  3. Which field shows what AWS actually did, like the rule ID it created?

  4. Why did event history find no GetObject events?

  5. What does a digest file let you prove?

  6. A trail says IsLogging True and LatestDeliveryError is empty. What else should you check?

  7. What does a second trail recording the same management events cost?

Key terms

  • Event: CloudTrail's record of one API call: who, when, from where, what was asked, and what came back.
  • Event history: the free, always-on 90 days of management events, one Region at a time.
  • Management event: a call that manages resources, like creating a bucket or opening a port.
  • Data event: a call on the data in a resource, like reading a file or running a function.
  • Trail: a configuration that writes selected events to an S3 bucket as files.
  • Multi-Region trail: a trail that records every Region into one bucket.
  • Event selector: a trail's rule for which events to record; basic or advanced.
  • Digest file: an hourly, signed list of the log files a trail delivered, with their hashes.
  • Global service events: events from services like IAM, recorded in us-east-1.
  • aws:SourceArn: a policy condition that names which resource may act, here which trail may write.

Go deeper