Skip to content
TrungCLN

NetworkingBeginner

Security group or NACL? Why the reply gets dropped: stateful, stateless, ephemeral ports

By Cao Le Nam TrungPublished Updated 36 min read

VPCSubnet webreply droppedClientNACLSGWeb :80
Diagram drawn with the official AWS Architecture Icons.

Key results

  • A NACL that only allows inbound TCP 80: the SYN reaches the web server, the reply to the client's ephemeral port is dropped, and curl waits 130.7 seconds before failing.
  • One outbound rule for TCP 1024-65535: the same curl returns HTTP 200 in 2 to 4 milliseconds.
  • Copying the Windows port range (49152-65535) makes a Linux client fail intermittently: source port 33000 times out, port 50000 works.
  • A security group tracks connections, so one inbound rule is enough; a NACL DENY rule only works when its number is lower than the ALLOW rule.

What you need

  • No prior knowledge of security groups or NACLs: the guide explains everything from scratch.
  • A Linux machine with Docker (about 2 GB free RAM) and AWS CLI v2. Setup is in the "Lab setup" guide.
  • Packet filtering runs for real with iptables in a container, playing the NACL and the security group. The AWS CLI part uses Moto, which only mocks the API and filters no traffic.
Time
35 min
Cost
$0, runs on your own machine
  • Amazon VPC
  • Security Group
  • Network ACL
  • iptables
  • Moto

Watch the lab video

Video thumbnail: Security group or NACL? Why the reply gets dropped: stateful, stateless, ephemeral ports

🎬 Goes live 19 Dec 2026, 20:00 (UTC+7)

Subscribe to YouTube @trungcln to get notified

You open the security group for port 80, you open the network ACL (NACL) for port 80, and the browser still spins and then times out. The web server is running; its log even shows the request arriving. The usual culprit is the reply packet: it goes back to a port you never thought about, and the NACL does not let it through.

This guide rebuilds that exact situation with 3 containers on your own machine, uses iptables to play the NACL and the security group, and uses tcpdump to show which packets pass and which are dropped. At the end you create the same rules with the AWS CLI to see what they really look like on AWS.

A few concepts first

Security group (SG)
A firewall attached to each instance (strictly, to each network interface). It only has "allow" rules; there are no "deny" rules.Example: The web instance's SG allows TCP 80 from 10.40.1.0/24.
Network ACL (NACL)
A filter at the edge of a subnet that checks every packet entering or leaving that subnet. It has both ALLOW and DENY rules.Example: The web subnet's NACL: rule 100 allows inbound TCP 80.
Stateful
The filter remembers each connection. Replies to a connection that was let in are let out automatically.Example: Security groups are stateful.
Stateless
The filter judges every packet as brand new, without knowing whether it is a request or a reply.Example: NACLs are stateless: the return direction needs its own rule.
Ephemeral port
A port number the client picks for each outgoing connection. The server's reply comes back to exactly this port.Example: The Linux client in this guide picks port 55904 to call port 80.
Rule number
Every NACL rule has a number from 1 to 32766. AWS evaluates from the lowest number up and stops at the first rule that matches.Example: Rule 90 DENY is evaluated before rule 100 ALLOW.

These two layers sit in different places. A packet coming in passes the NACL at the subnet edge first, then the instance’s security group:

VPC 10.40.0.0/16Subnet client 10.40.1.0/24Subnet web 10.40.2.0/24clientNACLSGwebNACL: filters at the subnet edge, for every instance in it · SG: filters per instance (per network interface)
A NACL is like the guard at the gate of an apartment complex: it checks everyone entering or leaving the whole complex and remembers no faces. A security group is like the lock on each apartment door: it only cares about its own flat, and it remembers which guests were invited in.

The lab model and how it runs

Before typing any command, you should know what the lab is made of, how the parts connect and which way packets travel. This section describes exactly what will exist on your machine once the lab is running.

Component diagram

Linux machine with Docker (the lab host)l04-clienteth0 10.40.1.10/24l04-fw (iptables)eth0 .1.254 · eth1 .2.254l04-web (HTTP :80)eth0 10.40.2.10/24l04-net-client · 10.40.1.0/24Docker bridge network · gateway 10.40.1.1l04-net-web · 10.40.2.0/24Docker bridge network · gateway 10.40.2.1eth0 ↔ vetheth0 ↔ vetheth1 ↔ vetheth0 ↔ vethAll 3 containers use the nicolaka/netshoot image and are created by dung.shnacl-in / nacl-out = NACL (stateless) · sg = security group (stateful) · all inside l04-fw
Every box above is something that really exists in the lab, with the exact name you will type in the commands. The two bars at the bottom are two Docker networks, like two virtual switches. fw is the only container plugged into both switches, so every packet between client and web has to pass through it.

The lab runs on one Linux machine with Docker. Docker runs several isolated “small machines” (called containers) on one real machine. Each container has its own network interfaces, IP addresses and routing table, just like a separate server. This guide uses 3 containers and 2 virtual networks.

What each component is

Component What it is Its role on real AWS Created by / file
l04-net-client A Docker bridge network, range 10.40.1.0/24; Docker keeps 10.40.1.1 as the gateway A subnet holding the user’s machine (client) docker network create in dung.sh
l04-net-web A Docker bridge network, range 10.40.2.0/24, gateway 10.40.2.1 The web server’s subnet, where the NACL is attached docker network create in dung.sh
l04-client A nicolaka/netshoot container with one interface, eth0 at 10.40.1.10 A user’s machine (or an EC2 instance in another subnet) calling the web server docker run in dung.sh
l04-web A nicolaka/netshoot container running python3 -m http.server 80, eth0 at 10.40.2.10 The EC2 web server docker run in dung.sh
l04-fw A nicolaka/netshoot container with two interfaces, eth0 10.40.1.254 and eth1 10.40.2.254, with packet forwarding on The web subnet boundary, where AWS applies the NACL and the security group docker run + docker network connect in dung.sh
Chains nacl-in, nacl-out Two iptables rule lists in l04-fw, with no connection state The NACL’s Inbound rules and Outbound rules tables quy-tac/nacl-stateless.sh
Chain sg An iptables rule list that uses conntrack (connection tracking) The web instance’s security group quy-tac/sg-stateful.sh
tcpdump A program that records packets crossing an interface Close to VPC Flow Logs, but packet by packet Included in the netshoot image
Moto + awsl Software that mocks the AWS APIs at 127.0.0.1:4566; awsl is the AWS CLI pointed at Moto The real EC2 API (creating VPCs, NACLs, security groups) The “Lab setup” guide; only used in step 9

How the components connect

Each Docker network works like a virtual switch. A container is plugged into the switch with a “virtual cable” called a veth pair (one end is eth0 inside the container, the other end is attached to the switch on the host). Docker names the switch (br- plus an id) and the cable (veth...) itself, differently on every build, so this guide refers to the network names instead.

Network Connects IP on each side
l04-net-client (10.40.1.0/24) l04-client:eth0 and l04-fw:eth0 client 10.40.1.10, fw 10.40.1.254, Docker gateway 10.40.1.1
l04-net-web (10.40.2.0/24) l04-fw:eth1 and l04-web:eth0 fw 10.40.2.254, web 10.40.2.10, Docker gateway 10.40.2.1

Client and web sit on two different networks with no direct link. To talk, they need a machine that sits on both networks to forward packets for them: that is l04-fw. Each container’s routing table decides where packets go:

Container Default gateway Extra route Meaning
l04-client 10.40.1.1 (Docker) 10.40.2.0/24 via 10.40.1.254 Packets for the web network go to fw
l04-web 10.40.2.1 (Docker) 10.40.1.0/24 via 10.40.2.254 Replies to the client network go to fw
l04-fw 10.40.1.1 (Docker) None needed: it already sits on both networks Receives on one interface, forwards out of the other

One call from the client to the web server takes 6 steps:

l04-client10.40.1.10l04-fwiptables FORWARDl04-web10.40.2.10:801 · eth03 · eth14 · eth16 · eth02 and 5: iptables checks packets here1. client: 10.40.2.10 is on another network, so its route sends the packet to fw 10.40.1.2542. fw receives it on eth0; iptables (FORWARD chain) checks it: nacl-in or sg3. if allowed: fw sends it out of eth1 to web 10.40.2.10 port 804. web replies to 10.40.1.10 on the client's ephemeral port; its route sends it to fw 10.40.2.2545. fw receives the reply on eth1; iptables checks the return direction: nacl-out or sg6. if allowed: fw sends it out of eth0 to the client, and curl gets the pageBlocked at step 2 or 5, the packet vanishes and the client only sees a timeout
Packets travel like letters through a sorting office: the client cannot hand them straight to the web server, so it gives them to fw, which checks them and passes them on. The lab blocks packets at step 2 or step 5, and tcpdump on fw shows at which step a packet stopped.
  1. l04-client builds a packet from 10.40.1.10:<ephemeral port> to 10.40.2.10:80. The destination is on another network, so its route says: send it to 10.40.1.254.
  2. l04-fw receives the packet on eth0. Because the packet is not for fw itself but passing through, Linux runs it through the iptables FORWARD chain, where this guide’s NACL or security group rules decide whether it passes or is dropped.
  3. If allowed, fw sends the packet out of eth1 to 10.40.2.10.
  4. l04-web replies from 10.40.2.10:80 to 10.40.1.10:<ephemeral port>. The web server’s route sends packets for the client network to 10.40.2.254.
  5. l04-fw receives the reply on eth1, and the FORWARD chain checks it again, this time in the return direction.
  6. If allowed, fw sends it out of eth0 to the client, and curl gets the page.

The whole guide revolves around steps 2 and 5: a NACL checks them independently, while a security group remembers step 2 and lets step 5 through automatically.

What is prepared for you

The lab directory holds these files (each file’s content appears in the steps below):

04-sg-vs-nacl/
├── dung.sh # creates 2 networks + 3 containers (step 1)
├── don.sh # removes the 3 containers + 2 networks
├── quy-tac/
│ ├── nacl-stateless.sh # NACL-style rules for l04-fw (step 2)
│ └── sg-stateful.sh # security-group-style rules for l04-fw (step 8)
└── don-moto.sh # deletes what step 9 created on Moto

Running ./dung.sh creates exactly 5 things: 2 Docker networks (l04-net-client, l04-net-web) and 3 containers (l04-client, l04-fw, l04-web). There are no filter rules yet, so at first every packet passes.

Part Real or mocked AWS equivalent
Packets, ephemeral ports, dropped or passed, waiting times Real: the Linux kernel handles the packets, iptables really filters The behaviour of NACLs (stateless) and security groups (stateful)
Where the filter sits Merged into one container, l04-fw, so you can see the packets NACL at the subnet boundary, security group on each instance’s network interface
VPC, subnet, NACL and security group in step 9 Mocked with Moto: configuration is stored, no packet is filtered Real AWS::EC2::VPC, Subnet, NetworkAcl, SecurityGroup resources

The whole run at a glance

This is the entire guide in order, with the result you should see. The details follow in the steps below.

# What you do Expected result
1 Build the lab with ./dung.sh, check IPs and routes 3 containers running, the client reaches the web server right away (hello from web 10.40.2.10)
2 Write NACL-style rules: allow only TCP 80 in quy-tac/nacl-stateless.sh ready
3 Load the rules, call the web server, run tcpdump on fw Broken: curl times out after 5 seconds; the reply enters fw and disappears
4 Call again with no time limit curl waits about 130 seconds before reporting an error
5 Fix: add an outbound rule for TCP 1024-65535 HTTP 200 in 2 to 4 milliseconds
6 Try a common mistake: open only 49152-65535 Port 33000 times out, port 50000 works
7 Try rule order: DENY as number 110, then 90 110 does not block, 90 does
8 Switch to security-group-style rules HTTP 200 with no return-direction rule
9 Create the same NACL and security group with the AWS CLI on Moto See the real rule shape: numbers, allow/deny
10 Clean up No lab containers, networks or Moto resources left

Step 1: Build the 3 containers

What you are doing: creating two virtual networks and three containers: the client on the first network, the web server on the second, and fw connected to both, forwarding packets between them. Save this as dung.sh:

dung.sh
IMG=nicolaka/netshoot:latest
docker network create --subnet 10.40.1.0/24 l04-net-client
docker network create --subnet 10.40.2.0/24 l04-net-web
docker run -d --name l04-fw --hostname fw --network l04-net-client --ip 10.40.1.254 \
--cap-add NET_ADMIN --sysctl net.ipv4.ip_forward=1 $IMG sleep infinity
docker network connect --ip 10.40.2.254 l04-net-web l04-fw
docker run -d --name l04-web --hostname web --network l04-net-web --ip 10.40.2.10 --cap-add NET_ADMIN $IMG \
sh -c 'ip route replace 10.40.1.0/24 via 10.40.2.254 && mkdir -p /srv && echo "hello from web 10.40.2.10" > /srv/index.html && cd /srv && exec python3 -m http.server 80'
docker run -d --name l04-client --hostname client --network l04-net-client --ip 10.40.1.10 --cap-add NET_ADMIN $IMG \
sh -c 'ip route replace 10.40.2.0/24 via 10.40.1.254 && exec sleep infinity'
Line What it means Why it is set this way
docker network create --subnet ... Creates two virtual networks, each with its own IP range Two separate ranges act like two subnets. If client and web shared one network, packets would go straight between them, never through fw, and the filter would see nothing.
--cap-add NET_ADMIN Lets the container change its routing table and iptables Without it, ip route and iptables inside the container fail with Operation not permitted.
--sysctl net.ipv4.ip_forward=1 Lets fw forward packets from one network to the other Linux is not a router by default. Without this line fw receives the client’s packets and discards them.
docker network connect --ip 10.40.2.254 ... Adds a second network interface to fw The first interface (eth0) faces the client, the second (eth1) faces the web server.
ip route replace 10.40.1.0/24 via 10.40.2.254 The web server sends packets for the client network through fw Without this route, replies follow Docker’s default route around fw, and the lab no longer models anything.
python3 -m http.server 80 Runs the web server on port 80 A fixed service port, like a real web server.

Run it, then create two aliases so the next commands are shorter:

Terminal window
./dung.sh
alias fw='docker exec l04-fw' client='docker exec l04-client'
client curl -s http://10.40.2.10/

Check exactly what was just created against the tables in “The lab model”:

Terminal window
docker network ls --filter name=l04- --format '{{.Name}} {{.Driver}}'; docker ps --filter name=l04- --format '{{.Names}} {{.Image}} {{.Status}}'
for c in l04-client l04-fw l04-web; do echo "== $c"; docker exec $c ip -br -4 addr show scope global; docker exec $c ip route; done
Command What it means Why
docker network ls --filter name=l04- Lists networks whose names start with l04- Shows only this guide’s networks, not others on the machine.
docker ps --filter name=l04- Lists this guide’s running containers Confirms all 3 containers run with the right image.
ip -br -4 addr show scope global The IPv4 address of each interface, in short form Compare with the “IP on each side” column above.
ip route The container’s routing table Confirms the via 10.40.1.254 and via 10.40.2.254 routes exist; without them packets would not pass through fw.
Output: 2 bridge networks, l04-net-client and l04-net-web; 3 running containers, l04-client, l04-web and l04-fw, using the nicolaka/netshoot image. l04-client: eth0 10.40.1.10/24, default via 10.40.1.1, 10.40.2.0/24 via 10.40.1.254. l04-fw: eth0 10.40.1.254/24, eth1 10.40.2.254/24. l04-web: eth0 10.40.2.10/24, default via 10.40.2.1, 10.40.1.0/24 via 10.40.2.254. curl from the client returns hello from web 10.40.2.10.
Real run: exactly 2 networks and 3 containers, with IPs and routes matching the diagram; the client reaches the web server while fw has no filter rules.

How to read it:

  • eth0@if176 means the container’s eth0 is linked to interface number 176 on the host: the other end of the veth cable. The number changes on every build.
  • On l04-client, the line 10.40.2.0/24 via 10.40.1.254 dev eth0 is the route we added: packets for the web network go through fw. On l04-web, 10.40.1.0/24 via 10.40.2.254 does the same for the return direction.
  • l04-fw has two proto kernel scope link lines: it sits directly on both networks, so it needs no extra route.
  • The last line, hello from web 10.40.2.10, means the client reaches the web server through fw. fw has no filter rules yet, so everything passes.

Step 2: Write NACL-style rules

What you are doing: giving fw the same rules as a NACL many people write the first time: allow inbound TCP 80 into the web subnet, deny everything else in both directions. Save as quy-tac/nacl-stateless.sh:

quy-tac/nacl-stateless.sh
iptables -F; iptables -X; conntrack -F 2>/dev/null
iptables -P FORWARD DROP
iptables -N nacl-in
iptables -N nacl-out
iptables -A FORWARD -s 10.40.1.0/24 -d 10.40.2.0/24 -j nacl-in
iptables -A FORWARD -s 10.40.2.0/24 -d 10.40.1.0/24 -j nacl-out
iptables -A nacl-in -s 10.40.1.0/24 -p tcp --dport 80 -m comment --comment "rule 100 ALLOW tcp/80" -j ACCEPT
iptables -A nacl-in -m comment --comment "rule * DENY all" -j DROP
iptables -A nacl-out -m comment --comment "rule * DENY all" -j DROP
Line What it means Why it is set this way
iptables -F; iptables -X; conntrack -F Clears old rules and the connection-tracking table You can rerun the file any number of times and always get the same state.
iptables -P FORWARD DROP Packets crossing fw that match nothing are dropped Like a NACL: anything not explicitly allowed is denied.
-N nacl-in, -N nacl-out Creates two separate rule lists A NACL has two tables: Inbound rules (into the subnet) and Outbound rules (out of the subnet). These chains are those two tables.
-s 10.40.1.0/24 -d 10.40.2.0/24 -j nacl-in Packets from the client network into the web network are checked by nacl-in The “into the web subnet” direction.
-s 10.40.2.0/24 -d 10.40.1.0/24 -j nacl-out Packets from the web network out to the client network are checked by nacl-out The “out of the web subnet” direction. The web server’s replies travel this way.
--dport 80 ... "rule 100 ALLOW tcp/80" -j ACCEPT Inbound rule 100: allow TCP to port 80 The comment carries the matching NACL rule number, so the output is easy to map.
"rule * DENY all" -j DROP The last rule in each direction: deny everything Every NACL ends with a rule numbered with an asterisk (*) that denies any packet matching no other rule. You cannot delete it.

Step 3: Call the web server and watch the reply get dropped

What you are doing: loading the rules, starting tcpdump on fw to record every TCP port 80 packet on both interfaces, then letting the client call the web server with a 5-second limit.

Terminal window
docker exec -i l04-fw sh < quy-tac/nacl-stateless.sh
docker exec -d l04-fw sh -c 'timeout 8 tcpdump -lnni any -t tcp port 80 > /tmp/td.txt 2>/dev/null'
client curl -sS --max-time 5 http://10.40.2.10/
fw awk '{print $1,$2,$4,$5,$6,$7,$8}' /tmp/td.txt
fw iptables -L nacl-out -nv --line-numbers
Option What it means Why
tcpdump -i any Captures on every interface of fw Shows which interface a packet came in on (In) and went out of (Out). A blocked packet has an In without an Out.
-t, -nn No timestamps, no name lookups for IPs and ports Short lines with raw port numbers.
curl --max-time 5 Gives up after 5 seconds Without a limit curl waits a long time (step 4 measures it).
awk '{print $1,$2,...}' Prints only interface, direction, source, destination and TCP flags Drops sequence numbers so the lines fit on screen.
iptables -L -nv Lists rules with packet counters The pkts column shows how many packets each rule caught.
Output: curl reports Connection timed out after 5001 milliseconds. tcpdump on fw: the SYN from 10.40.1.10.55904 comes in on eth0 and goes out on eth1 to 10.40.2.10.80; the SYN-ACK reply from 10.40.2.10.80 to 10.40.1.10.55904 only shows eth1 In, never eth0 Out. Chain nacl-out: rule * DENY all has dropped 7 packets.
Real run: the request gets through, the reply to port 55904 enters fw and disappears; exactly 7 packets were caught by the final deny rule of the outbound direction.

How to read it:

Line Meaning
eth0 In 10.40.1.10.55904 > 10.40.2.10.80: Flags [S] The connection-opening packet (SYN) from the client enters fw. 55904 is the ephemeral port the client picked, 80 is the web port.
eth1 Out ... Flags [S] fw forwards the SYN to the web server: inbound rule 100 matched.
eth1 In 10.40.2.10.80 > 10.40.1.10.55904: Flags [S.] The web server does reply (SYN-ACK, flags S.), to the client’s port 55904.
No eth0 Out line for [S.] The reply enters fw but never leaves towards the client: it is dropped in the outbound direction.
7 420 DROP ... rule * DENY all The outbound asterisk rule dropped 7 replies (the web server resends the SYN-ACK because it hears nothing back).

This is what stateless means: to a NACL, the reply from port 80 to port 55904 is a new packet that must match an outbound rule on its own. The rules from step 2 have no such rule.

client10.40.1.10NACLnacl-in / nacl-outweb10.40.2.10:80client10.40.1.10SGconntrackweb10.40.2.10:80SYN → :80rule 100 ✓rule * ✕SYN → :80allowed ✓tracked ✓NACL (stateless): remembers nothingThe reply is judged as a brand-new packet: no outbound rule covers port 55904, so it is deniedSecurity group (stateful): remembers the connectionThe reply belongs to a connection that was let in, so it is let out automatically, no outbound rule needed
Stateless is a guard with no memory: you get in, but on the way out you are checked from scratch and stopped because your name is not on the "may leave" list. Stateful is a guard with a logbook: whoever was let in is let out automatically.

Step 4: Measure how long the user waits

What you are doing: running curl again, this time without --max-time, to see how long a normal program waits before reporting an error, while recording every SYN the client resends.

Terminal window
docker exec -d l04-client sh -c 'timeout 140 tcpdump -lnni eth0 -ttt tcp port 80 > /tmp/syn.txt 2>/dev/null'
time client curl -sS http://10.40.2.10/
client awk '{print $1,$3,$4,$5,$6,$7}' /tmp/syn.txt
Output: curl reports Failed to connect to 10.40.2.10 port 80 after 130652 ms, and time shows real 2m10.903s. tcpdump on the client shows only 7 outgoing SYN packets, about 1, 2, 4, 8, 16 and 33 seconds apart, and no reply at all.
Real run: the client sends SYN 7 times, doubling the wait each time, never gets a reply, and gives up after about 130 seconds.
No outbound rule for ephemeral ports: the client resends SYN and never gets a reply7.3s15.5s31.6s65.1sSYN 1, 2, 3 (seconds 0, 1.0, 3.0)curl gives up: 130.7 secondsWith outbound 1024-65535: HTTP 200 after 0.002 to 0.004 secondsdone almost instantly (green mark at second 0)0s15s30s45s60s75s90s105s120s135s
Real measurements from steps 4 and 5: each orange dot is one SYN sent by the client, the gap doubling each time; Linux retries 6 times and then gives up.

How to read it: the client never sees a reply, so it assumes the SYN got lost and sends it again, waiting twice as long each time. Linux retries 6 times by default (tcp_syn_retries = 6), more than 2 minutes in total. For a user, that is a web page hanging for over 2 minutes before an error, while the server is perfectly healthy. When you see a timeout this long, think about the return path first.

Step 5: Open ephemeral ports for the return path

client 10.40.1.10ephemeral port :55904web 10.40.2.10service port :80Linux 32768-60999NACL should open 1024-65535 (ELB, NAT gateway, Lambda use this whole range)out: source :55904 → destination :80back: source :80 → destination :55904010243276849152Windows 49152-6553565535← TCP port scale
An ephemeral port is like a cloakroom ticket: you get a different number each time, and the coat comes back to that exact number. The NACL cannot know in advance which number will be handed out, so it has to open the whole range.

What you are doing: checking which range the Linux client uses for ephemeral ports, then adding an outbound rule for the ephemeral range, numbered 100.

Terminal window
client cat /proc/sys/net/ipv4/ip_local_port_range
fw iptables -I nacl-out 1 -d 10.40.1.0/24 -p tcp --dport 1024:65535 -m comment --comment "rule 100 ALLOW tcp/1024-65535" -j ACCEPT
for i in 1 2 3; do client curl -sS -o /dev/null -w "HTTP %{http_code} client port %{local_port} %{time_total}s\n" http://10.40.2.10/; done
fw iptables -L nacl-out -nv --line-numbers
Option What it means Why it is set this way
ip_local_port_range The Linux kernel’s ephemeral port range 32768 60999 on the lab machine. The AWS documentation says “many Linux kernels use ports 32768-61000”.
-I nacl-out 1 Inserts the rule at the top of the outbound chain It must come before the deny-all rule, just like rule 100 comes before the * rule.
-d 10.40.1.0/24 Only lets replies go back to the client network On a NACL this is the Destination column. Opening more than needed opens doors you do not need.
--dport 1024:65535 The destination port of the reply, which is the client’s ephemeral port AWS suggests 1024-65535 to cover every kind of client: Windows Server 2008 and later use 49152-65535; Elastic Load Balancing, NAT gateways and Lambda use 1024-65535.
-w "... %{local_port} ..." curl prints the source port it used You see the ephemeral port change on every call.
Output: ip_local_port_range is 32768 60999. After inserting rule 100 ALLOW tcp/1024-65535, three curl calls all return HTTP 200 with client ports 49818, 49828 and 49830, each taking 0.002 to 0.004 seconds. Chain nacl-out: rule 100 counts packets, rule * DENY does not increase.
Real run: with one extra outbound rule the reply reaches the ephemeral port, and each call takes 2 to 4 milliseconds.

How to read it: three HTTP 200 lines with client ports 49818, 49828 and 49830: a different port every time, all inside 32768-60999. Each call takes 0.002 to 0.004 seconds, compared with 130 seconds in step 4. That is why the outbound rule must open the whole range: you cannot know in advance which number the client will pick. The pkts counter of rule 100 goes up; the * rule catches nothing new.

Step 6: The wrong ephemeral range, an intermittent failure

What you are doing: reproducing a common mistake: copying a rule from a Windows-oriented guide that only opens 49152-65535, then forcing the client to use two different source ports to compare.

Terminal window
docker exec -i l04-fw sh < quy-tac/nacl-stateless.sh
fw iptables -I nacl-out 1 -d 10.40.1.0/24 -p tcp --dport 49152:65535 -m comment --comment "rule 100 ALLOW tcp/49152-65535" -j ACCEPT
for p in 33000 50000; do client curl -sS --local-port $p --max-time 3 -o /dev/null -w "port $p -> HTTP %{http_code}\n" http://10.40.2.10/; done
Output: with rule 100 ALLOW tcp/49152-65535, curl from port 33000 reports Connection timed out after 3000 milliseconds and HTTP 000, curl from port 50000 returns HTTP 200.
Real run: same client, same rule; source port 33000 is dropped, port 50000 works.

How to read it: port 33000 (outside 49152-65535) reports timed out, port 50000 (inside) returns HTTP 200. When Linux picks the port itself, the failure is intermittent: on the lab machine, one batch of 20 curl calls had 10 timeouts, and another batch had all 20 succeed because Linux happened to pick ports in the 52xxx range. Failures like this are very hard to track down unless you think of the ephemeral range.

Step 7: NACL rule order

100 · ALLOW · TCP 80first match → allow, stop110 · DENY · 10.40.1.10/32never evaluated* · DENY · allnot evaluated90 · DENY · 10.40.1.10/32first match → deny, stop100 · ALLOW · TCP 80not evaluated110 · DENY · 10.40.1.10/32not evaluated* · DENY · allDeny as rule 110 (after)Deny as rule 90 (before)Packet: 10.40.1.10 → 10.40.2.10:80Real result: HTTP 200, the block does nothingReal result: timeout, blocked
A NACL reads the list from the lowest number to the highest and stops at the first match, like a guard scanning a list from the top: if your name appears on an "allow" line first, the "ban" line further down no longer matters.

What you are doing: pretending 10.40.1.10 is an address you need to block. First place the DENY rule after the ALLOW rule (number 110), then before it (number 90), and see which one blocks.

Terminal window
fw iptables -I nacl-in 2 -s 10.40.1.10/32 -m comment --comment "rule 110 DENY 10.40.1.10/32" -j DROP
client curl -sS --max-time 3 -o /dev/null -w "HTTP %{http_code}\n" http://10.40.2.10/; fw iptables -L nacl-in -nv --line-numbers
fw iptables -Z nacl-in; fw iptables -I nacl-in 1 -s 10.40.1.10/32 -m comment --comment "rule 90 DENY 10.40.1.10/32" -j DROP
client curl -sS --max-time 3 -o /dev/null -w "HTTP %{http_code}\n" http://10.40.2.10/; fw iptables -L nacl-in -nv --line-numbers
Option What it means Why
-I nacl-in 2 Inserts at position 2, right after the ALLOW rule Equivalent to number 110 when the ALLOW rule is number 100.
-I nacl-in 1 Inserts at the top of the chain Equivalent to number 90: lower than 100, so evaluated first.
-s 10.40.1.10/32 Exactly one address /32 is a single IP, the way AWS expects a single address to be written.
-Z nacl-in Resets the packet counters to 0 So the second measurement only counts packets from the second test.

iptables also evaluates rules from the top and stops at the first match, so the position in the chain plays the role of the NACL rule number:

Position in iptables Matching NACL rule
1 rule 90 DENY 10.40.1.10/32
2 rule 100 ALLOW TCP 80 from 10.40.1.0/24
3 rule 110 DENY 10.40.1.10/32
4 rule * DENY all
Output: with the deny as rule 110 after rule 100, curl returns HTTP 200 and the counters show rule 100 ALLOW matching while rule 110 DENY stays at 0. With the deny as rule 90 at the top, curl times out with HTTP 000, rule 90 DENY catches 2 packets and every rule below stays at 0.
Real run: a deny rule placed after the allow rule is never evaluated; placed before it, it blocks at once.

How to read it: the first time you get HTTP 200, and the pkts column of rule 110 DENY is 0: the packet matched rule 100 and stopped there, so rule 110 was never evaluated. The second time curl times out, rule 90 DENY counts packets, and every rule below it stays at 0. A real NACL works the same way: to block one address inside a range that is already allowed, the DENY rule needs a lower number.

Step 8: A security group remembers connections

What you are doing: replacing the NACL rules with security-group-style rules: one inbound rule for TCP 80 and no rule at all for the return direction. Save as quy-tac/sg-stateful.sh:

quy-tac/sg-stateful.sh
iptables -F; iptables -X; conntrack -F 2>/dev/null
iptables -P FORWARD DROP
iptables -N sg
iptables -A FORWARD -j sg
iptables -A sg -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment "stateful: reply of a tracked flow" -j ACCEPT
iptables -A sg -s 10.40.1.0/24 -d 10.40.2.10 -p tcp --dport 80 -m comment --comment "inbound tcp/80 from 10.40.1.0/24" -j ACCEPT
iptables -A sg -m comment --comment "no allow rule matched" -j DROP
Line What it means Why it is set this way
-m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT Lets through every packet that belongs to a tracked connection This is the “stateful” part. A security group does it for you; with iptables you have to write it.
-s 10.40.1.0/24 -d 10.40.2.10 -p tcp --dport 80 The only allow rule: TCP 80 from the client network to the web server Like a security group inbound rule: source, protocol, port.
-j DROP at the end Anything that matches no allow rule is dropped A security group only has allow rules; whatever is not allowed cannot get in. This is the default, not a deny rule you add.
Terminal window
docker exec -i l04-fw sh < quy-tac/sg-stateful.sh
client curl -sS -o /dev/null -w "HTTP %{http_code} client port %{local_port} %{time_total}s\n" http://10.40.2.10/
fw iptables -L sg -nv --line-numbers
fw conntrack -L -p tcp --dport 80
Output: curl returns HTTP 200. Chain sg: the stateful ESTABLISHED,RELATED rule matches many packets, the inbound tcp/80 rule matches exactly 1 packet, the final drop rule stays at 0. conntrack -L shows one tcp TIME_WAIT connection between 10.40.1.10 and 10.40.2.10 port 80, marked ASSURED.
Real run: only the first packet needs the inbound rule; every later packet, replies included, passes thanks to the connection-tracking table.

How to read it:

  • HTTP 200 even though there is no outbound rule.
  • The inbound tcp/80 rule counts only 1 packet: the first SYN. Every other packet, in both directions, matches the stateful rule above it.
  • The conntrack line is the filter’s “logbook”: it holds both the forward direction (sport=<ephemeral port> dport=80) and the reverse direction (sport=80 dport=<ephemeral port>). [ASSURED] means packets were seen in both directions. Thanks to this entry, the reply is recognised as a reply rather than a stranger.

According to the AWS documentation, security groups use the same connection tracking: responses to allowed inbound traffic are allowed to leave regardless of outbound rules.

Step 9: The same rules with the AWS CLI

What you are doing: creating this guide’s NACL and security group with the AWS CLI to see their real shape: rule numbers, direction, action. awsl is the AWS CLI pointed at Moto running on your machine (setup is in the “Lab setup” guide).

Terminal window
VPC=$(awsl ec2 create-vpc --cidr-block 10.40.0.0/16 --query Vpc.VpcId --output text)
SUB=$(awsl ec2 create-subnet --vpc-id $VPC --cidr-block 10.40.2.0/24 --query Subnet.SubnetId --output text)
ACL=$(awsl ec2 create-network-acl --vpc-id $VPC --query NetworkAcl.NetworkAclId --output text)
awsl ec2 create-network-acl-entry --network-acl-id $ACL --ingress --rule-number 100 --protocol tcp --port-range From=80,To=80 --cidr-block 10.40.1.0/24 --rule-action allow
awsl ec2 create-network-acl-entry --network-acl-id $ACL --ingress --rule-number 90 --protocol -1 --cidr-block 10.40.1.10/32 --rule-action deny
awsl ec2 create-network-acl-entry --network-acl-id $ACL --egress --rule-number 100 --protocol tcp --port-range From=1024,To=65535 --cidr-block 10.40.1.0/24 --rule-action allow
awsl ec2 create-network-acl-entry --network-acl-id $ACL --ingress --rule-number 100 --protocol tcp --port-range From=443,To=443 --cidr-block 10.40.1.0/24 --rule-action allow
OLD=$(awsl ec2 describe-network-acls --filters Name=association.subnet-id,Values=$SUB --query 'NetworkAcls[0].Associations[0].NetworkAclAssociationId' --output text)
awsl ec2 replace-network-acl-association --association-id $OLD --network-acl-id $ACL --output text
awsl ec2 describe-network-acls --network-acl-ids $ACL --query 'sort_by(NetworkAcls[0].Entries,&RuleNumber)[].[RuleNumber,Egress,RuleAction,Protocol,CidrBlock,PortRange.From,PortRange.To]' --output text
Option What it means Why it is set this way
create-network-acl Creates a custom NACL for the VPC A newly created custom NACL blocks everything in both directions and is not associated with any subnet yet.
--ingress / --egress Rule for traffic into or out of the subnet Two separate tables, just like nacl-in and nacl-out in the lab.
--rule-number 100, 90 Rule number, evaluated from low to high Rule 90 DENY comes before rule 100 ALLOW, as in step 7.
--protocol -1 All protocols Blocks that address completely, not just port 80.
--port-range From=1024,To=65535 The ephemeral range for the return direction The rule that fixes the problem from step 3.
The fourth command reusing --rule-number 100 Tries to create two rules with the same number in the same direction Shows the NetworkAclEntryAlreadyExists error: each number can be used once per direction.
replace-network-acl-association Associates the new NACL with the web subnet Every subnet is always associated with exactly one NACL; a new subnet starts on the default NACL, so you replace the association rather than “add” one.
AWS CLI output: creating a duplicate rule 100 fails with NetworkAclEntryAlreadyExists, the network acl entry identified by 100 already exists; replace-network-acl-association returns a new association id; describe-network-acls lists 90 False deny -1 10.40.1.10/32, 100 False allow 6 10.40.1.0/24 80 80, and 100 True allow 6 10.40.1.0/24 1024 65535.
Real run on Moto: a NACL rule table with rule numbers, direction (Egress True means outbound), allow or deny action, protocol (6 is TCP) and port range.

How to read it: each line is one rule: RuleNumber, Egress (False is inbound, True is outbound), RuleAction, Protocol (6 is TCP, -1 is all protocols), CIDR, first port, last port. Two rules numbered 100 are fine because one is inbound and the other outbound. Creating a second inbound rule 100 is rejected.

Next, the security group:

Terminal window
SG=$(awsl ec2 create-security-group --group-name l04-web-sg \
--description 'web tcp 80' --vpc-id $VPC --query GroupId --output text)
awsl ec2 authorize-security-group-ingress --group-id $SG \
--protocol tcp --port 80 --cidr 10.40.1.0/24 --output text
awsl ec2 describe-security-group-rules --filters Name=group-id,Values=$SG \
--query 'SecurityGroupRules[].[IsEgress,IpProtocol,FromPort,ToPort,CidrIpv4]' --output text
Option What it means Why
authorize-security-group-ingress Adds an inbound rule The command is literally “authorize”: there is no command or option to create a deny rule.
--protocol tcp --port 80 --cidr 10.40.1.0/24 Allows TCP 80 from the client network Same as the inbound tcp/80 rule in step 8.
describe-security-group-rules Lists each rule of the security group, one per line Easy to compare with the NACL rule table above.
IsEgress True is outbound, False is inbound Like the NACL Egress column, but there is no rule number or allow/deny column to choose.
\ at the end of a line The command continues on the next line Only for readability; the shell joins the lines into one command.
AWS CLI output: authorize-security-group-ingress returns True and one SECURITYGROUPRULES line with 10.40.1.0/24, port 80, tcp, IsEgress False. describe-security-group-rules prints two lines: True -1 -1 -1 0.0.0.0/0 (the default outbound rule) and False tcp 80 80 10.40.1.0/24 (the inbound rule just added).
Real run on Moto: security group rules have no rule number and no allow or deny field, because every rule is an allow.

How to read it: compared with a NACL, security group rules have no rule number and no allow/deny column. AWS evaluates all rules before deciding, and every rule is an allow. The line True -1 -1 -1 0.0.0.0/0 is the default outbound rule that allows everything out (-1 means every protocol and port); False tcp 80 80 10.40.1.0/24 is the inbound rule you just added. You add no rule for ephemeral ports: replies pass because the security group remembers the connection.

Applying this on real AWS

  • Security groups are the primary control. The AWS documentation recommends security groups as the main mechanism, with NACLs for coarse subnet-level filtering or for denying a specific subset of traffic (something security groups cannot do).
  • Every NACL rule that allows one direction needs a rule for the return direction. Open inbound TCP 443 for a web server, and open outbound TCP 1024-65535; for instances in the subnet calling out, it is the reverse: outbound to the destination port, inbound 1024-65535.
  • To cut an active connection immediately, use a NACL. Changing a security group rule does not interrupt tracked connections right away; they continue until they time out. A NACL keeps no state, so adding a deny rule breaks the connection at once.
  • Default quotas: 20 rules per direction per NACL (adjustable up to 40, with possible impact on network performance); 60 inbound and 60 outbound rules per security group.
  • Some traffic is not filtered by NACLs or security groups: Amazon DNS (Route 53 Resolver), DHCP, instance metadata, Amazon Time Sync Service and a few reserved addresses of the VPC router. To filter DNS, use Route 53 Resolver DNS Firewall.
  • When you are not sure where packets are dropped, turn on VPC Flow Logs and look for REJECT records.

Common errors

Symptom Cause Fix
curl: (28) Failed to connect to ... after 130xxx ms while the server runs and its log shows the request The NACL allows the service port inbound but has no outbound rule for ephemeral ports Add outbound TCP 1024-65535 to the client range
Works sometimes, fails sometimes, no pattern Ephemeral range too narrow (for example only 49152-65535) while clients run Linux Open 1024-65535, or at least cover the range of every client type
You added a DENY rule but the address still gets in The DENY rule has a higher number than the ALLOW rule that matches first Recreate the DENY rule with a lower number
NetworkAclEntryAlreadyExists Duplicate rule number in the same direction Pick another number; number in steps of 10 or 100
NetworkAclEntryLimitExceeded The NACL rule quota is used up (20 per direction by default) Merge CIDR ranges, or request a quota increase
You create a new NACL and every connection in the subnet drops A new custom NACL denies everything and was associated before its rules were added Add all rules first, associate the subnet afterwards
Editing the NACL has no effect You edited the wrong NACL: the subnet is associated with another one (often the default NACL) describe-network-acls --filters Name=association.subnet-id,Values=<subnet> shows which NACL the subnet uses
Traffic between two instances in the same subnet is not blocked by the NACL NACLs only evaluate traffic entering and leaving the subnet, not traffic routed within it Filter between instances in one subnet with security groups
ping fails although the web page works ICMP is its own protocol, not covered by TCP rules. On the lab machine, with this guide’s NACL rules (ephemeral TCP ports already open), ping still lost 100% of packets Add ICMP rules to the security group (inbound) and to the NACL (both directions)
Some users hang when loading large pages Blocking all ICMP breaks Path MTU Discovery Allow ICMP type 3 code 4 in both directions on the NACL

Clean up

Terminal window
docker rm -f l04-client l04-web l04-fw
docker network rm l04-net-client l04-net-web
awsl ec2 replace-network-acl-association --association-id $(awsl ec2 describe-network-acls --network-acl-ids $ACL --query 'NetworkAcls[0].Associations[0].NetworkAclAssociationId' --output text) --network-acl-id $(awsl ec2 describe-network-acls --filters Name=vpc-id,Values=$VPC Name=default,Values=true --query 'NetworkAcls[0].NetworkAclId' --output text)
awsl ec2 delete-network-acl --network-acl-id $ACL
awsl ec2 delete-security-group --group-id $SG
awsl ec2 delete-subnet --subnet-id $SUB
awsl ec2 delete-vpc --vpc-id $VPC

FAQ

I already have security groups. Do I need NACLs? Not necessarily. Security groups are enough for most cases. NACLs help when you need to block a specific address range, want one guard rail for a whole subnet, or want protection in case someone launches an instance with the wrong security group.

Why not open exactly 32768-60999 outbound and keep it tight? Because clients are not only Linux. Windows uses 49152-65535; Elastic Load Balancing, NAT gateways and Lambda use 1024-65535. AWS suggests opening 1024-65535 and, if needed, adding DENY rules for dangerous ports in that range, numbered lower than the ALLOW rule.

Can a security group block one specific IP address? No. Security groups only have allow rules. To block, use a NACL DENY rule numbered lower than the ALLOW rule that lets that range in.

Does the default NACL block anything? No. A VPC’s default NACL allows all inbound and outbound traffic. Only a newly created custom NACL denies everything.

References

Related guides: Cloud and network lab setup (Docker, Moto, awsl) and VPN with 2 tunnels and BGP, where a stateful firewall breaks connections that leave one way and return another.

Cao Le Nam Trung

Cao Le Nam Trung

Cloud & Network Engineer · TrungCLN

Designs and runs AWS infrastructure, hybrid networking (VPN, BGP) and cloud security. Every guide on this site is built and run for real before it is written.

LinkedIn YouTube Facebook

Related guides

OfficeAWS Cloudtunnel-1 soft failuretunnel-2 carries trafficOffice LANRouter BGPVPN GatewayVPC

NetworkingIntermediate50 min

VPN with 2 tunnels and BGP: how long does failover really take?

Build two BGP routers over two tunnels like AWS Site-to-Site VPN, measure failover for hard and soft failures, and learn why every config line is there.