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.
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
- Security Hub, GuardDuty, Inspector and Detective — where Inspector findings go
- AWS Config — patch compliance as a Config-evaluated control
- Module 3: .NET on AWS — ECR, ECS/Fargate and Lambda deployments
- Tools: AWS CLI v2 (
learn-sandboxprofile), .NET 10 SDK, Docker
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:
- Discover what you run (inventory) and what's vulnerable (scanning).
- Assess each finding's risk in your context.
- Prioritise — fix the most dangerous first.
- Remediate — patch, upgrade a package, rebuild an image, change configuration, or apply a compensating control.
- Verify — the scanner confirms the finding is closed.
- 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 capability | What it scans | Key facts (checked 2026-11-18) |
|---|---|---|
| EC2 — agent-based | OS and application packages via the SSM Agent | Instance must be an SSM managed instance; includes deep inspection of language packages on Linux |
| EC2 — agentless / hybrid | EBS snapshots of instances without SSM | Hybrid mode scans SSM-managed instances with the agent and others agentlessly |
| ECR enhanced scanning | OS and language packages in images | On 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 scanning | Package dependencies in functions and layers | Continuous |
| Lambda code scanning | Your function code (for example hard-coded secrets, injection) | Add-on to standard scanning |
| CIS benchmark assessments | OS configuration against CIS benchmarks on EC2 | Scheduled scan configurations; extra charge |
| Code security | Repositories (SAST, SCA, IaC) | Per repository per scan type |
| SBOM export | CycloneDX or SPDX bill of materials for scanned resources | To S3 |
| Suppression rules | Filters with SUPPRESS action | Findings 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,NOorPARTIAL. - 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 equivalent | What's different |
|---|---|---|
| Defender for Servers vulnerability assessment (MDVM) | Inspector EC2 scanning | Agent-based via SSM, or agentless snapshots; continuous on new CVEs |
| Defender for Containers registry scanning (ACR) | Inspector ECR enhanced scanning | ECR also has free "basic" scanning; enhanced is Inspector |
| Defender for Cloud recommendations for Functions | Inspector Lambda standard + code scanning | Covers dependencies and code |
| Azure Update Manager (patch schedules, assessments) | Systems Manager Patch Manager + maintenance windows | Patch baselines define approval rules; compliance reported to SSM and Config |
| WSUS approval rules | Patch baseline approval rules (ApproveAfterDays, classifications, severities) | Baselines per OS; patch groups via tags or Quick Setup patch policies |
dotnet list package --vulnerable / Dependabot | Inspector Lambda/ECR language-package scanning; pipeline SCA | Use both: fail builds early, monitor continuously after deploy |
| Defender exemption (risk accepted) | Inspector suppression rules + your exception register | AWS 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
- Console → Amazon Inspector → Get started → Activate Inspector. For the lab, under Account management → Scanning, keep only Amazon ECR activated. A 15-day trial starts.
- Console → Amazon ECR → Private registry → Settings → Scanning configuration. Choose Enhanced scanning, add a filter for repository
hl-m05-*, frequency Continuous scanning. - 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.
- Inspector → General settings → ECR re-scan duration — view the push and pull/last-in-use durations.
- 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. - Inspector → Export SBOMs — CycloneDX to an S3 bucket.
- 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 $REGIONThe 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).
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.
<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>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);
}
}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));
}
}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;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
VulnFindingis 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.RiskAcceptanceis an exception record: which vulnerability on which resource, until when, under which reference. (It isn't calledException, which would clash withSystem.Exception.)SlaDaysencodes the policy as data. Changing an SLA is a policy decision, and having it in one place makes the change obvious in code review.RiskBandescalates 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).Evaluatecomputes the due date from first observed, not last observed — otherwise each rescan would restart the clock.- Exceptions match on both resource and vulnerability and must be unexpired; an expired exception counts as no exception, so overdue items reappear automatically.
InspectorComparison = Amazon.Inspector2.StringComparison— the SDK has its ownStringComparisontype that clashes withSystem.StringComparisonunder implicit usings; the alias avoids ambiguity.ActiveFindingsAsyncis anIAsyncEnumerablethat pages throughListFindingsusingNextToken, so memory stays flat even with tens of thousands of findings.page.Findings ?? []— in SDK for .NET v4, collection properties can benullwhen the service returns none; the null-coalescing avoids aNullReferenceException.f.Severity?.Value,f.ExploitAvailable?.Value,f.FixAvailable?.Value— these are SDK constant classes;.Valuegives the string.f.Epss?.Scoreis the EPSS probability.- The
contextcallback supplies business context (exposure, owner) from tags; Inspector's own network-reachability data could feedInternetExposedfor EC2. Program.csprints a summary per band and the worst overdue items, and returns exit code1if any P1/P2 is overdue — ready for a scheduled job that alerts.- 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 band | Definition | Remediation SLA | Who may accept risk |
|---|---|---|---|
| P1 | Critical exploitable or internet-exposed; High exploitable and internet-exposed | 3 days (emergency change) | CISO only, max 14 days |
| P2 | Critical; High with exploit likely (exploit public or EPSS ≥ 10%) | 14 days | CISO, max 30 days |
| P3 | High | 30 days | Head of security engineering, max 90 days |
| P4 | Medium | 90 days | System owner + security, max 180 days |
| P5 | Low / informational | 180 days or next rebuild | System 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
| Symptom | Likely cause | Fix |
|---|---|---|
ECR image shows UNSUPPORTED_OS or no findings | Base 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 CVE | Outside 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 endpoints | Fix SSM; add VPC endpoints; or enable hybrid scanning |
AccessDeniedException on create-sbom-export | Bucket or KMS key policy doesn't allow Inspector | Add the documented bucket and key policy statements |
Patch Install reports Failed on some instances | Package repository unreachable, disk full, or locked package manager | Check AWS-RunPatchBaseline output in Run Command; ensure egress to repositories |
| Instances patched but Inspector still shows the CVE | Reboot pending (kernel), or the scan hasn't run yet | Reboot per baseline; wait for the next scan or trigger one with a change |
| SLA tracker reports thousands overdue on day one | Historic backlog measured from first observed | Agree 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) | Price | Lab exposure |
|---|---|---|
| Inspector trial | 15 days free for new accounts (CIS assessments and on-demand AMI scans excluded) | Free |
| ECR image scanning | USD 0.09 per image initial scan, USD 0.01 per rescan | After the trial: 1 image ≈ USD 0.09 plus rescans |
| EC2 scanning | About USD 1.25 per instance per month (agent-based), USD 1.75 agentless | Not used in the lab |
| Lambda standard / code scanning | About USD 0.30 / USD 0.60 extra per function per month | Not used |
| ECR storage | USD 0.10 per GB-month | ~100 MB image for a day: under USD 0.01 |
| Patch Manager | No additional charge for patching EC2 with AWS-RunPatchBaseline ⚠ VERIFY | Free |
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 $REGIONExercises
- 🟢 Guided: Push the old
aspnet:6.0image to an enhanced-scanning repository, list its critical and high findings with fix available, then rebuild the image onmcr.microsoft.com/dotnet/aspnet:10.0with a new tag and push it. Compare the finding counts for both tags. - 🟡 Challenge: Extend the SLA tracker to read the
ecrImageInUseCountsignal (or anInUsetag) 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
cat > Dockerfile <<'EOF'
FROM mcr.microsoft.com/dotnet/aspnet:10.0
EOF
docker build -t $ACCOUNT.dkr.ecr.$REGION.amazonaws.com/hl-m05-vuln-demo:aspnet10 .
docker push $ACCOUNT.dkr.ecr.$REGION.amazonaws.com/hl-m05-vuln-demo:aspnet10
aws inspector2 list-finding-aggregations --aggregation-type AWS_ECR_CONTAINER --profile learn-sandbox --region us-east-1 \
--aggregation-request '{"awsEcrContainerAggregation":{"repositories":[{"comparison":"EQUALS","value":"hl-m05-vuln-demo"}]}}'Expect many findings (including critical/high) on the out-of-support .NET 6 image and few or none on the current .NET 10 image. Why: out-of-support runtimes and their base OS layers stop receiving fixes, so vulnerabilities accumulate. Staying on supported runtimes and rebuilding regularly removes most container findings without touching application code.
Add bool InUse to VulnFinding, map it from the Inspector data (or a tag), and in RiskBand return "P5" first when !InUse. Test: a CRITICAL exploitable finding with InUse = false → P5.
The risk: "not in use" is a point-in-time signal. An image that isn't running today may be deployed tomorrow (rollback, scaled-to-zero service, monthly batch job), and the in-use data refreshes only periodically. Safer variants: keep the band but pause the SLA clock while not in use, and block deployment of images with open P1/P2 findings in the pipeline.
- 16:30–17:00 — Am I affected? Search Inspector findings by CVE ID across the organisation (
list-findingswithvulnerabilityIdfilter, or Security Hub). Use SBOM exports to find packages that Inspector may not yet have mapped. Check vendor appliances and managed services separately (AWS publishes security bulletins for its services). - 17:00–18:00 — Prioritise: internet-facing services first (load balancers terminating TLS on instances, API containers), then internal. Classify as P1 under the standard.
- Mitigate quickly where patching takes longer: WAF rules or configuration changes if the vendor suggests them; restrict exposure via security groups.
- Fix: rebuild base images with patched OpenSSL; trigger pipelines for all affected services; run Patch Manager
Installvia an emergency maintenance window for EC2 fleets, canary first. - Communicate: an initial statement to the CIO by 17:00 (known affected count, plan), updates every two hours, incident ticket for audit trail.
- Verify: Inspector findings closing; residual list with owners and exceptions; post-incident review on the time to know "are we affected?".
Knowledge check
Answer: Inspector rescans automatically when resources change (new image, new function version, new package on an instance) and when new CVEs are added to its database that affect software you already run — no scheduled scans needed. For ECR images, this applies within the configured re-scan duration.
Answer: EPSS score, exploit availability, fix availability, network reachability/internet exposure, whether the image is in use, and the data classification of the affected account.
Answer: Update the base image or package in source, rebuild the image, push a new immutable tag, and redeploy the service. Inspector closes the finding when the vulnerable image is no longer active or is replaced.
Answer: A patch baseline defines which patches are approved (by classification, severity and an auto-approval delay) for an OS. A maintenance window defines when patching tasks such as AWS-RunPatchBaseline Install run, on which targets, with concurrency and error limits.
Answer: No. Suppression only hides findings from default views. Risk acceptance is a governance decision with an accountable owner, compensating controls and an expiry, recorded in the bank's risk register.
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
A company uses Amazon Inspector to scan its EC2 fleet. Some instances don't have the SSM Agent installed and are reported as unmanaged. The security team wants vulnerability coverage for all instances without installing agents on the unmanaged ones. What should they do?
- A. Enable Amazon GuardDuty Malware Protection
- B. Set the Inspector EC2 scan mode to hybrid so unmanaged instances are scanned agentlessly
- C. Enable ECR enhanced scanning
- D. Run AWS Config rule
ec2-managedinstance-patch-compliance-status-check
Answer: B. Hybrid mode uses agent-based scanning where SSM is available and agentless snapshot-based scanning elsewhere. A looks for malware, not vulnerabilities. C covers container images. D checks patch compliance only for managed instances.
A bank's policy requires critical vulnerabilities to be remediated within 14 days, with documented exceptions. Auditors want evidence of compliance across all accounts. Which approach provides this with the LEAST custom effort?
- A. Monthly manual screenshots of the Inspector console in each account
- B. Inspector delegated administration with findings aggregated centrally, a scheduled report computing time-to-remediate from first-observed dates, and an exception register referenced by named suppression rules
- C. Disable Inspector findings older than 14 days
- D. AWS Trusted Advisor checks
Answer: B. Centralised findings with first-observed dates and a governed exception register produce repeatable evidence. A is manual and not across time. C destroys evidence. D doesn't track vulnerability SLAs.
An operations team must install security patches on 400 Amazon Linux 2023 instances every Sunday at 02:00 London time, patching no more than a quarter of instances at once and stopping if any instance fails. Which solution meets these requirements?
- A. A cron job on each instance running
dnf update - B. A Systems Manager maintenance window with a Run Command task using
AWS-RunPatchBaseline(Operation=Install), MaxConcurrency 25% and MaxErrors 1, targeting instances by tag - C. AWS Config remediation with
AWS-RunPatchBaseline - D. An EventBridge scheduled rule that terminates and replaces instances
Answer: B. Maintenance windows provide scheduling with time zones, targeting, concurrency and error thresholds. A has no central control, concurrency or reporting. C isn't designed for scheduled fleet patching. D might work for immutable fleets, but doesn't meet "install patches" with the stated controls.
Amazon Inspector reports a critical vulnerability in a NuGet package inside a container image running on Amazon ECS. What should the developer do?
- A. Connect to the running container and update the package
- B. Update the package reference, rebuild the image, push a new tag to ECR and update the ECS service
- C. Add an Inspector suppression rule
- D. Restart the ECS tasks
Answer: B. Containers are immutable; fix in source and redeploy. A is lost on the next task start. C hides the problem. D restarts the same vulnerable image.
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.
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.
Incident response on AWS: runbooks, containment, forensics and evidence
Prepare for and run security incidents the way a bank must: a lifecycle and roles agreed in advance, runbooks for a leaked access key and a suspicious data download, isolating a compromised EC2 instance or credential without destroying evidence, preserving evidence with integrity, and knowing when legal and compliance must decide on notification.