Segmentation, private endpoints and egress filtering
Layer security groups, NACLs, VPC endpoint policies, DNS Firewall and AWS Network Firewall so a banking workload can reach only the services and partners it genuinely needs.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.EC2 4.1.x) · 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-17.
Learning objectives
By the end of this lesson you can:
- Explain the difference between security groups and network ACLs, and use security-group referencing to build tiers that never mention an IP address.
- Design segmentation at three levels: subnet tiers, VPCs and AWS accounts, and say which level a regulator or QSA will care about.
- Keep AWS API traffic off the internet with gateway and interface VPC endpoints, and restrict what flows through them with endpoint policies.
- Build an egress allow-list so the Payments Service can reach only its sanctions-screening partner, using Route 53 Resolver DNS Firewall and AWS Network Firewall domain-list rules.
- Describe a centralised inspection VPC behind AWS Transit Gateway, and estimate what it costs.
- Write a .NET
DelegatingHandlerthat refuses to call any host outside an allow-list, as defence in depth inside the application.
Prerequisites
- Module 2: Networking — VPCs, subnets, route tables, NAT gateways, security groups
- IAM in depth — policy grammar (endpoint policies use the same JSON)
- Boundaries, SCPs, RCPs and resource policies — helpful for the
aws:SourceVpcedata-perimeter pattern - Tools: AWS CLI v2 with the
learn-sandboxSSO profile, .NET 10 SDK, optionally Terraform 1.14 or the CDK CLI
Why this matters in banking
In 2019 a widely reported breach at a large US bank began with a server-side request forgery against a web application firewall that ran on EC2. The attacker tricked the server into calling the instance metadata service, collected the role credentials, and then used those credentials to list and copy S3 buckets. Every step of that chain is a network and identity segmentation failure: the server could talk to things it never needed to talk to, and the credentials worked from anywhere.
Harbourline Bank's Payments Service needs to talk to exactly four things: its database, AWS KMS and Secrets Manager, its message queues, and one sanctions-screening partner at api.sanctions-partner.example.com. If malware or a compromised NuGet package lands in that container, the network should make exfiltration hard: no route to arbitrary internet hosts, no DNS resolution of attacker domains, and AWS API calls that only work against Harbourline's own buckets. That is what this lesson builds.
Card-payment environments add a second motive. Under PCI DSS, every system that can talk to the cardholder data environment (CDE) can be pulled into audit scope. Good segmentation is how banks keep the CDE small. Your QSA (Qualified Security Assessor) decides whether segmentation is adequate — AWS cannot make that decision for you, and neither can this lesson. See PCI DSS on AWS.
The idea in plain language
A VPC is a private network that you own inside AWS. By default, nothing gets in from the internet, but anything inside can usually get out if you give it a NAT gateway. Most teams worry about the first half and forget the second.
You control traffic with several layers, each answering a different question:
| Layer | Question it answers | Where it lives |
|---|---|---|
| Security group (SG) | "Which sources may open a connection to this network interface, on which port?" | Attached to each network interface (ENI); stateful |
| Network ACL (NACL) | "Which packets may cross this subnet boundary at all?" | Attached to a subnet; stateless |
| Route table | "Where can packets from this subnet go next?" | Per subnet |
| VPC endpoint + endpoint policy | "Which AWS API calls, on which resources, may flow through this private door?" | In the VPC, per AWS service |
| DNS Firewall | "Which domain names may workloads even resolve?" | Route 53 Resolver, per VPC |
| AWS Network Firewall | "Which outbound flows, to which domains or IPs, using which protocols, may leave?" | Dedicated firewall subnets in the traffic path |
| Application allow-list | "Is this code allowed to call that host?" | Inside your .NET code |
Egress filtering means controlling what leaves. Segmentation means splitting the estate into zones so a compromise in one zone does not automatically reach another.
Analogy: Think of a bank branch. Security groups are the locks on each office door (staff badge required, only for that room). NACLs are the barriers at each corridor. Route tables are the floor plan — some corridors simply do not lead to the street. VPC endpoints are the internal pneumatic tubes to head office: valuables travel without ever going outside. DNS Firewall is the receptionist who refuses to look up phone numbers for anyone not on the approved list. Network Firewall is the guarded exit where every parcel leaving the building is checked against the list of approved couriers.
What problem each AWS service solves
| Service | Problem it solves | Limitations and sharp edges |
|---|---|---|
| Security groups | Fine-grained, stateful allow rules per ENI; can reference other SGs so tiers need no IPs | Allow-only (no deny rules); outbound defaults to "all traffic"; quota on rules per SG and SGs per ENI |
| Network ACLs | Coarse, stateless subnet-wide allow and deny rules; useful as a blunt backstop | Stateless — you must allow return traffic on ephemeral ports; numbered rule order; easy to break things |
| Gateway VPC endpoints | Private route to S3 and DynamoDB with no NAT; free | Only S3 and DynamoDB; work only from inside the VPC (not over VPN/peering from on-premises) |
| Interface VPC endpoints (PrivateLink) | Private ENIs for most AWS APIs (KMS, Secrets Manager, SQS, STS, ECR …) and for partner services | Charged per AZ per hour plus per GB; one endpoint per service per VPC unless centralised |
| Endpoint policies | Limit which principals and which resources can be used through an endpoint (data perimeter) | Do not grant permissions; the identity policy must still allow the call |
| Route 53 Resolver DNS Firewall | Block or allow DNS lookups by domain list; catches DNS tunnelling and C2 domains | Only filters queries that use the Route 53 Resolver; hard-coded IPs bypass it |
| AWS Network Firewall | Managed, stateful firewall with Suricata-compatible rules, domain allow-lists (TLS SNI / HTTP Host) and optional TLS inspection | About USD 0.395 per endpoint-hour per AZ plus USD 0.065 per GB in us-east-1; needs careful routing; SNI can be spoofed unless you add resolved-IP validation |
| NAT gateway | Lets private subnets start outbound IPv4 connections | Per-hour and per-GB charges; no filtering at all — it is not a firewall |
The NAT gateway trap
A NAT gateway translates addresses; it does not inspect anything. "Private subnet + NAT gateway" means "can reach the entire internet". Banks that rely on NAT alone for "egress control" usually discover this during a penetration test.
What AWS does and what you do
Security of the cloud: AWS runs the physical network, isolates VPCs from each other, operates the Network Firewall and DNS Firewall fleets, patches them, and scales them. Security in the cloud: you choose the rules, the routes, the domain lists, the logging, and you prove to your auditors that the rules match your policy. A Network Firewall with a rule allowing 0.0.0.0/0 is perfectly "managed" and perfectly useless.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Network Security Group (NSG) on a subnet or NIC | Security group (ENI) + network ACL (subnet) | AWS splits the two: SGs are stateful and allow-only; NACLs are stateless and support deny |
| Application Security Groups (ASGs) | Security-group referencing (source = sg-…) | Same idea: rules refer to a group, not IP ranges |
| Azure Firewall (FQDN rules, threat intel) | AWS Network Firewall (domain lists, Suricata rules, managed threat signatures) | Network Firewall uses Suricata syntax; routing must be done by you with route tables |
| Azure DNS Private Resolver + DNS security policy | Route 53 Resolver DNS Firewall | DNS Firewall attaches rule groups directly to VPCs |
| Private Endpoint / Private Link | Interface VPC endpoint / AWS PrivateLink | Similar; AWS adds endpoint policies that limit API calls through the endpoint |
| Service Endpoints (Storage, SQL) | Gateway VPC endpoints (S3, DynamoDB) | Free, route-table based |
| Hub-and-spoke VNet with Azure Firewall in the hub | Inspection VPC + Transit Gateway with appliance mode | Very similar pattern; TGW route tables replace UDRs |
| Azure Firewall Manager | AWS Firewall Manager | Central policy across accounts; charged per policy per Region |
Architecture
Segmented workload VPC for the Payments Service
Centralised inspection with Transit Gateway
Many banks run one inspection VPC in a network account and route every spoke's internet-bound traffic through it. This keeps the firewall rules, logs and NAT gateways in one place that the network security team owns — a segregation-of-duties win.
Appliance mode on the Transit Gateway attachment keeps both directions of a flow in the same Availability Zone, so the stateful firewall sees the whole conversation. Without it, return traffic can arrive at a different firewall endpoint, which drops it as "not part of a known flow".
Security-boundary view
| Zone | Trust level | Who can change it | Controls applied |
|---|---|---|---|
| Internet | Untrusted | Nobody | WAF, Shield, TLS |
| Public tier | Low | Platform team via pipeline | SG allows 443 from internet only to ALB |
| App tier | Medium | App team via pipeline | SG referencing, no IGW route, endpoint policies |
| Data tier | High | DBA + platform, change-controlled | Isolated subnets, SG from app-sg only, KMS encryption |
| Inspection VPC | Control plane | Network security team only (separate account) | Firewall rules, DNS Firewall, flow logs to log archive |
Step-by-step implementation
Replace IP-based rules with security-group referencing
A rule that says "allow 5432 from sg-app" means "allow from any ENI that carries the app security group". When the Payments Service scales from 2 to 40 tasks, nobody edits a rule. When someone launches a debugging instance without sg-app, it cannot reach the database. This is the AWS equivalent of Azure Application Security Groups.
Also remove the default "all outbound" rule from SGs in the data tier. A database should never initiate connections to the internet.
Use NACLs as a coarse backstop, not the main control
Put a deny-by-default NACL on the isolated data subnets that allows only the app subnet CIDRs on 5432 inbound and ephemeral ports (1024–65535) outbound back to them. Keep NACLs simple; their job is to catch an SG mistake, not to express your whole policy.
Add VPC endpoints so AWS API calls never need the internet
Create a gateway endpoint for S3 and interface endpoints for KMS, Secrets Manager, SQS, STS and CloudWatch Logs. Enable private DNS on interface endpoints so the SDK's normal hostnames (for example kms.us-east-1.amazonaws.com) resolve to the endpoint's private IPs. Your .NET code does not change at all.
Attach endpoint policies (the data perimeter)
An endpoint policy says what can flow through the door. For S3, restrict to Harbourline's own buckets so stolen credentials from another account cannot be used through your endpoint to upload your data to an attacker bucket. Pair it with a bucket policy that requires aws:SourceVpce so your buckets accept data-plane calls only through your endpoint.
Filter DNS with Route 53 Resolver DNS Firewall
Create a domain list with only the names the workload needs (api.sanctions-partner.example.com, plus AWS service names), an ALLOW rule for that list, and a final BLOCK rule for * (everything else). This "walled garden" stops DNS-based exfiltration and calls to command-and-control domains. Add the AWS-managed threat lists as an extra BLOCK rule in any VPC that does not use a walled garden.
Inspect and allow-list egress with AWS Network Firewall
In the inspection VPC, create a stateful domain list rule group of type ALLOWLIST with target types TLS_SNI and HTTP_HOST. Because the firewall reads the hostname from the TLS ClientHello (SNI), it can allow-list HTTPS destinations without decrypting the traffic. Add AWS_ROUTE_53_RESOLVED_DOMAIN as well so a client cannot lie in the SNI while connecting to an unrelated IP. Set HOME_NET to include the spoke CIDRs, because by default domain inspection only applies to the firewall VPC's own range.
Route traffic through the firewall
A firewall only inspects traffic that is routed to its endpoint. In the inspection VPC: TGW subnet route 0.0.0.0/0 → firewall endpoint; firewall subnet route 0.0.0.0/0 → NAT gateway; NAT subnet route 0.0.0.0/0 → IGW and 10.0.0.0/8 → firewall endpoint (so return traffic is inspected too). Mistakes here are the number-one cause of "the firewall is up but nothing is inspected".
Log everything and send it to the log-archive account
Enable Network Firewall alert and flow logs, DNS query logging for Resolver, and VPC Flow Logs. Send them to S3 in the log-archive account (see CloudTrail for banks) with a retention period agreed with compliance.
Add an application-level allow-list
Even with network controls, put a small allow-list inside the Payments Service's HttpClient pipeline (code below). If the network team ever opens a rule too widely, the application still refuses to send payment data to an unexpected host.
AWS Console instructions
Security groups: Console → VPC → Security groups → Create security group. Name hl-m05-app-sg, choose the VPC, add an inbound rule HTTPS 443 with Source = Custom → hl-m05-alb-sg (start typing sg- and pick it). Remove the default outbound rule and add HTTPS 443 to the endpoint security group only.
Gateway endpoint: VPC → Endpoints → Create endpoint → Type AWS services → search s3, choose the one with type Gateway → select the VPC and the private route tables → Policy: Custom → paste the policy from the CLI section.
DNS Firewall: VPC → DNS Firewall → Domain lists → Add domain list (hl-m05-allowed-domains). Then Rule groups → Add rule group → add rule allow-partners (domain list, action ALLOW, priority 100) and rule block-everything-else (a domain list containing *, action BLOCK, response NXDOMAIN, priority 200) → Associate VPC.
Network Firewall: VPC → Network Firewall → Network Firewall rule groups → Create rule group → Stateful → Domain list → domain .sanctions-partner.example.com, protocols HTTPS and HTTP, action Allow → capacity 100. Then Firewall policies → Create → attach the rule group. Finally Firewalls → Create firewall → choose the VPC and one dedicated /28 firewall subnet per AZ.
AWS CLI
# Variables used below (fictional IDs — replace with yours)
export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
VPC_ID=vpc-0abc1234def567890
APP_SG=sg-0aaa1111bbbb2222c
DB_SG=sg-0ddd3333eeee4444f
# 1. Allow PostgreSQL into the DB tier ONLY from ENIs carrying the app security group
aws ec2 authorize-security-group-ingress --group-id "$DB_SG" \
--ip-permissions 'IpProtocol=tcp,FromPort=5432,ToPort=5432,UserIdGroupPairs=[{GroupId='"$APP_SG"',Description="payments app tier"}]'
# 2. Find any security group in the account that allows SSH or RDP from the whole internet
aws ec2 describe-security-groups \
--filters Name=ip-permission.cidr,Values=0.0.0.0/0 \
--query "SecurityGroups[?IpPermissions[?FromPort==\`22\` || FromPort==\`3389\`]].[GroupId,GroupName]" \
--output table
# 3. Create an S3 gateway endpoint restricted to Harbourline buckets (data perimeter)
cat > s3-endpoint-policy.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [{
"Sid": "OnlyHarbourlineBuckets",
"Effect": "Allow",
"Principal": "*",
"Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::hl-m05-*", "arn:aws:s3:::hl-m05-*/*"],
"Condition": { "StringEquals": { "aws:PrincipalAccount": "111122223333" } }
}]
}
EOF
aws ec2 create-vpc-endpoint --vpc-id "$VPC_ID" \
--service-name com.amazonaws.us-east-1.s3 --vpc-endpoint-type Gateway \
--route-table-ids rtb-0123456789abcdef0 \
--policy-document file://s3-endpoint-policy.json \
--tag-specifications 'ResourceType=vpc-endpoint,Tags=[{Key=Project,Value=cea-lab},{Key=Lab,Value=m05-l14},{Key=Environment,Value=learn},{Key=Owner,Value=alex}]'
# 4. DNS Firewall walled garden: allow-list, then block everything else
ALLOW_ID=$(aws route53resolver create-firewall-domain-list --name hl-m05-allowed-domains \
--creator-request-id "$(date +%s)-a" --query FirewallDomainList.Id --output text)
aws route53resolver update-firewall-domains --firewall-domain-list-id "$ALLOW_ID" \
--operation ADD --domains "api.sanctions-partner.example.com" "*.amazonaws.com"
BLOCK_ID=$(aws route53resolver create-firewall-domain-list --name hl-m05-everything \
--creator-request-id "$(date +%s)-b" --query FirewallDomainList.Id --output text)
aws route53resolver update-firewall-domains --firewall-domain-list-id "$BLOCK_ID" \
--operation ADD --domains "*"
RG_ID=$(aws route53resolver create-firewall-rule-group --name hl-m05-walled-garden \
--creator-request-id "$(date +%s)-g" --query FirewallRuleGroup.Id --output text)
aws route53resolver create-firewall-rule --firewall-rule-group-id "$RG_ID" \
--firewall-domain-list-id "$ALLOW_ID" --priority 100 --action ALLOW --name allow-partners \
--creator-request-id "$(date +%s)-r1"
aws route53resolver create-firewall-rule --firewall-rule-group-id "$RG_ID" \
--firewall-domain-list-id "$BLOCK_ID" --priority 200 --action BLOCK \
--block-response NXDOMAIN --name block-everything-else --creator-request-id "$(date +%s)-r2"
aws route53resolver associate-firewall-rule-group --firewall-rule-group-id "$RG_ID" \
--vpc-id "$VPC_ID" --priority 101 --name hl-m05-walled-garden-assoc \
--creator-request-id "$(date +%s)-as"
# 5. Network Firewall: stateful domain allow-list rule group (HTTPS via SNI and HTTP via Host)
aws network-firewall create-rule-group --type STATEFUL --capacity 100 \
--rule-group-name hl-m05-partner-allowlist \
--rule-group '{
"RuleVariables": {"IPSets": {"HOME_NET": {"Definition": ["10.20.0.0/16","10.30.0.0/16"]}}},
"RulesSource": {"RulesSourceList": {
"Targets": [".sanctions-partner.example.com"],
"TargetTypes": ["TLS_SNI","HTTP_HOST"],
"GeneratedRulesType": "ALLOWLIST"}}}' \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m05-l14 Key=Environment,Value=learn Key=Owner,Value=alexWhat each block does:
- Adds an SG-referencing rule — no IP addresses involved.
- Audits the account for the two most dangerous mistakes (SSH 22 and RDP 3389 open to the world). The JMESPath query filters the response client-side.
- Creates the S3 gateway endpoint with a policy that only permits Harbourline's
hl-m05-*buckets and only principals from account111122223333. - Builds a DNS Firewall "walled garden": two domain lists, an allow rule at priority 100 and a block-all rule at priority 200, then attaches the rule group to the VPC. Lower priority numbers are evaluated first.
- Creates a Network Firewall domain allow-list. The leading dot in
.sanctions-partner.example.commeans "this domain and all its subdomains".HOME_NETincludes the spoke CIDRs so traffic arriving through the Transit Gateway is filtered too.
Wildcards differ between the two services
DNS Firewall uses *.example.com for subdomains and * for "everything". Network Firewall domain lists use a leading dot: .example.com. Mixing the syntaxes is a common reason rules silently do not match.
Infrastructure as Code
The CDK and Terraform examples build the workload VPC (isolated tiers, SG referencing, endpoints with policies) and the Network Firewall rule group, policy and firewall. The full inspection-VPC routing is described in the step-by-step section; it is long and account-specific, so build it in Module 10 style once your design is approved.
using Amazon.CDK;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.NetworkFirewall;
using Constructs;
namespace Harbourline.Payments.Infra;
public sealed class SegmentedVpcStack : Stack
{
public SegmentedVpcStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
{
// Three tiers, two AZs, NO NAT gateways: nothing in this VPC can reach the internet directly.
var vpc = new Vpc(this, "PaymentsVpc", new VpcProps
{
VpcName = "hl-m05-payments-vpc",
IpAddresses = IpAddresses.Cidr("10.20.0.0/16"),
MaxAzs = 2,
NatGateways = 0,
SubnetConfiguration =
[
new SubnetConfiguration { Name = "public", SubnetType = SubnetType.PUBLIC, CidrMask = 24 },
new SubnetConfiguration { Name = "app", SubnetType = SubnetType.PRIVATE_ISOLATED, CidrMask = 22 },
new SubnetConfiguration { Name = "data", SubnetType = SubnetType.PRIVATE_ISOLATED, CidrMask = 24 },
new SubnetConfiguration { Name = "firewall", SubnetType = SubnetType.PRIVATE_ISOLATED, CidrMask = 28 },
],
});
vpc.AddFlowLog("FlowLogs"); // defaults to CloudWatch Logs, ALL traffic
// Security groups that reference each other instead of IP ranges.
var albSg = new SecurityGroup(this, "AlbSg", new SecurityGroupProps { Vpc = vpc, AllowAllOutbound = false, SecurityGroupName = "hl-m05-alb-sg" });
var appSg = new SecurityGroup(this, "AppSg", new SecurityGroupProps { Vpc = vpc, AllowAllOutbound = false, SecurityGroupName = "hl-m05-app-sg" });
var dbSg = new SecurityGroup(this, "DbSg", new SecurityGroupProps { Vpc = vpc, AllowAllOutbound = false, SecurityGroupName = "hl-m05-db-sg" });
var endpointSg = new SecurityGroup(this, "EndpointSg", new SecurityGroupProps { Vpc = vpc, AllowAllOutbound = false, SecurityGroupName = "hl-m05-endpoint-sg" });
albSg.AddIngressRule(Peer.AnyIpv4(), Port.Tcp(443), "HTTPS from internet (WAF in front)");
albSg.AddEgressRule(appSg, Port.Tcp(8080), "to app tier only");
appSg.AddIngressRule(albSg, Port.Tcp(8080), "from ALB only");
appSg.AddEgressRule(dbSg, Port.Tcp(5432), "to database only");
appSg.AddEgressRule(endpointSg, Port.Tcp(443), "to AWS API endpoints");
dbSg.AddIngressRule(appSg, Port.Tcp(5432), "from app tier only");
endpointSg.AddIngressRule(appSg, Port.Tcp(443), "from app tier only");
// Gateway endpoint for S3 with a data-perimeter policy.
var s3Endpoint = vpc.AddGatewayEndpoint("S3Endpoint", new GatewayVpcEndpointOptions
{
Service = GatewayVpcEndpointAwsService.S3,
Subnets = [new SubnetSelection { SubnetGroupName = "app" }],
});
s3Endpoint.AddToPolicy(new PolicyStatement(new PolicyStatementProps
{
Sid = "OnlyHarbourlineBuckets",
Principals = [new AnyPrincipal()],
Actions = ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
Resources = ["arn:aws:s3:::hl-m05-*", "arn:aws:s3:::hl-m05-*/*"],
Conditions = new Dictionary<string, object>
{
["StringEquals"] = new Dictionary<string, object> { ["aws:PrincipalAccount"] = Account },
},
}));
// Interface endpoints for the AWS APIs the Payments Service needs.
foreach (var (name, svc) in new[]
{
("Kms", InterfaceVpcEndpointAwsService.KMS),
("SecretsManager", InterfaceVpcEndpointAwsService.SECRETS_MANAGER),
("Sqs", InterfaceVpcEndpointAwsService.SQS),
("Sts", InterfaceVpcEndpointAwsService.STS),
("Logs", InterfaceVpcEndpointAwsService.CLOUDWATCH_LOGS),
})
{
vpc.AddInterfaceEndpoint(name + "Endpoint", new InterfaceVpcEndpointOptions
{
Service = svc,
PrivateDnsEnabled = true,
SecurityGroups = [endpointSg],
Subnets = new SubnetSelection { SubnetGroupName = "app" },
});
}
// Optional (paid, about USD 0.40 per AZ-hour): deploy only with -c deployFirewall=true
if (Node.TryGetContext("deployFirewall") is "true")
{
var ruleGroup = new CfnRuleGroup(this, "PartnerAllowList", new CfnRuleGroupProps
{
RuleGroupName = "hl-m05-partner-allowlist",
Type = "STATEFUL",
Capacity = 100,
RuleGroup = new CfnRuleGroup.RuleGroupProperty
{
RuleVariables = new CfnRuleGroup.RuleVariablesProperty
{
IpSets = new Dictionary<string, object>
{
["HOME_NET"] = new CfnRuleGroup.IPSetProperty { Definition = ["10.20.0.0/16"] },
},
},
RulesSource = new CfnRuleGroup.RulesSourceProperty
{
RulesSourceList = new CfnRuleGroup.RulesSourceListProperty
{
GeneratedRulesType = "ALLOWLIST",
TargetTypes = ["TLS_SNI", "HTTP_HOST"],
Targets = [".sanctions-partner.example.com"],
},
},
},
});
var policy = new CfnFirewallPolicy(this, "EgressPolicy", new CfnFirewallPolicyProps
{
FirewallPolicyName = "hl-m05-egress-policy",
FirewallPolicy = new CfnFirewallPolicy.FirewallPolicyProperty
{
StatelessDefaultActions = ["aws:forward_to_sfe"],
StatelessFragmentDefaultActions = ["aws:forward_to_sfe"],
StatefulRuleGroupReferences = new[]
{
new CfnFirewallPolicy.StatefulRuleGroupReferenceProperty { ResourceArn = ruleGroup.AttrRuleGroupArn },
},
},
});
_ = new CfnFirewall(this, "EgressFirewall", new CfnFirewallProps
{
FirewallName = "hl-m05-egress-fw",
FirewallPolicyArn = policy.AttrFirewallPolicyArn,
VpcId = vpc.VpcId,
SubnetMappings = vpc.SelectSubnets(new SubnetSelection { SubnetGroupName = "firewall" })
.SubnetIds.Select(id => (object)new CfnFirewall.SubnetMappingProperty { SubnetId = id }).ToArray(),
DeleteProtection = false, // ⚠ learning shortcut: true in production
});
}
foreach (var (k, v) in new[] { ("Project", "cea-lab"), ("Lab", "m05-l14"), ("Environment", "learn"), ("Owner", "alex") })
{
Amazon.CDK.Tags.Of(this).Add(k, v);
}
}
}Complete code
Two small .NET programs. The first audits security groups with the AWS SDK; the second enforces an egress allow-list inside an HttpClient pipeline and runs without any AWS account.
1. Security-group auditor
<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.SgAuditor</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.EC2" Version="4.1.4" />
<!-- Needed at runtime so SSO profiles such as learn-sandbox resolve -->
<PackageReference Include="AWSSDK.SSO" Version="4.1.0.1" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
</ItemGroup>
</Project>using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
using Amazon.Runtime.CredentialManagement;
// Ports that must never be reachable from the whole internet in a Harbourline account.
int[] dangerousPorts = [22, 3389, 1433, 5432, 3306, 6379, 9200];
var chain = new CredentialProfileStoreChain();
if (!chain.TryGetAWSCredentials("learn-sandbox", out var credentials))
{
Console.Error.WriteLine("Profile learn-sandbox not found. Run: aws sso login --profile learn-sandbox");
return 1;
}
using var ec2 = new AmazonEC2Client(credentials, RegionEndpoint.USEast1);
var findings = new List<string>();
// Paginator walks every page of results for us.
await foreach (var sg in ec2.Paginators.DescribeSecurityGroups(new DescribeSecurityGroupsRequest()).SecurityGroups)
{
// SDK v4: collections are null when the service returns none, so default to empty.
foreach (var perm in sg.IpPermissions ?? [])
{
var openToWorld =
(perm.Ipv4Ranges ?? []).Any(r => r.CidrIp == "0.0.0.0/0") ||
(perm.Ipv6Ranges ?? []).Any(r => r.CidrIpv6 == "::/0");
if (!openToWorld) continue;
var allTraffic = perm.IpProtocol == "-1";
var from = perm.FromPort ?? 0;
var to = perm.ToPort ?? 65535;
var hits = dangerousPorts.Where(p => allTraffic || (p >= from && p <= to)).ToArray();
if (hits.Length > 0)
{
findings.Add($"{sg.GroupId} ({sg.GroupName}) in {sg.VpcId}: ports {string.Join(',', hits)} open to the internet");
}
else if (!(from == 443 && to == 443))
{
findings.Add($"{sg.GroupId} ({sg.GroupName}): {perm.IpProtocol} {from}-{to} open to the internet (review)");
}
}
}
if (findings.Count == 0)
{
Console.WriteLine("No world-open security group rules found.");
return 0;
}
Console.WriteLine($"{findings.Count} finding(s):");
findings.ForEach(f => Console.WriteLine(" - " + f));
return 2; // non-zero so a pipeline step fails2. Application-level egress allow-list
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RootNamespace>Harbourline.Payments.Egress</RootNamespace>
</PropertyGroup>
</Project>using System.Net;
namespace Harbourline.Payments.Egress;
/// <summary>
/// Refuses any outbound request whose host is not on the allow-list, or that is not HTTPS.
/// Defence in depth: the network should already block this, but code should not rely on it.
/// </summary>
public sealed class AllowListEgressHandler(IReadOnlyCollection<string> allowedHosts) : DelegatingHandler
{
private readonly HashSet<string> _allowed = new(allowedHosts, StringComparer.OrdinalIgnoreCase);
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
var uri = request.RequestUri ?? throw new InvalidOperationException("Request has no URI.");
if (uri.Scheme != Uri.UriSchemeHttps)
return Task.FromResult(Blocked(request, $"scheme {uri.Scheme} is not allowed"));
if (IPAddress.TryParse(uri.Host, out _))
return Task.FromResult(Blocked(request, "raw IP destinations are not allowed"));
if (!_allowed.Contains(uri.IdnHost))
return Task.FromResult(Blocked(request, $"host {uri.IdnHost} is not on the egress allow-list"));
return base.SendAsync(request, ct);
}
private static HttpResponseMessage Blocked(HttpRequestMessage request, string reason)
{
// Log a structured, PII-free event; a real service would use ILogger with a correlation ID.
Console.Error.WriteLine($"{{\"event\":\"egress_blocked\",\"reason\":\"{reason}\"}}");
return new HttpResponseMessage(HttpStatusCode.Forbidden)
{
RequestMessage = request,
ReasonPhrase = "Egress blocked by policy",
};
}
}using Harbourline.Payments.Egress;
// In production this list comes from configuration (Parameter Store / AppConfig), reviewed via pull request.
string[] allowList = ["api.sanctions-partner.example.com"];
// A terminal handler that never touches the network, so the demo runs offline.
var fakeNetwork = new FakeNetworkHandler();
using var client = new HttpClient(new AllowListEgressHandler(allowList) { InnerHandler = fakeNetwork });
string[] targets =
[
"https://api.sanctions-partner.example.com/v1/screen", // allowed
"https://attacker-drop.example.net/upload", // not on list
"http://api.sanctions-partner.example.com/v1/screen", // plain HTTP
"https://203.0.113.10/collect", // raw IP (TEST-NET-3)
];
foreach (var url in targets)
{
using var response = await client.GetAsync(url);
Console.WriteLine($"{(int)response.StatusCode} {response.ReasonPhrase,-28} {url}");
}
/// <summary>Stands in for the real network in this demo.</summary>
internal sealed class FakeNetworkHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct) =>
Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
RequestMessage = request,
ReasonPhrase = "OK (fake partner)",
});
}Expected output (dotnet run in EgressGuard/). The handler writes each block event as a JSON log line to standard error, so in a terminal it appears just before the matching status line; with 2>/dev/null you see only the four status lines:
200 OK (fake partner) https://api.sanctions-partner.example.com/v1/screen
{"event":"egress_blocked","reason":"host attacker-drop.example.net is not on the egress allow-list"}
403 Egress blocked by policy https://attacker-drop.example.net/upload
{"event":"egress_blocked","reason":"scheme http is not allowed"}
403 Egress blocked by policy http://api.sanctions-partner.example.com/v1/screen
{"event":"egress_blocked","reason":"raw IP destinations are not allowed"}
403 Egress blocked by policy https://203.0.113.10/collectCode explained line by line
Security-group auditor
int[] dangerousPorts = [...]— a C# 12 collection expression listing administrative and database ports that must never face the internet: SSH, RDP, SQL Server, PostgreSQL, MySQL, Redis, Elasticsearch.CredentialProfileStoreChain().TryGetAWSCredentials("learn-sandbox", ...)— loads the IAM Identity Center profile from~/.aws/config. TheAWSSDK.SSOandAWSSDK.SSOOIDCpackages must be referenced or SSO profiles fail at runtime.new AmazonEC2Client(credentials, RegionEndpoint.USEast1)— security groups are Regional, so the auditor checks one Region; loop over Regions in a real tool.ec2.Paginators.DescribeSecurityGroups(...).SecurityGroups— SDK v4 paginators return anIAsyncEnumerable, soawait foreachhandlesNextTokenfor you.sg.IpPermissions ?? []— in SDK v4, list properties arenull(not empty) when the response has no items. Forgetting this is the most common v3-to-v4 migration bug.openToWorld— true if any IPv4 range is0.0.0.0/0or any IPv6 range is::/0. IPv6 is often forgotten in audits.perm.IpProtocol == "-1"— "-1" means all protocols and all ports.perm.FromPort ?? 0— numeric properties are nullable in SDK v4.- The
else ifbranch reports any other world-open range except 443 as "review", because a public ALB legitimately allows 443. return 2— a non-zero exit code makes this usable as a pipeline gate.
Egress handler
DelegatingHandler— theHttpClientmiddleware pattern you already know from ASP.NET Core outgoing request pipelines (IHttpClientFactory+AddHttpMessageHandler).HashSetwithOrdinalIgnoreCase— DNS names are case-insensitive.uri.Scheme != Uri.UriSchemeHttps— blocks plain HTTP so data cannot leave unencrypted.IPAddress.TryParse(uri.Host, ...)— blocks raw IP destinations, which bypass DNS Firewall and are a classic exfiltration trick.uri.IdnHost— the punycode form of the host, so look-alike Unicode domains cannot sneak past a string comparison.Blocked(...)returns a synthetic403rather than throwing, so callers handle it like any other failed dependency. Log the event (without payload data) so the SOC can see attempts.- In
Program.cs,FakeNetworkHandlerreplaces the real socket handler so the demo is deterministic and offline; in production the inner handler is the defaultSocketsHttpHandler, andIHttpClientFactoryregistration would look likeservices.AddHttpClient("partner").AddHttpMessageHandler(...). - .NET's
HttpClienthonours theHTTPS_PROXYandNO_PROXYenvironment variables by default, so if your bank uses an explicit forward proxy you configure it in the container's environment, not in code.
Security considerations
⚠ Learning shortcut — not for production
The lab VPC uses one firewall subnet, DeleteProtection = false, and a hand-typed domain list. In production: one firewall endpoint per AZ in a separate network account, delete protection and policy-change protection on, domain lists managed in code with pull-request approval by the network security team, alert and flow logs shipped to the log-archive account, and Firewall Manager to enforce the policy across accounts.
- SNI is client-supplied. A malicious client can put an allowed name in the SNI and connect to any IP. Add the
AWS_ROUTE_53_RESOLVED_DOMAINtarget type so Network Firewall also checks that the destination IP was actually resolved for that domain, or add IP-based rules for partners with fixed addresses. - TLS inspection (decrypting egress traffic) is possible with Network Firewall using certificates from ACM, but it breaks certificate pinning, adds per-hour charges ⚠ VERIFY current advanced-inspection pricing, and puts decrypted payment data inside the firewall. Most banks inspect SNI only for payment traffic and reserve decryption for general web browsing. Get privacy and legal review before decrypting anything that may carry customer data.
- DNS Firewall does not stop hard-coded IPs. Pair it with Network Firewall or NACL/SG restrictions.
- Endpoint policies never grant access. They are a filter. The caller still needs an IAM allow, and the resource policy (for example the bucket policy) still applies.
- IMDSv2. Require IMDSv2 on every EC2 instance with a hop limit of 1 for containers, so SSRF cannot easily reach role credentials. This would have broken the 2019 attack chain.
- Separation of duties. The team that writes application code should not be able to edit egress allow-lists. Put the firewall in a network account owned by a different team.
Banking use case
Harbourline's Payments Service screens every outgoing payment against sanctions lists through a partner API, then submits FPS payments to a scheme gateway over a private connection. The network security team's design, approved by the CISO and reviewed by the PCI QSA for the card-related flows:
| Flow | Path | Control |
|---|---|---|
| Customer → Payments API | Internet → CloudFront/WAF → ALB | WAF managed rules, rate limits (WAF and Shield) |
| Payments Service → Aurora | App tier → data tier | SG referencing, isolated subnet, KMS |
| Payments Service → KMS, Secrets Manager, SQS | Interface endpoints | Endpoint policies restricted to the bank's organisation (aws:PrincipalOrgID) |
| Payments Service → sanctions partner | TGW → inspection VPC → NAT → internet | DNS Firewall walled garden + Network Firewall SNI allow-list + app allow-list |
| Payments Service → FPS gateway | Direct Connect / VPN to the scheme | No internet path at all |
| Anything else outbound | — | Dropped and alerted |
When the sanctions partner announces a new hostname, the change goes through a pull request to the domain-list repository, approved by network security, deployed by pipeline, and recorded as evidence of change control.
Common mistakes
- Treating a NAT gateway as egress control → NAT translates, it does not filter → put a firewall or proxy in the path, or remove internet routes entirely.
- Leaving the default "allow all outbound" rule on security groups → it is the default when you create an SG → set
AllowAllOutbound = falsein CDK and add explicit egress rules. - Forgetting
HOME_NETin a central inspection VPC → domain rules only apply to the firewall VPC's own CIDR by default → setHOME_NETto include all spoke CIDRs. - Asymmetric routing → return traffic bypasses the firewall or arrives in a different AZ → enable TGW appliance mode and route return paths back through the firewall endpoint in the same AZ.
- Missing private DNS on interface endpoints → SDK calls still go to public IPs via NAT → enable private DNS, or call the endpoint-specific DNS name.
- Endpoint policy using
"Resource": "*"→ no data perimeter at all → name your buckets/keys or useaws:ResourceOrgID. - Writing DNS Firewall and Network Firewall wildcards the same way →
*.example.comvs.example.com→ test with a lookup from inside the VPC.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| App times out calling Secrets Manager after you removed the NAT | No interface endpoint, or private DNS off | Create the endpoint with private DNS; allow 443 from app SG to endpoint SG |
AccessDenied from S3 only inside the VPC | Gateway endpoint policy does not list the bucket | Add the bucket ARN to the endpoint policy; check the bucket policy's aws:SourceVpce |
nslookup returns NXDOMAIN for an allowed partner | Rule priority wrong (block-all evaluated first) or domain missing from list | Allow rule needs a lower priority number than the block rule |
| Network Firewall drops all partner HTTPS traffic | Client uses an IP, no SNI, or SNI differs (e.g. www. prefix) | Check alert logs for the observed SNI; add the exact name or leading-dot wildcard |
| Connections hang through the inspection VPC | Asymmetric routing | Enable appliance mode on the TGW VPC attachment; check NAT subnet route back to the firewall |
| Firewall deployed but alert logs empty | Traffic not routed via the firewall endpoint | Inspect route tables; use VPC Reachability Analyzer from app ENI to the IGW |
| SG rule change "has no effect" on existing sessions | SGs are stateful; tracked connections persist | Restart the connection; for urgent containment see Incident response |
Cost and cleanup
| Item (us-east-1, checked 2026-11-17) | Price | Lab exposure |
|---|---|---|
| Security groups, NACLs, route tables, gateway endpoints | No charge | Free |
| Interface endpoint | About USD 0.01 per AZ-hour + USD 0.01 per GB ⚠ VERIFY hourly rate on the pricing calculator | 5 endpoints × 2 AZs × 2 h ≈ USD 0.20 |
| DNS Firewall | USD 0.0005 per domain per month + USD 0.60 per million queries | Effectively zero |
| Network Firewall endpoint | USD 0.395 per endpoint-hour per AZ + USD 0.065 per GB | 1 endpoint × 1 h ≈ USD 0.40 |
| NAT gateway | About USD 0.045 per hour + USD 0.045 per GB (NAT charges are waived when chained behind Network Firewall in the same path) | Avoid in this lab |
| Firewall Manager | About USD 100 per policy per Region per month | Design only |
| VPC Flow Logs to CloudWatch | Log ingestion charges | Set 1-day retention |
Free alternative: do the whole lesson as a design exercise plus the offline EgressGuard program, and deploy only the security groups, gateway endpoint and DNS Firewall (pennies). Deploy Network Firewall only if you can destroy it within the hour.
# CDK
cdk destroy --profile learn-sandbox
# Terraform
terraform destroy -var deploy_firewall=true
# CLI-created resources (reverse order)
aws route53resolver disassociate-firewall-rule-group --firewall-rule-group-association-id <assoc-id>
aws route53resolver list-firewall-rules --firewall-rule-group-id "$RG_ID" --query "FirewallRules[].FirewallDomainListId"
aws route53resolver delete-firewall-rule --firewall-rule-group-id "$RG_ID" --firewall-domain-list-id "$ALLOW_ID"
aws route53resolver delete-firewall-rule --firewall-rule-group-id "$RG_ID" --firewall-domain-list-id "$BLOCK_ID"
aws route53resolver delete-firewall-rule-group --firewall-rule-group-id "$RG_ID"
aws route53resolver delete-firewall-domain-list --firewall-domain-list-id "$ALLOW_ID"
aws route53resolver delete-firewall-domain-list --firewall-domain-list-id "$BLOCK_ID"
aws network-firewall delete-rule-group --rule-group-name hl-m05-partner-allowlist --type STATEFUL
aws ec2 delete-vpc-endpoints --vpc-endpoint-ids <vpce-id>
# Confirm nothing tagged for the lab remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
--query "ResourceTagMappingList[].ResourceARN"Exercises
- 🟢 Guided: Deploy the CDK stack without the firewall. From CloudShell in the VPC (or an SSM session on a test instance), resolve
api.sanctions-partner.example.comandexample.organd observe that only the first resolves once the DNS Firewall rule group is attached. Run the SG auditor against your sandbox account. - 🟡 Challenge: Add a bucket policy to
hl-m05-evidencethat denies all S3 data-plane actions unlessaws:SourceVpceequals your gateway endpoint ID, with an exception for your Identity Center admin role. Prove thataws s3 lsfrom your laptop fails and from inside the VPC succeeds. - 🔴 Live problem: A ticket from the Payments team: "Since the firewall change last night, about 3% of sanctions-screening calls time out. The partner says nothing changed. Fix it today." You have the Network Firewall alert logs and the TGW configuration. Work out what to check, in which order, and what you would change — without simply allowing all egress.
Assignment
Write a one-page egress policy for Harbourline's Payments VPC: a table of every allowed destination (AWS endpoint or partner domain), the protocol and port, the business justification, the owner, and the review date. Add a Mermaid diagram of the traffic path and commit both to your portfolio repository with the offline EgressGuard project and a unit test for each blocked case.
Solutions
After cdk deploy, associate the DNS Firewall rule group (CLI step 4). Inside the VPC:
nslookup api.sanctions-partner.example.com # resolves (or SERVFAIL if the fictional name has no record — but NOT blocked)
nslookup example.org # returns NXDOMAIN from DNS FirewallCheck Route 53 Resolver query logs (if enabled) to see the BLOCK action recorded. The auditor should report no findings for the lab VPC because CDK set AllowAllOutbound = false and only the ALB SG faces the internet on 443. Why: the walled garden evaluates rules in priority order — the allow list (100) matches first for permitted names; everything else falls through to block-all (200).
{
"Version": "2012-10-17",
"Statement": [{
"Sid": "DenyOutsideOurEndpoint",
"Effect": "Deny",
"Principal": "*",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::hl-m05-evidence", "arn:aws:s3:::hl-m05-evidence/*"],
"Condition": {
"StringNotEquals": { "aws:SourceVpce": "vpce-0123456789abcdef0" },
"ArnNotLike": { "aws:PrincipalArn": "arn:aws:iam::111122223333:role/aws-reserved/sso.amazonaws.com/AWSReservedSSO_SandboxAdmin_*" }
}
}]
}Why: an explicit deny in a resource policy wins over any allow. Two conditions in the same block are ANDed: the deny applies only when the request did not come through the endpoint and the caller is not the break-glass admin role. Keep the exception or you can lock yourself out of the bucket. Limit the action list to data-plane actions so you can still change the bucket policy.
- Read the alert logs first. Filter by the Payments VPC source CIDR and
dropaction. Look at thetls.snifield. A frequent finding: the partner uses a CDN, and some responses redirect clients to a second hostname (for examplecdn.sanctions-partner.example.net) that is not on the list. - Check for asymmetric routing. 3% partial failure smells like one AZ. Is appliance mode enabled on every TGW attachment? Does each AZ's NAT subnet route return traffic to the firewall endpoint in the same AZ?
- Check DNS. Does DNS Firewall allow the new name too? A Network Firewall fix alone will not help if the name is NXDOMAIN.
- Change narrowly: add the exact additional hostname, with
AWS_ROUTE_53_RESOLVED_DOMAIN, via pull request with partner confirmation; record the change. Do not switch to allow-all "temporarily" — temporary rules in banks tend to become permanent. - Add a CloudWatch alarm on the firewall's dropped-packet metric for that source so the next change is caught in minutes, not by the business.
Knowledge check
Answer: The rule means "any ENI that carries the referenced SG". It survives scaling, IP changes and redeployments, and a rogue instance without the SG is excluded. CIDR rules admit anything in the range, including a debugging instance someone launched in the same subnet.
Answer: NACLs are stateless, so the outbound NACL rule must allow return traffic to the client's ephemeral ports (1024–65535). SGs are stateful and do not need this.
Answer: Amazon S3 and Amazon DynamoDB. Everything else (KMS, Secrets Manager, SQS, STS …) uses interface endpoints.
Answer: No. It only limits what can pass through the endpoint. The request must still be allowed by the caller's identity policy and any resource policy, and not denied by SCPs or RCPs.
Answer: It reads the hostname from the TLS Server Name Indication in the unencrypted ClientHello. The weakness is that the client controls SNI; add resolved-IP validation (AWS_ROUTE_53_RESOLVED_DOMAIN) or IP rules to reduce spoofing.
Interview questions
- "How would you stop a compromised container from exfiltrating data?" — Layered: no direct internet route; egress via an inspection VPC with a domain allow-list; DNS Firewall walled garden; VPC endpoints with policies restricted to our org's resources; bucket policies requiring our endpoint; IMDSv2; least-privilege task role; GuardDuty for detection. Then the app-level allow-list as a last line.
- "Security groups or NACLs?" — Security groups for almost everything (stateful, per-ENI, referencing). NACLs as a coarse, rarely changed backstop, or for explicit deny of known-bad ranges.
- "Centralised or distributed firewalls?" — Centralised inspection VPC gives one policy, one log stream and separation of duties, at the cost of TGW data charges and a shared failure domain. Distributed firewalls per VPC isolate failures but multiply cost and rule drift. Firewall Manager helps either way.
- "What is a data perimeter?" — A set of preventive controls ensuring only trusted identities access trusted resources from expected networks, typically with SCPs, RCPs, endpoint policies and resource policies using
aws:PrincipalOrgID,aws:ResourceOrgIDandaws:SourceVpce.
Certification practice
A bank's workloads in 30 VPCs must reach only five partner HTTPS domains on the internet. The security team wants one place to manage the list, logs of every blocked attempt, and no decryption of traffic. Which solution meets these requirements with the least operational overhead?
- A. Security groups in each VPC with outbound rules to the partners' current IP addresses
- B. A centralised inspection VPC with AWS Network Firewall using a stateful domain-list allow rule (TLS SNI), attached via Transit Gateway with appliance mode
- C. A NAT gateway in each VPC and a NACL denying all outbound traffic except 443
- D. AWS WAF web ACLs with a geo-match rule on each Application Load Balancer
Answer: B. Domain lists inspect SNI without decryption, one central policy serves all spokes, and alert logs record drops. A breaks when partner IPs change and is managed 30 times. C allows 443 to the whole internet. D — WAF inspects inbound HTTP requests to your resources, not outbound traffic.
Developers in a workload account can upload to S3 through a gateway endpoint. The security team worries that stolen credentials from a personal AWS account could be used from inside the VPC to copy data to an external bucket. What is the most effective control?
- A. Add an S3 gateway endpoint policy that allows actions only on buckets owned by the organisation (
aws:ResourceOrgID) - B. Enable S3 Block Public Access on all buckets in the account
- C. Remove the gateway endpoint and use the NAT gateway instead
- D. Enable GuardDuty S3 Protection
Answer: A. The endpoint policy filters which resources can be reached through the endpoint, so external buckets are blocked. B controls public access to your buckets, not uploads to someone else's. C removes the control point entirely. D detects some anomalies but does not prevent the copy.
An application in private subnets with no internet access must read secrets from AWS Secrets Manager. What should the architect add?
- A. An internet gateway and a public IP on each instance
- B. An interface VPC endpoint for Secrets Manager with private DNS enabled, and a security group allowing 443 from the application
- C. A gateway VPC endpoint for Secrets Manager
- D. A VPC peering connection to the Secrets Manager VPC
Answer: B. Secrets Manager is reached privately through an interface endpoint (PrivateLink). A exposes instances. C — gateway endpoints exist only for S3 and DynamoDB. D — you cannot peer with an AWS service VPC.
After introducing a central Network Firewall behind a Transit Gateway, some long-lived connections from one VPC are dropped intermittently while others work. Firewall rules allow the destination. What is the most likely cause?
- A. The domain list uses a leading-dot wildcard
- B. Transit Gateway appliance mode is disabled on the inspection VPC attachment, causing asymmetric routing across AZs
- C. DNS Firewall is blocking the domain
- D. The security group on the firewall endpoint is missing an inbound rule
Answer: B. Without appliance mode, the two directions of a flow can traverse different AZs' firewall endpoints, and the stateful engine drops packets it has no state for. A is valid syntax. C would fail every connection, not some. D — Network Firewall endpoints do not use security groups.
Completion checklist
- I can explain SGs vs NACLs and SG referencing to a colleague in two sentences
- I built a VPC with no NAT and reached KMS and Secrets Manager through interface endpoints
- I wrote an endpoint policy and a bucket policy that form a data perimeter
- I created a DNS Firewall walled garden and saw a blocked lookup
- I can draw the inspection VPC routing, including the return path
- I ran the offline
EgressGuardprogram and understand each blocked case - I destroyed everything and confirmed nothing tagged
Project=cea-labremains
Key takeaways
- A NAT gateway is not a firewall; private subnets with NAT can reach the whole internet.
- Use security-group referencing for tiers and keep NACLs as a simple backstop.
- VPC endpoints plus endpoint policies plus resource policies form a data perimeter that stolen credentials cannot easily cross.
- DNS Firewall and Network Firewall domain allow-lists together give strong, auditable egress control without decrypting payment traffic.
- AWS runs the firewall fleet; Harbourline owns the rules, routes, logs and the evidence that they match policy. Segmentation adequacy for PCI DSS scope is decided by your QSA, not by AWS or this course.
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.
Data classification, masking and tokenisation
Classify banking data into four levels that drive real controls, find unclassified personal data with Macie, mask values by viewer role, and build a tokenisation vault for card numbers while knowing what it does and does not do for compliance scope.
AWS WAF and AWS Shield
Protect Harbourline's public banking APIs with AWS WAF managed rules, rate limiting and safe logging, and understand what Shield Standard gives you free and when Shield Advanced is worth USD 3,000 a month.