Thuta Learning
AWS Advanced
SecurityDevOpsAdvanced

Threat Detection & Audit: CloudTrail, Config, GuardDuty, Security Hub

AWS AdvancedLesson 2545 min

What you'll walk away with

  • Explain CloudTrail management vs data events, organization trails and log file integrity validation
  • Decide where AWS Config recorders, managed rules, conformance packs and remediation fit
  • Understand what GuardDuty analyzes and how to read its finding type names
  • Place Security Hub and Amazon Inspector in the overall picture
  • Build a GuardDuty finding → EventBridge rule → Lambda/SNS automated response pipeline

Explain it simply

Think of an office building

Think of your AWS organization as an office building. CloudTrail is the security camera recording who walked through which door and when — every API call, with the caller's identity, time and source IP. AWS Config is the inspector who keeps a dated record of how every room is set up and flags anything that breaks the building code.

GuardDuty is the guard watching the camera feeds for suspicious behavior, and Security Hub is the front desk where all the reports land in one queue.

None of these services stop an attack by themselves. Their job is to make sure that when something goes wrong you find out quickly, you can prove what happened, and — with a little automation — you can respond in minutes instead of days.

Problem → Why → Solution

An account nobody was watching

Imagine an access key for a CI user leaks into a public Git repository. Within minutes automated scanners find it, and someone starts launching large GPU instances in a Region your team never uses, to mine cryptocurrency. Nobody notices for nine days, until the monthly bill arrives.

When the team finally investigates, they discover CloudTrail was only ever viewed in one Region's 90-day Event history in the console, nobody had enabled GuardDuty, and the attacker had also created a new IAM user as a backdoor. Each of those facts is recoverable in principle, but answering 'what else did they touch?' takes days of manual digging.

what-the-team-found.sh
# What the team found when they finally looked
aws cloudtrail describe-trails --query 'trailList[].Name'
# []   <- no trail: only 90 days of management events, per Region

aws guardduty list-detectors
# { "DetectorIds": [] }   <- nobody was watching

Why this keeps happening

Audit and detection are invisible until the day you need them, so they get skipped. By default you only get a 90-day, per-Region view of management events. Without a trail, a detector and an alert path, the time between compromise and discovery is measured by your billing cycle.

Record, evaluate, detect, aggregate

Data event
A high-volume operation performed on or inside a resource (S3 GetObject/PutObject, Lambda Invoke, DynamoDB item reads and writes). Off by default and billed per event.

CloudTrail records API activity. Management events are control-plane actions such as RunInstances, CreateUser or PutBucketPolicy; they are logged by default and visible for 90 days in Event history. Data events are high-volume and billed per event, so you enable them selectively — for example only on buckets that hold sensitive data.

A trail turns that short history into a permanent record: it delivers log files to an S3 bucket (and optionally CloudWatch Logs). An organization trail, created from the management account or a delegated administrator, captures every account in AWS Organizations, and member accounts cannot switch it off.

Turn on log file integrity validation. CloudTrail then writes an hourly digest file containing the SHA-256 hash of each log file, signed with its own private key, so you can later prove logs were not altered or deleted. CloudTrail Lake is an alternative destination that keeps events in an event data store you query with SQL.

AWS Config answers a different question: not 'who called what' but 'what did this resource look like at a point in time, and is that compliant?'. The configuration recorder captures a configuration item whenever a supported resource changes. Rules evaluate those items — AWS managed rules such as s3-bucket-public-read-prohibited, or custom rules you write. A conformance pack bundles many rules and remediation actions into one deployable unit, and remediation can run an SSM Automation document automatically to fix a non-compliant resource.

GuardDuty is the detection engine. Its foundational data sources are CloudTrail management events, VPC Flow Logs and Route 53 Resolver DNS query logs; it reads them directly, so you do not have to enable those logs yourself. Optional protection plans add S3 data events, EKS audit logs, runtime monitoring, malware scanning and more. Findings are named like Recon:EC2/PortProbeUnprotectedPort — threat purpose, resource type, then the specific behavior — and carry a numeric severity.

Amazon Inspector continuously scans EC2 instances, ECR container images and Lambda functions for known software vulnerabilities (CVEs) and unintended network exposure. Security Hub aggregates findings from GuardDuty, Inspector, Config, Macie and partner tools into one normalized format, and runs security standards such as AWS Foundational Security Best Practices and the CIS AWS Foundations Benchmark against your accounts.

ServiceQuestion it answersMain input
CloudTrailWho called which API, and when?Every API call
AWS ConfigWhat did it look like, is it compliant?Configuration changes
GuardDutyIs this activity malicious?CloudTrail, Flow Logs, DNS
InspectorDoes this workload have known CVEs?EC2, ECR images, Lambda
Security HubHow bad is it overall?All of the above
text
ORGANIZATION-WIDE DETECTION AND AUDIT
-------------------------------------
  MEMBER ACCOUNTS (every Region)        CENTRAL ACCOUNTS
 +------------------------------+
 | API calls  ---> CloudTrail   |--org trail--> [S3 log archive + digests]
 | resources  ---> Config       |--aggregator-> [Config aggregator]
 | logs/flows ---> GuardDuty    |--findings---> [GuardDuty admin] ---+
 | EC2/ECR/Lambda -> Inspector  |--findings---> [Inspector admin] --+|
 +------------------------------+                                   ||
                                                                    vv
                                                         [Security Hub]
                                                               |
                               EventBridge rule (severity >= 7) |
                                                               v
                                         [Lambda triage] --> [SNS on-call]
Record → evaluate → detect → respond
  1. CloudTrail records every API call
  2. Config records resource state + rules
  3. GuardDuty turns signals into findings
  4. Security Hub aggregates and scores
  5. EventBridge routes findings to response

The first two are evidence, the third is judgement, the last two are action. Without evidence you cannot trust the judgement, and without action the judgement is just a number on a dashboard.

GuardDuty high-severity event pattern

guardduty-high.json
{
  "source": ["aws.guardduty"],
  "detail-type": ["GuardDuty Finding"],
  "detail": {
    "severity": [{ "numeric": [">=", 7] }]
  }
}

Every GuardDuty finding arrives on the default event bus with source 'aws.guardduty' and detail-type 'GuardDuty Finding'. Numeric matching selects only events whose detail.severity is 7 or higher (High and above). Fields not mentioned in the pattern are ignored by EventBridge.

A Lambda that triages GuardDuty findings

The EventBridge rule delivers the finding to a Lambda function. The function turns the severity into a label, keeps only the fields an on-call engineer needs, and publishes to an SNS topic. Anything below 7 is only logged — the rule already filters, but checking again in code means a widened rule cannot page people by accident.

guardduty_triage.py
import json
import os

import boto3

sns = boto3.client("sns")
TOPIC_ARN = os.environ["ALERT_TOPIC_ARN"]


def label(severity: float) -> str:
    if severity >= 9:
        return "CRITICAL"
    if severity >= 7:
        return "HIGH"
    if severity >= 4:
        return "MEDIUM"
    return "LOW"


def lambda_handler(event, context):
    finding = event["detail"]
    severity = float(finding["severity"])
    level = label(severity)
    if severity < 7:
        print(f"{finding['type']}: {level}, logged only")
        return {"published": False}

    message = {
        "account": finding["accountId"],
        "region": finding["region"],
        "type": finding["type"],
        "severity": severity,
        "resource": finding["resource"]["resourceType"],
        "title": finding["title"],
    }
    subject = f"[{level}] GuardDuty {finding['type']}"[:100]
    resp = sns.publish(TopicArn=TOPIC_ARN, Subject=subject, Message=json.dumps(message))
    print(f"{finding['type']}: {level}, alert published")
    return {"published": True, "messageId": resp["MessageId"]}


if __name__ == "__main__":
    def sample(finding_type, severity):
        return {
            "source": "aws.guardduty",
            "detail-type": "GuardDuty Finding",
            "detail": {
                "accountId": "111122223333",
                "region": "us-east-1",
                "type": finding_type,
                "severity": severity,
                "title": "Sample finding",
                "resource": {"resourceType": "AccessKey"},
            },
        }

    exfil = "UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS"
    lambda_handler(sample("Recon:EC2/PortProbeUnprotectedPort", 2), None)
    result = lambda_handler(sample(exfil, 8), None)
    print("published:", result["published"])

Not runnable in the browser

This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.

Code breakdown

  1. Topic from the environmentTOPIC_ARN = os.environ["ALERT_TOPIC_ARN"]

    The topic ARN comes from an environment variable instead of being hard-coded, so the same code deploys to dev and prod accounts with different topics.

  2. Severity to labelif severity >= 7: return "HIGH"

    GuardDuty severity is a number (for example 8.0). 7.0-8.9 is High, 4.0-6.9 is Medium and anything lower is Low. The label is for humans; the decision is still made on the number.

  3. Defense in depth on the filterif severity < 7: print(f"{finding['type']}: {level}, logged only")

    The rule only sends 7 and above, but the function checks again, so if someone edits the rule pattern, Low findings still never reach the on-call phone.

  4. Publish a compact messagesns.publish(TopicArn=TOPIC_ARN, Subject=subject, Message=json.dumps(message))

    A full finding is several KB of JSON. Only account, Region, type, severity and resource type are sent. An SNS subject is limited to 100 characters, hence the [:100] slice.

You should see
Recon:EC2/PortProbeUnprotectedPort: LOW, logged only
UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS: HIGH, alert published
published: True
From finding to on-call
  1. GuardDuty creates a finding
  2. Event lands on the default bus
  3. Rule matches severity >= 7
  4. Lambda trims and publishes
  5. SNS notifies on-call

Severity below 7

Stays in Security Hub for daily triage

Severity 7 or higher

On-call is notified within minutes

Wiring the pipeline with the CLI

Create a detector, add a rule with the pattern above, allow EventBridge to invoke the Lambda function, then test end to end with sample findings. Sample findings are marked as samples, so they are never confused with real ones.

wire-guardduty-alerts.sh
DETECTOR_ID=$(aws guardduty create-detector --enable \
  --finding-publishing-frequency FIFTEEN_MINUTES \
  --query DetectorId --output text)

aws events put-rule \
  --name guardduty-high-severity \
  --event-pattern file://guardduty-high.json

FN_ARN=arn:aws:lambda:us-east-1:111122223333:function:guardduty-triage
aws lambda add-permission \
  --function-name guardduty-triage \
  --statement-id allow-eventbridge \
  --action lambda:InvokeFunction \
  --principal events.amazonaws.com \
  --source-arn arn:aws:events:us-east-1:111122223333:rule/guardduty-high-severity

aws events put-targets \
  --rule guardduty-high-severity \
  --targets "Id=triage-lambda,Arn=$FN_ARN"

# Fire a sample finding through the whole pipeline
aws guardduty create-sample-findings \
  --detector-id "$DETECTOR_ID" \
  --finding-types UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS

As infrastructure as code it looks the same in CDK. The SnsTopic target adds the topic policy that lets EventBridge publish automatically.

finding-alerts.ts
import { App, Stack, StackProps } from "aws-cdk-lib";
import * as events from "aws-cdk-lib/aws-events";
import * as targets from "aws-cdk-lib/aws-events-targets";
import * as sns from "aws-cdk-lib/aws-sns";
import { Construct } from "constructs";

class FindingAlertsStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const topic = new sns.Topic(this, "SecurityAlerts");
    new events.Rule(this, "HighSeverityFindings", {
      description: "GuardDuty findings with severity 7 or higher",
      eventPattern: {
        source: ["aws.guardduty"],
        detailType: ["GuardDuty Finding"],
        detail: { severity: [{ numeric: [">=", 7] }] },
      },
      targets: [new targets.SnsTopic(topic)],
    });
  }
}

const app = new App();
new FindingAlertsStack(app, "FindingAlertsStack");
app.synth();

An organization-wide baseline

Per-account setup does not scale. Create one organization trail from the management account and delegate GuardDuty and Security Hub administration to a security account. GuardDuty is regional, so delegated admin and auto-enable must be configured in every Region you use. Config rules and remediation are best shipped as conformance packs.

org-baseline.sh
# Management account: org trail with integrity validation
aws cloudtrail create-trail \
  --name org-trail \
  --s3-bucket-name org-cloudtrail-logs-111122223333 \
  --is-organization-trail \
  --is-multi-region-trail \
  --enable-log-file-validation \
  --kms-key-id alias/cloudtrail-logs
aws cloudtrail start-logging --name org-trail

# Delegate GuardDuty and Security Hub to the security account (per Region)
aws guardduty enable-organization-admin-account --admin-account-id 444455556666
aws securityhub enable-organization-admin-account --admin-account-id 444455556666

# Security account: turn GuardDuty on for every current and future member
aws guardduty update-organization-configuration \
  --detector-id "$DETECTOR_ID" \
  --auto-enable-organization-members ALL

# Config managed rule plus automatic remediation
aws configservice put-config-rule --config-rule file://s3-public-read-rule.json
aws configservice put-remediation-configurations \
  --remediation-configurations file://s3-public-read-remediation.json

# Later, during an investigation: prove the logs were not tampered with
aws cloudtrail validate-logs \
  --trail-arn arn:aws:cloudtrail:us-east-1:111122223333:trail/org-trail \
  --start-time 2026-11-01T00:00:00Z
s3-public-read-remediation.json
[
  {
    "ConfigRuleName": "s3-bucket-public-read-prohibited",
    "TargetType": "SSM_DOCUMENT",
    "TargetId": "AWS-DisableS3BucketPublicReadWrite",
    "Parameters": {
      "AutomationAssumeRole": {
        "StaticValue": {
          "Values": ["arn:aws:iam::111122223333:role/ConfigRemediationRole"]
        }
      },
      "S3BucketName": { "ResourceValue": { "Value": "RESOURCE_ID" } }
    },
    "Automatic": true,
    "MaximumAutomaticAttempts": 3,
    "RetryAttemptSeconds": 60
  }
]

In production

What production teams actually do

Most multi-account setups send organization trail logs to a bucket in a dedicated Log Archive account, protected with S3 Object Lock and a tight bucket policy, so no workload account can delete anything. GuardDuty, Security Hub, Inspector and the Config aggregator live in a Security Tooling account as delegated administrator. If you use AWS Control Tower, it sets up the org trail and Config baseline for you.

Routing is split by severity: High and Critical page on-call, Medium opens a ticket, Low is reviewed weekly. Known benign behavior (for example an approved vulnerability scanner probing ports) gets a GuardDuty suppression rule.

Automated containment is applied carefully: reversible actions such as deactivating a leaked access key or moving an EC2 instance into an isolation security group run automatically, while irreversible actions such as terminating an instance wait for a human — terminating also destroys forensic evidence.

Common mistakes

Common mistakes

Keeping logs in the account they audit

If the trail bucket sits in the workload account, an attacker with admin access can stop logging and delete the bucket — erasing their own tracks. Send the organization trail to a separate Log Archive account and deny cloudtrail:StopLogging and cloudtrail:DeleteTrail with an SCP.

Enabling detection only in the home Region

GuardDuty, Security Hub and Config are regional. Attackers deliberately pick Regions you never look at. Turn them on in every enabled Region, or block unused Regions with an SCP — ideally both.

Sending every finding to a chat channel

Pipe every finding into Slack and within a week the channel is muted, so the one real High finding is missed. Filter by severity, write suppression rules for known benign behavior, and give every paging alert an owner and a runbook.

💰 Cost & Cleanup

CloudTrail: the first copy of management events delivered to a trail in each Region is free; additional copies and data events are charged per event, plus S3 storage. GuardDuty, Security Hub and Inspector have free trial periods, then bill by volume of events/logs analyzed, security checks run and resources scanned. Config bills per configuration item recorded and per rule evaluation — it can climb quickly in accounts with heavy churn.

After the lab, delete the rule, function, topic and detector. In a real organization keep the trail and detectors — they are your baseline, not lab leftovers.

Clean up when you are done

cleanup.sh
aws events remove-targets --rule guardduty-high-severity --ids triage-lambda
aws events delete-rule --name guardduty-high-severity
aws lambda delete-function --function-name guardduty-triage
aws sns delete-topic --topic-arn arn:aws:sns:us-east-1:111122223333:security-alerts
aws guardduty delete-detector --detector-id "$DETECTOR_ID"

Mini challenge

Page only on IAM credential findings

Your team wants to page on-call only for UnauthorizedAccess findings against the IAMUser resource type. Write the EventBridge event pattern.

  • Match only source 'aws.guardduty' and detail-type 'GuardDuty Finding'
  • Severity must be 7 or higher
  • The finding type must start with 'UnauthorizedAccess:IAMUser/'

Expected: UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS at severity 8 matches; Recon:EC2/PortProbeUnprotectedPort and a severity-5 IAM finding do not.

Show hint

EventBridge supports prefix matching on strings: { "prefix": "..." }. Two fields inside the same detail object are combined with AND automatically.

Show solution
iam-credential-findings.json
{
  "source": ["aws.guardduty"],
  "detail-type": ["GuardDuty Finding"],
  "detail": {
    "severity": [{ "numeric": [">=", 7] }],
    "type": [{ "prefix": "UnauthorizedAccess:IAMUser/" }]
  }
}

Quick quiz 1 / 3

Which of these is a CloudTrail data event that is not logged by default?

Quick quiz 2 / 3

An auditor asks you to prove CloudTrail logs were not modified after delivery. What is the best answer?

Quick quiz 3 / 3

Which logs must you enable yourself for GuardDuty's foundational detections to work?

What to remember

  • CloudTrail = who called what. Send an organization trail with integrity validation to a separate Log Archive account
  • AWS Config = what a resource looked like. Ship rules as conformance packs with SSM remediation
  • GuardDuty turns CloudTrail, Flow Logs and DNS into findings, Inspector finds CVEs, Security Hub aggregates everything
  • GuardDuty finding → EventBridge rule (severity >= 7) → Lambda/SNS cuts response time to minutes
  • Detection services are regional — enable them in every Region you use, with a delegated administrator

AWS CloudTrail User Guide — AWS Documentation

Amazon GuardDuty User Guide — AWS Documentation

AWS Config Developer Guide — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Threat Detection & Audit: CloudTrail, Config, GuardDuty, Security Hub | Thuta Learning