NetworkingBeginner
Security group or NACL? Why the reply gets dropped: stateful, stateless, ephemeral ports
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

🎬 Goes live 19 Dec 2026, 20:00 (UTC+7)
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:
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
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-clientbuilds a packet from10.40.1.10:<ephemeral port>to10.40.2.10:80. The destination is on another network, so its route says: send it to10.40.1.254.l04-fwreceives the packet oneth0. Because the packet is not for fw itself but passing through, Linux runs it through the iptablesFORWARDchain, where this guide’s NACL or security group rules decide whether it passes or is dropped.- If allowed, fw sends the packet out of
eth1to10.40.2.10. l04-webreplies from10.40.2.10:80to10.40.1.10:<ephemeral port>. The web server’s route sends packets for the client network to10.40.2.254.l04-fwreceives the reply oneth1, and theFORWARDchain checks it again, this time in the return direction.- If allowed, fw sends it out of
eth0to the client, andcurlgets 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 MotoRunning ./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:
IMG=nicolaka/netshoot:latestdocker network create --subnet 10.40.1.0/24 l04-net-clientdocker network create --subnet 10.40.2.0/24 l04-net-webdocker 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 infinitydocker network connect --ip 10.40.2.254 l04-net-web l04-fwdocker 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:
./dung.shalias 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”:
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. |

How to read it:
eth0@if176means the container’seth0is 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 line10.40.2.0/24 via 10.40.1.254 dev eth0is the route we added: packets for the web network go through fw. Onl04-web,10.40.1.0/24 via 10.40.2.254does the same for the return direction. l04-fwhas twoproto kernel scope linklines: 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:
iptables -F; iptables -X; conntrack -F 2>/dev/nulliptables -P FORWARD DROPiptables -N nacl-iniptables -N nacl-outiptables -A FORWARD -s 10.40.1.0/24 -d 10.40.2.0/24 -j nacl-iniptables -A FORWARD -s 10.40.2.0/24 -d 10.40.1.0/24 -j nacl-outiptables -A nacl-in -s 10.40.1.0/24 -p tcp --dport 80 -m comment --comment "rule 100 ALLOW tcp/80" -j ACCEPTiptables -A nacl-in -m comment --comment "rule * DENY all" -j DROPiptables -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.
docker exec -i l04-fw sh < quy-tac/nacl-stateless.shdocker 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.txtfw 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. |

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.
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.
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
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
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.
client cat /proc/sys/net/ipv4/ip_local_port_rangefw 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 ACCEPTfor 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/; donefw 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. |

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.
docker exec -i l04-fw sh < quy-tac/nacl-stateless.shfw 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 ACCEPTfor 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
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
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.
fw iptables -I nacl-in 2 -s 10.40.1.10/32 -m comment --comment "rule 110 DENY 10.40.1.10/32" -j DROPclient 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-numbersfw 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 DROPclient 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 |

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:
iptables -F; iptables -X; conntrack -F 2>/dev/nulliptables -P FORWARD DROPiptables -N sgiptables -A FORWARD -j sgiptables -A sg -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment "stateful: reply of a tracked flow" -j ACCEPTiptables -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 ACCEPTiptables -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. |
docker exec -i l04-fw sh < quy-tac/sg-stateful.shclient 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-numbersfw conntrack -L -p tcp --dport 80
How to read it:
HTTP 200even though there is no outbound rule.- The
inbound tcp/80rule counts only 1 packet: the first SYN. Every other packet, in both directions, matches thestatefulrule above it. - The
conntrackline 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).
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 allowawsl ec2 create-network-acl-entry --network-acl-id $ACL --ingress --rule-number 90 --protocol -1 --cidr-block 10.40.1.10/32 --rule-action denyawsl 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 allowawsl 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 allowOLD=$(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 textawsl 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. |

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:
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 textawsl 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. |

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
REJECTrecords.
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
docker rm -f l04-client l04-web l04-fwdocker network rm l04-net-client l04-net-webawsl 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 $ACLawsl ec2 delete-security-group --group-id $SGawsl ec2 delete-subnet --subnet-id $SUBawsl ec2 delete-vpc --vpc-id $VPCFAQ
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
- AWS: Control subnet traffic with network ACLs
- AWS: Custom network ACLs and ephemeral ports
- AWS: Default network ACL
- AWS: Create a network ACL
- AWS: Security group rules
- AWS: Compare security groups and network ACLs
- AWS: Security group connection tracking
- AWS: Amazon VPC quotas
- AWS: Path MTU Discovery and network ACLs
- AWS CLI: create-network-acl
- AWS re:Post: Allow users to reach a website on EC2 over HTTP/HTTPS
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.

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.
Related guides
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.

AWSBeginner30 min
ALB 502 or 503? Every target is unhealthy, yet the site still returns 200
A real lab with Envoy playing an ALB: all targets unhealthy still returns 200 (fail open), a closed app port gives 502, only an empty target group gives 503.