Skip to Content
Cloud Engineering Academy
5. Security for Banking & Finance

Security Hub, GuardDuty, Inspector and Detective: what each finds and how findings flow

Understand the AWS detection stack as one system: GuardDuty for threats, Inspector for vulnerabilities, Macie for sensitive data, Security Hub CSPM for posture, the unified AWS Security Hub for correlated risk, and Detective for investigation, then route findings to Harbourline's SOC with a .NET triage function.

intermediate⏱ 2 h 30 min🟡 Low costSCS-C03SAA-C03CLF-C02

Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.SimpleNotificationService 4.1.0.2) · Amazon.Lambda.Core 3.4.0 · AWS CLI v2 · CDK v2 (Amazon.CDK.Lib 2.277.0) · Terraform AWS provider v6 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Say precisely what Amazon GuardDuty, Amazon Inspector, Amazon Macie, AWS Security Hub CSPM, the unified AWS Security Hub and Amazon Detective each detect, and what they don't.
  • Explain the difference between the original service (now Security Hub CSPM, findings in ASFF) and the unified Security Hub that went GA in December 2025 (findings in OCSF, exposure findings, resource-based pricing).
  • Design the multi-account pattern: a delegated administrator in a security tooling account, organisation-wide auto-enable, and cross-Region aggregation.
  • Route findings with EventBridge to a C# triage Lambda that pages the SOC for critical findings, opens tickets for medium ones and ignores sample findings.
  • Run the lab safely: enable the services in one Region during free trials, generate sample findings, then disable everything.

Prerequisites

  • CloudTrail for banks — GuardDuty analyses CloudTrail events; Detective uses them for investigation
  • AWS Config — Security Hub CSPM controls run on service-linked Config rules
  • S3 protection — Macie and S3 data-protection settings
  • Tools: AWS CLI v2 (learn-sandbox profile), .NET 10 SDK, Amazon.Lambda.Tools, optionally CDK or Terraform

Why this matters in banking

At 03:12 on a Sunday, an EC2 instance in Harbourline's batch-reconciliation account starts querying a domain associated with cryptocurrency mining. At 03:40, an IAM role session from that instance calls ListBuckets and GetObject on a bucket of statement PDFs — from an IP address outside AWS. Who notices?

  • If Harbourline only has preventive controls, nobody notices until the cloud bill or a customer complaint.
  • If it has detection services but findings go to a console nobody watches, the evidence exists but nothing happens.
  • If findings flood a shared mailbox (hundreds of low-severity port scans every day), the critical one gets lost.

Regulators expect banks to detect, respond to and report incidents in a timely way — for example the UK's operational-resilience regime, PCI DSS requirements for monitoring and alert response, and UK GDPR breach notification within 72 hours of becoming aware of a reportable personal data breach. Detection services are how you "become aware". This lesson is about turning them into a working pipeline, with routing and ownership — not about switching everything on and hoping.

The idea in plain language

Think of the AWS detection stack as specialists feeding a control room:

SpecialistQuestion it answersTypical finding
GuardDuty"Is someone attacking or abusing my account right now?"Credentials used from an unusual location; EC2 talking to a known command-and-control server; crypto-mining; malware on an EBS volume; a multi-stage attack sequence
Inspector"What known vulnerabilities do my workloads have?"CVE-2024-xxxx in a NuGet package in an ECR image; an EC2 instance missing an OS patch; a Lambda function with a vulnerable dependency
Macie"Where is sensitive data in S3, and is it exposed?"A CSV with names and IBANs in a bucket without encryption; a bucket shared with another account
Security Hub CSPM"Are my resources configured according to best-practice standards?"S3 bucket without Block Public Access; root user without MFA; FSBP / CIS / PCI DSS control failures
Security Hub (unified)"Which of all these problems is the biggest risk right now?"An exposure finding: an internet-reachable EC2 instance with a critical CVE and an over-privileged role that can read customer data
Detective"What exactly happened, and what else is involved?"Not findings — interactive graphs and timelines for investigating a finding

Analogy: GuardDuty is the guard watching live CCTV for intruders. Inspector is the building surveyor listing broken locks. Macie is the auditor who finds customer files left on desks. Security Hub CSPM is the compliance checklist inspector. The unified Security Hub is the control-room supervisor who says "the broken lock on the vault door, next to the unattended files, is our top priority". Detective is the investigator who replays the footage after an alarm.

What problem the AWS services solve

Amazon GuardDuty

  • Foundational sources (no agents, no log configuration needed): CloudTrail management events, VPC Flow Logs and Route 53 Resolver DNS query logs. GuardDuty reads its own copies — you don't need to enable Flow Logs or DNS logging yourself.
  • Protection plans (optional, priced separately): S3 Protection (S3 data events), EKS Protection (audit logs), Runtime Monitoring (agent for EKS, ECS on Fargate and EC2), Malware Protection (EC2/EBS scans and S3 object scanning), RDS Protection (Aurora/RDS login activity), Lambda Protection (network activity), and AI Protection.
  • Extended Threat Detection correlates multiple signals into attack sequence findings with Critical severity. It's on by default when GuardDuty is enabled, at no additional cost ⚠ VERIFY current wording.
  • Severity: Critical 9.0–10.0, High 7.0–8.9, Medium 4.0–6.9, Low 1.0–3.9.
  • Trusted IP lists and threat lists, suppression rules for known-benign patterns, and sample findings for testing.

Amazon Inspector

Continuous vulnerability scanning for EC2 (agent-based through SSM, or agentless snapshots), ECR container images, and Lambda functions (packages and, optionally, code). Findings carry CVSS, an Inspector score, EPSS and exploit-availability data. Covered in depth in Vulnerability management.

Amazon Macie

Discovers sensitive data (names, addresses, financial account numbers, credentials) in S3, through automated sampling and targeted discovery jobs, and evaluates bucket security posture. Covered in S3 protection.

AWS Security Hub CSPM (the original Security Hub)

  • Runs security standards: AWS Foundational Security Best Practices (FSBP), CIS AWS Foundations Benchmark, PCI DSS, NIST SP 800-53, and others. Each standard is a set of controls; most controls use service-linked AWS Config rules, so Config must be recording the relevant resources.
  • Receives findings from GuardDuty, Inspector, Macie, Config, IAM Access Analyzer, Firewall Manager and partner products, normalised in the AWS Security Finding Format (ASFF).
  • Automation rules update or suppress findings; custom actions and EventBridge trigger responses; cross-Region aggregation collects findings in one Region; central configuration manages standards across the organisation.
  • Only sees findings generated after it is enabled, and only in the Regions where it's enabled.

AWS Security Hub (unified, GA 2 December 2025)

  • One place to enable and manage GuardDuty, Inspector, Macie and CSPM across an organisation, with near real-time risk analytics.
  • Exposure findings correlate signals (for example reachability + vulnerability + permissions + sensitive data) and are prioritised by severity.
  • Findings use the Open Cybersecurity Schema Framework (OCSF); the API adds GetFindingsV2 with OCSF-field filters. Trends data is kept for up to a year.
  • Pricing changed: an Essentials plan priced per resource unit (for example one EC2 instance, 12 Lambda functions, 18 ECR images or 125 IAM identities per unit), with add-ons such as Threat Analytics; existing CSPM customers move to resource-based pricing with unlimited checks and finding ingestion. A 30-day trial per account per Region covers the Essentials capabilities. ⚠ VERIFY plan details on the pricing page before budgeting — this changed recently.

Amazon Detective

Builds a behaviour graph from CloudTrail, VPC Flow Logs, GuardDuty findings and EKS audit logs (and more), so you can pivot from a finding to "everything this role did in the last 24 hours, compared with its baseline". It's an investigation tool, not a finding source. It requires GuardDuty to be enabled (AWS has stated at least 48 hours before enabling Detective ⚠ VERIFY), has a 30-day free trial, and is priced per GB ingested (USD 2.00 per GB for the first 1,000 GB per account per Region per month).

Honest limitations:

  • Regional. Every one of these services is enabled per Region. Attackers love unused Regions — enable GuardDuty in all enabled Regions, or disable unused Regions with an SCP.
  • Findings are not incidents. Every service produces false positives and benign positives (your own penetration test). Without triage rules and ownership, findings become noise.
  • No retroactive detection. Turning GuardDuty on today doesn't analyse last month.
  • They don't respond for you. Response is EventBridge, Lambda, SSM Automation and people — see Incident response.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Microsoft Defender for Cloud — CSPM (secure score, recommendations)Security Hub CSPM standards and controls; unified Security HubAWS splits threat detection, vulnerability scanning and posture into separate services that feed one hub
Defender for Servers / Containers (threat detection)GuardDuty (+ Runtime Monitoring, Malware Protection)GuardDuty's foundational detection needs no agent
Defender vulnerability assessment (Qualys/MDVM)Amazon InspectorInspector scans ECR images and Lambda functions as well as servers
Microsoft Purview data classificationAmazon MacieS3 only
Defender attack path analysisSecurity Hub exposure findingsCorrelation across reachability, vulnerabilities and permissions
Microsoft Sentinel investigation graphAmazon DetectiveDetective isn't a SIEM; many banks still export to Sentinel, Splunk or similar
Regulatory compliance dashboard (PCI DSS v4 initiative)Security Hub CSPM PCI DSS standard; Config conformance packsMapping aids only; your QSA decides
Logic Apps / Sentinel playbooksEventBridge rules + Lambda / Step Functions / SSM AutomationEvent-driven, code-first

Architecture

Pattern: AWS Organizations designates the security tooling account as delegated administrator for each service. Auto-enable switches the services on in every new account. Findings from all accounts and Regions aggregate in one Region of the security tooling account. Workload teams can see their own findings but can't disable detectors — back that with an SCP denying guardduty:DeleteDetector, guardduty:DisassociateFromAdministratorAccount, securityhub:DisableSecurityHub and similar.

How a finding flows

Step-by-step implementation

Choose the security tooling account and Regions

Use a dedicated security tooling account (in Control Tower this is usually called Audit). Decide your aggregation Region (Harbourline uses eu-west-2 in production; the lab uses us-east-1). List all Regions enabled in the organisation; any Region you don't use should be blocked by an SCP so attackers can't hide there.

Delegate administration

From the management account, register the security tooling account as delegated administrator for GuardDuty, Security Hub, Inspector, Macie and Detective. Turn on auto-enable for all existing and new member accounts.

Enable GuardDuty everywhere, then add protection plans by need

Foundational detection in every Region. Add S3 Protection for accounts with customer data, Runtime Monitoring for container platforms, Malware Protection for EC2 and S3 upload buckets (customer document uploads), RDS Protection for Aurora.

Enable Security Hub and choose standards

Enable Security Hub CSPM (or the unified Security Hub, which includes CSPM) with FSBP and CIS as the baseline. Enable the PCI DSS standard only in cardholder-data-environment accounts. Configure cross-Region aggregation into the aggregation Region.

Define severity → action routing

Agree with the SOC: Critical and High page the on-call engineer within minutes; Medium creates a ticket with a 3-business-day SLA; Low is reviewed weekly in aggregate. Encode it in EventBridge rules plus the triage Lambda. Write automation rules or suppression rules for known benign patterns — with an owner and expiry date for each.

Integrate with the bank's SIEM

Most banks keep a central SIEM. Export Security Hub findings (EventBridge → Firehose → SIEM, or a partner integration). Keep AWS as the source of truth for status updates so analysts don't work findings twice.

Enable Detective for investigations

Once GuardDuty is established, enable Detective in the security tooling account. Train analysts to pivot from a GuardDuty finding to Detective's entity profile.

Test the pipeline regularly

Generate GuardDuty sample findings monthly and confirm the page reaches on-call. Sample findings are marked as samples — the triage function treats them specially so they don't page anyone at 3 a.m. by mistake, but do test the route.

AWS Console instructions

  1. Console → GuardDuty → Get started → Enable GuardDuty. A 30-day trial starts for this account and Region. Under Settings → Sample findings → Generate sample findings.
  2. Console → GuardDuty → Findings. Filter by Severity: High. Open [SAMPLE] UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS and read the resource, actor and action sections.
  3. Console → Security Hub. Follow the enable flow; choose the standards (in the lab, only FSBP) ⚠ VERIFY the current enablement screens, which changed with the unified Security Hub.
  4. Console → Security Hub → Findings (or CSPM → Findings). Filter Product name = GuardDuty — the sample findings appear here too.
  5. Console → Amazon Inspector → Get started → Activate — choose only Amazon ECR scanning for the lab to keep it small.
  6. Console → Detective — read the prerequisites; in the lab, do the design-only exercise unless GuardDuty has been on for the required period.
  7. Console → EventBridge → Rules → Create rule — pattern AWS services → GuardDuty → GuardDuty Finding, target Lambda function (the triage function below).

AWS CLI

PROFILE=learn-sandbox
REGION=us-east-1

# --- GuardDuty ---
DETECTOR=$(aws guardduty create-detector --enable --finding-publishing-frequency FIFTEEN_MINUTES \
  --tags Project=cea-lab,Lab=m05-l19,Environment=learn,Owner=you \
  --query DetectorId --output text --profile $PROFILE --region $REGION)

# Sample findings (all types if --finding-types is omitted)
aws guardduty create-sample-findings --detector-id $DETECTOR --profile $PROFILE --region $REGION \
  --finding-types "UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS" "CryptoCurrency:EC2/BitcoinTool.B!DNS"

# High and critical findings, newest first
aws guardduty list-findings --detector-id $DETECTOR --profile $PROFILE --region $REGION \
  --finding-criteria '{"Criterion":{"severity":{"Gte":7}}}' \
  --sort-criteria AttributeName=updatedAt,OrderBy=DESC --max-results 10

# Suppression (filter with ARCHIVE action): auto-archive findings from the pen-test IP range
aws guardduty create-filter --detector-id $DETECTOR --name hl-pentest-2026q4 --action ARCHIVE --rank 1 \
  --description "Approved pen test CHG-12345 until 2026-12-15" \
  --finding-criteria '{"Criterion":{"service.action.networkConnectionAction.remoteIpDetails.ipAddressV4":{"Eq":["203.0.113.10"]}}}' \
  --profile $PROFILE --region $REGION

# --- Security Hub CSPM (original API) ---
aws securityhub enable-security-hub --no-enable-default-standards --profile $PROFILE --region $REGION
aws securityhub batch-enable-standards --profile $PROFILE --region $REGION \
  --standards-subscription-requests '[{"StandardsArn":"arn:aws:securityhub:us-east-1::standards/aws-foundational-security-best-practices/v/1.0.0"}]'

# Findings in ASFF from GuardDuty, still active
aws securityhub get-findings --profile $PROFILE --region $REGION --max-items 5 --filters '{
  "ProductName":[{"Value":"GuardDuty","Comparison":"EQUALS"}],
  "RecordState":[{"Value":"ACTIVE","Comparison":"EQUALS"}]}' \
  --query "Findings[].{Title:Title,Sev:Severity.Label,Resource:Resources[0].Id}"

# --- Unified Security Hub (OCSF) ---
# aws securityhub enable-security-hub-v2   # ⚠ VERIFY command availability in your CLI version
# aws securityhub get-findings-v2 --max-results 5   # OCSF findings; filters use OCSF field names

# --- Inspector: ECR only for the lab ---
aws inspector2 enable --resource-types ECR --profile $PROFILE --region $REGION
aws inspector2 list-coverage --profile $PROFILE --region $REGION --max-results 5

# --- Organisation (design reference — run from the management account) ---
# aws guardduty enable-organization-admin-account --admin-account-id 222233334444
# aws securityhub enable-organization-admin-account --admin-account-id 222233334444
# aws inspector2 enable-delegated-admin-account --delegated-admin-account-id 222233334444
# aws macie2 enable-organization-admin-account --admin-account-id 222233334444
# aws detective enable-organization-admin-account --account-id 222233334444

EventBridge patterns you'll use:

pattern-guardduty-high.json
{
  "source": ["aws.guardduty"],
  "detail-type": ["GuardDuty Finding"],
  "detail": { "severity": [{ "numeric": [">=", 4] }] }
}
pattern-securityhub-cspm-critical.json
{
  "source": ["aws.securityhub"],
  "detail-type": ["Security Hub Findings - Imported"],
  "detail": {
    "findings": {
      "Severity": { "Label": ["CRITICAL", "HIGH"] },
      "Workflow": { "Status": ["NEW"] },
      "RecordState": ["ACTIVE"]
    }
  }
}

The unified Security Hub publishes OCSF findings to EventBridge with a different detail type ⚠ VERIFY the exact detail-type string before building rules on it.

Infrastructure as Code

The stacks enable GuardDuty and Security Hub CSPM with FSBP in one Region, create SNS topics, and wire an EventBridge rule to the triage Lambda.

DetectionStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.Events;
using Amazon.CDK.AWS.Events.Targets;
using Amazon.CDK.AWS.GuardDuty;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.Logs;
using Amazon.CDK.AWS.SecurityHub;
using Amazon.CDK.AWS.SNS;
using Constructs;

namespace Harbourline.Security.Infra;

public sealed class DetectionStack : Stack
{
    public DetectionStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
    {
        Tags.SetTag("Project", "cea-lab");
        Tags.SetTag("Lab", "m05-l19");
        Tags.SetTag("Environment", "learn");

        _ = new CfnDetector(this, "GuardDuty", new CfnDetectorProps
        {
            Enable = true,
            FindingPublishingFrequency = "FIFTEEN_MINUTES",
        });

        var hub = new CfnHub(this, "SecurityHub", new CfnHubProps { EnableDefaultStandards = false });
        var fsbp = new CfnStandard(this, "Fsbp", new CfnStandardProps
        {
            StandardsArn = $"arn:aws:securityhub:{Region}::standards/aws-foundational-security-best-practices/v/1.0.0",
        });
        fsbp.AddDependency(hub);

        var page = new Topic(this, "SocPage", new TopicProps { TopicName = "hl-m05-soc-page", EnforceSSL = true });
        var ticket = new Topic(this, "SocTicket", new TopicProps { TopicName = "hl-m05-soc-ticket", EnforceSSL = true });

        var triage = new Function(this, "Triage", new FunctionProps
        {
            Runtime = Runtime.DOTNET_10,   // ⚠ VERIFY the constant name in your CDK version
            Architecture = Architecture.ARM_64,
            Handler = "Harbourline.Security.FindingTriage::Harbourline.Security.FindingTriage.Function::HandleAsync",
            Code = Code.FromAsset("../FindingTriage/bin/Release/net10.0/publish"),
            MemorySize = 512,
            Timeout = Duration.Seconds(15),
            LogRetention = RetentionDays.ONE_WEEK,
            Environment = new Dictionary<string, string>
            {
                ["PAGE_TOPIC_ARN"] = page.TopicArn,
                ["TICKET_TOPIC_ARN"] = ticket.TopicArn,
            },
        });
        page.GrantPublish(triage);
        ticket.GrantPublish(triage);

        _ = new Rule(this, "GuardDutyFindings", new RuleProps
        {
            RuleName = "hl-m05-guardduty-medium-plus",
            EventPattern = new EventPattern
            {
                Source = ["aws.guardduty"],
                DetailType = ["GuardDuty Finding"],
                Detail = new Dictionary<string, object>
                {
                    ["severity"] = new object[] { new Dictionary<string, object> { ["numeric"] = new object[] { ">=", 4 } } },
                },
            },
            Targets = [new LambdaFunction(triage, new LambdaFunctionProps { RetryAttempts = 2 })],
        });
    }
}

Complete code

The triage function receives GuardDuty findings from EventBridge, classifies them, and publishes a short, structured message to the right SNS topic. Design decisions:

  • Sample findings never page. They're routed to the ticket topic with a [TEST] prefix, so monthly pipeline tests are visible but harmless.
  • Severity bands follow GuardDuty's documented ranges.
  • Account context: a small map of account IDs to owning teams and data classification (in production, read it from AWS Organizations tags or a CMDB).
  • No sensitive payloads in notifications: the message carries the finding ID, type, account and resource, and a console link — not the full JSON.
FindingTriage/FindingTriage.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <AssemblyName>Harbourline.Security.FindingTriage</AssemblyName>
    <RootNamespace>Harbourline.Security.FindingTriage</RootNamespace>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.Core" Version="3.4.0" />
    <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="3.0.1" />
    <PackageReference Include="AWSSDK.SimpleNotificationService" Version="4.1.0.2" />
  </ItemGroup>
</Project>
FindingTriage/Triage.cs
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Harbourline.Security.FindingTriage;

// EventBridge envelope; "detail" is the GuardDuty finding.
public sealed record EventBridgeEvent(
    [property: JsonPropertyName("id")] string Id,
    [property: JsonPropertyName("detail-type")] string DetailType,
    [property: JsonPropertyName("source")] string Source,
    [property: JsonPropertyName("account")] string Account,
    [property: JsonPropertyName("region")] string Region,
    [property: JsonPropertyName("detail")] JsonElement Detail);

public enum Route { Page, Ticket, Ignore }

public sealed record AccountContext(string Team, string DataClass);

public sealed record TriageDecision(Route Route, string Band, string Subject, string Message);

public static class Triage
{
    // Fictional account inventory; production reads Organizations tags or the CMDB.
    private static readonly Dictionary<string, AccountContext> Accounts = new()
    {
        ["111122223333"] = new("platform-sandbox", "none"),
        ["444455556666"] = new("payments", "restricted"),
        ["777788889999"] = new("data-platform", "confidential"),
    };

    public static string Band(double severity) => severity switch
    {
        >= 9.0 => "CRITICAL",
        >= 7.0 => "HIGH",
        >= 4.0 => "MEDIUM",
        _ => "LOW",
    };

    public static TriageDecision Decide(EventBridgeEvent evt)
    {
        var d = evt.Detail;
        var type = d.GetProperty("type").GetString() ?? "unknown";
        var severity = d.GetProperty("severity").GetDouble();
        var findingId = d.GetProperty("id").GetString() ?? evt.Id;
        var accountId = d.TryGetProperty("accountId", out var a) ? a.GetString() ?? evt.Account : evt.Account;
        var resourceType = d.TryGetProperty("resource", out var r) && r.TryGetProperty("resourceType", out var rt)
            ? rt.GetString() ?? "unknown" : "unknown";

        var isSample = d.TryGetProperty("service", out var svc)
            && svc.TryGetProperty("additionalInfo", out var info)
            && info.TryGetProperty("sample", out var s)
            && s.ValueKind == JsonValueKind.True;

        var ctx = Accounts.GetValueOrDefault(accountId, new AccountContext("unknown-owner", "unknown"));
        var band = Band(severity);

        // Restricted-data accounts escalate one band: a MEDIUM there is treated like HIGH.
        var effective = ctx.DataClass == "restricted" && band == "MEDIUM" ? "HIGH" : band;

        var route = isSample ? Route.Ticket
            : effective is "CRITICAL" or "HIGH" ? Route.Page
            : effective == "MEDIUM" ? Route.Ticket
            : Route.Ignore;

        var prefix = isSample ? "[TEST] " : "";
        var subject = Truncate($"{prefix}[{effective}] GuardDuty {type} in {accountId}", 100);  // SNS subject limit
        var link = $"https://{evt.Region}.console.aws.amazon.com/guardduty/home?region={evt.Region}#/findings?search=id%3D{findingId}";

        var message = JsonSerializer.Serialize(new
        {
            findingId,
            type,
            severity,
            band,
            effectiveBand = effective,
            accountId,
            owningTeam = ctx.Team,
            dataClass = ctx.DataClass,
            region = evt.Region,
            resourceType,
            sample = isSample,
            consoleLink = link,
            runbook = RunbookFor(type),
        }, new JsonSerializerOptions { WriteIndented = true });

        return new TriageDecision(route, effective, subject, message);
    }

    public static string RunbookFor(string findingType) => findingType switch
    {
        var t when t.StartsWith("UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration", StringComparison.Ordinal)
            => "IR-02 Compromised role credentials",
        var t when t.StartsWith("UnauthorizedAccess:IAMUser", StringComparison.Ordinal)
            => "IR-01 Leaked access key",
        var t when t.StartsWith("CryptoCurrency:", StringComparison.Ordinal) || t.StartsWith("Backdoor:EC2", StringComparison.Ordinal)
            => "IR-03 Compromised EC2 instance",
        var t when t.Contains("S3", StringComparison.Ordinal) || t.StartsWith("Exfiltration:", StringComparison.Ordinal)
            => "IR-04 Suspicious data download",
        var t when t.StartsWith("AttackSequence:", StringComparison.Ordinal)
            => "IR-00 Major incident — attack sequence",
        _ => "IR-99 General triage",
    };

    private static string Truncate(string s, int max) => s.Length <= max ? s : s[..(max - 1)] + "…";
}
FindingTriage/Function.cs
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

[assembly: LambdaSerializer(typeof(DefaultLambdaJsonSerializer))]

namespace Harbourline.Security.FindingTriage;

public sealed class Function
{
    private readonly IAmazonSimpleNotificationService _sns;
    private readonly string _pageTopic;
    private readonly string _ticketTopic;

    public Function() : this(
        new AmazonSimpleNotificationServiceClient(),
        Environment.GetEnvironmentVariable("PAGE_TOPIC_ARN") ?? throw new InvalidOperationException("PAGE_TOPIC_ARN not set"),
        Environment.GetEnvironmentVariable("TICKET_TOPIC_ARN") ?? throw new InvalidOperationException("TICKET_TOPIC_ARN not set")) { }

    public Function(IAmazonSimpleNotificationService sns, string pageTopic, string ticketTopic)
    {
        _sns = sns;
        _pageTopic = pageTopic;
        _ticketTopic = ticketTopic;
    }

    public async Task HandleAsync(EventBridgeEvent evt, ILambdaContext context)
    {
        if (evt.Source != "aws.guardduty")
        {
            context.Logger.LogWarning($"Ignoring event from {evt.Source}");
            return;
        }

        var decision = Triage.Decide(evt);
        context.Logger.LogInformation($"event={evt.Id} route={decision.Route} band={decision.Band}");

        var topic = decision.Route switch
        {
            Route.Page => _pageTopic,
            Route.Ticket => _ticketTopic,
            _ => null,
        };
        if (topic is null) return;

        await _sns.PublishAsync(new PublishRequest
        {
            TopicArn = topic,
            Subject = decision.Subject,
            Message = decision.Message,
            MessageAttributes = new Dictionary<string, MessageAttributeValue>
            {
                ["band"] = new() { DataType = "String", StringValue = decision.Band },
            },
        });
    }
}
FindingTriage.Tests/TriageTests.cs
using System.Text.Json;
using Harbourline.Security.FindingTriage;
using Xunit;

public sealed class TriageTests
{
    private static EventBridgeEvent Event(double severity, string type, string account, bool sample = false) =>
        new("evt-1", "GuardDuty Finding", "aws.guardduty", account, "us-east-1",
            JsonDocument.Parse($$"""
            {
              "id": "f-123", "type": "{{type}}", "severity": {{severity}}, "accountId": "{{account}}",
              "resource": { "resourceType": "AccessKey" },
              "service": { "additionalInfo": { "sample": {{(sample ? "true" : "false")}} } }
            }
            """).RootElement);

    [Theory]
    [InlineData(9.5, "CRITICAL")]
    [InlineData(8.0, "HIGH")]
    [InlineData(5.0, "MEDIUM")]
    [InlineData(2.0, "LOW")]
    public void Bands_follow_guardduty_ranges(double sev, string band) => Assert.Equal(band, Triage.Band(sev));

    [Fact]
    public void High_finding_pages()
    {
        var d = Triage.Decide(Event(8.0, "UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS", "777788889999"));
        Assert.Equal(Route.Page, d.Route);
        Assert.Contains("IR-02", d.Message);
    }

    [Fact]
    public void Medium_in_restricted_account_escalates_to_page() =>
        Assert.Equal(Route.Page, Triage.Decide(Event(5.0, "Recon:IAMUser/MaliciousIPCaller", "444455556666")).Route);

    [Fact]
    public void Sample_never_pages()
    {
        var d = Triage.Decide(Event(9.5, "AttackSequence:IAM/CompromisedCredentials", "444455556666", sample: true));
        Assert.Equal(Route.Ticket, d.Route);
        Assert.StartsWith("[TEST]", d.Subject);
    }
}

Code explained line by line

  1. EventBridgeEvent — EventBridge wraps every service event in the same envelope (id, detail-type, source, account, region, detail). The JSON names contain hyphens, hence JsonPropertyName.
  2. JsonElement Detail — finding schemas are large and evolve; keeping detail as a JsonElement lets the code read only what it needs without brittle classes.
  3. Band uses a C# switch expression over GuardDuty's documented ranges (Critical 9.0–10.0, High 7.0–8.9, Medium 4.0–6.9, Low 1.0–3.9).
  4. isSample reads service.additionalInfo.sample, which GuardDuty sets to true on sample findings. Each TryGetProperty guards against missing fields.
  5. Accounts — an in-code lookup is a deliberate simplification. Production code reads account tags from AWS Organizations (ListTagsForResource) and caches them.
  6. The restricted-data escalation encodes a bank policy: a medium finding in the payments account deserves faster attention than the same finding in a sandbox.
  7. The SNS Subject is truncated to 100 characters, the SNS limit for email subjects.
  8. consoleLink lets the on-call engineer jump straight to the finding; the message avoids copying the full finding JSON (which may include IPs, usernames and resource names) into email.
  9. RunbookFor maps finding families to runbook IDs so the person paged knows which procedure to open. AttackSequence: findings come from Extended Threat Detection.
  10. Function has two constructors: Lambda uses the parameterless one; tests inject a fake SNS client.
  11. evt.Source != "aws.guardduty" — defensive: if someone widens the EventBridge rule, the function doesn't misinterpret other event shapes.
  12. MessageAttributes["band"] allows SNS subscription filter policies, for example a separate SMS subscription that only receives CRITICAL.
  13. The tests build realistic events with raw string literals ($$""") and verify routing rules — including the important "sample never pages" rule.

Security considerations

⚠ Learning shortcut — not for production

The lab enables services in one Region of one account, keeps the triage function in the same account, hard-codes the account inventory and sends notifications by email. In production: delegated administration from a security tooling account, all enabled Regions covered (and unused Regions blocked by SCP), auto-enable for new accounts, SCPs preventing detectors from being disabled, findings exported to the bank's SIEM, an on-call paging tool instead of email, and an owner and expiry for every suppression rule.

  • Suppression is a security decision. Every suppression or archive rule hides evidence. Require a ticket reference, an owner and an expiry; review quarterly.
  • Protect the detectors. SCP-deny guardduty:DeleteDetector, guardduty:UpdateDetector (to stop disabling), guardduty:DisassociateFromAdministratorAccount, securityhub:DisableSecurityHub, inspector2:Disable, macie2:DisableMacie — except for the security automation role.
  • Findings contain personal data. IP addresses, usernames, and Macie samples of sensitive data. Restrict who can read findings and what goes into notifications.
  • Don't auto-remediate everything. Automatically isolating an instance on a medium finding in production can cause an outage. Automate containment only for high-confidence, high-severity findings, and only where the business has agreed.
  • Trust lists can blind you. A trusted IP list stops GuardDuty from generating findings for those IPs. Keep it tiny and justified.

Banking use case

Harbourline's SOC defines the following finding-handling standard (fictional):

SourceScopeRoutingSLA
GuardDuty Critical/HighAll accounts, all RegionsPage on-call via triage LambdaAcknowledge in 15 min, contain in 4 h
GuardDuty MediumRestricted-data accountsPage (escalated)As above
GuardDuty MediumOther accountsTicket3 business days
Inspector Critical with fix available, internet-reachableProductionTicket to owning team7 days (see Vulnerability management)
Security Hub exposure finding CriticalProductionPageSame day
Security Hub CSPM control failures (FSBP, CIS)AllWeekly report per teamNext sprint
Security Hub CSPM PCI DSS standardCDE accounts onlyMonthly report to PCI programmePer remediation plan
Macie sensitive data in non-approved bucketAllTicket to data owner + DPO notified2 business days

Every page has a runbook; every suppression rule is in a register; and the monthly sample-finding test is recorded as evidence that monitoring works. The detection design document notes that none of this makes Harbourline "compliant" — it's one set of controls in the bank's wider monitoring and incident-management framework.

Cost reasoning (fictional, 120 accounts): GuardDuty is driven by CloudTrail event, flow log and DNS volumes plus protection plans; Security Hub by resource units; Inspector by instances, images and functions; Detective by ingested GB. Harbourline ran each trial in a representative account, used the services' own usage pages to project monthly cost, and decided to enable Malware Protection for S3 only on the customer-upload bucket.

Common mistakes

  • Enabling in one Region only → attackers mine crypto in ap-southeast-3 → enable everywhere or block unused Regions.
  • Security Hub CSPM controls all "No data" → AWS Config not recording → enable Config for the resource types the controls need.
  • Turning on every standard → thousands of duplicate failures → baseline with FSBP (+ CIS), add PCI DSS only in scope.
  • Sending all findings to one mailbox → alert fatigue → route by severity and ownership; aggregate lows.
  • Suppressing without expiry → a pen-test exception still hides real attacks a year later → owner, ticket and expiry on every suppression.
  • Forgetting trials end → a surprise bill on day 31 → set budgets and calendar reminders; disable lab services the same day.
  • Treating Detective as a detection service → it's for investigation; it doesn't raise alerts.

Troubleshooting

SymptomLikely causeFix
EventBridge rule never firesRule in a different Region from the finding, or pattern mismatch (severity is a number)Create rules per Region or in the aggregation Region for Security Hub events; use numeric matching
Lambda invoked but nothing publishedMissing sns:Publish permission or wrong topic ARN env varCheck CloudWatch Logs; grant publish on both topics
GuardDuty findings missing in Security HubSecurity Hub not enabled in that Region, or integration disabledEnable Security Hub in the Region; check Integrations
BadRequestException creating a GuardDuty filterInvalid criterion field nameUse field names from the GuardDuty finding schema; test with list-findings first
Detective won't enableGuardDuty not enabled long enough, or data volume above the limitWait, or check the prerequisites page
Duplicate findings for one controlSame control in several standardsTurn on consolidated control findings in Security Hub CSPM ⚠ VERIFY default for new accounts
Inspector shows "Unmanaged EC2 instance"SSM agent not running or no instance profile with SSM permissionsFix SSM, or use agentless scanning

Cost and cleanup

Item (checked 2026-11-18)PriceLab exposure
GuardDuty30-day free trial per account per Region (per protection plan not yet used); then e.g. CloudTrail management events about USD 4.00 per million, flow/DNS logs about USD 1.00 per GB for the first 500 GBFree in trial
Security Hub (unified)30-day trial of Essentials; then per resource unit; add-ons extraFree in trial
Security Hub CSPM30-day free trial; Config items it needs are charged by ConfigCents for Config CIs
Inspector15-day free trial; then e.g. ECR USD 0.09 per initial image scan, USD 0.01 per rescanFree in trial
Detective30-day free trial; then USD 2.00 per GB for the first 1,000 GBDesign-only in the lab
Lambda, EventBridge, SNS emailFree tierFree

Free alternative: if your trials have already been used, do the design exercise and run the TriageTests locally with sample events — no AWS needed.

PROFILE=learn-sandbox
REGION=us-east-1

# CDK / Terraform
cdk destroy --profile $PROFILE        # or: terraform destroy

# CLI-created resources
DETECTOR=$(aws guardduty list-detectors --query "DetectorIds[0]" --output text --profile $PROFILE --region $REGION)
aws guardduty delete-detector --detector-id $DETECTOR --profile $PROFILE --region $REGION
aws securityhub disable-security-hub --profile $PROFILE --region $REGION
aws inspector2 disable --resource-types ECR --profile $PROFILE --region $REGION
aws sns delete-topic --topic-arn arn:aws:sns:us-east-1:111122223333:hl-m05-soc-page --profile $PROFILE --region $REGION
aws sns delete-topic --topic-arn arn:aws:sns:us-east-1:111122223333:hl-m05-soc-ticket --profile $PROFILE --region $REGION

# Confirm everything is off
aws guardduty list-detectors --profile $PROFILE --region $REGION
aws securityhub describe-hub --profile $PROFILE --region $REGION   # expect an error: not subscribed
aws inspector2 batch-get-account-status --profile $PROFILE --region $REGION \
  --query "accounts[].resourceState"
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
  --query "ResourceTagMappingList[].ResourceARN" --profile $PROFILE --region $REGION

Disabling Security Hub CSPM also disables its standards; if you enabled AWS Config only for this lesson, stop the recorder too (see the AWS Config lesson).

Exercises

  • 🟢 Guided: Enable GuardDuty and Security Hub CSPM (FSBP) in us-east-1, deploy the triage stack, subscribe your email to both topics, and generate the two sample findings from the CLI section. Confirm one [TEST] email arrives on the ticket topic for each, and find the same findings in Security Hub. Then tear everything down.
  • 🟡 Challenge: Add a second EventBridge rule for Security Hub Findings - Imported with Severity.Label CRITICAL from Inspector, and extend the triage function to handle the ASFF shape (detail.findings[]), routing internet-reachable critical vulnerabilities to the page topic.
  • 🔴 Live problem: The SOC lead says: "We got 1,400 GuardDuty findings last week; analysts ignore them. Fix it." There's no budget for more staff. Propose a plan for the next four weeks.

Assignment

Write Harbourline's "finding-handling standard" for your portfolio: the services and scope per account type, the routing table with SLAs, the suppression-rule register template, the SCP that protects detectors, the EventBridge patterns, and the triage function with tests. Include a one-page diagram of the multi-account detection architecture.

Solutions

Knowledge check

Interview questions

  • "Walk me through how you'd set up threat detection for 100 AWS accounts." — Delegated admin in a security tooling account; GuardDuty everywhere with auto-enable; protection plans by risk; Security Hub with FSBP/CIS and cross-Region aggregation; Inspector and Macie where relevant; SCPs protecting detectors; EventBridge routing by severity and context; SIEM export; Detective for investigations; monthly pipeline tests.
  • "How do you prevent alert fatigue?" — Tune at source, suppress documented benign patterns with expiry, route by severity and data classification, enrich with ownership and runbooks, prefer correlated findings (attack sequences, exposure findings), and measure on-call load.
  • "GuardDuty says an EC2 role's credentials are being used outside AWS. What do you do?" — Treat as High: identify the role and instance, revoke active sessions for the role, investigate with CloudTrail/Detective what the credentials did, isolate the instance, preserve evidence, and follow the compromised-credentials runbook.
  • "Inspector, Security Hub CSPM and Config overlap — why use all three?" — They answer different questions: vulnerabilities in software (Inspector), configuration against standards (CSPM, built on Config), and custom configuration controls plus history (Config). Security Hub brings them together for prioritisation.

Certification practice

Completion checklist

  • I can say in one sentence what each of GuardDuty, Inspector, Macie, Security Hub CSPM, Security Hub and Detective does
  • I enabled GuardDuty and Security Hub in one Region and generated sample findings
  • My triage Lambda routed findings by severity, account context and sample flag, and its tests pass
  • I can draw the delegated-administrator, multi-Region detection architecture
  • I disabled every service I enabled and confirmed no detectors or tagged resources remain

Key takeaways

  • Detection on AWS is a team of specialists: GuardDuty (threats), Inspector (vulnerabilities), Macie (sensitive data), Security Hub CSPM (posture), the unified Security Hub (correlated risk) and Detective (investigation).
  • Security Hub split in 2025: Security Hub CSPM is the original (ASFF, standards); the unified Security Hub adds exposure findings, OCSF and resource-based pricing. Use the right name.
  • Everything is regional and per account. Use delegated administration, auto-enable, all-Region coverage and SCPs to keep it on.
  • Findings only matter if they reach an owner: route with EventBridge by severity and business context, enrich, suppress with discipline, and test the path monthly.
  • Free trials make labs cheap, but set reminders and disable everything the same day.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page