A coding-agent sandbox reads untrusted text all day: READMEs, issues, package metadata, web pages. Any of it can contain instructions, and an agent that follows them will try to reach a host you never planned for, perhaps to upload a tarball of the repository. Security groups filter by IP address and port, not by hostname, so they can’t express “GitHub yes, everything else no”. AWS Network Firewall can: it sits in the route between the sandbox subnets and the internet and inspects the hostname in each TLS handshake or HTTP request.
⚡ TL;DR
- Route the sandbox subnets’ internet traffic through a Network Firewall endpoint, in both directions.
- Use a policy with strict rule order, a domain allowlist rule group, and the default actions
aws:drop_establishedplusaws:alert_established. Under strict order the allowlist does not block other domains by itself; the default action does.- Domain lists match the TLS SNI or HTTP Host header, not IP addresses. Add IP-based rules if you need protection against forged hostnames.
- Keep AWS traffic (CodeArtifact, S3, Bedrock) on VPC endpoints so it never needs the internet path.
- Prove the policy from inside a sandbox with a probe that must fail for unlisted hosts.
Who this is for: platform engineers running agent sandboxes on ECS, CodeBuild, Batch or EC2 in a VPC. The CloudFormation template passes cfn-lint, and its rule group and policy pass botocore’s validation for the Network Firewall API. It wasn’t deployed for this post, so test in a non-production VPC first.
Why sandbox egress needs its own policy
| Control | Filters by hostname? | Fit for sandboxes |
|---|---|---|
| Security groups | No (IP and port) | Baseline only; keep them tight anyway |
| Network ACLs | No (IP and port, stateless) | Coarse backstop |
| NAT gateway alone | No | Gives the sandbox the whole internet |
| Network Firewall domain lists | Yes (TLS SNI, HTTP Host) | Egress allowlist, central logs |
| VPC endpoints | Not needed: traffic stays on AWS’s network to one service | Best for AWS APIs |

Step 1: Route both directions through the firewall
The Network Firewall documentation’s rule for routing is to insert the firewall endpoint into the traffic flow in both directions. For sandboxes in private subnets with a NAT gateway, one layout is:
| Route table | Destination | Target |
|---|---|---|
| Sandbox subnets | 0.0.0.0/0 | Firewall endpoint in the same Availability Zone |
| Firewall subnet | 0.0.0.0/0 | NAT gateway |
| NAT gateway subnet | Sandbox subnet CIDR | Firewall endpoint (return traffic) |
| NAT gateway subnet | 0.0.0.0/0 | Internet gateway |
With the firewall in front of the NAT gateway, it sees each sandbox’s own private IP, so the alert logs tell you which task tried to connect. Each firewall endpoint serves one Availability Zone; the CloudFormation EndpointIds attribute returns them as AZ:vpce-id pairs, in no particular order, so map each sandbox subnet to the endpoint in its own zone.
Step 2: A strict-order domain allowlist
The behavior of an allowlist depends on the policy’s rule order, and this is where many configurations go wrong. The Network Firewall docs state that an Allow domain list denies non-matching traffic of the inspected protocols only when the policy uses default action order; under strict order, that denial doesn’t apply. AWS recommends strict order because you control exactly how rules are evaluated, so this template uses it and puts the deny in the policy’s default actions. The docs also recommend aws:drop_established with strict order for domain lists, because the firewall needs an established connection to see the hostname.
AWSTemplateFormatVersion: "2010-09-09"
Description: Deny-by-default egress for coding-agent sandbox subnets (Network Firewall, strict order).
Parameters:
VpcId: {Type: AWS::EC2::VPC::Id}
FirewallSubnetId: {Type: AWS::EC2::Subnet::Id}
SandboxSubnetIds: {Type: "List<AWS::EC2::Subnet::Id>"}
SandboxRouteTableId: {Type: String}
EndpointSecurityGroupId: {Type: AWS::EC2::SecurityGroup::Id}
Resources:
AllowDomains:
Type: AWS::NetworkFirewall::RuleGroup
Properties:
RuleGroupName: agent-sandbox-allow-domains
Type: STATEFUL
Capacity: 100
RuleGroup:
StatefulRuleOptions: {RuleOrder: STRICT_ORDER}
RulesSource:
RulesSourceList:
GeneratedRulesType: ALLOWLIST
TargetTypes: [TLS_SNI, HTTP_HOST]
Targets:
- github.com # exact names: clone and API
- api.github.com
- codeload.github.com
# A leading dot (".example.com") matches every subdomain; add hosts only when logs show a need.
Policy:
Type: AWS::NetworkFirewall::FirewallPolicy
Properties:
FirewallPolicyName: agent-sandbox-egress
FirewallPolicy:
StatelessDefaultActions: ["aws:forward_to_sfe"]
StatelessFragmentDefaultActions: ["aws:forward_to_sfe"]
StatefulEngineOptions: {RuleOrder: STRICT_ORDER}
StatefulRuleGroupReferences:
- {ResourceArn: !GetAtt AllowDomains.RuleGroupArn, Priority: 10}
# Anything the allowlist didn't pass is dropped and logged once the connection is established.
StatefulDefaultActions: ["aws:drop_established", "aws:alert_established"]
Firewall:
Type: AWS::NetworkFirewall::Firewall
Properties:
FirewallName: agent-sandbox-egress
FirewallPolicyArn: !Ref Policy
VpcId: !Ref VpcId
SubnetMappings: [{SubnetId: !Ref FirewallSubnetId}]
DeleteProtection: true
# AWS traffic stays on VPC endpoints: the local route wins over 0.0.0.0/0, so it never reaches the firewall.
S3Gateway: # CodeArtifact serves package assets from S3
Type: AWS::EC2::VPCEndpoint
Properties:
VpcId: !Ref VpcId
ServiceName: !Sub com.amazonaws.${AWS::Region}.s3
VpcEndpointType: Gateway
RouteTableIds: [!Ref SandboxRouteTableId]
CodeArtifactApi:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcId: !Ref VpcId
ServiceName: !Sub com.amazonaws.${AWS::Region}.codeartifact.api
VpcEndpointType: Interface
PrivateDnsEnabled: true
SubnetIds: !Ref SandboxSubnetIds
SecurityGroupIds: [!Ref EndpointSecurityGroupId]
CodeArtifactRepos:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcId: !Ref VpcId
ServiceName: !Sub com.amazonaws.${AWS::Region}.codeartifact.repositories
VpcEndpointType: Interface
PrivateDnsEnabled: true
SubnetIds: !Ref SandboxSubnetIds
SecurityGroupIds: [!Ref EndpointSecurityGroupId]
AlertLogs:
Type: AWS::Logs::LogGroup
Properties: {LogGroupName: /network-firewall/agent-sandbox/alert, RetentionInDays: 90}
Logging:
Type: AWS::NetworkFirewall::LoggingConfiguration
Properties:
FirewallArn: !Ref Firewall
LoggingConfiguration:
LogDestinationConfigs:
- LogType: ALERT
LogDestinationType: CloudWatchLogs
LogDestination: {logGroup: !Ref AlertLogs}
Outputs:
EndpointIds:
Description: "Per-AZ endpoint ids, as AZ:vpce-id. Route the sandbox subnets' 0.0.0.0/0 to the one in their AZ."
Value: !Join [",", !GetAtt Firewall.EndpointIds]What the pieces do:
- Stateless default
aws:forward_to_sfesends every packet to the stateful engine, where the real decisions happen. - The allowlist matches TLS SNI and HTTP Host.
github.commatches only that name; a leading dot, as in.example.com, matches all subdomains. Start small and add hosts when the alert logs show a legitimate need. aws:drop_establishedandaws:alert_establisheddrop and log anything the allowlist didn’t pass. For connectionless protocols such as UDP, the docs note that drop established drops all packets.- VPC endpoints for CodeArtifact (the
codeartifact.apiandcodeartifact.repositoriesendpoints, plus an S3 gateway endpoint, because CodeArtifact serves package assets from S3). The route to an endpoint is more specific than0.0.0.0/0, so this traffic never reaches the firewall, and npm or pip don’t need public registries. - Alert logs go to CloudWatch Logs, so every dropped attempt is searchable.
The template was checked two ways: cfn-lint, and botocore’s validation of the rule group and policy against the CreateRuleGroup and CreateFirewallPolicy API shapes:
"""Check the rule group and policy against the Network Firewall API shapes (botocore), offline."""
import boto3
import yaml
from botocore.validate import ParamValidator
class Loader(yaml.SafeLoader): pass
for tag in ("!Ref", "!GetAtt", "!Sub", "!Join"):
Loader.add_constructor(tag, lambda l, n: "arn:aws:network-firewall:us-east-1:111122223333:stateful-rulegroup/x")
res = yaml.load(open("egress.yaml"), Loader=Loader)["Resources"]
model = boto3.client("network-firewall", region_name="us-east-1").meta.service_model
checks = {
"CreateRuleGroup": {"RuleGroupName": "x", "Type": "STATEFUL", "Capacity": 100,
"RuleGroup": res["AllowDomains"]["Properties"]["RuleGroup"]},
"CreateFirewallPolicy": {"FirewallPolicyName": "x",
"FirewallPolicy": res["Policy"]["Properties"]["FirewallPolicy"]},
}
for op, params in checks.items():
report = ParamValidator().validate(params, model.operation_model(op).input_shape)
print(op, "valid" if not report.has_errors() else report.generate_report())cfn-lint: no errors
CreateRuleGroup valid
CreateFirewallPolicy validWhat a domain list can’t do
The firewall uses the SNI or Host header, not the destination IP address, when evaluating domain lists. A client that controls its own TLS handshake could send an allowed name to a different IP. The docs suggest separate IP-based rules if you need to cover manipulated SNI or Host headers. Also remember that the domain list only covers HTTP and TLS: with this policy, git over SSH on port 22 is dropped, so sandboxes should clone over HTTPS. DNS queries to the VPC’s own resolver aren’t covered by this firewall at all; Route 53 Resolver DNS Firewall is the service for filtering those.
Step 3: Prove it from inside a sandbox
Run a probe inside a sandbox task after every network or policy change. Allowed hosts must complete a TLS handshake; unlisted hosts must not:
"""Run inside a sandbox task after every network change: allowed hosts connect, others must not."""
import socket
import ssl
import sys
ALLOWED = ["github.com", "api.github.com"]
MUST_FAIL = ["pypi.org", "example.com", "pastebin.com"]
def tls_ok(host: str, timeout: float = 5.0) -> bool:
try:
with socket.create_connection((host, 443), timeout=timeout) as sock:
with ssl.create_default_context().wrap_socket(sock, server_hostname=host):
return True # handshake done: the firewall let this SNI through
except OSError: # dropped (timeout), reset, or DNS failure
return False
failures = [f"{h} should connect" for h in ALLOWED if not tls_ok(h)]
failures += [f"{h} is reachable but should be blocked" for h in MUST_FAIL if tls_ok(h)]
print("\n".join(failures) or "egress policy OK")
sys.exit(1 if failures else 0)Run on this article’s build machine, which has open egress, the probe fails, as it should:
pypi.org is reachable but should be blocked
example.com is reachable but should be blocked
pastebin.com is reachable but should be blockedInside a correctly configured sandbox it prints egress policy OK. Run it in CI against a staging sandbox, so a route table change that bypasses the firewall fails a build instead of going unnoticed.
Worked example: a README asks the agent to upload the repo
- A dependency’s README tells the agent to “verify the build” by uploading a tarball to a paste site. The agent runs
curlto that host. - The TLS handshake’s SNI doesn’t match the allowlist; under strict order the connection reaches the default action and is dropped and logged.
curltimes out. - The alert log shows the sandbox’s private IP, the hostname and the time. The task ID from your orchestrator maps the IP to the agent session.
- Follow-up: the tool result showing the failed upload goes into your prompt-injection test set, and the dependency is flagged for review.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Unlisted domains still reachable | Strict order with an allowlist but no drop default action | Set aws:drop_established (and alert) as stateful defaults |
| Nothing is filtered | Sandbox route doesn’t point at the firewall endpoint | Fix the route tables; run the probe |
| Connections hang after the handshake starts | Return traffic not routed through the firewall | Route the sandbox CIDR to the firewall endpoint from the NAT subnet |
| Cross-zone traffic and outages when a zone fails | Sandbox subnets routed to another zone’s endpoint | One endpoint per zone, mapped from EndpointIds |
npm install fails | CodeArtifact endpoints or S3 gateway endpoint missing | Add all three; check private DNS on the interface endpoints |
git clone git@... fails | SSH isn’t HTTP/TLS, so the default drop applies | Clone over HTTPS |
Checklist
- ☐ Sandbox subnets route
0.0.0.0/0to the firewall endpoint in their own zone; return path also through the firewall - ☐ Policy uses strict order with drop and alert default actions
- ☐ Allowlist starts minimal; additions come from alert logs
- ☐ AWS traffic on VPC endpoints (CodeArtifact, S3, Bedrock)
- ☐ Alert logs in CloudWatch Logs, with the sandbox IP mapped to the agent session
- ☐ Egress probe runs in CI after every network change
FAQ
Why not use default action order, where the allowlist blocks by itself?
That works too. AWS recommends strict order because you can see and control the exact evaluation order as you add rule groups. Whichever you use, confirm with the probe that unlisted hosts are blocked.
Does this stop all data exfiltration?
No. It blocks unplanned destinations. An agent could still push data to an allowed host, such as a repository it can write to, so keep tool permissions narrow too.
Do model calls go through the firewall?
They don’t need to. Use a Bedrock interface VPC endpoint; see PrivateLink for Bedrock.
Is there a bandwidth limit?
The docs state Network Firewall supports up to 100 Gbps per Availability Zone, shared across the endpoints in that zone.
Official documentation
- Network Firewall stateful domain list rule groups
- Rule evaluation order and default actions
- VPC route table configuration for Network Firewall
- AWS::NetworkFirewall::Firewall (EndpointIds)
- CodeArtifact VPC endpoints
Last updated on October 10, 2026
Watch: 100 Days of AI on YouTube
Short videos from CheatCoders, one AI engineering topic per day.
Most viewed
- Python Decorators Explained: From Simple Wrappers to Production Patterns
- AI Agent Frameworks in 2025: LangGraph vs CrewAI vs AutoGen vs Raw API
- Claude Code vs Cursor vs GitHub Copilot: Choose by Workflow, and Set Up One Repo That Works With All Three
- Python String Methods: Every str Method With Real Production Examples
- API Debugging in 30 Seconds: The Fastest Ways to Fix API Issues
Newly added
- n8n vs AI Agent: I Gave Both the Same Job (Local, Ollama)
- Local AI Video Generator: Build Your Own App (Free, Python, No GPU)
- AI Wrote Raw Binary Instead of Code. Here’s What Happened (WebAssembly)
- I Built a Browser That Only Runs Encrypted Binary (Ep 1)
- RAG From Scratch: Chunking, Embeddings, Reranking and Evaluation (Real Numbers)
Deep-dive PDF
Get the expanded guide for this post — extra diagrams-style checklists, failure modes, and a production walkthrough. Free when you subscribe to CheatCoders.
Already subscribed? or open the subscribe page.
Discover more from CheatCoders
Subscribe to get the latest posts sent to your email.