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

Vulnerability management: Amazon Inspector, patching SLAs and Patch Manager

Run vulnerability management the way a bank must: continuous Amazon Inspector scanning of EC2, ECR images and Lambda functions, risk-based prioritisation with CVSS, EPSS and reachability, patching SLAs with evidence, Systems Manager Patch Manager, and a governed exception process.

intermediate⏱ 2 h 🟡 Low costSCS-C03SOA-C03DVA-C03

Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.Inspector2 4.1.1) · 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:

  • Explain the vulnerability-management lifecycle (discover, assess, prioritise, remediate, verify, report) and where AWS services fit.
  • Configure Amazon Inspector for EC2 (agent-based and agentless/hybrid), ECR container images (enhanced, continuous scanning, re-scan duration) and Lambda (standard and code scanning), and use suppression rules, CIS assessments and SBOM export.
  • Prioritise findings using severity, the Inspector score, EPSS, exploit availability, fix availability and network reachability — not CVSS alone.
  • Define banking-grade patching SLAs, measure them with a .NET 10 tool that reads Inspector findings, and manage exceptions with risk acceptance.
  • Automate OS patching with Systems Manager Patch Manager, patch baselines and maintenance windows — and know why container and Lambda "patching" means rebuilding and redeploying.

Prerequisites

Why this matters in banking

Most breaches that exploit software flaws use vulnerabilities that were already known and already fixable. In a bank, the story usually goes like this: a scanner reported the issue months ago, the finding sat in a spreadsheet with 9,000 others, the team that owned the server had changed, and the exception that "temporarily" accepted the risk expired without anyone noticing.

Harbourline's problems are typical:

  • Volume. Thousands of findings across EC2, hundreds of container images and Lambda functions. Teams can't fix everything at once, so prioritisation must be defensible.
  • Ownership. A finding without an owner is never fixed. Resources must be tagged to teams.
  • Evidence. Auditors and regulators ask: "What's your patching policy? Show me how you measure it. Show me the overdue items and their risk acceptances." PCI DSS, for example, has explicit requirements on identifying vulnerabilities, ranking them by risk and installing critical patches promptly (version 4.0 requirement 6.3.3 sets one month for critical patches ⚠ VERIFY current wording with your QSA).
  • Containers and serverless. You can't "log in and patch" an immutable image. The fix is a rebuilt image and a redeployment — so vulnerability management is part of the delivery pipeline.

The idea in plain language

Vulnerability management is a loop:

  1. Discover what you run (inventory) and what's vulnerable (scanning).
  2. Assess each finding's risk in your context.
  3. Prioritise — fix the most dangerous first.
  4. Remediate — patch, upgrade a package, rebuild an image, change configuration, or apply a compensating control.
  5. Verify — the scanner confirms the finding is closed.
  6. Report — measure against SLAs; escalate breaches; track exceptions.

Amazon Inspector does continuous discovery and assessment for EC2 instances, ECR images and Lambda functions. "Continuous" means it rescans automatically when you deploy something new and when a new CVE is published that affects software you already run. You don't schedule scans.

Systems Manager Patch Manager does OS-level remediation for EC2 and on-premises servers: it scans for and installs missing patches according to a patch baseline, inside a maintenance window, and reports compliance.

Analogy: Inspector is the building surveyor who walks every floor continuously and re-checks everything whenever a manufacturer issues a safety recall. Patch Manager is the maintenance crew that fixes the boilers during the agreed Sunday-night window. The SLA is the rule that "gas leaks are fixed within a day, dripping taps within a month", and the exception register is the signed note saying why one boiler can't be replaced until next quarter and what extra checks happen in the meantime.

What problem the AWS service solves

Inspector capabilityWhat it scansKey facts (checked 2026-11-18)
EC2 — agent-basedOS and application packages via the SSM AgentInstance must be an SSM managed instance; includes deep inspection of language packages on Linux
EC2 — agentless / hybridEBS snapshots of instances without SSMHybrid mode scans SSM-managed instances with the agent and others agentlessly
ECR enhanced scanningOS and language packages in imagesOn push or continuous; continuous rescans on new CVEs within the re-scan duration (for scanning activated on or after 15 October 2026: 7 days by default, based on last-in-use date)
Lambda standard scanningPackage dependencies in functions and layersContinuous
Lambda code scanningYour function code (for example hard-coded secrets, injection)Add-on to standard scanning
CIS benchmark assessmentsOS configuration against CIS benchmarks on EC2Scheduled scan configurations; extra charge
Code securityRepositories (SAST, SCA, IaC)Per repository per scan type
SBOM exportCycloneDX or SPDX bill of materials for scanned resourcesTo S3
Suppression rulesFilters with SUPPRESS actionFindings aren't deleted, just hidden from default views

Finding enrichment you prioritise with:

  • Severity (CRITICAL, HIGH, MEDIUM, LOW, INFORMATIONAL, UNTRIAGED) and the vendor CVSS score.
  • Inspector score — CVSS adjusted with environmental context (for example network reachability of an EC2 instance).
  • EPSS — the Exploit Prediction Scoring System's probability that a CVE will be exploited in the wild in the next 30 days.
  • Exploit available — whether public exploit code is known.
  • Fix available — YES, NO or PARTIAL.
  • Network reachability findings for EC2 — open paths from the internet to a port.
  • For ECR, image in use data — whether an image is running in ECS or EKS.

Honest limitations:

  • Inspector finds known vulnerabilities in supported OSs and package ecosystems. It doesn't find logic flaws in your code (that's code review, SAST and penetration testing), and unsupported OS versions get limited coverage.
  • Agent-based EC2 scanning depends on a healthy SSM Agent and an instance profile; unmanaged instances silently fall out of coverage unless you use hybrid mode.
  • ECR images outside the re-scan duration stop being rescanned. Old images that still run in production — for example a batch job image pulled once a month — need attention ⚠ check your re-scan settings against how often images are pulled.
  • The 15-day free trial is short; Inspector costs scale with instances, images and functions.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Defender for Servers vulnerability assessment (MDVM)Inspector EC2 scanningAgent-based via SSM, or agentless snapshots; continuous on new CVEs
Defender for Containers registry scanning (ACR)Inspector ECR enhanced scanningECR also has free "basic" scanning; enhanced is Inspector
Defender for Cloud recommendations for FunctionsInspector Lambda standard + code scanningCovers dependencies and code
Azure Update Manager (patch schedules, assessments)Systems Manager Patch Manager + maintenance windowsPatch baselines define approval rules; compliance reported to SSM and Config
WSUS approval rulesPatch baseline approval rules (ApproveAfterDays, classifications, severities)Baselines per OS; patch groups via tags or Quick Setup patch policies
dotnet list package --vulnerable / DependabotInspector Lambda/ECR language-package scanning; pipeline SCAUse both: fail builds early, monitor continuously after deploy
Defender exemption (risk accepted)Inspector suppression rules + your exception registerAWS suppression hides findings; the governance record must live elsewhere

Architecture

The key insight: two remediation paths. Mutable servers are patched in place by Patch Manager. Immutable artefacts (images, functions) are fixed by upgrading dependencies or base images in source, rebuilding and redeploying — Inspector then closes the finding automatically when the vulnerable version is no longer present.

Step-by-step implementation

Write the policy first

Agree SLAs per risk band with security, risk and the business (example in the Banking use case). Define who owns findings (resource tag Owner or Team), the exception process (who may accept risk, for how long, with which compensating controls) and how SLA performance is reported.

Enable Inspector organisation-wide

Delegate administration to the security tooling account, auto-enable EC2, ECR and Lambda scanning for all members, and set EC2 scan mode to hybrid so instances without SSM are still covered agentlessly.

Make every EC2 instance an SSM managed instance

Attach an instance profile with AmazonSSMManagedInstanceCore, make sure the SSM Agent runs and instances can reach SSM endpoints (VPC interface endpoints in private subnets). This enables agent-based scanning and Patch Manager.

Configure ECR

Set the registry to enhanced scanning with continuous scanning for production repositories. Choose re-scan durations that cover your oldest still-running images. Use lifecycle policies to delete images that are no longer deployed so they don't create noise.

Shift left in the pipeline

Fail builds on critical, fixable vulnerabilities before images reach ECR (the pipeline-scanning lesson listed in the module overview covers SCA and container scanning tools). Inspector then watches what's deployed for CVEs published after the build.

Prioritise with context

Use a risk score that combines severity, EPSS, exploit availability, fix availability and exposure (internet reachability, data classification of the account). Critical + exploit available + internet-facing comes first.

Patch servers with Patch Manager

Create patch baselines (or use AWS defaults), group instances by tag, run Scan daily and Install in maintenance windows, reboot as agreed. Patch non-production first, then production a few days later.

Measure, escalate and report

Run the SLA tracker daily; send overdue items to owners and their managers; review exceptions monthly; produce a monthly metrics pack (open by band, mean time to remediate, SLA attainment, exceptions).

AWS Console instructions

  1. Console → Amazon Inspector → Get started → Activate Inspector. For the lab, under Account management → Scanning, keep only Amazon ECR activated. A 15-day trial starts.
  2. Console → Amazon ECR → Private registry → Settings → Scanning configuration. Choose Enhanced scanning, add a filter for repository hl-m05-*, frequency Continuous scanning.
  3. Push an image (see CLI), then Inspector → Findings → By container image. Open a finding and read: CVE ID, severity, Inspector score, EPSS, exploit available, fix available and the fixed-in version.
  4. Inspector → General settings → ECR re-scan duration — view the push and pull/last-in-use durations.
  5. Inspector → Suppression rules → Create rule — e.g. suppress findings for a repository named hl-m05-sandbox-* with severity LOW. Name it with a ticket reference and expiry.
  6. Inspector → Export SBOMs — CycloneDX to an S3 bucket.
  7. Console → Systems Manager → Patch Manager — view the default patch baselines per OS; Create patch policy (Quick Setup) to scan daily and install weekly for instances tagged PatchGroup=hl-m05-batch.

AWS CLI

PROFILE=learn-sandbox
REGION=us-east-1
ACCOUNT=$(aws sts get-caller-identity --query Account --output text --profile $PROFILE)

# --- Inspector: ECR only for the lab ---
aws inspector2 enable --resource-types ECR --profile $PROFILE --region $REGION

# Registry-level enhanced scanning, continuous for hl-m05-* repositories
aws ecr put-registry-scanning-configuration --scan-type ENHANCED --profile $PROFILE --region $REGION \
  --rules '[{"scanFrequency":"CONTINUOUS_SCAN","repositoryFilters":[{"filter":"hl-m05-*","filterType":"WILDCARD"}]}]'

# A repository and a deliberately old image (an out-of-support .NET runtime) to produce findings
aws ecr create-repository --repository-name hl-m05-vuln-demo --image-tag-mutability IMMUTABLE \
  --encryption-configuration encryptionType=AES256 \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m05-l20 Key=Environment,Value=learn Key=Owner,Value=you \
  --profile $PROFILE --region $REGION
aws ecr get-login-password --profile $PROFILE --region $REGION | \
  docker login --username AWS --password-stdin $ACCOUNT.dkr.ecr.$REGION.amazonaws.com
docker pull mcr.microsoft.com/dotnet/aspnet:6.0
docker tag mcr.microsoft.com/dotnet/aspnet:6.0 $ACCOUNT.dkr.ecr.$REGION.amazonaws.com/hl-m05-vuln-demo:aspnet6-eol
docker push $ACCOUNT.dkr.ecr.$REGION.amazonaws.com/hl-m05-vuln-demo:aspnet6-eol

# Coverage: is the image being scanned?
aws inspector2 list-coverage --profile $PROFILE --region $REGION \
  --filter-criteria '{"resourceType":[{"comparison":"EQUALS","value":"AWS_ECR_CONTAINER_IMAGE"}]}' \
  --query "coveredResources[].{Id:resourceId,Status:scanStatus.statusCode,Reason:scanStatus.reason}"

# Active critical/high findings with a fix available
aws inspector2 list-findings --profile $PROFILE --region $REGION --max-results 20 \
  --filter-criteria '{
    "findingStatus":[{"comparison":"EQUALS","value":"ACTIVE"}],
    "severity":[{"comparison":"EQUALS","value":"CRITICAL"},{"comparison":"EQUALS","value":"HIGH"}],
    "fixAvailable":[{"comparison":"EQUALS","value":"YES"}]}' \
  --query "findings[].{Sev:severity,Score:inspectorScore,Epss:epss.score,Exploit:exploitAvailable,Title:title}"

# Counts by severity (useful for dashboards)
aws inspector2 list-finding-aggregations --aggregation-type ACCOUNT --profile $PROFILE --region $REGION

# Suppression rule (hides, does not delete) — always name the ticket and expiry
aws inspector2 create-filter --name "CHG-20417-sandbox-low-until-2026-12-31" --action SUPPRESS \
  --description "Sandbox low findings; owner platform-team; expires 2026-12-31" \
  --filter-criteria '{"ecrImageRepositoryName":[{"comparison":"PREFIX","value":"hl-m05-sandbox"}],
                      "severity":[{"comparison":"EQUALS","value":"LOW"}]}' \
  --profile $PROFILE --region $REGION

# SBOM export (CycloneDX) for the repository to S3
aws inspector2 create-sbom-export --report-format CYCLONEDX_1_4 --profile $PROFILE --region $REGION \
  --resource-filter-criteria '{"ecrRepositoryName":[{"comparison":"EQUALS","value":"hl-m05-vuln-demo"}]}' \
  --s3-destination bucketName=hl-m05-reports-$ACCOUNT,keyPrefix=sbom,kmsKeyArn=arn:aws:kms:us-east-1:$ACCOUNT:key/EXAMPLE

# EC2 scan mode: hybrid (agent where SSM is healthy, agentless otherwise)
aws inspector2 update-configuration --ec2-configuration scanMode=EC2_HYBRID --profile $PROFILE --region $REGION

# --- Patch Manager (EC2) ---
# Which default baseline applies to Amazon Linux 2023?
aws ssm get-default-patch-baseline --operating-system AMAZON_LINUX_2023 --profile $PROFILE --region $REGION
# Scan-only run against tagged instances (no changes made)
aws ssm send-command --document-name AWS-RunPatchBaseline --profile $PROFILE --region $REGION \
  --targets Key=tag:PatchGroup,Values=hl-m05-batch --parameters Operation=Scan \
  --comment "Daily patch compliance scan"
# Compliance summary
aws ssm list-compliance-summaries --filters Key=ComplianceType,Values=Patch,Type=EQUAL --profile $PROFILE --region $REGION

The create-sbom-export call requires an S3 bucket and a KMS key policy that allow Inspector to write ⚠ VERIFY the required key and bucket policy statements in the Inspector user guide before running it.

Infrastructure as Code

The stacks configure ECR enhanced continuous scanning, a suppression filter, and a Patch Manager baseline with a weekly maintenance window for instances tagged PatchGroup=hl-m05-batch. Inspector activation itself is done with the CLI or Organizations auto-enable (the Terraform provider also offers aws_inspector2_enabler).

VulnMgmtStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.ECR;
using Amazon.CDK.AWS.InspectorV2;
using Amazon.CDK.AWS.SSM;
using Constructs;

namespace Harbourline.Security.Infra;

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

        _ = new Repository(this, "Repo", new RepositoryProps
        {
            RepositoryName = "hl-m05-vuln-demo",
            ImageTagMutability = TagMutability.IMMUTABLE,
            RemovalPolicy = RemovalPolicy.DESTROY,
            EmptyOnDelete = true,
            LifecycleRules = [new LifecycleRule { MaxImageCount = 10, Description = "Keep the last 10 images" }],
        });

        _ = new CfnRegistryScanningConfiguration(this, "EnhancedScanning", new CfnRegistryScanningConfigurationProps
        {
            ScanType = "ENHANCED",
            Rules = new[]
            {
                new CfnRegistryScanningConfiguration.ScanningRuleProperty
                {
                    ScanFrequency = "CONTINUOUS_SCAN",
                    RepositoryFilters = new[]
                    {
                        new CfnRegistryScanningConfiguration.RepositoryFilterProperty { Filter = "hl-m05-*", FilterType = "WILDCARD" },
                    },
                },
            },
        });

        _ = new CfnFilter(this, "SandboxLowSuppression", new CfnFilterProps
        {
            Name = "CHG-20417-sandbox-low-until-2026-12-31",
            Description = "Sandbox low findings; owner platform-team; expires 2026-12-31",
            FilterAction = "SUPPRESS",
            FilterCriteria = new CfnFilter.FilterCriteriaProperty
            {
                EcrImageRepositoryName = new[] { new CfnFilter.StringFilterProperty { Comparison = "PREFIX", Value = "hl-m05-sandbox" } },
                Severity = new[] { new CfnFilter.StringFilterProperty { Comparison = "EQUALS", Value = "LOW" } },
            },
        });

        var baseline = new CfnPatchBaseline(this, "Al2023Baseline", new CfnPatchBaselineProps
        {
            Name = "hl-m05-al2023",
            OperatingSystem = "AMAZON_LINUX_2023",
            Description = "Security patches: critical/important after 3 days, others after 14",
            ApprovalRules = new CfnPatchBaseline.RuleGroupProperty
            {
                PatchRules = new[]
                {
                    new CfnPatchBaseline.RuleProperty
                    {
                        ApproveAfterDays = 3,
                        ComplianceLevel = "CRITICAL",
                        PatchFilterGroup = new CfnPatchBaseline.PatchFilterGroupProperty
                        {
                            PatchFilters = new[]
                            {
                                new CfnPatchBaseline.PatchFilterProperty { Key = "CLASSIFICATION", Values = ["Security"] },
                                new CfnPatchBaseline.PatchFilterProperty { Key = "SEVERITY", Values = ["Critical", "Important"] },
                            },
                        },
                    },
                    new CfnPatchBaseline.RuleProperty
                    {
                        ApproveAfterDays = 14,
                        ComplianceLevel = "MEDIUM",
                        PatchFilterGroup = new CfnPatchBaseline.PatchFilterGroupProperty
                        {
                            PatchFilters = new[] { new CfnPatchBaseline.PatchFilterProperty { Key = "CLASSIFICATION", Values = ["Security", "Bugfix"] } },
                        },
                    },
                },
            },
            PatchGroups = ["hl-m05-batch"],
        });

        var window = new CfnMaintenanceWindow(this, "Window", new CfnMaintenanceWindowProps
        {
            Name = "hl-m05-sunday-0200",
            Schedule = "cron(0 2 ? * SUN *)",
            ScheduleTimezone = "Europe/London",
            Duration = 3,
            Cutoff = 1,
            AllowUnassociatedTargets = false,
        });

        var target = new CfnMaintenanceWindowTarget(this, "Targets", new CfnMaintenanceWindowTargetProps
        {
            WindowId = window.Ref,
            ResourceType = "INSTANCE",
            Targets = new[] { new CfnMaintenanceWindowTarget.TargetsProperty { Key = "tag:PatchGroup", Values = ["hl-m05-batch"] } },
        });

        _ = new CfnMaintenanceWindowTask(this, "InstallTask", new CfnMaintenanceWindowTaskProps
        {
            WindowId = window.Ref,
            TaskType = "RUN_COMMAND",
            TaskArn = "AWS-RunPatchBaseline",
            Priority = 1,
            MaxConcurrency = "25%",   // patch a quarter of the fleet at a time
            MaxErrors = "1",          // stop on the first failure
            Targets = new[] { new CfnMaintenanceWindowTask.TargetProperty { Key = "WindowTargetIds", Values = [target.Ref] } },
            TaskInvocationParameters = new CfnMaintenanceWindowTask.TaskInvocationParametersProperty
            {
                MaintenanceWindowRunCommandParameters = new CfnMaintenanceWindowTask.MaintenanceWindowRunCommandParametersProperty
                {
                    Parameters = new Dictionary<string, object>
                    {
                        ["Operation"] = new[] { "Install" },
                        ["RebootOption"] = new[] { "RebootIfNeeded" },
                    },
                },
            },
        });

        _ = baseline;
    }
}

Complete code

A daily SLA tracker for the security team. It pulls active Inspector findings, computes each one's risk band using Harbourline's policy (severity escalated by exploit availability, EPSS and internet exposure), works out the due date from the first-observed time, and reports overdue findings — minus any covered by an approved, unexpired exception.

The policy logic is pure C# with no AWS dependency, so it's unit-testable; the AWS part is a small adapter.

VulnSla/VulnSla.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <RootNamespace>Harbourline.Security.VulnSla</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AWSSDK.Inspector2" Version="4.1.1" />
  </ItemGroup>
</Project>
VulnSla/SlaPolicy.cs
namespace Harbourline.Security.VulnSla;

public sealed record VulnFinding(
    string FindingArn,
    string Title,
    string Severity,          // CRITICAL, HIGH, MEDIUM, LOW, INFORMATIONAL, UNTRIAGED
    DateTimeOffset FirstObservedAt,
    string ResourceId,
    string ResourceType,
    string? VulnerabilityId,  // e.g. CVE-2025-12345
    bool ExploitAvailable,
    double? Epss,             // 0..1
    bool FixAvailable,
    bool InternetExposed,
    string OwnerTeam);

public sealed record RiskAcceptance(string VulnerabilityId, string ResourceId, DateOnly Expires, string Reference);

public sealed record SlaResult(VulnFinding Finding, string RiskBand, DateTimeOffset DueAt, bool Overdue, int DaysOverdue, string? ExceptionRef);

public static class SlaPolicy
{
    // Harbourline (fictional) remediation SLAs in calendar days per risk band.
    public static readonly IReadOnlyDictionary<string, int> SlaDays = new Dictionary<string, int>
    {
        ["P1"] = 3,    // critical and actively exploitable or internet-exposed
        ["P2"] = 14,   // critical, or high with elevated exploit likelihood
        ["P3"] = 30,   // high
        ["P4"] = 90,   // medium
        ["P5"] = 180,  // low / informational
    };

    public static string RiskBand(VulnFinding f)
    {
        var likely = f.ExploitAvailable || (f.Epss ?? 0) >= 0.1;
        return f.Severity switch
        {
            "CRITICAL" when likely || f.InternetExposed => "P1",
            "CRITICAL" => "P2",
            "HIGH" when likely && f.InternetExposed => "P1",
            "HIGH" when likely => "P2",
            "HIGH" => "P3",
            "MEDIUM" => "P4",
            _ => "P5",
        };
    }

    public static SlaResult Evaluate(VulnFinding f, DateTimeOffset now, IEnumerable<RiskAcceptance> exceptions)
    {
        var band = RiskBand(f);
        var due = f.FirstObservedAt.AddDays(SlaDays[band]);
        var exception = exceptions.FirstOrDefault(e =>
            e.ResourceId == f.ResourceId &&
            e.VulnerabilityId == f.VulnerabilityId &&
            e.Expires >= DateOnly.FromDateTime(now.UtcDateTime));

        var overdue = now > due && exception is null;
        var daysOverdue = overdue ? (int)Math.Floor((now - due).TotalDays) : 0;
        return new SlaResult(f, band, due, overdue, daysOverdue, exception?.Reference);
    }
}
VulnSla/InspectorSource.cs
using Amazon.Inspector2;
using Amazon.Inspector2.Model;
using InspectorComparison = Amazon.Inspector2.StringComparison;

namespace Harbourline.Security.VulnSla;

public sealed class InspectorSource(IAmazonInspector2 inspector)
{
    // Reads ACTIVE findings page by page and maps them to the policy model.
    public async IAsyncEnumerable<VulnFinding> ActiveFindingsAsync(
        Func<Resource, (bool InternetExposed, string Owner)> context,
        [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct = default)
    {
        var request = new ListFindingsRequest
        {
            MaxResults = 100,
            FilterCriteria = new FilterCriteria
            {
                FindingStatus = [new StringFilter { Comparison = InspectorComparison.EQUALS, Value = "ACTIVE" }],
            },
        };

        do
        {
            var page = await inspector.ListFindingsAsync(request, ct);
            foreach (var f in page.Findings ?? [])
            {
                var resource = f.Resources?.FirstOrDefault();
                if (resource is null) continue;
                var (exposed, owner) = context(resource);

                yield return new VulnFinding(
                    FindingArn: f.FindingArn,
                    Title: f.Title ?? "(no title)",
                    Severity: f.Severity?.Value ?? "UNTRIAGED",
                    FirstObservedAt: f.FirstObservedAt is { } first ? new DateTimeOffset(first, TimeSpan.Zero) : DateTimeOffset.UtcNow,
                    ResourceId: resource.Id,
                    ResourceType: resource.Type?.Value ?? "UNKNOWN",
                    VulnerabilityId: f.PackageVulnerabilityDetails?.VulnerabilityId,
                    ExploitAvailable: f.ExploitAvailable?.Value == "YES",
                    Epss: f.Epss?.Score,
                    FixAvailable: f.FixAvailable?.Value == "YES",
                    InternetExposed: exposed,
                    OwnerTeam: owner);
            }
            request.NextToken = page.NextToken;
        } while (!string.IsNullOrEmpty(request.NextToken));
    }
}
VulnSla/Program.cs
using Amazon.Inspector2;
using Harbourline.Security.VulnSla;

// Approved exceptions would come from the risk register; two fictional examples here.
List<RiskAcceptance> exceptions =
[
    new("CVE-2025-00001", "i-0abc123def4567890", new DateOnly(2026, 12, 31), "RISK-0412"),
];

// Context: in production, look up resource tags (Owner, Exposure) or the CMDB.
(bool, string) Context(Amazon.Inspector2.Model.Resource r) =>
    (r.Tags?.GetValueOrDefault("Exposure") == "internet", r.Tags?.GetValueOrDefault("Owner") ?? "unassigned");

var now = DateTimeOffset.UtcNow;
var source = new InspectorSource(new AmazonInspector2Client());
var results = new List<SlaResult>();

await foreach (var f in source.ActiveFindingsAsync(Context))
    results.Add(SlaPolicy.Evaluate(f, now, exceptions));

Console.WriteLine($"Active findings: {results.Count}");
foreach (var g in results.GroupBy(r => r.RiskBand).OrderBy(g => g.Key))
    Console.WriteLine($"  {g.Key}: {g.Count()} open, {g.Count(r => r.Overdue)} overdue, {g.Count(r => r.ExceptionRef is not null)} under exception");

Console.WriteLine("\nOverdue (worst first):");
foreach (var r in results.Where(r => r.Overdue).OrderBy(r => r.RiskBand).ThenByDescending(r => r.DaysOverdue).Take(25))
    Console.WriteLine($"  {r.RiskBand} +{r.DaysOverdue,3}d  {r.Finding.OwnerTeam,-16} {r.Finding.VulnerabilityId,-16} {r.Finding.ResourceId}");

return results.Any(r => r.Overdue && r.RiskBand is "P1" or "P2") ? 1 : 0;
VulnSla.Tests/SlaPolicyTests.cs
using Harbourline.Security.VulnSla;
using Xunit;
using Ex = Harbourline.Security.VulnSla.RiskAcceptance;

public sealed class SlaPolicyTests
{
    private static VulnFinding F(string sev, bool exploit = false, double? epss = null, bool internet = false, int ageDays = 0) =>
        new("arn:f", "t", sev, new DateTimeOffset(2026, 11, 1, 0, 0, 0, TimeSpan.Zero).AddDays(-ageDays),
            "i-0abc", "AWS_EC2_INSTANCE", "CVE-2025-00001", exploit, epss, true, internet, "payments");

    [Theory]
    [InlineData("CRITICAL", true, false, "P1")]
    [InlineData("CRITICAL", false, true, "P1")]
    [InlineData("CRITICAL", false, false, "P2")]
    [InlineData("HIGH", true, true, "P1")]
    [InlineData("HIGH", true, false, "P2")]
    [InlineData("HIGH", false, true, "P3")]
    [InlineData("MEDIUM", true, true, "P4")]
    [InlineData("LOW", false, false, "P5")]
    public void Bands(string sev, bool exploit, bool internet, string band) =>
        Assert.Equal(band, SlaPolicy.RiskBand(F(sev, exploit, internet: internet)));

    [Fact]
    public void High_epss_counts_as_likely() => Assert.Equal("P2", SlaPolicy.RiskBand(F("HIGH", epss: 0.35)));

    [Fact]
    public void Overdue_after_sla()
    {
        var now = new DateTimeOffset(2026, 11, 1, 0, 0, 0, TimeSpan.Zero);
        var r = SlaPolicy.Evaluate(F("CRITICAL", ageDays: 20), now, []);   // P2 = 14 days
        Assert.True(r.Overdue);
        Assert.Equal(6, r.DaysOverdue);
    }

    [Fact]
    public void Valid_exception_suppresses_breach_but_expired_one_does_not()
    {
        var now = new DateTimeOffset(2026, 11, 1, 0, 0, 0, TimeSpan.Zero);
        var f = F("CRITICAL", ageDays: 20);
        Assert.False(SlaPolicy.Evaluate(f, now, [new Ex("CVE-2025-00001", "i-0abc", new DateOnly(2026, 12, 31), "RISK-1")]).Overdue);
        Assert.True(SlaPolicy.Evaluate(f, now, [new Ex("CVE-2025-00001", "i-0abc", new DateOnly(2026, 10, 1), "RISK-1")]).Overdue);
    }
}

Code explained line by line

  1. VulnFinding is the tool's own model. Mapping AWS types into it keeps policy code independent of the SDK and lets you feed findings from other scanners later.
  2. RiskAcceptance is an exception record: which vulnerability on which resource, until when, under which reference. (It isn't called Exception, which would clash with System.Exception.)
  3. SlaDays encodes the policy as data. Changing an SLA is a policy decision, and having it in one place makes the change obvious in code review.
  4. RiskBand escalates by likelihood (public exploit or EPSS ≥ 10%) and exposure (internet-facing). A critical CVE that is exploitable or exposed is P1 (3 days); without either, P2 (14 days).
  5. Evaluate computes the due date from first observed, not last observed — otherwise each rescan would restart the clock.
  6. Exceptions match on both resource and vulnerability and must be unexpired; an expired exception counts as no exception, so overdue items reappear automatically.
  7. InspectorComparison = Amazon.Inspector2.StringComparison — the SDK has its own StringComparison type that clashes with System.StringComparison under implicit usings; the alias avoids ambiguity.
  8. ActiveFindingsAsync is an IAsyncEnumerable that pages through ListFindings using NextToken, so memory stays flat even with tens of thousands of findings.
  9. page.Findings ?? [] — in SDK for .NET v4, collection properties can be null when the service returns none; the null-coalescing avoids a NullReferenceException.
  10. f.Severity?.Value, f.ExploitAvailable?.Value, f.FixAvailable?.Value — these are SDK constant classes; .Value gives the string. f.Epss?.Score is the EPSS probability.
  11. The context callback supplies business context (exposure, owner) from tags; Inspector's own network-reachability data could feed InternetExposed for EC2.
  12. Program.cs prints a summary per band and the worst overdue items, and returns exit code 1 if any P1/P2 is overdue — ready for a scheduled job that alerts.
  13. The tests cover every band, the EPSS threshold, the overdue maths and exception expiry — the parts auditors and engineers will argue about.

Security considerations

⚠ Learning shortcut — not for production

The lab scans one repository in one account, pushes a deliberately vulnerable image, keeps exceptions in code, and reads owner and exposure from tags without validation. In production: Inspector delegated administration for all accounts and Regions, an exception register with approvals (risk owner, security, expiry, compensating controls), owner tags enforced by SCP or tag policies, findings routed through Security Hub, and SLA reports reviewed in the risk committee.

  • Never deploy the demo image. It's deliberately out of support. Delete it after the lab.
  • Suppression ≠ acceptance. A suppression rule only hides findings in Inspector. Risk acceptance is a governance decision recorded with an accountable owner and an expiry. Every suppression rule should reference an exception or a documented false positive.
  • Patching can break things. Use canary groups, maintenance windows, MaxConcurrency/MaxErrors, and pre/post health checks. A failed patch on a payments server is an operational-resilience event too.
  • Emergency patching path. For actively exploited critical vulnerabilities, define an expedited change process that can bypass the normal weekly window — with post-implementation review.
  • SBOMs reveal your attack surface. They are useful for incident response ("are we affected by CVE-X?") but should be access-controlled.
  • Scanner roles have broad read access. Agentless scanning uses snapshots of your volumes; treat the service-linked role and the scanning configuration as sensitive.

Banking use case

Harbourline's (fictional) vulnerability management standard:

Risk bandDefinitionRemediation SLAWho may accept risk
P1Critical exploitable or internet-exposed; High exploitable and internet-exposed3 days (emergency change)CISO only, max 14 days
P2Critical; High with exploit likely (exploit public or EPSS ≥ 10%)14 daysCISO, max 30 days
P3High30 daysHead of security engineering, max 90 days
P4Medium90 daysSystem owner + security, max 180 days
P5Low / informational180 days or next rebuildSystem owner

Monthly metrics pack for the technology risk committee: open findings per band and per team; SLA attainment (percentage closed within SLA); mean time to remediate per band; overdue items over 30 days; number of active exceptions and those expiring in the next 30 days.

Worked example: CVE-2025-xxxxx (fictional), a remote-code-execution flaw in a JSON library, appears in Inspector for 14 container images and 3 Lambda functions on a Tuesday. EPSS is 0.62 and a public exploit exists. Two images run internet-facing APIs → P1; the rest → P2. The platform team bumps the package in the shared base image, the pipeline rebuilds and redeploys all 14 services by Thursday, Inspector closes the findings automatically, and the SLA report shows every P1 closed in 2 days. One legacy batch image can't be rebuilt until a vendor update arrives; the CISO accepts the risk for 14 days, with the compensating control that the batch job's security group has no inbound rules and egress is limited to one endpoint.

Common mistakes

  • Prioritising by CVSS alone → teams drown in "critical" findings that aren't exploitable in context → combine severity with EPSS, exploit availability, exposure and data classification.
  • Patching containers in place → changes lost on the next deploy → fix the Dockerfile or base image, rebuild and redeploy.
  • EC2 instances outside SSM → silent coverage gaps → use hybrid scan mode and alert on unmanaged instances.
  • Suppression rules with no owner or expiry → permanent blind spots → name rules with references and review dates.
  • Measuring from "last observed" → the SLA clock never runs → measure from first observed.
  • Leaving old images in ECR → noise from images nobody runs → lifecycle policies and "image in use" filters.
  • Ignoring Lambda → serverless dependencies age quietly → enable Lambda standard scanning and rebuild functions regularly.

Troubleshooting

SymptomLikely causeFix
ECR image shows UNSUPPORTED_OS or no findingsBase OS not supported, or media type unsupported (e.g. manifest list)Check supported OSs and media types; push single-platform images
Image not rescanned for a new CVEOutside re-scan duration (push or last-in-use date)Increase re-scan duration or redeploy/pull the image
EC2 instance shows "Unmanaged EC2 instance"SSM Agent stopped, no instance profile, or no route to SSM endpointsFix SSM; add VPC endpoints; or enable hybrid scanning
AccessDeniedException on create-sbom-exportBucket or KMS key policy doesn't allow InspectorAdd the documented bucket and key policy statements
Patch Install reports Failed on some instancesPackage repository unreachable, disk full, or locked package managerCheck AWS-RunPatchBaseline output in Run Command; ensure egress to repositories
Instances patched but Inspector still shows the CVEReboot pending (kernel), or the scan hasn't run yetReboot per baseline; wait for the next scan or trigger one with a change
SLA tracker reports thousands overdue on day oneHistoric backlog measured from first observedAgree a baseline date and a backlog-reduction plan with risk; don't hide the backlog

Cost and cleanup

Item (checked 2026-11-18, us-east-1)PriceLab exposure
Inspector trial15 days free for new accounts (CIS assessments and on-demand AMI scans excluded)Free
ECR image scanningUSD 0.09 per image initial scan, USD 0.01 per rescanAfter the trial: 1 image ≈ USD 0.09 plus rescans
EC2 scanningAbout USD 1.25 per instance per month (agent-based), USD 1.75 agentlessNot used in the lab
Lambda standard / code scanningAbout USD 0.30 / USD 0.60 extra per function per monthNot used
ECR storageUSD 0.10 per GB-month~100 MB image for a day: under USD 0.01
Patch ManagerNo additional charge for patching EC2 with AWS-RunPatchBaseline ⚠ VERIFYFree

Free alternative: skip Inspector and run an open-source scanner locally on the same image (for example docker run --rm aquasec/trivy image mcr.microsoft.com/dotnet/aspnet:6.0), save its JSON output, and adapt the SLA tracker's VulnFinding mapping to read it.

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

aws ecr delete-repository --repository-name hl-m05-vuln-demo --force --profile $PROFILE --region $REGION
# Back to basic scanning for the registry
aws ecr put-registry-scanning-configuration --scan-type BASIC --rules '[]' --profile $PROFILE --region $REGION
# Delete the suppression rule
FILTER_ARN=$(aws inspector2 list-filters --profile $PROFILE --region $REGION \
  --query "filters[?name=='CHG-20417-sandbox-low-until-2026-12-31'].arn | [0]" --output text)
aws inspector2 delete-filter --arn $FILTER_ARN --profile $PROFILE --region $REGION
# Deactivate Inspector scanning types you enabled
aws inspector2 disable --resource-types ECR --profile $PROFILE --region $REGION

# Or: cdk destroy / terraform destroy

docker image rm mcr.microsoft.com/dotnet/aspnet:6.0

# Confirm
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

Exercises

  • 🟢 Guided: Push the old aspnet:6.0 image to an enhanced-scanning repository, list its critical and high findings with fix available, then rebuild the image on mcr.microsoft.com/dotnet/aspnet:10.0 with a new tag and push it. Compare the finding counts for both tags.
  • 🟡 Challenge: Extend the SLA tracker to read the ecrImageInUseCount signal (or an InUse tag) and drop images that aren't running anywhere to the P5 band, with a test. Explain in two sentences the risk of doing this.
  • 🔴 Live problem: A widely reported critical vulnerability in OpenSSL is announced on Friday at 16:00 with exploitation in the wild. The CIO asks at 16:30: "Are we affected, where, and when will it be fixed?" Plan your next four hours.

Assignment

Publish a "vulnerability management standard" for Harbourline in your portfolio: risk bands, SLAs, exception rules, metrics; the patch baseline and maintenance window as IaC; the SLA tracker with tests; and a one-page process diagram from finding to closure, including the emergency path.

Solutions

Knowledge check

Interview questions

  • "How do you prioritise thousands of vulnerability findings?" — Combine severity with exploit likelihood (EPSS, known exploits), exposure (internet-facing, reachable), asset criticality and data classification; define bands with SLAs; fix by root cause (base images, shared libraries) rather than one finding at a time.
  • "What's different about vulnerability management for containers and serverless?" — Immutability: you rebuild and redeploy rather than patch in place; scanning shifts left into the pipeline plus continuous registry scanning; lifecycle policies remove unused images; base-image ownership is key.
  • "How would you evidence patch compliance to an auditor?" — The written standard; Patch Manager compliance and Inspector findings over time; SLA reports with attainment metrics; exception register with approvals; samples tracing a finding from detection to closure.
  • "An application team says they can't patch for three months. What do you do?" — Assess risk; agree compensating controls (network restriction, WAF virtual patching, monitoring); formal risk acceptance by the right authority with expiry; track the remediation plan; escalate if it slips.

Certification practice

Completion checklist

  • I can describe the vulnerability-management lifecycle and Inspector's coverage for EC2, ECR and Lambda
  • I scanned an image, read CVSS, Inspector score, EPSS and fix availability, and fixed it by rebuilding
  • I wrote risk bands with SLAs and the SLA tracker's tests pass
  • I can explain patch baselines, maintenance windows and safe rollout settings
  • I deleted the repository, suppression rule and Inspector configuration, and confirmed nothing tagged remains

Key takeaways

  • Vulnerability management is a governed loop — discover, assess, prioritise, remediate, verify, report — not a scan.
  • Amazon Inspector scans EC2 (agent, agentless or hybrid), ECR images and Lambda continuously, rescanning when new CVEs appear.
  • Prioritise with context: severity plus EPSS, exploit availability, fix availability, exposure and data classification. Measure SLAs from first observed.
  • Servers are patched with Patch Manager baselines and maintenance windows; containers and functions are fixed by rebuilding and redeploying.
  • Suppression hides; only a recorded, expiring risk acceptance accepts risk. Evidence is policy + metrics + exceptions.

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