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

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.

intermediate⏱ 2 h 🟡 Low costSCS-C03SAA-C03

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 DelegatingHandler that refuses to call any host outside an allow-list, as defence in depth inside the application.

Prerequisites

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:

LayerQuestion it answersWhere 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

ServiceProblem it solvesLimitations and sharp edges
Security groupsFine-grained, stateful allow rules per ENI; can reference other SGs so tiers need no IPsAllow-only (no deny rules); outbound defaults to "all traffic"; quota on rules per SG and SGs per ENI
Network ACLsCoarse, stateless subnet-wide allow and deny rules; useful as a blunt backstopStateless — you must allow return traffic on ephemeral ports; numbered rule order; easy to break things
Gateway VPC endpointsPrivate route to S3 and DynamoDB with no NAT; freeOnly 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 servicesCharged per AZ per hour plus per GB; one endpoint per service per VPC unless centralised
Endpoint policiesLimit 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 FirewallBlock or allow DNS lookups by domain list; catches DNS tunnelling and C2 domainsOnly filters queries that use the Route 53 Resolver; hard-coded IPs bypass it
AWS Network FirewallManaged, stateful firewall with Suricata-compatible rules, domain allow-lists (TLS SNI / HTTP Host) and optional TLS inspectionAbout 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 gatewayLets private subnets start outbound IPv4 connectionsPer-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 equivalentWhat's different
Network Security Group (NSG) on a subnet or NICSecurity 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 policyRoute 53 Resolver DNS FirewallDNS Firewall attaches rule groups directly to VPCs
Private Endpoint / Private LinkInterface VPC endpoint / AWS PrivateLinkSimilar; 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 hubInspection VPC + Transit Gateway with appliance modeVery similar pattern; TGW route tables replace UDRs
Azure Firewall ManagerAWS Firewall ManagerCentral 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

ZoneTrust levelWho can change itControls applied
InternetUntrustedNobodyWAF, Shield, TLS
Public tierLowPlatform team via pipelineSG allows 443 from internet only to ALB
App tierMediumApp team via pipelineSG referencing, no IGW route, endpoint policies
Data tierHighDBA + platform, change-controlledIsolated subnets, SG from app-sg only, KMS encryption
Inspection VPCControl planeNetwork 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=alex

What each block does:

  1. Adds an SG-referencing rule — no IP addresses involved.
  2. 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.
  3. Creates the S3 gateway endpoint with a policy that only permits Harbourline's hl-m05-* buckets and only principals from account 111122223333.
  4. 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.
  5. Creates a Network Firewall domain allow-list. The leading dot in .sanctions-partner.example.com means "this domain and all its subdomains". HOME_NET includes 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.

infra/SegmentedVpcStack.cs
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

SgAuditor/SgAuditor.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <RootNamespace>Harbourline.Security.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>
SgAuditor/Program.cs
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 fails

2. Application-level egress allow-list

EgressGuard/EgressGuard.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <RootNamespace>Harbourline.Payments.Egress</RootNamespace>
  </PropertyGroup>
</Project>
EgressGuard/AllowListEgressHandler.cs
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",
        };
    }
}
EgressGuard/Program.cs
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/collect

Code explained line by line

Security-group auditor

  1. 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.
  2. CredentialProfileStoreChain().TryGetAWSCredentials("learn-sandbox", ...) — loads the IAM Identity Center profile from ~/.aws/config. The AWSSDK.SSO and AWSSDK.SSOOIDC packages must be referenced or SSO profiles fail at runtime.
  3. new AmazonEC2Client(credentials, RegionEndpoint.USEast1) — security groups are Regional, so the auditor checks one Region; loop over Regions in a real tool.
  4. ec2.Paginators.DescribeSecurityGroups(...).SecurityGroups — SDK v4 paginators return an IAsyncEnumerable, so await foreach handles NextToken for you.
  5. sg.IpPermissions ?? [] — in SDK v4, list properties are null (not empty) when the response has no items. Forgetting this is the most common v3-to-v4 migration bug.
  6. openToWorld — true if any IPv4 range is 0.0.0.0/0 or any IPv6 range is ::/0. IPv6 is often forgotten in audits.
  7. perm.IpProtocol == "-1" — "-1" means all protocols and all ports.
  8. perm.FromPort ?? 0 — numeric properties are nullable in SDK v4.
  9. The else if branch reports any other world-open range except 443 as "review", because a public ALB legitimately allows 443.
  10. return 2 — a non-zero exit code makes this usable as a pipeline gate.

Egress handler

  1. DelegatingHandler — the HttpClient middleware pattern you already know from ASP.NET Core outgoing request pipelines (IHttpClientFactory + AddHttpMessageHandler).
  2. HashSet with OrdinalIgnoreCase — DNS names are case-insensitive.
  3. uri.Scheme != Uri.UriSchemeHttps — blocks plain HTTP so data cannot leave unencrypted.
  4. IPAddress.TryParse(uri.Host, ...) — blocks raw IP destinations, which bypass DNS Firewall and are a classic exfiltration trick.
  5. uri.IdnHost — the punycode form of the host, so look-alike Unicode domains cannot sneak past a string comparison.
  6. Blocked(...) returns a synthetic 403 rather than throwing, so callers handle it like any other failed dependency. Log the event (without payload data) so the SOC can see attempts.
  7. In Program.cs, FakeNetworkHandler replaces the real socket handler so the demo is deterministic and offline; in production the inner handler is the default SocketsHttpHandler, and IHttpClientFactory registration would look like services.AddHttpClient("partner").AddHttpMessageHandler(...).
  8. .NET's HttpClient honours the HTTPS_PROXY and NO_PROXY environment 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_DOMAIN target 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:

FlowPathControl
Customer → Payments APIInternet → CloudFront/WAF → ALBWAF managed rules, rate limits (WAF and Shield)
Payments Service → AuroraApp tier → data tierSG referencing, isolated subnet, KMS
Payments Service → KMS, Secrets Manager, SQSInterface endpointsEndpoint policies restricted to the bank's organisation (aws:PrincipalOrgID)
Payments Service → sanctions partnerTGW → inspection VPC → NAT → internetDNS Firewall walled garden + Network Firewall SNI allow-list + app allow-list
Payments Service → FPS gatewayDirect Connect / VPN to the schemeNo 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 = false in CDK and add explicit egress rules.
  • Forgetting HOME_NET in a central inspection VPC → domain rules only apply to the firewall VPC's own CIDR by default → set HOME_NET to 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 use aws:ResourceOrgID.
  • Writing DNS Firewall and Network Firewall wildcards the same way → *.example.com vs .example.com → test with a lookup from inside the VPC.

Troubleshooting

SymptomLikely causeFix
App times out calling Secrets Manager after you removed the NATNo interface endpoint, or private DNS offCreate the endpoint with private DNS; allow 443 from app SG to endpoint SG
AccessDenied from S3 only inside the VPCGateway endpoint policy does not list the bucketAdd the bucket ARN to the endpoint policy; check the bucket policy's aws:SourceVpce
nslookup returns NXDOMAIN for an allowed partnerRule priority wrong (block-all evaluated first) or domain missing from listAllow rule needs a lower priority number than the block rule
Network Firewall drops all partner HTTPS trafficClient 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 VPCAsymmetric routingEnable appliance mode on the TGW VPC attachment; check NAT subnet route back to the firewall
Firewall deployed but alert logs emptyTraffic not routed via the firewall endpointInspect route tables; use VPC Reachability Analyzer from app ENI to the IGW
SG rule change "has no effect" on existing sessionsSGs are stateful; tracked connections persistRestart the connection; for urgent containment see Incident response

Cost and cleanup

Item (us-east-1, checked 2026-11-17)PriceLab exposure
Security groups, NACLs, route tables, gateway endpointsNo chargeFree
Interface endpointAbout USD 0.01 per AZ-hour + USD 0.01 per GB ⚠ VERIFY hourly rate on the pricing calculator5 endpoints × 2 AZs × 2 h ≈ USD 0.20
DNS FirewallUSD 0.0005 per domain per month + USD 0.60 per million queriesEffectively zero
Network Firewall endpointUSD 0.395 per endpoint-hour per AZ + USD 0.065 per GB1 endpoint × 1 h ≈ USD 0.40
NAT gatewayAbout 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 ManagerAbout USD 100 per policy per Region per monthDesign only
VPC Flow Logs to CloudWatchLog ingestion chargesSet 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.com and example.org and 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-evidence that denies all S3 data-plane actions unless aws:SourceVpce equals your gateway endpoint ID, with an exception for your Identity Center admin role. Prove that aws s3 ls from 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

Knowledge check

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:ResourceOrgID and aws:SourceVpce.

Certification practice

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 EgressGuard program and understand each blocked case
  • I destroyed everything and confirmed nothing tagged Project=cea-lab remains

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.

On this page