Skip to Content
Cloud Engineering Academy
2. AWS Networking & Infrastructure

AWS Network Firewall: centralised inspection and domain-based egress filtering

Understand how AWS Network Firewall inspects traffic, write stateless and Suricata-compatible stateful rules, route traffic through firewall endpoints symmetrically, and choose between distributed and centralised inspection designs.

advanced⏱ 1 h 50 min🔴 Paid — optionalSCS-C03SAA-C03SOA-C03

Assumes: .NET 10 LTS (file-based app) · AWS CLI v2 · CDK v2 (Amazon.CDK.Lib 2.277.0) · Terraform AWS provider v6 · Suricata 7 (local rule testing) · Region us-east-1. Verified against official sources on 2026-11-18.

How this lesson relates to Module 5

Segmentation, private endpoints and egress filtering in the security module covers why a bank filters egress and builds a domain allow-list end to end. This lesson goes deeper into the mechanics: the rule engines, rule order, routing patterns, symmetry, logging and cost. Read either first; they complement each other.

Learning objectives

By the end of this lesson you can:

  • Name the parts of AWS Network Firewall — firewall, firewall policy, rule groups, firewall endpoints — and say what each one does.
  • Explain the two engines: stateless (5-tuple, per packet, ordered by priority) and stateful (Suricata-compatible, per flow, with domain lists and protocol awareness).
  • Choose between default action order and strict order, and explain why "drop established" is the usual default for an allow-list.
  • Write route tables that send traffic through firewall endpoints in both directions, for the distributed, centralised (Transit Gateway) and combined with NAT models.
  • Read firewall alert and flow logs, and estimate cost with the NAT gateway discount.
  • Test Suricata rules locally for free before spending a cent.

Prerequisites

Why this matters in banking

Harbourline's Payments Service must call exactly three things on the internet: a sanctions-screening partner, a card-scheme API and a currency-rates feed. A NAT gateway would let it call anything — including an attacker's server if a dependency is compromised. Regulators and card schemes increasingly expect banks to restrict and monitor outbound connections from sensitive environments, and incident responders need to know what tried to leave.

Security groups cannot express "only api.sanctions-partner.example", because they work on IP addresses, and partner IPs change. A firewall that understands domains and protocols can: it reads the TLS Server Name Indication (SNI) or the HTTP Host header and decides per connection. AWS Network Firewall is the managed way to do that in a VPC, without running your own appliances.

The idea in plain language

AWS Network Firewall is a managed, highly available firewall that you insert into a route. AWS runs the fleet; you get a firewall endpoint (a special VPC endpoint) in a subnet of each Availability Zone. You then change route tables so traffic goes to the endpoint on its way somewhere else. Traffic that does not route through the endpoint is not inspected — the firewall is only as good as your routes.

Inside, two engines look at the traffic:

  1. A fast stateless engine that checks each packet against simple rules (addresses, ports, protocol) and either passes it, drops it, or forwards it to…
  2. A stateful engine that tracks connections and runs Suricata-compatible rules — the open-source IDS/IPS rule language — including domain lists for TLS and HTTP.

Analogy: a bank's post room. The stateless engine is the clerk who checks the address label and bins anything to a blacklisted postcode. The stateful engine opens the envelope's cover sheet (not the letter) to see who it is really for, and checks it against the approved-correspondents list. Neither works if internal post is allowed to bypass the post room — that is routing.

What problem the AWS service solves

NeedSecurity groups / NACLsRoute 53 Resolver DNS FirewallAWS Network Firewall
Allow by IP and portYesNoYes
Allow by domain nameNoBlocks lookups onlyYes — TLS SNI and HTTP Host
Stop a process that connects by raw IPOnly if IP is knownNoYes (default-deny everything not explicitly allowed)
IDS/IPS signatures (e.g. known malware C2)NoDomain threat listsYes — Suricata rules and AWS managed threat signatures
Inspect inside TLSNoNoOptional TLS inspection (decrypt/re-encrypt)
Central for many VPCsNoShared via Firewall ManagerYes, via Transit Gateway or shared endpoints

Sharp edges, honestly:

  • Cost. USD 0.395 per firewall endpoint per hour per AZ plus USD 0.065 per GB processed (us-east-1). Two AZs is about USD 577 per month before data. Not something to leave running in a sandbox.
  • Routing is your job. Asymmetric routing (request through the firewall in AZ a, reply in AZ b, or not at all) breaks stateful inspection and causes mysterious drops.
  • SNI is not proof. A client can lie in its SNI. Domain filtering stops honest misconfiguration and most malware, but determined attackers can use domain fronting or encrypted ClientHello in some setups. TLS inspection closes more of that gap, at a cost in complexity and privacy review.
  • It is a layer-3/4/7 network control, not a WAF. For HTTP ingress protection (SQL injection, bots), use AWS WAF on the load balancer or API.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Azure Firewall (Standard / Premium)AWS Network FirewallBoth managed. AWS uses Suricata rule syntax; Azure uses its own rule collections
Application rules with FQDNsStateful domain list rule groups, or Suricata tls.sni / http.host rulesSame idea: match SNI/Host
Network rulesStateless rules, or stateful 5-tuple rulesAWS has a separate stateless engine evaluated first
Azure Firewall Premium IDPS / TLS inspectionSuricata signatures, AWS managed threat signature rule groups, TLS inspection configurationTLS inspection needs certificates in ACM
Firewall Policy + Firewall ManagerFirewall policy + AWS Firewall ManagerFirewall Manager can deploy firewalls across accounts in an Organization
Forced tunnelling via UDR 0.0.0.0/0 → firewall private IPRoute 0.0.0.0/0 → firewall endpoint (vpce-…)You target the endpoint ID, not an IP, and need one per AZ
Hub VNet with Azure FirewallInspection VPC behind Transit Gateway with appliance modeAppliance mode keeps flows in one AZ for symmetry

Architecture

The building blocks

Model 1 — distributed, with NAT (one VPC, per-AZ)

Route tables, per AZ (AZ a shown):

Route tableAssociated withRoutes
app-rt-aApp subnet AZ a10.17.0.0/16 local; 0.0.0.0/0 → nat-a
public-rt-aPublic subnet AZ a (NAT)10.17.0.0/16 local; 0.0.0.0/0 → vpce-fw-a
firewall-rtFirewall subnets10.17.0.0/16 local; 0.0.0.0/0 → igw
edge-rtThe Internet Gateway (edge association)10.17.0.0/16 local; public subnet a CIDR → vpce-fw-a; public subnet b CIDR → vpce-fw-b

The edge route table is what most people miss. Without it, replies from the internet go straight from the IGW to the NAT gateway, bypassing the firewall — the stateful engine sees the request but not the response, and drops or mis-tracks the flow.

Placing the firewall between NAT and IGW means the firewall sees the NAT gateway's address as the source. Placing it before the NAT (app subnet → firewall → NAT) lets rules and logs see the real workload IPs; banks often prefer that for attribution. Both are valid; pick deliberately.

Model 2 — centralised inspection with Transit Gateway

All spoke traffic — to the internet, to on-premises and, if you choose, between spokes (east-west) — is routed to the inspection VPC. One firewall serves dozens of VPCs. Two essentials:

  • Appliance mode on the inspection VPC's Transit Gateway attachment. Without it, Transit Gateway may send the request through the endpoint in AZ a and the reply through AZ b; the stateful engine in AZ b never saw the start of the flow and drops it.
  • Two Transit Gateway route tables: a spoke table (associated with spoke attachments) whose default route points to the inspection attachment, and a firewall table (associated with the inspection attachment) with routes back to every spoke. Details are in VPC peering and Transit Gateway.

AWS has also added a native Transit Gateway attachment for Network Firewall, which removes the need to build the inspection VPC yourself ⚠ VERIFY current availability and pricing in your Region before designing around it. And one firewall can now have secondary endpoints in other VPCs (billed at USD 0.158 per secondary endpoint-hour per AZ in us-east-1), a middle ground between distributed and centralised.

Choosing a model

ModelProsConsTypical bank use
Distributed (firewall per VPC)Simple routing, blast radius per VPC, no TGWCost scales with VPC count × AZs; rules managed per VPC (use Firewall Manager)A few high-risk VPCs (card data environment)
Centralised inspection VPCOne set of rules, cost shared, inspects east-west tooTGW data processing charges, appliance-mode and routing complexity, shared blast radiusMost production estates
Combined (central egress + local ingress)Ingress stays close to the ALB; egress centralisedTwo patterns to operateInternet-facing apps with strict egress rules

The rule engines in detail

Stateless engine

  • Evaluates every packet against rules in priority order (lowest number first). First match wins.
  • Matches on source/destination CIDR, ports, protocol and TCP flags.
  • Actions: pass, drop, or forward to stateful (aws:forward_to_sfe), plus optional custom actions to publish CloudWatch metrics.
  • The policy's stateless default action — for both full packets and fragments — is almost always forward to stateful. Use stateless rules only for cheap, early drops (for example, a known-bad CIDR list) or to pass very high-volume trusted traffic.

Stateful engine

  • Tracks flows (connections) and evaluates Suricata-compatible rules, including protocol keywords (tls.sni, http.host), flow state (flow:to_server,established) and thresholds.
  • Three ways to write stateful rules:
    1. Domain lists — a list of domains, an allow/deny choice, and targets TLS_SNI and/or HTTP_HOST. Simplest.
    2. 5-tuple rules — structured protocol/source/destination/port with pass, drop, alert or reject.
    3. Suricata-compatible rule strings — full control.
  • AWS managed rule groups add threat signatures and domain lists maintained by AWS (for example, malware and botnet domains).

Rule order: the decision that changes everything

Default action orderStrict order (recommended)
How rules are evaluatedBy action type: all pass first, then drop, then reject, then alertExactly in the order you set (rule group priority, then rule order inside)
Default actionNone (traffic not matching any drop passes)You choose: drop all, drop established, alert all, alert established
SuitsDeny-listsAllow-lists, readable top-to-bottom like a traditional firewall

Why "drop established"? For an allow-list based on SNI, the firewall must let the TCP three-way handshake complete so it can see the TLS ClientHello that carries the SNI. "Drop all" would drop the SYN before any domain is visible, so no allowed domain could ever connect. "Drop established" lets the handshake through, then drops any established flow that no pass rule matched. Pair it with alert established so every drop is logged.

A strict-order egress allow-list in Suricata syntax

harbourline-egress.rules
# Allow the three approved partners over TLS, matched on SNI (exact host or subdomain).
pass tls $HOME_NET any -> $EXTERNAL_NET 443 (tls.sni; content:"api.sanctions-partner.example"; nocase; endswith; flow:to_server,established; msg:"allow sanctions screening"; sid:1001001; rev:1;)
pass tls $HOME_NET any -> $EXTERNAL_NET 443 (tls.sni; content:"cardscheme.example"; nocase; endswith; flow:to_server,established; msg:"allow card scheme API"; sid:1001002; rev:1;)
pass tls $HOME_NET any -> $EXTERNAL_NET 443 (tls.sni; content:"rates.example.net"; nocase; endswith; flow:to_server,established; msg:"allow FX rates feed"; sid:1001003; rev:1;)

# Explicitly drop TLS without SNI and plain HTTP to the internet, with a logged reason.
drop tls $HOME_NET any -> $EXTERNAL_NET any (msg:"TLS to unapproved destination"; flow:to_server,established; sid:1001900; rev:1;)
drop http $HOME_NET any -> $EXTERNAL_NET any (msg:"Plain HTTP egress not allowed"; flow:to_server,established; sid:1001901; rev:1;)

Notes:

  • endswith with a leading host makes x.api.sanctions-partner.example match too. To match only the exact host, add startswith as well. A domain list rule group expresses ".cardscheme.example" (leading dot = subdomains) for you.
  • $HOME_NET defaults to the VPC CIDR the firewall is in. In a centralised model, override it in the rule group's rule variables with all spoke CIDRs (Harbourline: 10.16.0.0/12), or the rules will never match spoke traffic.
  • sid values must be unique within the rule group.

Step-by-step implementation

1. Write and test rules locally (free)

Validate syntax with Suricata in Docker before touching AWS. Save the rules above as harbourline-egress.rules and run:

docker run --rm -v "${PWD}:/rules" jasonish/suricata:7.0 -T -S /rules/harbourline-egress.rules -v

-T is Suricata's test mode: it loads the configuration and rules and reports errors without inspecting traffic. A clean run ends with a message that the configuration was loaded successfully. AWS Network Firewall supports a subset of Suricata features ⚠ VERIFY the supported keyword list in the Network Firewall developer guide; local Suricata validates syntax, not AWS support.

2. Create the rule groups

Create a stateful rule group in strict order with your rule strings, and capacity sized for growth (capacity is fixed at creation). Optionally add an AWS managed threat-signature group.

3. Create the firewall policy

Stateless default actions: forward to stateful (full packets and fragments). Stateful engine: strict order, default actions drop established and alert established. Attach the rule groups with priorities.

4. Create the firewall

Choose the VPC and one dedicated firewall subnet per AZ (a /28 is enough; the subnet must contain nothing else). Turn on delete protection and subnet change protection in production.

5. Configure logging

Send alert logs to CloudWatch Logs (short retention, for alarms) and flow logs to S3 (long retention). Add TLS logs if you use TLS inspection.

6. Change routes — last, and AZ by AZ

Only when the firewall shows Ready in every AZ, update route tables to target the endpoint in the same AZ. Do one AZ, test, then the next. Add the IGW edge route table for return traffic.

7. Test and read the logs

From an app instance: an allowed domain should connect; anything else should time out (dropped) and appear in the alert log with your msg text.

AWS Console instructions

  • Rule group: Console → VPC → Network Firewall → Network Firewall rule groups → Create rule group → Stateful rule group → Suricata compatible rule string, rule evaluation order Strict, capacity 100, paste the rules, tags.
  • Policy: Firewall policies → Create firewall policy → stateless default Forward to stateful rule groups; stateful rule order Strict; default actions Drop established and Alert established; add the rule group.
  • Firewall: Firewalls → Create firewall → VPC, one firewall subnet per AZ, the policy, delete protection on.
  • Endpoint IDs: open the firewall → Firewall details → Firewall endpoints lists the vpce-… ID per AZ — use these as route targets.
  • Logging: firewall → Firewall details → Logging → Edit → alert to CloudWatch Logs, flow to S3.

AWS CLI

$p = '--profile', 'learn-sandbox', '--region', 'us-east-1'

# Rule group from the local rules file (strict order)
aws network-firewall create-rule-group @p --rule-group-name hl-m02-egress-allow --type STATEFUL --capacity 100 `
  --rules file://harbourline-egress.rules `
  --stateful-rule-options RuleOrder=STRICT_ORDER `
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m02-l15 Key=Environment,Value=learn

# Policy: stateless forwards everything, stateful uses strict order with drop/alert established
$rg = aws network-firewall describe-rule-group @p --rule-group-name hl-m02-egress-allow --type STATEFUL --query RuleGroupResponse.RuleGroupArn --output text
$policy = @"
{
  "StatelessDefaultActions": ["aws:forward_to_sfe"],
  "StatelessFragmentDefaultActions": ["aws:forward_to_sfe"],
  "StatefulEngineOptions": { "RuleOrder": "STRICT_ORDER" },
  "StatefulDefaultActions": ["aws:drop_established", "aws:alert_established"],
  "StatefulRuleGroupReferences": [ { "ResourceArn": "$rg", "Priority": 10 } ]
}
"@
$policy | Set-Content -Encoding ascii policy.json
aws network-firewall create-firewall-policy @p --firewall-policy-name hl-m02-egress-policy --firewall-policy file://policy.json

# Firewall in two dedicated subnets
aws network-firewall create-firewall @p --firewall-name hl-m02-egress-fw --vpc-id vpc-0123456789abcdef0 `
  --firewall-policy-arn (aws network-firewall describe-firewall-policy @p --firewall-policy-name hl-m02-egress-policy --query FirewallPolicyResponse.FirewallPolicyArn --output text) `
  --subnet-mappings SubnetId=subnet-0fw0000000000000a SubnetId=subnet-0fw0000000000000b `
  --delete-protection --tags Key=Project,Value=cea-lab Key=Lab,Value=m02-l15

# Endpoint per AZ (route targets) once Status is READY
aws network-firewall describe-firewall @p --firewall-name hl-m02-egress-fw `
  --query "FirewallStatus.{Status:Status,Endpoints:SyncStates.*.Attachment.EndpointId}"

# Point the NAT subnet's default route at the firewall endpoint in the same AZ
aws ec2 replace-route @p --route-table-id rtb-0public00000000a --destination-cidr-block 0.0.0.0/0 --vpc-endpoint-id vpce-0fwa000000000000a

--delete-protection must be turned off (update-firewall-delete-protection --no-delete-protection) before you can delete the firewall in teardown.

Infrastructure as Code

EgressFirewall.cs
using Amazon.CDK;
using Amazon.CDK.AWS.NetworkFirewall;
using Constructs;

namespace Harbourline.Networking.Inspection;

/// <summary>Strict-order egress allow-list firewall. L1 (Cfn*) constructs: there is no stable L2 yet.</summary>
public sealed class EgressFirewall : Construct
{
    public EgressFirewall(Construct scope, string id, string vpcId, string[] firewallSubnetIds, string rules)
        : base(scope, id)
    {
        var ruleGroup = new CfnRuleGroup(this, "Allow", new CfnRuleGroupProps
        {
            RuleGroupName = "hl-egress-allow",
            Type = "STATEFUL",
            Capacity = 100,
            RuleGroup = new CfnRuleGroup.RuleGroupProperty
            {
                RulesSource = new CfnRuleGroup.RulesSourceProperty { RulesString = rules },
                StatefulRuleOptions = new CfnRuleGroup.StatefulRuleOptionsProperty { RuleOrder = "STRICT_ORDER" },
                RuleVariables = new CfnRuleGroup.RuleVariablesProperty
                {
                    // In a centralised model HOME_NET must cover every spoke, not just the inspection VPC.
                    IpSets = new Dictionary<string, object>
                    {
                        ["HOME_NET"] = new CfnRuleGroup.IPSetProperty { Definition = ["10.16.0.0/12"] },
                    },
                },
            },
        });

        var policy = new CfnFirewallPolicy(this, "Policy", new CfnFirewallPolicyProps
        {
            FirewallPolicyName = "hl-egress-policy",
            FirewallPolicy = new CfnFirewallPolicy.FirewallPolicyProperty
            {
                StatelessDefaultActions = ["aws:forward_to_sfe"],
                StatelessFragmentDefaultActions = ["aws:forward_to_sfe"],
                StatefulEngineOptions = new CfnFirewallPolicy.StatefulEngineOptionsProperty { RuleOrder = "STRICT_ORDER" },
                StatefulDefaultActions = ["aws:drop_established", "aws:alert_established"],
                StatefulRuleGroupReferences =
                [
                    new CfnFirewallPolicy.StatefulRuleGroupReferenceProperty { ResourceArn = ruleGroup.AttrRuleGroupArn, Priority = 10 },
                ],
            },
        });

        Firewall = new CfnFirewall(this, "Firewall", new CfnFirewallProps
        {
            FirewallName = "hl-egress-fw",
            VpcId = vpcId,
            FirewallPolicyArn = policy.AttrFirewallPolicyArn,
            SubnetMappings = firewallSubnetIds.Select(s => (object)new CfnFirewall.SubnetMappingProperty { SubnetId = s }).ToArray(),
            DeleteProtection = true,
            SubnetChangeProtection = true,
        });
    }

    /// <summary>Endpoint IDs come back as "az:vpce-id" strings in Firewall.AttrEndpointIds.</summary>
    public CfnFirewall Firewall { get; }
}

AttrEndpointIds returns entries like us-east-1a:vpce-…; split them with Fn.Split and Fn.Select to build per-AZ routes ⚠ VERIFY the exact format in your CDK version.

Complete code

Rule files written by hand drift and break: a missing semicolon or a duplicate sid fails the whole rule group update. Harbourline generates its egress rules from a reviewed allow-list file. This .NET 10 file-based app validates the list and emits strict-order Suricata rules:

egressrules.cs
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

// Usage: dotnet run egressrules.cs -- allowlist.txt > harbourline-egress.rules
// allowlist.txt: one entry per line: <domain> <owner> <ticket>   e.g.  api.sanctions-partner.example payments CHG-1042
// A leading dot (".cardscheme.example") means "this domain and all subdomains".

const int FirstSid = 1001001;
var hostPattern = new Regex(@"^\.?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$", RegexOptions.CultureInvariant);

if (args.Length != 1 || !File.Exists(args[0]))
{
    Console.Error.WriteLine("Usage: dotnet run egressrules.cs -- <allowlist.txt>");
    return 1;
}

var errors = new List<string>();
var entries = new List<(string Domain, string Owner, string Ticket)>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var lineNo = 0;

foreach (var raw in File.ReadLines(args[0]))
{
    lineNo++;
    var line = raw.Trim();
    if (line.Length == 0 || line.StartsWith('#'))
    {
        continue;
    }

    var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
    if (parts.Length != 3)
    {
        errors.Add($"line {lineNo}: expected '<domain> <owner> <ticket>'");
        continue;
    }

    var domain = parts[0].ToLowerInvariant();
    if (!hostPattern.IsMatch(domain))
    {
        errors.Add($"line {lineNo}: '{domain}' is not a valid host name");
    }
    else if (domain is ".com" or ".net" or ".org" or ".example" || domain.Count(c => c == '.') < 2 && domain.StartsWith('.'))
    {
        errors.Add($"line {lineNo}: '{domain}' is too broad (a whole TLD or registrable-domain wildcard needs security approval)");
    }
    else if (!seen.Add(domain))
    {
        errors.Add($"line {lineNo}: duplicate '{domain}'");
    }
    else if (!Regex.IsMatch(parts[2], @"^CHG-\d+$"))
    {
        errors.Add($"line {lineNo}: ticket '{parts[2]}' must look like CHG-1234");
    }
    else
    {
        entries.Add((domain, parts[1], parts[2]));
    }
}

if (errors.Count > 0)
{
    errors.ForEach(e => Console.Error.WriteLine(e));
    return 2;
}

var rules = new StringBuilder();
rules.AppendLine("# Generated by egressrules.cs - do not edit by hand.");
var sid = FirstSid;
foreach (var (domain, owner, ticket) in entries)
{
    var exact = !domain.StartsWith('.');
    var host = domain.TrimStart('.');
    // exact host: startswith + endswith on the full name; wildcard: endswith ".domain" so "evilcardscheme.example" can't match.
    var match = exact
        ? $"content:\"{host}\"; nocase; startswith; endswith;"
        : $"content:\".{host}\"; nocase; endswith;";
    rules.AppendLine(string.Create(CultureInfo.InvariantCulture,
        $"pass tls $HOME_NET any -> $EXTERNAL_NET 443 (tls.sni; {match} flow:to_server,established; msg:\"allow {host} owner={owner} {ticket}\"; sid:{sid++}; rev:1;)"));
}

rules.AppendLine(string.Create(CultureInfo.InvariantCulture,
    $"drop tls $HOME_NET any -> $EXTERNAL_NET any (msg:\"TLS to unapproved destination\"; flow:to_server,established; sid:{sid++}; rev:1;)"));
rules.AppendLine(string.Create(CultureInfo.InvariantCulture,
    $"drop http $HOME_NET any -> $EXTERNAL_NET any (msg:\"Plain HTTP egress not allowed\"; flow:to_server,established; sid:{sid}; rev:1;)"));

Console.Write(rules.ToString());
return 0;

Example allowlist.txt:

# domain                        owner     change ticket
api.sanctions-partner.example   payments  CHG-1042
.cardscheme.example             cards     CHG-1077
rates.example.net               treasury  CHG-1101
dotnet run egressrules.cs -- allowlist.txt > harbourline-egress.rules
docker run --rm -v "${PWD}:/rules" jasonish/suricata:7.0 -T -S /rules/harbourline-egress.rules

Code explained line by line

  1. const int FirstSid = 1001001; — Suricata signature IDs must be unique; a fixed block per rule group keeps them predictable across regenerations.
  2. hostPattern — a conservative host-name regex: lowercase labels of 1–63 characters, no leading/trailing hyphen, an alphabetic TLD, optional leading dot for wildcards.
  3. The foreach loop skips blank lines and # comments so the allow-list can carry review notes.
  4. Each line must have exactly three fields: domain, owner, change ticket. Every allowed destination is traceable to a person and an approved change — exactly what an auditor will ask.
  5. The "too broad" check refuses whole TLDs and wildcards on a bare registrable domain (e.g. .example.com with only one dot after stripping) without a separate approval. Wide wildcards are how allow-lists quietly become allow-everything.
  6. Duplicate detection uses a case-insensitive HashSet.
  7. Validation errors go to stderr with line numbers and the tool exits 2, so a CI pipeline fails before anything reaches AWS.
  8. For an exact host, startswith; endswith; on the full name means SNI must equal the host. For a wildcard, matching endswith on .cardscheme.example (with the dot) allows subdomains but not evilcardscheme.example.
  9. string.Create(CultureInfo.InvariantCulture, …) — interpolation that never picks up a machine's locale, a good habit for any generated config.
  10. The two drop rules at the end make the deny explicit and give logs a readable msg. The policy's default actions (drop established, alert established) are the safety net behind them.
  11. Output goes to stdout, so the same tool works in a pipeline step that writes the file and runs suricata -T.

Security considerations

⚠ Learning shortcut — not for production

A lab firewall in one AZ saves money but makes egress depend on a single AZ. Production deploys an endpoint in every AZ that has workloads, and routes each AZ to its own endpoint, so an AZ failure doesn't take down egress for the others and traffic doesn't cross AZs (which also costs money).

⚠ Learning shortcut — not for production

The lab skips TLS inspection. Production may decrypt selected traffic to catch threats hidden in TLS, but that means managing certificates in ACM, deploying a trusted CA to workloads, a privacy/data-protection review (you are reading customer data in transit), and excluding categories such as health or banking sites of employees. Many banks decide not to decrypt payment traffic and rely on SNI allow-lists plus endpoint controls.

  • Fail closed and alert. Strict order with drop established; alarm on spikes in the alert log.
  • Protect the firewall itself: delete protection, subnet change protection, policy change protection, and IAM so only the network team can change policies. Log all network-firewall:* API calls with CloudTrail.
  • Manage centrally. AWS Firewall Manager can enforce a baseline Network Firewall policy across all accounts in an Organization and report non-compliant VPCs.
  • Defence in depth. Combine with Route 53 Resolver DNS Firewall (block lookups of bad domains), security groups (only the payment tasks can reach the egress path) and application-level allow-lists (see the DelegatingHandler in the Module 5 lesson).
  • Logs contain personal data (source IPs, domains visited). Agree retention and access with your data-protection officer.

Banking use case

Harbourline runs a central inspection VPC in the network hub account (10.16.0.0/16) behind its Transit Gateway:

  • Egress: all spoke VPCs default-route to the inspection attachment. Strict-order rule groups: an AWS managed threat-signature group first, then per-team allow-lists generated by egressrules.cs from Git, then explicit drops. Owners and change tickets appear in every alert message.
  • East-west: traffic between the Payments VPC and the Accounts VPC is also routed through inspection; a 5-tuple rule group allows only the documented service ports.
  • Hybrid: traffic from on-premises (LDN-DC1, MAN-DC2) into the card-data VPC passes through inspection; flow logs from the firewall feed the SOC.
  • Card data environment: has its own distributed firewall as well, so the PCI DSS segmentation boundary is enforced inside the CDE VPC itself. Whether this segmentation is sufficient for scope reduction is decided by Harbourline's QSA, not by AWS or this course.

Common mistakes

  • No IGW edge route table in the distributed model → replies bypass the firewall → stateful drops and half-open flows.
  • Appliance mode off on the inspection VPC attachment → cross-AZ asymmetry → intermittent drops that look like application bugs.
  • Routing an AZ to another AZ's endpoint → cross-AZ charges and an AZ dependency.
  • "Drop all" default with an SNI allow-list → the SYN is dropped before the SNI is visible; nothing connects.
  • $HOME_NET left at the inspection VPC CIDR in a centralised design → spoke traffic never matches the pass rules → everything dropped.
  • Capacity too small — rule group capacity can't be changed after creation; plan for growth.
  • Putting workloads in the firewall subnet — the firewall can't inspect traffic from its own subnet.

Troubleshooting

SymptomLikely causeFix
Allowed domain times outDefault action "drop all"; or $HOME_NET wrong; or SNI differs from what you expectUse drop established; set HOME_NET; check the alert log's tls.sni value
Works in one AZ onlyRoute table in the other AZ still points at NAT/IGW, or at the wrong endpointCompare per-AZ route tables; each AZ → its own vpce
Intermittent drops via Transit GatewayAppliance mode disabledmodify-transit-gateway-vpc-attachment --options ApplianceModeSupport=enable
Inbound to ALB broken after inserting firewallMissing IGW edge association or return routeEdge route table: public subnet CIDR → firewall endpoint
Rule group update rejectedSuricata syntax error, duplicate sid, unsupported keyword, or capacity exceededRun suricata -T locally; check the error text; create a larger group
No alert logsLogging not configured, or no drop/alert rules matchedConfigure ALERT logging; add alert established default
Firewall stuck in PROVISIONINGNormal for several minutesWait; check subnet is dedicated and in the right AZ
Can't delete firewallDelete protection onupdate-firewall-delete-protection --no-delete-protection

Cost and cleanup

Prices (us-east-1, checked 2026-11-18 on the Network Firewall pricing page):

  • Firewall endpoint: USD 0.395 per endpoint-hour per AZ.
  • Data processed: USD 0.065 per GB.
  • Secondary endpoints: USD 0.158 per endpoint-hour per AZ (no separate processing charge).
  • NAT gateway discount: for each firewall endpoint-hour, one NAT gateway-hour in the same Region is not charged, and NAT data processing is waived up to the amount of traffic the firewall processed (the pricing page caps the example at 5,000 GB).
  • TLS inspection (advanced inspection): an extra hourly rate per AZ; no us-east-1 figure was published on the page ⚠ VERIFY.

Worked examples:

  • Lab, 1 AZ, 1 hour, under 1 GB: 0.395 + 0.065 ≈ USD 0.46, plus subnet/NAT costs (NAT hour waived).
  • Production distributed, 3 AZs, 730 hours, 2 TB: 3 × 0.395 × 730 = 865.05 + 2,000 × 0.065 = 130 → about USD 995/month per VPC.
  • Centralised, same 3 AZs for 20 spoke VPCs: one firewall ≈ USD 995/month at 2 TB, plus Transit Gateway attachments (20 × USD 0.05 × 730 = USD 730) and TGW data processing (USD 0.02 per GB). Centralisation wins as VPC count grows.

Free alternative (recommended for this course): write the allow-list, generate rules with egressrules.cs, validate them with Suricata in Docker, and draw the route tables for the distributed and centralised models on paper — including the IGW edge route table and the two TGW route tables. That covers everything the exams ask.

Deploy-and-destroy (optional, about USD 0.50): one firewall in one AZ in a throwaway VPC, test, then delete within the hour:

$p = '--profile', 'learn-sandbox', '--region', 'us-east-1'
# 1. Restore routes first (point 0.0.0.0/0 back at the NAT gateway or IGW)
aws ec2 replace-route @p --route-table-id rtb-0public00000000a --destination-cidr-block 0.0.0.0/0 --gateway-id igw-0123456789abcdef0
# 2. Remove protection and delete the firewall (takes several minutes)
aws network-firewall update-firewall-delete-protection @p --firewall-name hl-m02-egress-fw --no-delete-protection
aws network-firewall delete-firewall @p --firewall-name hl-m02-egress-fw
# 3. When the firewall is gone, delete the policy and rule group
aws network-firewall delete-firewall-policy @p --firewall-policy-name hl-m02-egress-policy
aws network-firewall delete-rule-group @p --rule-group-name hl-m02-egress-allow --type STATEFUL
# 4. Log groups, then the tag check
aws logs delete-log-group @p --log-group-name /hl/m02/network-firewall/alert
aws resourcegroupstaggingapi get-resources @p --tag-filters Key=Project,Values=cea-lab --query "ResourceTagMappingList[].ResourceARN"

Exercises

  • 🟢 Guided: Generate rules from the example allow-list with egressrules.cs, validate them with Suricata in Docker, then deliberately add a duplicate domain and a .com wildcard and confirm the tool rejects both.
  • 🟡 Challenge: Draw (Mermaid or paper) the full route-table set for a centralised inspection VPC serving the Payments (10.17.0.0/16) and Accounts (10.18.0.0/16) VPCs with internet egress through NAT and inspection of east-west traffic. Include both TGW route tables and all inspection-VPC subnet route tables for two AZs.
  • 🔴 Live problem: After the network team moved egress inspection to the central firewall, the Payments team reports that calls to the sanctions partner fail about half the time, always from tasks in us-east-1b. Calls from us-east-1a always work. Nothing in the rules changed. Investigate.

Assignment

Add an egress/ folder to your portfolio repository: allowlist.txt, the generator, a GitHub Actions workflow (or script) that runs the generator and suricata -T on every pull request, and a README with the centralised routing diagram. This is a realistic "policy as code" artefact for a network-security interview.

Solutions

Knowledge check

Interview questions

  • "Security groups already filter traffic — why add Network Firewall?" — SGs filter by IP/port and can't express domains or detect threats. Network Firewall adds SNI/Host allow-lists, IDS/IPS signatures and central logging, and it can enforce a default-deny egress policy across many VPCs.
  • "Distributed or centralised inspection?" — Centralised for most estates (one rule set, shared cost, east-west inspection) using Transit Gateway with appliance mode; distributed for a few high-risk VPCs that need local enforcement or a separate blast radius. Cost and routing complexity decide the rest.
  • "What breaks when you insert a firewall into an existing VPC?" — Asymmetric routing: missing edge route tables, cross-AZ endpoints, appliance mode off. Change routes last, AZ by AZ, with a rollback.
  • "Would you decrypt TLS?" — Only where the risk justifies it and after a privacy review; for payment traffic, SNI allow-lists plus endpoint controls are often the agreed balance.

Certification practice

Completion checklist

  • I can describe firewall, policy, rule groups and endpoints
  • I can explain strict order and why drop established is the usual default
  • I generated and validated a rule file locally with Suricata
  • I drew route tables for distributed and centralised models, including the edge route table and appliance mode
  • If I deployed anything, I deleted the firewall, policy, rule group and logs, and the tag check is clean

Key takeaways

  • Network Firewall inspects only what you route through its endpoints — routing design is firewall design.
  • Stateless engine: fast, per packet, forward to stateful by default. Stateful engine: Suricata, domains, flows.
  • Use strict order with drop established + alert established for allow-lists.
  • Keep both directions in the same AZ: per-AZ endpoints, IGW edge route tables, Transit Gateway appliance mode.
  • It is expensive per hour; centralise for scale, and use the free local workflow (generate, suricata -T, draw routes) to learn.

Further reading

Next steps: see how inspection fits into an organisation-wide design in multi-account network architecture.

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