Skip to content

Firewalls: iptables/nftables, Security Groups, Network ACLs, Egress Control ​

"Packets are routed before the firewall rules can be applied, effectively ignoring your firewall configuration." — Docker documentation, Packet filtering and firewalls (on docker run -p and ufw)

Summary: A firewall is a list of rules that decide, packet by packet or flow by flow, what may enter, leave or cross a machine or a network; the whole skill is knowing where the rule list sits (host, container bridge, subnet, interface of a cloud instance, pod) and what it can see (the 5-tuple, the connection state, the interface).
Focus: What a firewall filters on, stateless vs stateful, default-deny, the netfilter hooks and tables, iptables and nftables syntax, conntrack, logging and rate limits, ICMP and PMTUD, IPv6, Docker's firewall rules, Kubernetes NetworkPolicy, AWS security groups and network ACLs against GCP and Azure, egress control, listener binding as a second wall, and how to audit all of it.
Learning goal: Read any ruleset (iptables, nft, security group, NACL, NetworkPolicy), say which packet it lets through and why, write a default-deny policy for a server, a container host and a namespace, and recognise the five classic failures (ephemeral ports, Docker bypass, unenforced policy, blocked health checks, blocked ICMP).

This chapter is packet filtering as a developer meets it: a Linux server you deploy to, docker run -p, a cloud security group, a Kubernetes namespace. It builds on network models (what a packet is made of), IP addressing and CIDR (what the rules match), NAT and port forwarding (the rewrites that happen next to filtering) and ports, sockets and connections (what a listening socket is, how conntrack and ephemeral ports behave). The container models live in Docker networking and Kubernetes networking; tunnels that replace open ports are in VPNs and tunnels; a symptom-first view is the troubleshooting playbook. Attack-side material (DDoS, WAF, volumetric floods) is the system-design chapter DDoS and network security; security architecture is security foundations, identity-based rules are authorization and zero trust and service identity is mTLS. This page does not repeat them.

Page map ​

If you are looking forGo to
The tables to memoriseEverything in one minute
Why firewalls exist, three misunderstandingsWhy firewalls exist
netfilter, iptables, nftables, security groups: who invented whatWhere it comes from
5-tuple, state, interface, directionWhat a firewall filters on
Stateless vs statefulStateless vs stateful
Default-deny and allow-listsDefault-deny
Hook points, tables, packet-flow diagramnetfilter hooks and tables
ESTABLISHED,RELATED, ct state, conntrack toolconntrack and states
-A INPUT -p tcp --dport 22 -m conntrack ... decodediptables syntax
nft list ruleset, sets, maps, inet, iptables-nftnftables
ufw and firewalldFront-ends
log, limit rate, meters, fail2banLogging and rate limiting
Why not block all ICMP, PMTUD, hex dumpICMP
No NAT to hide behindIPv6 firewalling
-p bypasses ufw, DOCKER-USER, Docker 28+Docker and firewalls
Default allow, selectors, CNI support, eBPFKubernetes NetworkPolicy
SG, NACL, GCP, Azure comparedCloud firewalls
Exfiltration, supply chain, NAT gateway, FQDN rulesEgress control
Host vs perimeter, bind to 127.0.0.1Host vs perimeter, Listener binding
WAF vs firewall vs security groupLayer table
It worked yesterdayCommon failures
Counters, flow logs, conntrack -LAuditing
Rule evaluation order, verdicts, prioritiesMechanics
Go: policy checker, Unix socket admin listenerSolving the classic problems
Laravel: CIDR middleware, TrustProxies, webhooksLaravel
Which control for which situationChoosing
Monolith to distributedIn architecture
Reproduce itLab
Misconceptions, cheat sheet, glossaryMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

What a rule can look at. Every row is unpacked later.

Match fieldExampleNeeds state?Where it exists
Source / destination IPip saddr 10.0.0.0/8Noiptables, nft, SG, NACL, NetworkPolicy ipBlock
Protocoltcp, udp, icmp, ipv6-icmpNoeverywhere
Source / destination porttcp dport 22Noeverywhere (not ICMP)
TCP flagstcp flags synNoiptables, nft (not clouds)
Interface and directioniifname "eth0", -i eth0, INPUT vs OUTPUTNohosts; clouds attach rules to an ENI, a subnet or a NIC
Connection statect state established,relatedYesiptables -m conntrack, nft ct state, SG (implicit)
Labels instead of addressespod labels, SG references, tags, service tagsDependsNetworkPolicy, SG, GCP tags, Azure ASG

The five places a rule list can live.

PlaceProductScopeDefault for new traffic
The Linux hostiptables, nftables, ufw, firewalldOne machine, all interfacesACCEPT (until you set a policy)
The container bridgeDocker's own rules in DOCKER-* chainsContainers on this hostPublished ports open to everyone
The cloud network interfaceAWS security group, GCP firewall rule, Azure NSGOne instance (or a tagged set)Inbound deny, outbound allow
The cloud subnetAWS network ACLEverything in a subnetDefault NACL allows all; a new custom one denies all
The podKubernetes NetworkPolicy (enforced by the CNI)Pods in a clusterAllow all until a policy selects the pod

The five failures to expect.

SymptomUsual causeChapter section
SG allows 443, clients still time outNACL blocks the return traffic to ephemeral portsFailures
ufw denies 5432, the database is public anywayDocker published the port; the packet never reaches INPUTDocker
NetworkPolicy applied, nothing changedThe CNI does not enforce NetworkPolicyKubernetes
Load balancer marks all targets unhealthyHealth-check source not allowed by SG or NACLFailures
Small requests work, big uploads hangICMP "fragmentation needed" / "packet too big" is droppedICMP

Why firewalls exist ​

A machine that listens on a port accepts anyone who can reach it. Most services were never designed to face the whole internet: a database, a Redis, an admin panel, sshd with password login, a metrics endpoint. A firewall is the cheapest place to say "this port is for these clients only", because it works for every program on the machine, including the ones nobody remembers installing.

Without a firewallWith one
Every listening socket is a public serviceOnly the ports you named are reachable
One misconfigured service (Redis without a password) is a breachThe same mistake is reachable only from the allowed range
A compromised process can talk to anythingEgress rules limit where it can send data or fetch tools
Scanning finds everything in minutesDropped packets give scanners nothing; logs show who tried

The everyday picture. A building with a doorman. The doorman does not read your letters (that is the application); he looks at who you are (source address), which door you are using (port) and whether someone inside called for you (connection state). A stateless doorman has a list for people coming in and another for people going out, and checks both lists every time. A stateful doorman remembers "this visitor was invited" and lets the reply back without a second look.

Three misunderstandings, up front.

MisunderstandingReality
"NAT hides my servers, so IPv6 needs no firewall"NAT was never a security mechanism; RFC 4864 says so plainly. With IPv6 every host has a global address, so the firewall is the only wall
"My firewall denies the port, so the port is closed"A firewall hides a port from the network; the process still listens. Another path (Docker's DNAT, a second interface, a pod network) can reach it
"Block ICMP, it is only ping"ICMP carries the errors that make TCP work (fragmentation needed, destination unreachable). Blocking all of it creates MTU black holes

Where it comes from ​

SourceWhat it gave us
ipfwadm, ipchains (Linux 1.x, 2.2)The first Linux packet filters; rules in kernel lists
iptables / netfilter (Linux 2.4, 2001)Hooks in the network stack, tables (filter, nat, mangle, raw), connection tracking and the -m match extensions
nftables (merged in Linux 3.13)One rule engine and one tool nft replacing iptables, ip6tables, arptables, ebtables; sets, maps, the inet family
RFC 4864 (2007)"Local Network Protection for IPv6": why NAT is not a firewall and what to do instead
RFC 4890 (2007)"ICMPv6 Filtering Recommendations": which ICMPv6 messages must never be dropped
RFC 1191 / RFC 4821Path MTU Discovery for IPv4 and the "packetization layer" variant that survives dropped ICMP
AWS VPC security groupsThe instance-level, stateful, allow-only model that every cloud copied in some form
Kubernetes NetworkPolicy (networking.k8s.io/v1)A label-based, additive allow model enforced by the network plugin
Cilium and eBPFPolicy enforced in eBPF programs in the kernel instead of long iptables lists

The nftables project states its own purpose: "nftables is the modern Linux kernel packet classification framework. New code should use it instead of the legacy {ip,ip6,arp,eb}_tables (xtables) infrastructure." The same page lists what went wrong with iptables: one extension per protocol, "Faster packet classification through enhanced generic set and map infrastructure", and "Simplified dual stack IPv4/IPv6 administration, through the new inet family".

The concept catalogue ​

What a firewall filters on: the 5-tuple, state, interface and direction Must-know ​

In plain words: A rule is a question about the packet header ("is the source in this range and the destination port 22?") plus an answer ("accept" or "drop"). The firewall reads the header; it does not understand HTTP, SQL or users.

Common misunderstanding: "A firewall can allow GET /health but not POST /admin." A packet filter sees addresses, ports, flags and the connection state. URLs, methods and cookies are inside the payload (and inside TLS); that is a proxy or WAF job, see the layer table.

Definition: The classic key is the 5-tuple: source IP, source port, destination IP, destination port, protocol. Four more inputs matter in practice: the interface the packet came in or goes out on, the direction relative to the host (into the host, out of it, or across it), the connection state (new, established, related, invalid) and the packet's marks and flags. Azure's documentation uses the same model for its rules: "Security rules are evaluated and applied based on the five-tuple information of source, source port, destination, destination port, and protocol."

 Ethernet | IPv4 header                          | TCP header                       | payload
          | proto=6  src=172.19.0.3 dst=172.19.0.2 | sport=52386 dport=5432 flags=SYN |
              ^^^^^^^   ^^^^^^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
              protocol  source / destination IP        source / destination port   => the 5-tuple

A real capture of one packet that a default-deny host dropped, with every byte that a rule can match. The frame came from tcpdump -n -XX on a Linux container; offsets are from the start of the Ethernet frame:

18:01:24.562436 IP 172.19.0.3.52386 > 172.19.0.2.5432: Flags [S], seq 1812388152, win 64240, length 0
	0x0000:  3e20 ea32 077e 4660 4252 9bd4 0800 4500  >..2.~F`BR....E.
	0x0010:  003c e465 4000 4006 fe2a ac13 0003 ac13  .<.e@.@..*......
	0x0020:  0002 cca2 1538 6c06 d938 0000 0000 a002  .....8l..8......
OffsetBytesFieldValueA rule that matches it
0x003e20 ea32 077e / 4660 4252 9bd4dest MAC / source MACthe two NICsether saddr (rarely used)
0x0c0800EtherTypeIPv4meta protocol ip
0x0e45version 4, header length 5 words20-byte header(implicit)
0x1640 / 06TTL 64 / protocol 6TCPip protocol tcp (-p tcp)
0x1aac13 0003source IP172.19.0.3ip saddr 172.19.0.3
0x1eac13 0002destination IP172.19.0.2ip daddr 172.19.0.2
0x22cca2source port52386 (ephemeral)tcp sport 52386
0x241538destination port5432tcp dport 5432
0x2f02 (in a002: header length 10 words, flags 02)TCP flagsSYN onlytcp flags syn, ct state new

Real scenarios: an allow rule for 10.0.0.0/8 on port 22; a drop for every SYN to 5432 from outside the VPC; an egress rule that allows only tcp dport 443 to a payments provider; a security group that names another security group instead of an address.

ProductFields it can match
iptables / nftablesEverything in the table above, plus marks, packet length, owner uid (-m owner), rate, hash, geo (extension)
AWS security groupProtocol, port range, ICMP type and code, source or destination as CIDR, prefix list or another SG
AWS network ACLProtocol, port range, ICMP type and code, CIDR; numbered rules
GCP VPC firewall ruleProtocol and ports, source or destination ranges, source and target tags or service accounts, direction, priority
Azure NSGThe 5-tuple, service tags, application security groups, priority
Kubernetes NetworkPolicyPod and namespace labels, ipBlock CIDRs, protocol and port (TCP, UDP, SCTP)

Stateless vs stateful Must-know ​

In plain words: A stateless filter judges every packet alone, so you must allow the request and, separately, the reply. A stateful filter remembers the connection: allow the request, and the reply is allowed automatically.

Common misunderstanding: "Stateful means it tracks TCP only." Linux conntrack, AWS security groups and the others also track UDP and ICMP "flows" with timeouts; for UDP a flow is "a packet went out, so a packet from the same address and port may come back".

Definition: A stateful firewall keeps a table of flows. The first packet of a flow is evaluated against the rules; if accepted, the flow is recorded, and later packets of that flow (both directions) match the table and skip the rules. A stateless firewall has no table; every packet is matched against the rule list again.

Stateful (Linux conntrack, AWS security group)        Stateless (AWS network ACL)
1  client -> :443  SYN        rule says allow, flow recorded       rule IN 100 allows tcp 443
2  server -> client:51344 SYN,ACK   matches the flow: allowed     rule OUT needed for ephemeral 51344
3  client -> :443  ACK, data  matches the flow: allowed           rule IN 100 again
4  server -> client:51344 data      matches the flow: allowed     rule OUT again

Real scenarios: a web server with one inbound rule that works without any outbound rule (stateful); a subnet that "allows 443" but every connection stalls because the outbound ephemeral range is missing (stateless); a rule change that does not kill the SSH session you are typing in (stateful, because the connection is already tracked).

ProductStateful?Detail
Linux netfilterOnly if you use conntrack (ct state)Loaded by default when a rule needs it; you write ct state established,related accept yourself
AWS security groupYes"responses to inbound traffic are allowed to flow out of the instance regardless of outbound security group rules, and vice versa"
AWS network ACLNo"responses to that traffic are not automatically allowed"
GCP VPC firewallYes (as designed)See the cloud section for the sourcing note
Azure NSGYes"Network security group rules only affect new connections"
Kubernetes NetworkPolicyYes"Reply traffic for those allowed connections will also be implicitly allowed"

Fix / how to use it: In nftables and iptables always put the established rule near the top (it is the hot path). In AWS leave NACLs at their defaults unless you need a subnet-level deny, and when you do, add the ephemeral return range.

Default-deny and allow-lists Must-know ​

In plain words: Start from "nothing is allowed", then list what is. The opposite (allow everything, then try to list the bad things) never ends.

Common misunderstanding: "Default deny on INPUT is enough." Egress, FORWARD and the container network each have their own default. A host can be perfect on INPUT and still be an open relay for traffic it forwards, or send secrets anywhere.

Definition: A chain's policy is the verdict for a packet that matches no rule. policy drop makes the chain an allow-list; every accept rule is an exception to the denial. Clouds give you this on the inbound side of a security group and on NACLs (an implicit final "deny all", rule number *).

Policy ACCEPT (the iptables/nft default)      Policy DROP (an allow-list)
rule 1  drop  tcp dport 23                     rule 1  accept ct established,related
rule 2  drop  tcp dport 3306                   rule 2  accept tcp dport {80,443}
...(you forgot 6379)                           (policy)  drop   everything else, including 6379
6379 is open                                   6379 is closed

Real scenarios: a Redis installed by a package manager that listens on all interfaces; a debug port opened for an hour and forgotten; a new service on a new port that nobody added to a blocklist.

ProductDefault for new traffic
iptables, nftables (no ufw)ACCEPT in every chain
ufw"default incoming policy of deny, a default forward policy of deny, and a default outgoing policy of allow" (ufw man page, Ubuntu)
firewalldInter-zone traffic denied, intra-zone allowed by zone principles
AWS security groupNo inbound rules (deny), one allow-all outbound rule
AWS default NACLAllows all inbound and outbound; a new custom NACL denies all until you add rules
Azure NSGDefault rules at priorities 65000, 65001, 65500: allow VNet and load balancer inbound, deny the rest
Kubernetes"if no policies exist in a namespace, then all ingress and egress traffic is allowed"

Fix / how to use it: Before you set policy drop on a remote machine, make sure your own SSH rule is in place first (or the change is scheduled to revert), otherwise you lock yourself out. The lab shows the order.

netfilter hooks and tables Must-know ​

In plain words: The Linux kernel calls your rules at fixed points along a packet's path. Which point you choose decides what the packet looks like when your rule sees it (already NATed or not, headed for this host or for another).

Common misunderstanding: "INPUT is where all incoming packets are filtered." Only packets addressed to this host reach INPUT. Packets that the host routes to somewhere else (containers, VMs, a router role) go through FORWARD and never touch INPUT. Docker's published ports are exactly that case.

Definition: netfilter defines five hooks for IPv4 and IPv6: prerouting (just after arrival), input (for a local process), forward (routed through the host), output (from a local process) and postrouting (just before leaving). Packets for this host see prerouting then input; packets sent by the host see output then postrouting; packets routed through it see prerouting, forward, postrouting. The nftables wiki words the same: "Traffic flowing to the local machine in the input path sees the prerouting and input hooks. Then, the traffic that is generated by local processes follows the output and postrouting path." The extra ingress hook (kernel 4.2) attaches to one interface and runs before prerouting, before fragments are reassembled.

NIC inpacket arrivesPREROUTINGraw, mangle, nat(DNAT)routingdecisionINPUTmangle, filterLocal processnginx, php-fpm, sshdFORWARDmangle, filterOUTPUTraw, mangle, nat, filterPOSTROUTINGmangle, nat(SNAT)NIC outpacket leavesfor this hostother destLocal replies and locally started connections take the dashed path: process, OUTPUT, routing, POSTROUTING.A routed packet (host as router) never touches INPUT or OUTPUT: PREROUTING, FORWARD, POSTROUTING.

iptables arranges rules in tables, each with a purpose, and each table registers chains at some hooks:

TablePurposeHooks (chains) it hasTypical rule
rawRun before conntrack; mark packets as NOTRACKPREROUTING, OUTPUTExempt a busy DNS server from conntrack; Docker drops direct-routed packets here
mangleChange packet fields (TOS, TTL, marks)all fivePolicy routing marks, MSS clamping
natRewrite addresses; consulted for the first packet of a flow onlyPREROUTING (DNAT), OUTPUT, POSTROUTING (SNAT, MASQUERADE), INPUT-j DNAT, -j MASQUERADE (see NAT)
filterAccept or dropINPUT, FORWARD, OUTPUTYour allow-list
securitySELinux-style labelsINPUT, FORWARD, OUTPUTRare

Order inside one hook is decided by priority. The nft man page lists the numbers: conntrack defrag -400, raw -300, conntrack -200, mangle -150, DNAT -100, filter 0, security 50, SNAT 100. That is why DNAT happens before the filter table sees the packet (so FORWARD matches the container's address, not the published one) and SNAT happens after.

TimelineWhat the kernel does with a packet to a published container port
1NIC receives the frame, conntrack creates an entry (priority -200)
2nat PREROUTING DNAT rewrites host:8080 to 172.18.0.2:80 (priority -100)
3Routing decision: the destination is a local bridge, not this host, so the packet goes to forward
4filter FORWARD: DOCKER-USER, then Docker's own chains
5nat POSTROUTING may masquerade; the frame leaves through the bridge

Real scenarios: an iptables rule on INPUT that does nothing for a container port; an OUTPUT rule that blocks a PHP-FPM worker from reaching a payments host; a raw rule that keeps a noisy UDP service out of the conntrack table.

ProductWhere its rules attach
iptablesFixed chains in fixed tables (INPUT, FORWARD, ...)
nftablesBase chains you create with type filter hook input priority filter; in any table; regular chains you jump to
ufwufw-before-input, ufw-user-input and similar chains jumped to from INPUT/FORWARD/OUTPUT
firewalldZones compiled to nftables (or iptables) chains with names like filter_IN_public
DockerDOCKER-USER, DOCKER-FORWARD, DOCKER, DOCKER-CT, DOCKER-BRIDGE, DOCKER-INTERNAL in filter; DOCKER in nat; PREROUTING drops in raw
Kubernetes kube-proxyKUBE-SERVICES and KUBE-NODEPORTS chains in nat, KUBE-FORWARD in filter

conntrack and ESTABLISHED,RELATED Must-know ​

In plain words: conntrack is the kernel's notebook of connections. A rule can ask "is this packet part of a connection I already allowed?" and wave it through without re-reading the rule list.

Common misunderstanding: "ESTABLISHED means the TCP handshake finished." For conntrack it means traffic has been seen in both directions; a UDP or ICMP flow becomes ESTABLISHED after the first reply too. That is also why a rate limit on ICMP echo placed after the established rule never fires (the lab shows it).

Definition: Each packet gets one of these states, which nft calls ct state and iptables calls -m conntrack --ctstate:

StateMeaningTypical rule
newFirst packet of a flow, not seen beforetcp dport 443 ct state new accept
establishedPart of a flow with traffic in both directionsct state established,related accept (first rule)
relatedA new flow that is tied to an existing one: an ICMP error about a flow, an FTP data connection through a helperSame rule as above
invalidCannot be placed in any flow (out-of-window TCP, bogus flags)ct state invalid drop
untrackedExempted with a raw rule (notrack)You must allow these explicitly

The nft man page says the state bits are mutually exclusive, so the list form ct state established,related and the set form ct state { established, related } "match exactly the same packets".

$ conntrack -L -p tcp
tcp  6 116 TIME_WAIT src=172.17.0.6 dst=172.17.0.4 sport=56564 dport=18080 src=172.18.0.2 dst=172.17.0.6 sport=80 dport=56564 [ASSURED] mark=0 use=1
        ^   ^^^         original direction (as the client sent it)       reply direction (as the server answers after DNAT)
        proto number, seconds left until the entry expires

The first tuple is what the client sent; the second is the expected reply. For a DNAT'd flow the second tuple already shows the container (172.18.0.2:80). That is how the kernel reverses NAT, and also how -m conntrack --ctorigdstport 18080 in DOCKER-USER can still match the port the client used.

KnobMeaningDefault / note
net.netfilter.nf_conntrack_maxMax entries in the tableDefault is nf_conntrack_buckets x 4 (kernel doc); when full, new flows are dropped and the kernel logs a "table full" message
nf_conntrack_tcp_timeout_establishedIdle seconds before an established TCP entry expires432000 (5 days) in the kernel doc
conntrack -C / conntrack -SCount of entries / per-CPU statistics (insert_failed, drop)First thing to check on a busy node
conntrack -ELive event streamWatch flows appear

Real scenarios: a node that drops new connections under load because conntrack is full (see ports, sockets and connections); a Kubernetes node whose kube-proxy rules add thousands of entries; a DNS server where NOTRACK doubles throughput.

iptables syntax decoded Must-know ​

In plain words: An iptables command is a sentence: "in this table and chain, append a rule that matches these packet properties and does this".

Common misunderstanding: "Rules are independent, order does not matter." The first matching rule with a final verdict wins, so a broad ACCEPT above a specific DROP makes the DROP dead. And -A appends at the end, after any rule that already accepts everything.

Definition: The anatomy of one rule:

iptables  -t filter  -A INPUT  -p tcp --dport 22  -m conntrack --ctstate NEW,ESTABLISHED  -j ACCEPT
   |         |          |        |       |            |              |                         |
   |         |          |        |       |            |              |                         +-- target (verdict or jump)
   |         |          |        |       |            |              +-- option of that extension
   |         |          |        |       |            +-- load match extension "conntrack"
   |         |          |        |       +-- destination port (needs -p tcp or udp)
   |         |          |        +-- protocol
   |         |          +-- chain; -A append, -I insert at position, -D delete, -R replace
   |         +-- table (default filter)
   +-- the command; iptables-nft on modern distros (see nftables below)
PieceMeaning
-A, -I [n], -D, -R, -F, -X, -NAppend, insert (default position 1), delete, replace, flush chain, delete chain, new chain
-P INPUT DROPSet the chain policy
-s, -d, -i, -oSource, destination, in-interface, out-interface; ! negates
-p tcp --dport 22, --sport, --dports 80,443Protocol and ports; --dports needs -m multiport
-m state --state / -m conntrack --ctstateConnection state (the second is current; state is the old spelling)
-m limit --limit 5/min --limit-burst 5Token-bucket match, usually in front of LOG
-m recent, -m hashlimit, -m connlimitPer-source counters, per-source rate, per-source connection count
-j ACCEPT, DROP, REJECT, LOG, RETURN, DNAT, MASQUERADE, or a chain nameTarget; DROP is silent, REJECT answers with an error

Real output of a default-deny INPUT built by hand and listed with the three audit commands. Run in an Alpine container with --cap-add NET_ADMIN:

$ iptables -P INPUT DROP
$ iptables -A INPUT -i lo -j ACCEPT
$ iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$ iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
$ iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "ipt-drop: "
$ iptables -S
-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "ipt-drop: "
$ iptables -L INPUT -v -n --line-numbers
Chain INPUT (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1        0     0 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
2        0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
3        0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:22 ctstate NEW
4        0     0 LOG        all  --  *      *       0.0.0.0/0            0.0.0.0/0            limit: avg 5/min burst 5 LOG flags 0 level 4 prefix "ipt-drop: "

iptables -S prints commands you can replay; iptables -L -v -n prints counters (packets and bytes per rule), -n skips DNS lookups, --line-numbers gives the position you pass to -D and -I. iptables-save and iptables-restore dump and load the whole ruleset atomically.

Real scenarios: a SYN-flood-limited SSH rule; a DNAT for a port forward; a -j REJECT --reject-with tcp-reset for an internal service that should fail fast.

ProductNotes
iptables-legacy (xtables)The original kernel interface; separate binaries per family (iptables, ip6tables, arptables, ebtables)
iptables-nftThe same command line, but rules are stored as nftables rules; iptables --version prints (nf_tables)
iptables-restoreAtomic bulk load; the right way to change many rules

nftables: the successor Must-know ​

In plain words: nftables is the same kernel packet engine with one tool (nft), one rule language, and set and map data structures that let a single rule match a list of ten thousand addresses.

Common misunderstanding: "iptables and nftables are two firewalls, pick one." On a current distribution, the iptables command is usually a shim that writes nftables rules (iptables-nft); both views show the same kernel state. Mixing the two carelessly is what causes surprises, not their coexistence.

Definition: nftables has no predefined tables or chains. You create a table in an address family (ip, ip6, inet for both, arp, bridge, netdev), then base chains attached to hooks with a priority and a policy, and regular chains you jump to. The nftables wiki: "In a major change from iptables, which predefines chains at every hook (i.e. INPUT chain in filter table), nftables predefines no chains at all."

Real nft list ruleset of a default-deny web server, with a named set and rate-limited ICMP (the complete file is web-server.nft):

table inet filter {
	set admin_v4 {
		type ipv4_addr
		flags interval
		elements = { 10.0.0.0/8, 172.16.0.0/12 }
	}
	chain input {
		type filter hook input priority filter; policy drop;
		ct state invalid counter packets 0 bytes 0 drop
		ip protocol icmp icmp type echo-request limit rate over 5/second burst 10 packets drop
		ct state established,related accept
		iifname "lo" accept
		tcp dport { 80, 443 } ct state new accept
		ip saddr @admin_v4 tcp dport 22 ct state new accept
		limit rate 5/minute burst 5 packets log group 100 prefix "nft-input-drop: " counter packets 2 bytes 120
	}
	chain forward { type filter hook forward priority filter; policy drop; }
	chain output  { type filter hook output  priority filter; policy accept; }
}
nftables ideaSyntaxWhy it beats iptables
One table for both familiestable inet filterOne rule covers IPv4 and IPv6; no ip6tables twin
Anonymous settcp dport { 80, 443 }One rule instead of two, evaluated as a set
Named setset admin_v4 { type ipv4_addr; flags interval; } then ip saddr @admin_v4Update the set at runtime with nft add element; no rule reload
Interval setsflags interval, elements = { 10.0.0.0/8 }CIDR blocks as set members
Dynamic sets and metersflags dynamic, timeout; update @s { ip saddr limit rate 3/minute }Per-source rate limits (iptables hashlimit, recent)
Mapsdnat to tcp dport map { 80 : 10.0.0.5, 443 : 10.0.0.6 }A lookup table as an action: one rule for many port forwards
Concatenationsip saddr . tcp dport @allowedA set of pairs: "address X may reach port Y" in one lookup
Atomic reloadnft -f fileThe whole file applies or none of it does

The shim and the translator are real commands. Actual output from Alpine with iptables v1.8.13 (nf_tables):

$ iptables-translate -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
nft 'add rule ip filter INPUT tcp dport 22 ct state new,established counter accept'
$ iptables-translate -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
nft 'add rule ip nat POSTROUTING oifname "eth0" ip saddr 10.0.0.0/24 counter masquerade'
$ nft list ruleset        # after the iptables commands above
table ip filter {
	chain INPUT {
		type filter hook input priority filter; policy drop;
		iifname "lo" counter packets 0 bytes 0 accept
		...
# Warning: table ip filter is managed by iptables-nft, do not touch!

That last line is the warning to take seriously: a table created by iptables-nft should be changed with iptables, not edited with nft. Put your own nftables rules in a separate table (table inet myfw) and they live beside it.

Real scenarios: a firewall with a 50 000-entry blocklist as one set; a port-forward table as one map; a host reloaded atomically from a Git-managed file; a dual-stack server where one inet table replaces four iptables commands.

Productnftables status
Current Debian, Ubuntu, RHEL and Fedora releasesiptables is the nft shim by default (check iptables --version)
firewalldnftables backend in current releases
Dockeriptables backend by default; the Docker page documents an nftables backend, marked experimental there, in which "there is no DOCKER-USER chain"
Kubernetes kube-proxyiptables and ipvs modes; an nftables mode also exists
CiliumeBPF datapath; does not use iptables for policy

ufw and firewalld: front-ends Important ​

In plain words: ufw and firewalld are friendlier tools that write iptables or nftables rules for you. They are where most servers' rules actually come from.

Common misunderstanding: "ufw is a firewall." It is a front-end for netfilter, and it only manages the chains it owns (INPUT, FORWARD, OUTPUT). Anything that jumps around those chains, like Docker's DNAT plus FORWARD rules, is outside its reach.

Definition: The ufw man page: ufw is "program for managing a netfilter firewall"; "On installation, ufw is disabled with a default incoming policy of deny, a default forward policy of deny, and a default outgoing policy of allow, with stateful tracking for NEW connections for incoming and forwarded connections." firewalld describes itself as "a simple, stateful, zone-based firewall": traffic ingresses one zone and egresses one zone, a zone defines a level of trust, intra-zone is allowed and inter-zone denied by default.

$ ufw default deny incoming
$ ufw default allow outgoing
$ ufw allow from 10.0.0.0/8 to any port 22 proto tcp
$ ufw allow 443/tcp
$ ufw limit 22/tcp         # rate limit: ufw denies a source that opens many new connections in a short time
$ ufw enable && ufw status verbose
$ firewall-cmd --permanent --zone=public --add-service=https
$ firewall-cmd --permanent --zone=internal --add-source=10.0.0.0/8
$ firewall-cmd --permanent --zone=internal --add-port=22/tcp
$ firewall-cmd --reload
$ firewall-cmd --list-all-zones
Questionufwfirewalld
Default distributionsUbuntu, Debian-familyRHEL, Fedora, CentOS Stream, SUSE
ModelAllow/deny/reject/limit rules with a default policyZones, services, rich rules, policies between zones
Backendiptables or nftables (via the iptables-nft shim)nftables by default
Change without restartufw allow ...firewall-cmd --add-service (runtime) plus --permanent and --reload
Docker interactionDocker's published ports bypass itDocker creates a docker zone with target ACCEPT and a docker-forwarding policy

Logging and rate limiting Important ​

In plain words: A drop is silent. To learn what the firewall is dropping you add a log rule just before the drop, and you cap its rate so a scan cannot fill the disk.

Common misunderstanding: "I will log everything I drop." A busy host drops millions of packets; unlimited logging becomes the outage. Log a sample (limit rate 5/minute), keep counters for the rest.

Definition: nftables has log (kernel log, or log group N to send to userspace via nflog) and counter. iptables has the LOG and NFLOG targets. Rate limiting is a token bucket: limit rate 5/second burst 10 packets. Per-source limits use a dynamic set (meters in the wiki's words: "ratelimit inbound TCP connections to port 22 per source IP address").

# per-source SSH rate limit: three new connections per minute per address, the rest is dropped
table inet filter {
  set ssh_meter { type ipv4_addr; flags dynamic; timeout 60s; }
  chain input {
    type filter hook input priority filter; policy drop;
    ct state established,related accept
    tcp dport 22 ct state new update @ssh_meter { ip saddr limit rate 3/minute } accept
  }
}

Real capture of the logged drops through nflog group 100 with tcpdump (kernel log is not visible inside an unprivileged container; nflog is):

$ tcpdump -l -n -i nflog:100
17:42:11.697290 IP 172.19.0.3.41840 > 172.19.0.2.5432: Flags [S], seq 2330625817, win 64240, length 0
1 packet captured

Only one SYN appears although two were dropped: the log rule is limited to a burst of 5 and one earlier test had used the bucket. That is the limiter working.

ToolDoes what
log / LOGWrites to the kernel ring buffer (dmesg, journalctl -k); prefix tells you which rule
log group N / NFLOGSends the packet to a userspace listener (tcpdump -i nflog:N, ulogd)
counterPackets and bytes per rule; no log volume
limit rateToken bucket per rule
Meters (dynamic sets)Per-source buckets with a timeout
fail2banReads auth logs and inserts per-IP drop rules into a set or chain for a time
CrowdSecShared blocklists; ban decisions written to nft sets

Real scenarios: log the first five drops per minute with a prefix per chain; fail2ban banning a brute-forcing IP on port 22; a meter that caps new connections per client to the API.

ICMP: why you should not block all of it Must-know ​

In plain words: ICMP is the network's error channel. When a packet is too big for a link, a router answers with an ICMP "too big" message, and the sender shrinks its packets. If a firewall eats that message, the sender never learns, and large transfers hang while small ones work.

Common misunderstanding: "ICMP is just ping, so blocking it is hardening." Ping (echo request) is one of many ICMP types. Destination unreachable (type 3, including code 4 "fragmentation needed") and time exceeded are essential; RFC 4890 lists "Traffic That Must Not Be Dropped" for IPv6, starting with Destination Unreachable, Packet Too Big, Time Exceeded and Parameter Problem.

Definition: Path MTU Discovery (RFC 1191 for IPv4, with the DF bit set; IPv6 has the same mechanism and routers never fragment) works because routers drop an oversized packet and return an ICMP message that carries the next-hop MTU. RFC 4890 on IPv6: the Packet Too Big message "is vital to the correct functioning of Path MTU Discovery". RFC 4821 describes the fallback that detects black holes without ICMP (Packetization Layer PMTUD, enabled in Linux by net.ipv4.tcp_mtu_probing).

1  client -> server   TCP 1500-byte packet, DF=1  (e.g. a TLS record in a large upload)
2  router (link MTU 1400) drops it, sends ICMP type 3 code 4 "fragmentation needed, next-hop MTU 1400"
3a firewall allows ICMP  -> client lowers its MSS, resends in 1360-byte segments, works
3b firewall drops ICMP   -> client never hears, retransmits the same size, hangs  (MTU black hole)

A real ICMP echo request captured the same way (the header layout is the one that icmp type and icmp code match):

	0x0000:  3e20 ea32 077e 4660 4252 9bd4 0800 4500
	0x0010:  0024 5359 4000 4001 8f54 ac13 0003 ac13   <- 0x17: protocol 01 = ICMP
	0x0020:  0002 0800 c03a 006c 0000 d1a2 65b6 0000   <- 0x22: type 08 (echo request), code 00, checksum c03a, id 006c, seq 0000
ICMP messageIPv4 type/codeICMPv6 typeAllow in?Why
Destination unreachable (incl. fragmentation needed)3 / 0-15, 3/41YesErrors for flows you started; PMTUD
Packet Too Big(3/4 on IPv4)2YesPMTUD on IPv6; routers do not fragment
Time exceeded113Yestraceroute, loops
Parameter problem124YesHeader errors
Echo request / reply8 / 0128 / 129Optional, rate-limitedReachability checks; RFC 4890 says IPv6 echo need not be filtered
Neighbor / router discoveryn/a (ARP)133-136Yes on IPv6NDP replaces ARP; blocking it breaks the LAN
Redirect5137NoCan steer traffic

Real scenarios: a VPN or tunnel with MTU 1400 where curl to a small page works but a file upload hangs; a security group with only "TCP 443" and no ICMP, behind a Geneve or WireGuard link; AWS's own NACL page that has a section "Path MTU Discovery and network ACLs".

Fix: allow ICMP errors in every default-deny policy (as in the lab ruleset), rate-limit echo, and where you cannot control the path clamp MSS (iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu).

ProductHow to allow the essential ICMP
nftablesip protocol icmp icmp type { destination-unreachable, time-exceeded, parameter-problem } accept; meta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, ... } accept
iptables-p icmp --icmp-type destination-unreachable -j ACCEPT, and ip6tables -p ipv6-icmp -j ACCEPT
AWS security groupAdd an inbound rule: custom ICMP, type 3 code 4 (fragmentation needed) and ICMPv6 type 2; the stateful SG returns errors for tracked flows
AWS network ACLThe AWS NACL page has a PMTUD section; add an inbound ICMP rule for type 3 code 4
Kubernetes NetworkPolicy"behaviour is undefined" for ARP and ICMP; depends on the CNI

IPv6 firewalling: no NAT to hide behind Must-know ​

In plain words: With IPv4 at home, NAT happened to block unsolicited inbound connections. With IPv6 every device has a public address, and only the firewall stands between it and the internet.

Common misunderstanding: "Nobody can find an IPv6 address, there are too many." RFC 4864 does say a 64-bit subnet takes thousands of years to scan, but hosts leak addresses through DNS, logs, certificate transparency and predictable EUI-64 or low-numbered addresses. The same RFC: "IPv4 NAT was not developed as a security mechanism."

Definition: Every IPv6 rule needs an IPv6 twin; forgetting ip6tables leaves the machine fully open on IPv6 while IPv4 looks locked down. In nftables the inet family handles both with one ruleset. IPv6 also needs ICMPv6 (neighbor discovery, packet too big) allowed or the network stops working, and filtering ip6 nexthdr only sees the first header: the nft man page cautions that "ip6 nexthdr tcp will only match if the ipv6 packet does not contain any extension headers", so use meta l4proto tcp (it "will also skip any IPv6 extension headers").

# WRONG: IPv4 closed, IPv6 wide open (the iptables habit)
iptables  -P INPUT DROP
# ip6tables -P INPUT DROP   <- forgotten

# RIGHT: one inet table, same rules for both families
table inet filter { chain input { type filter hook input priority filter; policy drop; ... } }

Real scenarios: a cloud VM with a public IPv6 and a security group that only has IPv4 rules (the IPv6 rule is a separate ::/0 entry in AWS, GCP and Azure); a Kubernetes dual-stack cluster with NetworkPolicy ipBlock for IPv4 only; a home router that forwards IPv6 with no firewall.

ProductIPv6 detail
AWS security groupSeparate rules for ::/0 and IPv6 CIDRs; one SG can hold both
AWS network ACL"IPv4 and IPv6 traffic are evaluated separately"; IPv6 rules have their own numbers
GCPSource and destination ranges accept IPv4 and IPv6 CIDRs; the API says "Both IPv4 and IPv6 are supported"
Linuxip6tables, or inet family in nftables; ufw manages both when IPV6=yes
Dockerip6tables option and its own IPv6 chains; IPv6 publishing is covered below

Docker and firewalls Must-know ​

In plain words: Docker writes its own firewall rules. A published port (-p 8080:80) is opened by Docker, for everyone, in a part of the rule list that your ufw rules never see.

Common misunderstanding: "ufw deny 5432 protects my published Postgres." The Docker documentation spells the opposite out: "Docker routes container traffic in the nat table, which means that packets are diverted before it reaches the INPUT and OUTPUT chains that ufw uses." And: "Publishing container ports is insecure by default. Meaning, when you publish a container's ports it becomes available not only to the Docker host, but to the outside world as well."

Definition: Docker creates, in the filter table, the chains DOCKER-USER ("a placeholder for user-defined rules that will be processed before rules in the DOCKER-FORWARD and DOCKER chains"), DOCKER-FORWARD, DOCKER, DOCKER-BRIDGE, DOCKER-INTERNAL, DOCKER-CT and, for Swarm, DOCKER-INGRESS; in the nat table a DOCKER chain with the DNAT rules; in the raw table PREROUTING drops for direct-routed access. It also enables IP forwarding and, with the iptables backend, sets the FORWARD policy to DROP so only what Docker accepts is forwarded.

Internetto host:8080nat PREROUTINGDOCKER: DNAT to172.18.0.2:80routing:dest is acontainerINPUT (ufw)never reachedFORWARDDOCKER-USER firstDOCKER-FORWARDDOCKER, DOCKER-CTContainernginx :80only if dest = hostPut your own rules in DOCKER-USER (iptables) or a separate nft tablewith a forward-hook base chain (nftables). Match the ORIGINAL port with-m conntrack --ctorigdstport, because DNAT has already rewritten it.

Real rules on Docker 29.10 (inside a Docker-in-Docker daemon), after docker run -d -p 18080:80 nginx:alpine and -p 127.0.0.1:18081:80:

$ iptables -S FORWARD
-P FORWARD ACCEPT
-A FORWARD -j DOCKER-USER
-A FORWARD -j DOCKER-FORWARD
$ iptables -t nat -S DOCKER
-N DOCKER
-A DOCKER ! -i docker0 -p tcp -m tcp --dport 18080 -j DNAT --to-destination 172.18.0.2:80
-A DOCKER -d 127.0.0.1/32 ! -i docker0 -p tcp -m tcp --dport 18081 -j DNAT --to-destination 172.18.0.5:80
$ iptables -t raw -S
-P PREROUTING ACCEPT
-A PREROUTING -d 172.18.0.2/32 ! -i docker0 -j DROP
-A PREROUTING -d 127.0.0.1/32 ! -i lo -p tcp -m tcp --dport 18081 -j DROP

The first PREROUTING rule drops packets sent straight to the container's own address from outside the bridge, so only the published port works. The second one is the Docker 28 fix for loopback-published ports (see below).

TimelineExperiment (all real, run from two other containers as "external" clients)
1ext1 and ext2 reach the published port: wget http://172.17.0.4:18080/ succeeds for both
2Real ufw 0.36.2 is installed in the same Docker host (ufw default deny incoming, ufw allow 22/tcp, ufw enable) and ufw deny 18080/tcp is added; ufw status lists it as DENY and the INPUT policy is DROP. ext1 still gets the page and the ufw-user-input DROP rule for 18080 stays at 0 packets
3iptables -I DOCKER-USER -i eth0 ! -s 172.17.0.5 -p tcp -m conntrack --ctorigdstport 18080 -j DROP goes in
4ext1 (172.17.0.5) still succeeds; ext2 times out ("download timed out"); the rule's counter shows 3 packets dropped

How to restrict published ports properly:

GoalHowWhy it works
Only the host (or a reverse proxy on the host) reaches it-p 127.0.0.1:8080:80 (and -p '[::1]:8080:80')"If you include the localhost IP address (127.0.0.1, or ::1) with the publish flag, only the Docker host can access the published container port."
Only some clients reach itA rule at the top of DOCKER-USER, matching the original port: iptables -I DOCKER-USER -i ext_if ! -s 192.0.2.0/24 -p tcp -m conntrack --ctorigdstport 8080 -j DROPDOCKER-USER runs before Docker's rules; DNAT has already rewritten the destination, so you match the original with conntrack
Allow repliesiptables -I DOCKER-USER -m state --state RELATED,ESTABLISHED -j ACCEPT placed before the dropsContainers' outgoing flows must come back
Everything private by defaultChange the default publish address: daemon ip: 127.0.0.1, or network option com.docker.network.bridge.host_binding_ipv4=127.0.0.1New -p flags bind to loopback unless you name an address
Not published at allSame user-defined network, no -p; talk by container nameContainers reach each other on the bridge; nothing is reachable from outside
nftables backendCreate your own table with a forward-hook base chain and a lower priority number than Docker's"In Docker's nftables implementation, there is no DOCKER-USER chain"

What changed in Docker 28 (documented behaviour). The Docker port-publishing page warns: "In releases older than 28.0.0, hosts within the same L2 segment (for example, hosts connected to the same network switch) can reach ports published to localhost." The Docker iptables and nftables pages add the current behaviour for direct routing: packets sent straight to a container's address are dropped by the raw-table rules shown above unless you opt in with com.docker.network.bridge.trusted_host_interfaces, the allow-direct-routing daemon option, or the nat-unprotected gateway mode. A published port to 0.0.0.0 is still open to everyone, so Docker 28 closes the side doors, not the front one.

Real scenarios: a Compose file with ports: ["5432:5432"] on a cloud VM whose security group is open to the world; a CI host where ufw status shows "deny" and an exposed Redis answers anyway; a staging server where 127.0.0.1: binds plus an nginx on the host are the only way in.

ProductWhat to do
Docker (iptables backend)Bind to 127.0.0.1 or use DOCKER-USER; keep iptables: true
Docker (nftables backend)Your own table with a forward base chain; mark-based accepts via --bridge-accept-fwmark
ufwDoes not control published ports; use ufw-docker-style rules in DOCKER-USER, or bind to loopback
firewalldDocker adds a docker zone, target ACCEPT; restrict with a rich rule or a policy
PodmanUses netavark with its own nftables/iptables chains; rootless Podman publishes through a userspace proxy
ComposeSame flags: ports: ["127.0.0.1:8080:80"]

Kubernetes NetworkPolicy Must-know ​

In plain words: A NetworkPolicy says which pods may talk to which pods, by label. Until a policy selects a pod, that pod accepts and sends everything.

Common misunderstanding: "I applied the YAML, so traffic is restricted." The Kubernetes documentation is blunt: "Creating a NetworkPolicy resource without a controller that implements it will have no effect." The API server stores the object; the network plugin (CNI) enforces it, and not every plugin does.

Definition: A pod is isolated for ingress when some NetworkPolicy selects it and lists Ingress in policyTypes; likewise for egress. An isolated pod accepts only what the union of the matching policies allows ("The effects of those ingress lists combine additively", so order does not matter and there is no deny rule). A connection needs both the source's egress and the destination's ingress to allow it. Reply traffic is implicitly allowed. Traffic to and from the pod's own node is always allowed, and a pod cannot block access to itself.

ns: ingress-nginxpodapp.kubernetes.io/name=ingress-nginxns: shop (default-deny ingress + egress)apilabel app=apilistens :8080dblabel app=dblistens :5432otherlabel app=othernot selected: deniedpayments203.0.113.0/24ns: kube-systemkube-dns pods, UDP/TCP 53TCP 8080TCP 5432TCP 443 (ipBlock)DNS egress (allow-dns policy)db has no egress rule forapi, only replies are allowed"other" to db: dropped

The selector rules are the part people get wrong. In a from or to list, each list item is OR-ed; inside one item the selectors are AND-ed:

from:
  - namespaceSelector: {matchLabels: {user: alice}}     # item 1: ANY pod in namespaces labelled user=alice
  - podSelector: {matchLabels: {role: client}}          # item 2: OR pods role=client in THIS namespace

from:
  - namespaceSelector: {matchLabels: {user: alice}}     # one item, two selectors = AND:
    podSelector: {matchLabels: {role: client}}          # pods role=client in namespaces user=alice

A namespace has no name field to match, but "The Kubernetes control plane sets an immutable label kubernetes.io/metadata.name on all namespaces", so match on that label.

Step 1, default-deny for both directions in a namespace (from the Kubernetes docs pattern):

yaml
# Step 1: isolate every pod in the namespace for ingress AND egress.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: shop
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]

Step 2: a default-deny egress policy "also blocks DNS traffic", so allow it:

yaml
# Step 2: without this, a default-deny egress policy breaks name resolution too.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns-egress
  namespace: shop
spec:
  podSelector: {}
  policyTypes: [Egress]
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - { protocol: UDP, port: 53 }
        - { protocol: TCP, port: 53 }

Step 3 and 4: let the ingress controller reach the API, the API reach the database, and the API reach one external CIDR:

yaml
# Step 3: the api pods accept traffic on 8080 only from the ingress controller's namespace
# AND only from pods labelled as the controller (one `from` item with BOTH selectors = AND).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-ingress
  namespace: shop
spec:
  podSelector:
    matchLabels: { app: api }
  policyTypes: [Ingress]
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: ingress-nginx
          podSelector:
            matchLabels:
              app.kubernetes.io/name: ingress-nginx
      ports:
        - { protocol: TCP, port: 8080 }
yaml
# Step 4: the database accepts 5432 only from api pods in the same namespace,
# and the api may reach the database and an external payments CIDR, nothing else.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-ingress
  namespace: shop
spec:
  podSelector:
    matchLabels: { app: db }
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector:
            matchLabels: { app: api }
      ports:
        - { protocol: TCP, port: 5432 }
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-egress
  namespace: shop
spec:
  podSelector:
    matchLabels: { app: api }
  policyTypes: [Egress]
  egress:
    - to:
        - podSelector:
            matchLabels: { app: db }
      ports:
        - { protocol: TCP, port: 5432 }
    - to:
        - ipBlock:
            cidr: 203.0.113.0/24   # payments provider (documentation range)
      ports:
        - { protocol: TCP, port: 443 }
FieldMeaningTrap
podSelector: {}All pods in the policy's namespaceEmpty selector means everything, not nothing
policyTypesIngress, Egress or bothIf omitted, Ingress is always set; Egress only if the policy has egress rules
ingress[].from / egress[].toList of peers: podSelector, namespaceSelector, ipBlockAND within an item, OR between items
ipBlockA CIDR with optional exceptMeant for cluster-external IPs; Service or NodePort rewriting may happen before or after policy ("not defined"), so the source seen can be a node or load balancer
ports[].port, endPortA port or a rangeThe CNI must support endPort, otherwise only the single port is applied
protocolTCP, UDP, SCTPFor ICMP and ARP the behaviour is undefined
ingress: [{}]Allow all ingressUsed to override or document openness

What NetworkPolicy cannot do (documentation list): log allowed or denied connections, explicitly deny (the model is allow-only), target Services by name, apply default policies to every namespace (the API has none), do anything TLS-related, block host-local or node traffic. Those are CNI extensions (Cilium and Calico policy CRDs) or the realm of a service mesh.

Enforcement: the CNI must support it. The documentation's "Install a Network Policy Provider" page lists Antrea, Calico, Cilium and Kube-router. kind's documentation describes its default network as "a simple networking implementation (kindnetd)" that you can replace with disableDefaultCNI: true, noting that "many common CNI manifests are known to work, e.g. Calico"; that is the safe way to test policy in kind. Calico and Cilium implement policy by programming iptables/ipsets (Calico) or eBPF (Cilium: "At the foundation of Cilium is a new Linux kernel technology called eBPF"). With eBPF the rule list is a set of hash lookups in the kernel, not a linear iptables chain, and policy can match identities and DNS names (FQDN rules) that plain NetworkPolicy cannot. It also means Kubernetes nodes may show no iptables rule for the policy at all: use the CNI's tooling (cilium monitor, calicoctl), not iptables -S.

CNIEnforces core NetworkPolicy?Extra policy API
CalicoYesGlobalNetworkPolicy, deny rules, ordering, host endpoints
CiliumYes (eBPF)CiliumNetworkPolicy, FQDN egress, L7 HTTP/Kafka rules, Hubble flow logs
Antrea, Kube-routerYesOwn CRDs (Antrea)
kind default (kindnetd)Check before relying on it; install Calico with disableDefaultCNI: trueNone
A CNI with no policy controllerNo: the object is stored and ignoredNone
Managed clusters (EKS, GKE, AKS)Needs the provider's policy engine switched on or a plugin installedProvider-specific

Pod lifecycle: a pod started before the controller finished programming a new policy "may start unprotected"; policy is not retroactive for in-flight connections ("implementation defined").

$ kubectl -n shop get networkpolicy
$ kubectl -n shop describe networkpolicy api-ingress     # shows how the selectors were interpreted
$ kubectl -n shop exec other -- curl -s -m 3 http://$DB_IP:5432   # timeout = dropped, not refused

Real scenarios: a multi-tenant cluster where each namespace gets a default-deny and an allow-DNS policy from a template; a database that only the API pods can reach; a namespace whose egress is limited to one payments CIDR; kube-system pods reaching everything as before.

Cloud firewalls: security groups, NACLs, GCP rules, Azure NSGs Must-know ​

In plain words: A cloud security group is a firewall you attach to a server's network card; a network ACL is a second firewall at the edge of a subnet. They filter before the packet reaches the operating system, so no iptables is involved and no one on the machine can turn them off.

Common misunderstanding: "Security groups and NACLs are two names for the same thing." They differ in scope, statefulness and rule model. The AWS documentation's own table: security group is instance level, "Allow rules only", "Evaluates all rules before deciding", return traffic "Automatically allowed (stateful)"; network ACL is subnet level, "Allow and deny rules", "Evaluates rules in ascending order until a match", return traffic "Must be explicitly allowed (stateless)".

Definition (AWS). A security group is associated with network interfaces (ENIs), so it follows the instance, the load balancer or the Lambda ENI. "You can specify allow rules, but not deny rules." A new group has no inbound rules and one allow-all outbound rule. A rule's source or destination can be a CIDR, a prefix list or another security group ("security group referencing"), which expresses "the web tier may reach the DB tier" without addresses. Multiple groups on one ENI are unioned. A network ACL is associated with a subnet; each rule has a number from 1 to 32766 and is evaluated in order; a final * rule denies everything. It is stateless: "If, for example, you create a NACL rule to allow specific inbound traffic to a subnet, responses to that traffic are not automatically allowed."

Client198.51.100.9:51344VPC subnet 10.0.1.0/24 (network ACL boundary)Network ACLstateless, orderedIN 100 allow tcp 443IN * deny allOUT 100 allow tcp 1024-65535OUT * deny allSecurity groupstateful, allow onlyIN allow tcp 443from 0.0.0.0/0reply allowed byconnection tracking(no OUT rule needed)InstanceENI, nginx :443Solid: request to :443. Dashed: reply from :443 to the client's ephemeral port 51344.Forget the NACL outbound rule for 1024-65535 and the reply dies at the subnet edge.
Inbound  to the web server (TCP 443 from a browser at 198.51.100.9:51344)
  NACL   IN   rule 100  allow tcp 443  from 0.0.0.0/0          -> match, stop
  SG     IN   allow tcp 443 from 0.0.0.0/0                      -> match
Outbound reply (server 10.0.1.25:443 -> 198.51.100.9:51344)
  SG     OUT  no rule needed: connection tracking says "reply"
  NACL   OUT  rule 100  allow tcp 1024-65535 to 0.0.0.0/0       -> REQUIRED, otherwise the reply is dropped at the subnet edge

The ephemeral range is chosen by the client's OS: the AWS page lists "Many Linux kernels (including the Amazon Linux kernel) use ports 32768-61000. Requests originating from Elastic Load Balancing use ports 1024-65535. ... Windows Server 2008 and later versions use ports 49152-65535. A NAT gateway uses ports 1024-65535." In practice open 1024-65535 on the NACL for the return direction.

Connection tracking details that bite (EC2 documentation): "When you change a security group rule, its tracked connections are not immediately interrupted. The security group continues to allow packets until existing connections time out." A flow allowed by an all-open rule pair (0.0.0.0/0 both ways) is untracked, so removing that rule drops the session immediately. For protocols other than TCP, UDP and ICMP only the address and protocol are tracked, with a 600-second window. Neither security groups nor NACLs filter traffic to the Route 53 Resolver, DHCP, instance metadata (IMDS) or the Time Sync Service; use DNS Firewall and IMDS options for those.

GCP and Azure. GCP VPC firewall rules attach to a VPC network and select instances by target tags or target service accounts ("If targetTags are specified, then the firewall rule applies only to instances in the VPC network that have one of those tags"). Each rule has a direction (INGRESS default or EGRESS), allow or deny, and a priority: "an integer between 0 and 65535 ... The default value is 1000 ... Lower values indicate higher priority ... DENY rules take precedence over ALLOW rules if they have equal priority", and "VPC networks have implied rules with a priority of 65535". Source tags "cannot be used to control traffic to an instance's external IP address". Azure NSGs attach to a subnet or a NIC, rules have a priority "between 100 and 4096", the first match stops processing, default rules sit at 65000, 65001 and 65500 (allow VNet, allow load balancer, deny all inbound; mirrored for outbound), and "Network security group rules only affect new connections". Sources can be service tags (a Microsoft-maintained set of prefixes) or application security groups (labels on VMs).

PropertyAWS security groupAWS network ACLGCP VPC firewall ruleAzure NSGKubernetes NetworkPolicy
Attached toENI (instance, LB, Lambda)SubnetVPC network, selecting by tag or service accountSubnet or NICPods (by label)
StatefulYesNoYes (see note)YesYes
Allow / denyAllow onlyAllow and denyAllow and denyAllow and denyAllow only
Rule orderNone (all rules unioned)Ascending rule number, first matchPriority 0-65535, lower first; deny wins tiesPriority 100-4096, lowest firstNone (additive)
Default inboundDenyDefault NACL allow all; custom NACL deny allImplied deny (priority 65535)Deny (65500)Allow until selected
Default outboundAllow allSame as inboundImplied allow (priority 65535)Allow (65000-65500 defaults)Allow until selected
References to other groupsSG IDs, prefix listsCIDRs onlyTags, service accountsService tags, ASGsPod and namespace selectors
Changes affect existing flowsNot tracked onesYes immediatelyPer cloud docsNoCNI-defined
LoggingVPC Flow LogsVPC Flow LogsFirewall Rules LoggingVirtual network flow logs (NSG flow logs retire 2027-09-30)CNI-specific (Hubble, Calico flow logs)
CostFreeFreeFreeFreeFree (CNI is the cost)

Sourcing note: the GCP statements about priority, target tags and implied rules come from Google's Compute API schema (Firewall resource description, published in googleapis' GitHub); Google's documentation site refuses automated fetching from this machine, so GCP's statefulness and the direction of the implied rules are stated here from general knowledge, not from a fetched page.

Real scenarios: the three-tier app (ALB security group allows 443 from the world; app SG allows 8080 only from the ALB's SG; DB SG allows 5432 only from the app SG); a subnet-wide NACL deny for a known-bad CIDR, which a security group cannot express; a GCP rule "allow tcp:5432 from tag web to tag db"; an Azure NSG using the Storage service tag.

Fix / how to use it (Terraform and AWS CLI):

# a security group rule that references another group instead of an address
aws ec2 authorize-security-group-ingress --group-id sg-0db --protocol tcp --port 5432 --source-group sg-0app

# a NACL pair: allow HTTPS in, and the ephemeral range out
aws ec2 create-network-acl-entry --network-acl-id acl-0abc --ingress --rule-number 100 --protocol tcp --port-range From=443,To=443 --cidr-block 0.0.0.0/0 --rule-action allow
aws ec2 create-network-acl-entry --network-acl-id acl-0abc --egress  --rule-number 100 --protocol tcp --port-range From=1024,To=65535 --cidr-block 0.0.0.0/0 --rule-action allow

Egress control Important ​

In plain words: Ingress rules keep strangers out; egress rules limit where your own servers may connect. A server that can only talk to three destinations cannot ship your data to a fourth.

Common misunderstanding: "We are behind a firewall, outbound is safe." After a compromise, the attacker's first moves are outbound: download a payload, open a reverse shell, exfiltrate data, call back to a command server. Default-allow egress makes all of that work.

Definition: Egress control is an allow-list on outbound connections: by destination CIDR and port, or by domain name. The supply-chain case is real: a build or a runtime composer install, npm install, go get or docker pull can run code from a registry you do not control; limiting build and runtime hosts to your registries and mirrors narrows what a malicious package can reach.

LayerHow to restrict egressLimit
Hostnftables output chain with policy drop and per-destination accepts (the Go generator below emits it)IP-based; CDN addresses change
DockerDOCKER-USER rules on -o ext_if, an internal network (docker network create --internal), a forward proxy containerPer host
Security groupRemove the default allow-all outbound rule, add specific onesSG cannot filter by domain; cannot block DNS to the Route 53 Resolver
NACLSubnet-wide outbound deny and allow listStateless: replies need return rules
KubernetesNetworkPolicy egress with ipBlock/selectors; Cilium toFQDNs (see the manifest below); egress gateways give pods a fixed source IPCore NetworkPolicy has no DNS names
Cloud DNS-awareAWS Network Firewall (domain allow-lists via stateful rule groups), Route 53 Resolver DNS Firewall, Azure Firewall FQDN rules, GCP Cloud NAT plus firewall policiesPaid service; inspection point
ProxyOutbound HTTP(S) only through a proxy that enforces an allow-list (squid, Envoy)Apps must honour HTTP_PROXY
yaml
# Cilium extension (not core Kubernetes): allow egress by DNS name.
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: api-egress-fqdn
  namespace: shop
spec:
  endpointSelector:
    matchLabels: { app: api }
  egress:
    - toEndpoints:
        - matchLabels:
            io.kubernetes.pod.namespace: kube-system
            k8s-app: kube-dns
      toPorts:
        - ports: [{ port: "53", protocol: ANY }]
          rules:
            dns:
              - matchPattern: "*"      # lets Cilium see the lookups it must map to IPs
    - toFQDNs:
        - matchName: api.payments.example
        - matchName: registry.npmjs.org
      toPorts:
        - ports: [{ port: "443", protocol: TCP }]

NAT gateway plus domain filtering. Private subnets reach the internet through a NAT gateway (see NAT in the cloud). A NAT gateway forwards anything; to enforce "only these domains" you place a firewall in the path (AWS Network Firewall, a Squid or Envoy proxy, or the provider's firewall service) so the route table sends private-subnet traffic through the inspection point first. A fixed Elastic IP on the NAT gateway also gives partners one address to allow-list.

Kubernetes egress gateways. A group of pods leaves the cluster through a designated node or gateway so the destination sees a stable source IP and so one place enforces egress policy. Cilium calls it Egress Gateway; Calico has egress gateways; both are CNI features, not core NetworkPolicy.

What to allow when you tighten egress: DNS (to your resolver only), NTP, package registries or mirrors, the payments and email providers, your observability endpoints, the cloud metadata address from workloads that need it, and health-check return traffic. Log what the new policy drops for a week before enforcing (log rule or flow logs).

Real scenarios: a payments service that can only call two CIDRs and the database; a CI runner limited to your registry mirror; a pod allowed to reach only api.payments.example:443.

Host firewalls on servers vs the perimeter Important ​

In plain words: A perimeter firewall (security group, edge appliance, NACL) protects many machines from outside; a host firewall (nftables on the box) protects one machine from everything, including its neighbours.

Common misunderstanding: "The security group is enough." A security group stops the internet. It does not stop another instance in the same group, a compromised neighbour in the VPC, or a mistake in the group itself. Defence in depth means two independent walls, so one wrong rule is not a breach.

AspectPerimeter (SG, NACL, edge firewall)Host firewall (nftables, ufw)
Managed byCloud API, Terraform, network teamConfig management, image bake, the server owner
SeesTraffic entering or leaving the instance or subnetEverything incl. east-west and loopback
Survives a root compromise on the hostYesNo: root can flush it
Central auditYes (flow logs)Per host (counters, logs)
Per-process controlNoYes: -m owner --uid-owner on OUTPUT
Typical failureToo-broad CIDR such as 0.0.0.0/0Rules lost on reboot; Docker bypass

Use both: the perimeter for coarse, centrally reviewed boundaries; the host for the specific "this service accepts these clients" and for egress limits. Persist host rules (nft list ruleset > /etc/nftables.conf, netfilter-persistent, firewall-cmd --permanent).

Application listener binding: the second wall Important ​

In plain words: If a service only listens on 127.0.0.1, no firewall mistake can expose it to the network, because the socket does not exist on the network interface.

Common misunderstanding: "localhost and 0.0.0.0 are both 'local'." 0.0.0.0 means "every interface", including the public one. 127.0.0.1 means "the loopback only".

Definition: The address a server passes to bind() decides which interfaces can reach it. A service behind a reverse proxy on the same host should listen on loopback or a Unix socket; only the proxy listens publicly. For admin endpoints, a Unix socket with file permissions removes the port entirely (the Go example).

$ ss -ltn                                      # Local Address column
LISTEN 0  511   127.0.0.1:9000   0.0.0.0:*    # php-fpm: only nginx on this host can reach it
LISTEN 0  511   0.0.0.0:80       0.0.0.0:*    # nginx: public on purpose
LISTEN 0  128   0.0.0.0:6379     0.0.0.0:*    # redis on every interface: one firewall mistake from a breach
ServiceWhere to set the bind address
PostgreSQLlisten_addresses = 'localhost' (default) or a private IP
MySQL / MariaDBbind-address = 127.0.0.1
Redisbind 127.0.0.1 -::1, protected-mode yes
MongoDBnet.bindIp: 127.0.0.1
nginx / php-fpmlisten 127.0.0.1:9000; or a Unix socket listen = /run/php/php-fpm.sock
Docker-p 127.0.0.1:8080:80
Laravelphp artisan serve --host=127.0.0.1; Octane --host=127.0.0.1 behind nginx
Gohttp.Server{Addr: "127.0.0.1:8080"} instead of ":8080"
KubernetesContainers must listen on 0.0.0.0 inside the pod for Services to work; use NetworkPolicy to restrict

WAF vs firewall vs security group Important ​

In plain words: They look at different layers. A security group and a packet filter read headers; a WAF reads HTTP.

Common misunderstanding: "The WAF replaces the firewall" (or the opposite). A WAF never sees a port it does not terminate; a security group never sees an SQL injection. Each blocks things the other cannot.

ControlLayerSeesBlocksDoes not stop
nftables / iptablesL3-L4 (conntrack adds state)5-tuple, flags, stateUnwanted ports and sourcesSQL injection on an allowed port
AWS security groupL3-L4, stateful, per ENI5-tuple of new flowsSame, at the instanceAnything on an allowed port
AWS network ACLL3-L4, stateless, per subnet5-tuple per packetSubnet-wide CIDRs and portsApplication attacks
NetworkPolicyL3-L4, per podPod labels, CIDRs, portsEast-west trafficApplication attacks, anything L7
Network firewall (AWS Network Firewall, NGFW)L3-L7 inspectionDomain names (SNI), signaturesExfiltration to unlisted domainsEncrypted payload content
L7 proxy / ingress / API gatewayL7HTTP method, path, headersUnauthenticated routes, oversized bodiesNetwork-layer floods
WAFL7Request contentSQLi, XSS patterns, bad bots, rate abuseDirect access to a non-HTTP port
mTLS / service meshL4-L7 identityCertificate identityCallers without a valid identityCompromised but valid services

DDoS mitigation, WAF rule design and bot control are in DDoS and network security; mTLS in mTLS.

Common failures ​

SymptomCauseHow to confirmFix
Security group allows 443 but the page never loads (SYN reaches the instance, the SYN-ACK never arrives)NACL outbound lacks the ephemeral range; stateless NACL drops the replyVPC Flow Logs show ACCEPT inbound and REJECT for the return flow; compare NACL outbound rulesAdd outbound allow tcp 1024-65535 (and inbound for the reverse case)
Database port is public although ufw status says denyDocker published it; DNAT sends it through FORWARD, not INPUTdocker ps shows 0.0.0.0:5432->5432; iptables -t nat -S DOCKERBind 127.0.0.1:5432:5432, or a DOCKER-USER drop matching --ctorigdstport 5432
NetworkPolicy applied, traffic unchangedCNI does not implement it, or the policy selects different labelskubectl describe networkpolicy; check the CNI; labels on the podsUse Calico/Cilium/Antrea/Kube-router; fix selectors
After default-deny egress, every pod fails with name errorsDNS not allowednslookup times outAdd the allow-DNS policy
Load balancer marks every target unhealthyThe target's SG or NACL blocks the health-check source (the LB's SG or subnet)Target group health reason; SG inbound rulesAllow the LB SG (or its subnet) on the health-check port; NACL: the AWS docs warn that a deny for 0.0.0.0/0 or the subnet CIDR stops health checks
Small requests succeed, large uploads or TLS handshakes with big certificates hangICMP "fragmentation needed" or "packet too big" dropped: MTU black holeping -M do -s 1472 host fails at a size, tracepath, tcpdump icmpAllow ICMP type 3 code 4 and ICMPv6 type 2; clamp MSS
SSH worked, then died right after ufw enable or policy dropEstablished rule missing or placed after the dropConsole access; nft list ruleset orderct state established,related accept first; schedule an auto-revert
New connections fail under load, old ones workconntrack table fulldmesg shows a conntrack "table full" message; conntrack -CRaise nf_conntrack_max, shorten timeouts, notrack for known flows
IPv4 locked down, IPv6 openNo ip6tables/inet rules, or SG missing ::/0ss -ltn6, nmap -6Use an inet table, add IPv6 rules
Rules vanish after rebootNot persistednft list ruleset is empty after bootnftables.service with /etc/nftables.conf; netfilter-persistent
iptables -L looks empty but traffic is still filteredRules live in nftables tables, another table, or another network namespacenft list ruleset, iptables-nft -S, ip netnsList with the matching tool and namespace
Admin UI reachable from the internetService bound to 0.0.0.0 and SG too widess -ltn, scan from outsideBind to loopback or a Unix socket; narrow the SG
Webhook provider cannot reach youSource IP not allowed by SG, or provider ranges changedFlow logs; provider's published rangesAllow the provider ranges from a managed list; verify signatures too

Auditing ​

QuestionCommandWhat to read
What rules exist, in nft form?nft list rulesetTables, chains, hooks, priorities, policies; -a adds handles
What rules exist, in iptables form?iptables -S, iptables-saveReplayable text; -t nat, -t raw, -t mangle for other tables
Which rule is actually matching?iptables -L -n -v --line-numbers or nft list ruleset with counterPacket and byte counters per rule
Live trace of one packetnft monitor trace after meta nftrace set 1 on a matchEach rule the packet passes
What flows are tracked?conntrack -L, conntrack -C, conntrack -SState, NAT tuples, timeouts, insert_failed
What is listening?ss -ltnupLocal address (loopback or all interfaces) and the process
What is reachable from outside?nmap -sS -p- host from another network, nc -zv host portOpen vs filtered (timeout) vs closed (refused)
Which firewall is active?ufw status verbose, firewall-cmd --list-all, systemctl status nftablesThe front-end's view
What did the cloud allow or reject?AWS VPC Flow Logs, GCP Firewall Rules Logging, Azure virtual network flow logsACCEPT/REJECT per 5-tuple
What does Kubernetes enforce?kubectl get networkpolicy -A, kubectl describe networkpolicy, cilium monitor --type drop, calicoctl get networkpolicyPolicies, selectors, drops
Docker's rulesiptables -S DOCKER-USER, iptables -t nat -S DOCKER, docker network inspectPublished ports and your own rules

An AWS VPC Flow Logs record is a line of fields, and the pair of ACCEPT/REJECT tells you whether the NACL or SG decided. The default format is version account-id interface-id srcaddr dstaddr srcport dstport protocol packets bytes start end action log-status:

2 123456789012 eni-0a1b2c3d 198.51.100.9 10.0.1.25 51344 443 6 12 4880 1700000000 1700000060 ACCEPT OK
2 123456789012 eni-0a1b2c3d 10.0.1.25 198.51.100.9 443 51344 6 10 9800 1700000000 1700000060 REJECT OK

The first line (the request) is accepted; the second (the reply) is rejected: the NACL outbound rule is missing. Refused vs timeout is also a signal: a closed port (no listener, firewall allows) answers with RST ("connection refused"), a filtered port (DROP) gives nothing (timeout), and a REJECT gives a quick error. See the troubleshooting playbook.

Mechanics ​

How a ruleset is evaluated. The nft man page summarises it: for each hook "the attached chains are evaluated in order of their priorities"; "An accept verdict ... ends the evaluation of the current base chain ... The packet advances to the next base chain. Thus a packet is ultimately accepted if and only if no (matching) rule or base chain policy issues a drop verdict"; and "A drop verdict ... immediately ends the evaluation of the whole ruleset." Consequences: two independent tables (yours and Docker's, ufw's and firewalld's) at the same hook both get a vote, and a drop anywhere wins. That is why a Docker ACCEPT can never override your DROP, but your ACCEPT cannot override Docker's DROP either. "Even if a packet is accepted by the ruleset it may still get discarded by other means, for example ... net.ipv4.conf.*.rp_filter."

Verdict / statementEffectNote
acceptStops this base chain; next base chain at the same hook still runsIn iptables, ACCEPT in a built-in chain ends that chain's traversal for that table
dropPacket discarded, sender sees nothingFinal for the whole ruleset
rejectDiscards and sends ICMP unreachable or TCP RSTFaster failure; leaks that a host exists
jump chain / goto chainEvaluate a regular chain; jump returns, goto does notChains in other tables cannot be called
returnBack to the calling chainPolicy applies at the end of a base chain
log / counter / limitNon-terminating statementsPlace before the verdict
dnat / snat / masqueradeNAT in the nat hooks, first packet of a flow onlyReply and later packets are translated by conntrack
notrackSkip conntrack for this packet (raw priority)You must then match with stateless rules

Performance. iptables walks a list linearly: a thousand rules means a thousand comparisons per new flow. nftables sets (hash, rbtree, interval) turn "is this address in the list" into one lookup, and ct state established shortcuts later packets, so the order "invalid, established, then specifics" is both correct and fast. Kubernetes with thousands of Services is what pushed kube-proxy to IPVS, nftables and eBPF datapaths. Cloud firewalls scale on the provider's side, but have quotas (rules per group, groups per interface, NACL rules per NACL).

Per-product behaviour that surprises.

ProductBehaviour
Linux, iptables REJECT vs DROPDROP hides a closed port (client times out, scanner learns nothing); REJECT is friendlier for internal clients and avoids long timeouts
Linux, loopbackAllow iifname "lo" or local services stop talking to each other (DNS stub, PHP-FPM over TCP)
Linux, rp_filterReverse path filtering can drop asymmetric traffic regardless of your rules
DockerContainer-to-container on one user-defined bridge is allowed; published ports are DOCKER-chain rules; iptables: false breaks masquerading
AWSSG changes apply instantly to new flows; tracked flows survive; NACL changes break flows immediately
GCPPriority 0-65535; deny wins ties; implied rules at 65535
AzurePriority 100-4096; same-priority conflicts are not allowed; existing connections survive a rule removal
KubernetesAdditive allow-only model; enforcement by CNI; NodePort or LB source IP may be rewritten before policy

Solving the classic problems ​

ProblemSolutionHowCost / limitation
A server must expose only web and SSHDefault-deny host policy + security grouppolicy drop, established first, then tcp dport {80,443} and an admin setRemote lockout risk while editing
Rules drift between hostsRules generated from one policy fileThe Go generator below, Terraform, AnsibleA generator is code you must test
A container's published port is publicBind to loopback, or DOCKER-USER filter-p 127.0.0.1:..., --ctorigdstport rulesPer host; nftables backend needs its own table
Namespace has no isolationDefault-deny + allow-DNS + explicit allowsNetworkPolicy templates per namespaceNeeds an enforcing CNI
Return traffic blocked in a subnetEphemeral return rule on the NACL, or no custom NACLOutbound allow tcp 1024-65535Wide port range, a coarse control
Brute force on SSHPer-source rate limit, key-only auth, VPN or bastionnft meter, fail2ban, VPNShared NAT addresses get caught together
Admin UI must not face the internetUnix socket or loopback listener + CIDR middlewareGo example below, Laravel middlewareAdmin tools must run on or tunnel to the host
Exfiltration after a compromiseEgress allow-listoutput chain policy drop, NetworkPolicy egress, FQDN firewallMaintenance of allowed destinations
Webhook from a providerSource CIDR allow-list plus signatureallow.cidr middleware, HMAC checkProvider ranges change
Big uploads hangAllow ICMP errors, clamp MSSRules aboveNone worth mentioning

A policy checker and nftables generator in Go ​

The goal: one small YAML file lists the flows a host allows ("allowed flows"), a program validates it and prints the nftables ruleset that denies everything else. It rejects what would silently produce a wrong rule (bad CIDR, unknown protocol, missing ports), splits IPv4 and IPv6 peers into separate rules inside one inet table, emits the established, invalid, ICMP and ping-guard rules from the lab, and turns an egress: list into an output chain with policy drop. It is a teaching generator: the YAML subset is parsed by hand to keep the module dependency-free; for real use take gopkg.in/yaml.v3.

The policy file:

yaml
# Allowed flows for one host. Anything not listed is dropped.
name: web
ingress:
  - name: public-web
    from: [any]
    proto: tcp
    ports: [80, 443]
  - name: admin-ssh
    from: [10.0.0.0/8, 192.0.2.0/24, "2001:db8:100::/48"]
    proto: tcp
    ports: [22]
  - name: metrics
    from: [10.1.0.0/16]
    proto: tcp
    ports: [9100]
egress:
  - name: postgres
    to: [10.2.0.0/24]
    proto: tcp
    ports: [5432]
  - name: dns
    to: [10.0.0.2/32]
    proto: udp
    ports: [53]
  - name: https-out
    to: [203.0.113.0/24]
    proto: tcp
    ports: [443]

The program:

go
// policygen reads a YAML list of allowed flows and prints an nftables ruleset
// that denies everything else. It uses only the standard library plus a tiny
// parser for the fixed YAML shape shown in policy.yaml.
package main

import (
	"bufio"
	"fmt"
	"io"
	"net/netip"
	"os"
	"sort"
	"strconv"
	"strings"
)

// Flow is one allowed (direction-less) flow: who, which protocol, which ports.
type Flow struct {
	Name  string
	Peers []string // CIDRs or "any"
	Proto string   // tcp or udp
	Ports []uint16
}

// Policy holds the ingress and egress allow-lists of one host.
type Policy struct {
	Name    string
	Ingress []Flow
	Egress  []Flow
}

// Parse reads the restricted YAML subset: top-level name, ingress, egress;
// list items start with "- name:", other keys are from/to, proto, ports.
func Parse(r io.Reader) (*Policy, error) {
	p := &Policy{}
	var section *[]Flow
	var cur *Flow
	sc := bufio.NewScanner(r)
	for n := 1; sc.Scan(); n++ {
		line := strings.TrimRight(sc.Text(), " \t")
		if i := strings.Index(line, "#"); i >= 0 {
			line = strings.TrimRight(line[:i], " \t")
		}
		if strings.TrimSpace(line) == "" {
			continue
		}
		trim := strings.TrimSpace(line)
		switch {
		case strings.HasPrefix(line, "name:"):
			p.Name = strings.TrimSpace(strings.TrimPrefix(line, "name:"))
		case line == "ingress:":
			section = &p.Ingress
		case line == "egress:":
			section = &p.Egress
		case strings.HasPrefix(trim, "- name:"):
			if section == nil {
				return nil, fmt.Errorf("line %d: flow outside ingress/egress", n)
			}
			*section = append(*section, Flow{Name: strings.TrimSpace(strings.TrimPrefix(trim, "- name:"))})
			cur = &(*section)[len(*section)-1]
		case cur != nil:
			key, val, ok := strings.Cut(trim, ":")
			if !ok {
				return nil, fmt.Errorf("line %d: expected key: value", n)
			}
			val = strings.TrimSpace(val)
			switch key {
			case "from", "to":
				cur.Peers = splitList(val)
			case "proto":
				cur.Proto = val
			case "ports":
				for _, s := range splitList(val) {
					v, err := strconv.ParseUint(s, 10, 16)
					if err != nil || v == 0 {
						return nil, fmt.Errorf("line %d: bad port %q", n, s)
					}
					cur.Ports = append(cur.Ports, uint16(v))
				}
			default:
				return nil, fmt.Errorf("line %d: unknown key %q", n, key)
			}
		default:
			return nil, fmt.Errorf("line %d: unexpected %q", n, trim)
		}
	}
	return p, sc.Err()
}

func splitList(v string) []string {
	v = strings.Trim(v, "[]")
	var out []string
	for _, s := range strings.Split(v, ",") {
		if s = strings.Trim(strings.TrimSpace(s), "\"'"); s != "" {
			out = append(out, s)
		}
	}
	return out
}

// Validate rejects anything that would silently produce a wrong rule.
func (p *Policy) Validate() error {
	for _, f := range append(append([]Flow{}, p.Ingress...), p.Egress...) {
		if f.Proto != "tcp" && f.Proto != "udp" {
			return fmt.Errorf("flow %q: proto must be tcp or udp, got %q", f.Name, f.Proto)
		}
		if len(f.Ports) == 0 || len(f.Peers) == 0 {
			return fmt.Errorf("flow %q: ports and peers are required", f.Name)
		}
		for _, peer := range f.Peers {
			if peer == "any" {
				continue
			}
			if _, err := netip.ParsePrefix(peer); err != nil {
				return fmt.Errorf("flow %q: bad CIDR %q: %w", f.Name, peer, err)
			}
		}
	}
	return nil
}

// split separates peers into IPv4 prefixes, IPv6 prefixes and the "any" flag.
func split(peers []string) (v4, v6 []string, any bool) {
	for _, peer := range peers {
		if peer == "any" {
			any = true
			continue
		}
		pf := netip.MustParsePrefix(peer)
		if pf.Addr().Is4() {
			v4 = append(v4, pf.String())
		} else {
			v6 = append(v6, pf.String())
		}
	}
	return
}

func portSet(ports []uint16) string {
	sorted := append([]uint16(nil), ports...)
	sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })
	s := make([]string, len(sorted))
	for i, p := range sorted {
		s[i] = strconv.Itoa(int(p))
	}
	return "{ " + strings.Join(s, ", ") + " }"
}

// rules renders one chain body. dir is "saddr" for ingress and "daddr" for egress.
func rules(flows []Flow, dir, portKey string) []string {
	var out []string
	for _, f := range flows {
		v4, v6, any := split(f.Peers)
		ports := portSet(f.Ports)
		out = append(out, "# "+f.Name)
		if any {
			out = append(out, fmt.Sprintf("%s %s %s ct state new accept", f.Proto, portKey, ports))
		}
		if len(v4) > 0 {
			out = append(out, fmt.Sprintf("ip %s { %s } %s %s %s ct state new accept", dir, strings.Join(v4, ", "), f.Proto, portKey, ports))
		}
		if len(v6) > 0 {
			out = append(out, fmt.Sprintf("ip6 %s { %s } %s %s %s ct state new accept", dir, strings.Join(v6, ", "), f.Proto, portKey, ports))
		}
	}
	return out
}

// Render produces the full nftables script.
func (p *Policy) Render() string {
	var b strings.Builder
	w := func(format string, a ...any) { fmt.Fprintf(&b, format+"\n", a...) }
	w("#!/usr/sbin/nft -f")
	w("# generated from policy %q; do not edit by hand", p.Name)
	w("flush ruleset")
	w("table inet filter {")
	w("\tchain input {")
	w("\t\ttype filter hook input priority filter; policy drop;")
	w("\t\tct state invalid drop")
	// The ping limiter must precede "established": later echo requests of a flow count as established.
	w("\t\tip protocol icmp icmp type echo-request limit rate over 5/second burst 10 packets drop")
	w("\t\tmeta l4proto ipv6-icmp icmpv6 type echo-request limit rate over 5/second burst 10 packets drop")
	w("\t\tct state established,related accept")
	w("\t\tiifname \"lo\" accept")
	w("\t\tip protocol icmp icmp type { destination-unreachable, time-exceeded, parameter-problem, echo-request } accept")
	w("\t\tmeta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert, echo-request } accept")
	for _, r := range rules(p.Ingress, "saddr", "dport") {
		w("\t\t%s", r)
	}
	w("\t\tlimit rate 5/minute burst 5 packets log prefix \"%s-in-drop: \" counter", p.Name)
	w("\t}")
	w("\tchain forward {")
	w("\t\ttype filter hook forward priority filter; policy drop;")
	w("\t}")
	w("\tchain output {")
	if len(p.Egress) == 0 {
		w("\t\ttype filter hook output priority filter; policy accept;")
	} else {
		w("\t\ttype filter hook output priority filter; policy drop;")
		w("\t\tct state established,related accept")
		w("\t\toifname \"lo\" accept")
		w("\t\tip protocol icmp accept")
		w("\t\tmeta l4proto ipv6-icmp accept")
		for _, r := range rules(p.Egress, "daddr", "dport") {
			w("\t\t%s", r)
		}
		w("\t\tlimit rate 5/minute burst 5 packets log prefix \"%s-out-drop: \" counter", p.Name)
	}
	w("\t}")
	w("}")
	return b.String()
}

func main() {
	in := io.Reader(os.Stdin)
	if len(os.Args) > 1 {
		f, err := os.Open(os.Args[1])
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(2)
		}
		defer f.Close()
		in = f
	}
	p, err := Parse(in)
	if err == nil {
		err = p.Validate()
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, "policy error:", err)
		os.Exit(1)
	}
	fmt.Print(p.Render())
}

Real run, then the syntax check with nft -c (check only, loads nothing) and a live test of the egress policy in a container: before loading, a TCP connection to 1.1.1.1:80 succeeds; after loading the generated ruleset (egress default-drop, 1.1.1.1 not in the list), it times out; the drop counter climbs:

$ go run ./policygen policygen/policy.yaml > web.nft
$ nft -c -f web.nft && echo SYNTAX-OK
SYNTAX-OK
$ nc -z -w3 1.1.1.1 80; echo "before: rc=$?"
Connection to 1.1.1.1 80 port [tcp/http] succeeded!
before: rc=0
$ nft -f web.nft && nc -z -w3 1.1.1.1 80; echo "after (egress default-drop): rc=$?"
after (egress default-drop): rc=1
$ nft list chain inet filter output | tail -4
		ip daddr 10.0.0.2 udp dport 53 ct state new accept
		ip daddr 203.0.113.0/24 tcp dport 443 ct state new accept
		limit rate 5/minute burst 5 packets log prefix "web-out-drop: " counter packets 3 bytes 180
	}

The generated input chain (head), showing the two details that matter: the ping limiter sits before the established rule, and IPv4 and IPv6 peers are separate rules:

	chain input {
		type filter hook input priority filter; policy drop;
		ct state invalid drop
		ip protocol icmp icmp type echo-request limit rate over 5/second burst 10 packets drop
		meta l4proto ipv6-icmp icmpv6 type echo-request limit rate over 5/second burst 10 packets drop
		ct state established,related accept
		iifname "lo" accept
		...
		# public-web
		tcp dport { 80, 443 } ct state new accept
		# admin-ssh
		ip saddr { 10.0.0.0/8, 192.0.2.0/24 } tcp dport { 22 } ct state new accept
		ip6 saddr { 2001:db8:100::/48 } tcp dport { 22 } ct state new accept

The IPv6 rules were syntax-checked only; the lab network is IPv4-only.

An admin listener with no port to firewall: a Unix socket ​

An admin or debug endpoint (metrics, pprof, a "drain" command) does not need a TCP port at all. A Unix domain socket is a file; who may connect is decided by the file's permissions, so there is nothing for a scanner to find and nothing for a firewall rule to forget. This is the "port-knock-free" alternative to hiding an admin port behind knock sequences: remove the port.

go
// unixadmin serves the public API on TCP and the admin API ONLY on a Unix
// socket. There is no admin port to firewall, scan or forget to firewall:
// access is decided by file permissions on the socket (and its directory).
package main

import (
	"errors"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"syscall"
	"time"
)

func listenUnix(path string) (net.Listener, error) {
	if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
		return nil, err
	}
	// A stale socket file from a crashed run makes Listen fail with EADDRINUSE.
	if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
		return nil, err
	}
	// Create the socket with mode 0600 from the first instant (no chmod race).
	old := syscall.Umask(0o177)
	defer syscall.Umask(old)
	return net.Listen("unix", path)
}

func main() {
	public := http.NewServeMux()
	public.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "public ok")
	})
	public.HandleFunc("/admin/", http.NotFound) // never served here

	admin := http.NewServeMux()
	admin.HandleFunc("/admin/status", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "admin ok, pid %d, time %s\n", os.Getpid(), time.Now().Format(time.RFC3339))
	})

	sock := "/tmp/unixadmin/admin.sock"
	if len(os.Args) > 1 {
		sock = os.Args[1]
	}
	ln, err := listenUnix(sock)
	if err != nil {
		log.Fatal(err)
	}
	go func() { log.Fatal((&http.Server{Handler: admin, ReadHeaderTimeout: 5 * time.Second}).Serve(ln)) }()

	// Bind the public listener explicitly: 127.0.0.1 behind a reverse proxy,
	// 0.0.0.0 only when something must reach it directly.
	log.Println("public on 127.0.0.1:8080, admin on", sock)
	log.Fatal((&http.Server{Addr: "127.0.0.1:8080", Handler: public, ReadHeaderTimeout: 5 * time.Second}).ListenAndServe())
}

Real run on macOS (the socket mode is srw-------, owner only; the public listener returns 404 for /admin/):

$ go build -o unixadmin ./unixadmin && ./unixadmin /tmp/uatest/admin.sock &
2026/11/25 21:15:50 public on 127.0.0.1:8080, admin on /tmp/uatest/admin.sock
$ ls -l /tmp/uatest/
srw-------@ 1 m.negahi  wheel  0 Nov 25 21:15 admin.sock
$ curl -s --unix-socket /tmp/uatest/admin.sock http://x/admin/status
admin ok, pid 24143, time 2026-11-25T21:15:50+03:30
$ curl -s -o /dev/null -w "public /admin -> %{http_code}\n" http://127.0.0.1:8080/admin/status
public /admin -> 404
DetailWhy it matters
syscall.Umask(0o177) around ListenThe socket is created 0600 from the start; chmod after Listen leaves a window
Removing a stale socket firstA crashed run leaves the file; Listen would fail with "address already in use"
Directory mode 0750The directory is a second permission check
Public server on 127.0.0.1:8080A reverse proxy on the host is the only public listener
Reaching it remotelyssh -L can forward a local port to a remote Unix socket (-L 9090:/run/app/admin.sock); see VPNs and tunnels
ContainersMount the socket with a volume; in Kubernetes use a shared emptyDir between sidecars

Allow-lists in the database (SQL) ​

When the allow-list is data (admin ranges, partner webhook ranges, customer IP restrictions) keep it in PostgreSQL with cidr and test membership with the <<= operator (contained within or equal). The same technique matches flow logs. Real run on PostgreSQL 16:

sql
CREATE TABLE firewall_allowlist (
    id          bigserial PRIMARY KEY,
    list_name   text        NOT NULL,
    cidr        cidr        NOT NULL,
    note        text,
    expires_at  timestamptz,
    UNIQUE (list_name, cidr)
);
INSERT INTO firewall_allowlist (list_name, cidr, note) VALUES
    ('admin',            '10.0.0.0/8',           'office VPN'),
    ('admin',            '2001:db8:100::/48',    'office IPv6'),
    ('webhook:payments', '203.0.113.0/24',       'provider published range');

-- is this client allowed? (false for 198.51.100.9)
SELECT EXISTS (SELECT 1 FROM firewall_allowlist
                WHERE list_name = 'admin' AND inet '198.51.100.9' <<= cidr
                  AND (expires_at IS NULL OR expires_at > now())) AS allowed;
--  allowed
-- ---------
--  f

-- which ports are rejected most? (flow-log table loaded from VPC Flow Logs)
SELECT dstport, count(*) AS rejects, count(DISTINCT srcaddr) AS sources
  FROM flow_log
 WHERE action = 'REJECT' AND start_time > now() - interval '1 hour'
 GROUP BY dstport ORDER BY rejects DESC;
--  dstport | rejects | sources
--     5432 |       2 |       2      <- a scanner hitting the database port
--    51344 |       1 |       1      <- a reply rejected on an ephemeral port: the NACL bug

-- the NACL signature: a request ACCEPTed and its mirrored reply REJECTed
SELECT a.srcaddr, a.srcport, a.dstport
  FROM flow_log a
  JOIN flow_log b ON b.srcaddr = a.dstaddr AND b.dstaddr = a.srcaddr
                 AND b.srcport = a.dstport AND b.dstport = a.srcport
 WHERE a.action = 'ACCEPT' AND b.action = 'REJECT';

Laravel and PHP: the application-level second wall ​

Laravel should not be the only thing between a stranger and /admin, but it should be a wall too. Two rules: the check uses the real client address (TrustProxies correctly configured), and the check is deny-by-default.

TrustProxies first, because every IP check depends on it. Laravel's docs: "you may enable the Illuminate\Http\Middleware\TrustProxies middleware that is included in your Laravel application ... Your trusted proxies should be specified using the trustProxies middleware method in your application's bootstrap/app.php file". Trust the load balancer's CIDR, never * on a host that anyone can reach directly: with *, any client can send X-Forwarded-For: 10.4.5.6 and be treated as an office address. See the same topic for NAT in NAT and port forwarding.

php
<?php

use App\Http\Middleware\AllowFromCidr;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Trust ONLY the load balancer's subnet (the same CIDR your security group
        // allows on port 80/443 from the LB). Never '*' on a host that is reachable directly.
        $middleware->trustProxies(
            at: ['10.20.0.0/24'],
            headers: Request::HEADER_X_FORWARDED_FOR
                | Request::HEADER_X_FORWARDED_HOST
                | Request::HEADER_X_FORWARDED_PORT
                | Request::HEADER_X_FORWARDED_PROTO,
        );

        $middleware->alias(['allow.cidr' => AllowFromCidr::class]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

The allow-lists as configuration (so staging and production differ):

php
<?php

// config/firewall.php
// Application-level allow-lists. They are the SECOND wall: the first one is
// the security group / nftables rule that already keeps strangers away.
return [
    // Who may open /admin/*. Read from the environment so staging and prod differ.
    'admin_cidrs' => array_filter(explode(',', (string) env('ADMIN_CIDRS', '10.0.0.0/8,127.0.0.1/32,::1/128'))),

    // Providers that call our webhooks, with the source ranges they publish.
    // Keep these in config/DB and refresh them: providers change ranges.
    'webhook_sources' => [
        'payments' => array_filter(explode(',', (string) env('PAYMENTS_WEBHOOK_CIDRS', '203.0.113.0/24,2001:db8:beef::/48'))),
    ],
];

The middleware. Symfony\Component\HttpFoundation\IpUtils::checkIp (Laravel's request is a Symfony request) accepts one address or a list, IPv4 and IPv6, with CIDR notation. It returns 404, not 403, so a scanner cannot distinguish "no such page" from "forbidden":

php
<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpFoundation\Response;

/**
 * Deny by default: the request is served only when the client address is inside one of
 * the CIDR blocks of the named list in config/firewall.php.
 *
 * Usage: Route::middleware('allow.cidr:admin_cidrs') or 'allow.cidr:webhook_sources.payments'.
 *
 * $request->ip() is only the real client when TrustProxies is configured for
 * YOUR proxies; with 'at' => '*' anybody can spoof X-Forwarded-For and walk through.
 */
final class AllowFromCidr
{
    public function handle(Request $request, Closure $next, string $list): Response
    {
        $allowed = (array) config('firewall.'.$list, []);
        $ip = $request->ip();

        if ($ip === null || $allowed === [] || ! IpUtils::checkIp($ip, $allowed)) {
            // 404 (not 403) tells a scanner nothing about what exists here.
            logger()->warning('firewall.app_denied', [
                'list' => $list,
                'ip' => $ip,
                'remote_addr' => $request->server('REMOTE_ADDR'),
                'path' => $request->path(),
            ]);

            abort(404);
        }

        return $next($request);
    }
}

Using it on admin routes and on the webhook route, with the signature as the real proof:

php
<?php

// routes/web.php and routes/api.php (excerpt)
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\PaymentWebhookController;
use Illuminate\Support\Facades\Route;

// Admin: network allow-list first, then authentication, then authorization.
Route::middleware(['allow.cidr:admin_cidrs', 'auth', 'can:view-admin'])
    ->prefix('admin')
    ->group(function (): void {
        Route::get('/', [DashboardController::class, 'index']);
    });

// Webhook: source IP is a cheap pre-filter; the HMAC signature in the
// controller is the real proof (IPs are shared, ranges change, headers can lie).
Route::post('/webhooks/payments', PaymentWebhookController::class)
    ->middleware('allow.cidr:webhook_sources.payments'); // in routes/api.php: no session, no CSRF
php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class PaymentWebhookController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        // Defence in depth: the network layer let this packet in, now prove the sender knows the secret.
        $expected = hash_hmac('sha256', $request->getContent(), (string) config('services.payments.webhook_secret'));
        $given = (string) $request->header('X-Signature', '');

        if (! hash_equals($expected, $given)) {
            abort(401);
        }

        // ... enqueue the event; answer fast so the provider does not retry.
        return response()->json(['ok' => true], 202);
    }
}

A feature test that includes the spoofing case. The third test is the important one: with no trusted proxy configured, a forged X-Forwarded-For is ignored:

php
<?php

declare(strict_types=1);

namespace Tests\Feature;

use Illuminate\Support\Facades\Route;
use Tests\TestCase;

final class AllowFromCidrTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        config(['firewall.admin_cidrs' => ['10.0.0.0/8', '2001:db8:100::/48']]);
        Route::middleware('allow.cidr:admin_cidrs')->get('/admin-ping', fn () => 'pong');
    }

    public function test_inside_the_range_is_served(): void
    {
        $this->withServerVariables(['REMOTE_ADDR' => '10.4.5.6'])->get('/admin-ping')->assertOk();
        $this->withServerVariables(['REMOTE_ADDR' => '2001:db8:100::7'])->get('/admin-ping')->assertOk();
    }

    public function test_outside_the_range_is_hidden(): void
    {
        $this->withServerVariables(['REMOTE_ADDR' => '198.51.100.9'])->get('/admin-ping')->assertNotFound();
    }

    public function test_spoofed_forwarded_for_is_ignored_without_a_trusted_proxy(): void
    {
        // The peer is a stranger; the header claims to be an admin. trustProxies does not trust the peer.
        $this->withServerVariables(['REMOTE_ADDR' => '198.51.100.9'])
            ->withHeaders(['X-Forwarded-For' => '10.4.5.6'])
            ->get('/admin-ping')
            ->assertNotFound();
    }
}
PieceWhy
$middleware->trustProxies(at: ['10.20.0.0/24'], headers: ...)Only the load balancer's subnet may set X-Forwarded-*; matches the SG rule that allows only the LB to reach port 80
Request::ip()The client address after proxy resolution; REMOTE_ADDR is the peer (the proxy)
IpUtils::checkIp($ip, $cidrs)CIDR matching for both families; no regex, no ip2long bugs
Middleware order allow.cidr then auth then canNetwork, identity, permission: three independent checks
abort(404) and a warning logHides the route and leaves an audit trail with REMOTE_ADDR
Webhook IP allow-list plus hash_equals on an HMACIP ranges are shared and change; the signature proves possession of the secret
Config from .envADMIN_CIDRS differs per environment; no code change to rotate ranges

Pitfalls that belong to the network, not the framework: behind Cloudflare, the peer is a Cloudflare address and the client IP is in a header only Cloudflare may set (restrict origin traffic to Cloudflare ranges in the security group, then trust them); behind a Kubernetes Service of type NodePort or LoadBalancer with externalTrafficPolicy: Cluster, the source is SNATed to a node (use Local or PROXY protocol); CGNAT means one IPv4 can be many people, so an IP allow-list is a boundary, not an identity (authorization and zero trust).

Choosing ​

SituationRecommendationExtra techniqueReason
One VPS running nginx, PHP, Postgresnftables (or ufw) default-deny: 80, 443, SSH from your IPBind Postgres and PHP-FPM to loopback or a socket; fail2banTwo walls: firewall and listener
Cloud web appSecurity groups per tier referencing each other; default NACLFlow logs; no 0.0.0.0/0 except the LB's 443Least privilege without address bookkeeping
Need to block a hostile CIDR subnet-wideCustom NACL deny rule with a low numberReturn-port rules; WAF for L7SGs cannot deny
Docker host with Compose127.0.0.1: publishes + a reverse proxyDOCKER-USER rules, cloud SGufw does not see published ports
Kubernetes multi-tenantDefault-deny + allow-DNS per namespaceCalico/Cilium for logging, FQDN, global policyCore NetworkPolicy is allow-only and namespaced
Locking down egress for a payments serviceEgress allow-list by CIDR; FQDN with Cilium or a firewall serviceNAT gateway with a fixed IP, domain filteringLimits exfiltration and supply-chain callbacks
Public admin toolDo not expose it: VPN, bastion, SSH tunnel, Unix socketCIDR middleware as a backstopA closed port cannot be attacked
Webhook receiverPublic endpoint, signature verificationProvider CIDR allow-list from a managed listIPs are not identity
Home router with IPv6Stateful inbound-deny firewallAllow specific services onlyNo NAT, so no accidental protection
Very large blocklists or many rulesnftables sets or ipset, or eBPFReload atomically from filesLinear iptables chains do not scale
Compliance and auditFlow logs plus change-managed rules in GitTerraform plan reviewProves what was allowed

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

Example. One VPS with Laravel (nginx plus PHP-FPM) and PostgreSQL. The provider firewall allows 80 and 443 from anywhere and 22 from the office IP. The host runs the nftables file from this chapter (default-deny, established, ICMP errors, tcp dport {80,443}, the admin_v4 set for SSH). PHP-FPM listens on a Unix socket, PostgreSQL on localhost. A port scan from outside sees two open ports and nothing else; a leaked .env with the database password is still useless from the internet because 5432 is not reachable. Admin routes also pass the allow.cidr middleware.

Modular monolith ​

Example. One deployable, several modules (billing, catalogue, reporting), two databases (OLTP and a reporting replica) on separate hosts in private subnets. Security groups name tiers, not addresses: app-sg allows 443 from alb-sg; db-sg allows 5432 from app-sg only; reporting-sg allows 5432 from the reporting host's SG. A module that suddenly needs the other database fails closed, forcing a conversation. Egress: the app SG allows 443 to payment and email CIDRs plus DNS; the rest is dropped. The NACLs stay at defaults so only one layer is debugged on day one.

Microservices ​

Example. Fifteen services in one Kubernetes cluster, namespace per team. Every namespace gets the same three policies from a template: default-deny, allow-DNS, allow-from-ingress for services that have a route. The order service may call inventory and payments; payments may call out only to the provider's CIDRs and its database. A new service starts with no access and the pull request that adds a policy is the design review ("who calls this?"). Calico or Cilium provides the enforcement and flow logs; the platform team adds Cilium toFQDNs rules for SaaS APIs. NetworkPolicy answers "which pods may connect"; mTLS answers "who is calling". Both are needed because pod labels are not identities that cross clusters, and a compromised pod with an allowed label still connects.

Distributed data: replicas, caches, multi-region ​

Example. A primary in region A, replicas and a Redis cluster in region B over a VPN or peering. Security groups allow the replication port (5432, 6379 and 16379 for the cluster bus) only between the data-tier SGs of the two regions; the CIDRs of the peer region are in a managed prefix list so a route change is one edit. A NACL at the data subnet denies everything except the peer CIDR and the app tier, and carries explicit ephemeral-port rules for replication replies. Cross-region links often have a smaller MTU (VPN encapsulation): replication stalls on large COPY batches until ICMP "fragmentation needed" is allowed or MSS is clamped. Failover must not depend on a rule someone edits by hand: the standby region's rules are applied from the same Terraform module and verified by a test that runs nc -z from each tier.

Scaling path ​

Load / sizeWhat breaks firstWhat to change
1 server, 1xDocker publishes a database, or 0.0.0.0 listenersLoopback binds, default-deny, one reviewed ruleset
10 servers, 10xRule drift; hand-edited security groupsGenerate rules from one policy file or Terraform module; prefix lists; flow logs on
100 services, 100xAddress-based rules do not map to pods that moveNetworkPolicy by label, CNI with identity (Cilium), SG references, default-deny templates
Thousands of rules or nodesLinear iptables chains slow connection setup; conntrack tables fillnftables sets, eBPF datapath, kube-proxy in IPVS or nftables mode, notrack where safe
Multi-region, many accountsInconsistent baselines, shadow rulesCentral firewall policy (AWS Firewall Manager, GCP hierarchical policies, Azure Firewall Manager), org-level guardrails, automated drift detection
Zero trust targetIP allow-lists lag behind realityIdentity-based access (mTLS, workload identity, ZTNA) with network rules as the coarse outer wall

Lab ​

Everything below ran on this machine in Docker containers with --cap-add NET_ADMIN (the capability CAP_NET_ADMIN lets a container edit its own network namespace's rules), each in its own network namespace, so nothing touches the host. Section 3 used a Docker-in-Docker daemon (docker:dind, Docker 29.10, --privileged) so that Docker's own firewall rules could be changed safely. The NetworkPolicy section (5) was not run: no Kubernetes cluster was available, so its output is marked expected. IPv6 rules were syntax-checked with nft -c but not exercised (the Docker network was IPv4-only).

1. A default-deny nft ruleset for a web server. The complete file is the one the chapter quotes; tested with nc:

txt
#!/usr/sbin/nft -f
# Default-deny host firewall for a single web server (IPv4 + IPv6 in one table).
flush ruleset

table inet filter {
    # Who may reach SSH. Intervals allow CIDR blocks in a set.
    set admin_v4 {
        type ipv4_addr
        flags interval
        elements = { 172.16.0.0/12, 10.0.0.0/8 }
    }

    chain input {
        type filter hook input priority filter; policy drop;

        # 1. Packets conntrack cannot place in any flow are never legitimate.
        ct state invalid counter drop

        # 2. Ping flood guard. It must come BEFORE the established rule: after the first
        #    reply, conntrack marks later echo requests of the same flow ESTABLISHED, and
        #    they would skip any rate limit placed after that rule.
        ip protocol icmp icmp type echo-request limit rate over 5/second burst 10 packets drop
        meta l4proto ipv6-icmp icmpv6 type echo-request limit rate over 5/second burst 10 packets drop

        # 3. Replies to connections we (or the peer, with a rule below) started.
        ct state established,related accept

        # 4. Loopback is always local traffic.
        iifname "lo" accept

        # 5. ICMP: keep the parts that make TCP work (PMTUD, errors, ping; the flood guard is rule 2).
        ip protocol icmp icmp type { destination-unreachable, time-exceeded, parameter-problem } accept
        ip protocol icmp icmp type echo-request accept
        meta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert } accept
        meta l4proto ipv6-icmp icmpv6 type echo-request accept

        # 6. The services this machine offers.
        tcp dport { 80, 443 } ct state new accept
        ip saddr @admin_v4 tcp dport 22 ct state new accept

        # 7. Everything else: log a few samples (nflog group 100), then the policy drops it.
        limit rate 5/minute burst 5 packets log group 100 prefix "nft-input-drop: " counter
    }

    chain forward {
        type filter hook forward priority filter; policy drop;
    }

    chain output {
        type filter hook output priority filter; policy accept;
    }
}
bash
docker network create fwlab
docker run -d --name fwsrv --network fwlab --cap-add NET_ADMIN -v "$PWD/nft:/nft:ro" alpine sh -c \
  'apk add -q nftables tcpdump conntrack-tools netcat-openbsd iproute2; sleep 3600'
docker run -d --name fwcli --network fwlab alpine sh -c 'apk add -q netcat-openbsd; sleep 3600'
# listeners on 80, 443, 22 and 5432 inside fwsrv
docker exec fwsrv sh -c 'for p in 80 443 22 5432; do (while true; do echo "port $p" | nc -l -p $p >/dev/null 2>&1; done) & done'
SRV=$(docker inspect -f '{{.NetworkSettings.Networks.fwlab.IPAddress}}' fwsrv)    # 172.19.0.2 here
for p in 80 443 22 5432; do docker exec fwcli nc -z -w 2 $SRV $p && echo "$p open" || echo "$p filtered"; done
# before the ruleset: all four open
docker exec fwsrv nft -f /nft/web-server.nft
# after: 80, 443 open; 22 open (the client's 172.19.0.3 is inside admin_v4 172.16.0.0/12); 5432 times out

Real output after loading: 80 open, 443 open, 22 open, 5432 timeout (nc exit 1 after the 2-second wait).

ExperimentResult
nc -z -w 3 SRV 9999 with an input drop policy3.01 s then exit 1 (silent drop)
Add nft add rule inet filter input tcp dport 9999 reject with tcp reset0.00 s, exit 1 ("connection refused" at once)
nft delete element inet filter admin_v4 '{ 172.16.0.0/12 }' then nc -z -w2 SRV 22exit 1: the client is no longer in the set, SSH is filtered
ping -c 100 -i 0.01 SRV with the flood guard after the established rule0% loss: the guard never fired, because later echo requests are ESTABLISHED
The same with the guard before the established rule (the file above)100 sent, 15 received, 85% loss

The last two rows are the reason rule 2 in the file sits above the established rule.

2. Log the drops. Listen on nflog group 100 while a client probes a blocked port:

bash
docker exec -d fwsrv sh -c 'timeout 8 tcpdump -l -n -i nflog:100 > /tmp/nflog.txt 2>&1'
docker exec fwcli nc -z -w 1 172.19.0.2 5432
docker exec fwsrv cat /tmp/nflog.txt
# 17:42:11.697290 IP 172.19.0.3.41840 > 172.19.0.2.5432: Flags [S], seq 2330625817, win 64240, length 0
docker exec fwsrv nft list ruleset | grep 'log group'     # counters: "counter packets 2 bytes 120" after two probes
docker exec fwsrv conntrack -L                            # flows tracked so far

3. Protect a published Docker port with DOCKER-USER. Inside a Docker-in-Docker daemon (docker run -d --name fwdind --privileged -e DOCKER_TLS_CERTDIR= docker:dind, then docker save alpine nginx:alpine | docker exec -i fwdind docker load). Two outside clients are plain containers on the outer bridge; the Docker host's eth0 address was 172.17.0.4.

bash
docker exec fwdind docker run -d --name pubtest -p 18080:80 nginx:alpine
# ext1 = 172.17.0.5, ext2 = 172.17.0.6 (two "external" clients)
docker exec ext1 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ && echo reachable      # reachable
docker exec ext2 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ && echo reachable      # reachable

# A host-firewall rule on INPUT does not see the published port (ufw installed and enabled, "ufw deny 18080/tcp"):
docker exec fwdind iptables -L ufw-user-input -v -n     # DROP tcp dpt:18080    0 packets
docker exec ext1 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ && echo "still reachable"

# The right place:
docker exec fwdind iptables -I DOCKER-USER -i eth0 ! -s 172.17.0.5 -p tcp -m conntrack --ctorigdstport 18080 -j DROP
docker exec ext1 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ && echo reachable      # reachable
docker exec ext2 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ || echo blocked        # wget: download timed out
docker exec fwdind iptables -L DOCKER-USER -v -n
#  3   180 DROP  tcp  --  eth0  *  !172.17.0.5  0.0.0.0/0  ctorigdstport 18080

Also real: after docker run -d -p 127.0.0.1:18081:80 nginx:alpine an outside client gets "connection refused/blocked" at 172.17.0.4:18081, while wget http://127.0.0.1:18081/ from the host itself works. The Docker 28 raw-table rule (-A PREROUTING -d 127.0.0.1/32 ! -i lo -p tcp -m tcp --dport 18081 -j DROP) is what enforces it. Clean up: docker rm -f fwdind ext1 ext2.

4. iptables syntax and translation. In a container with apk add iptables nftables:

bash
iptables-translate -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
# nft 'add rule ip filter INPUT tcp dport 22 ct state new,established counter accept'
iptables -P INPUT DROP; iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
iptables -S; iptables -L INPUT -v -n --line-numbers; nft list ruleset   # same rules, two views

5. NetworkPolicy on kind (expected output, not run here). Create the cluster without the default CNI and install Calico (kind's documentation states that disableDefaultCNI: true is supported and that Calico manifests are known to work), then:

bash
cat <<'YAML' | kind create cluster --config=-
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
  disableDefaultCNI: true
YAML
kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.28.0/manifests/calico.yaml
kubectl create namespace shop
kubectl -n shop run db --image=nginx:alpine --labels=app=db
kubectl -n shop run api --image=curlimages/curl --labels=app=api --command -- sleep 3600
kubectl -n shop run other --image=curlimages/curl --labels=app=other --command -- sleep 3600
DB=$(kubectl -n shop get pod db -o jsonpath='{.status.podIP}')
kubectl -n shop exec other -- curl -s -m 3 -o /dev/null -w '%{http_code}\n' http://$DB     # expect 200 (default allow)
kubectl apply -f 00-default-deny.yaml
kubectl -n shop exec other -- curl -s -m 3 -o /dev/null -w '%{http_code}\n' http://$DB     # expect 000 and exit 28 (timeout, not refused)
cat <<'YAML' | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: db-from-api, namespace: shop}
spec:
  podSelector: {matchLabels: {app: db}}
  policyTypes: [Ingress]
  ingress:
    - from: [{podSelector: {matchLabels: {app: api}}}]
      ports: [{protocol: TCP, port: 80}]
YAML
kubectl -n shop exec api   -- curl -s -m 3 -o /dev/null -w '%{http_code}\n' http://$DB     # still 000: default-deny-all also blocks api EGRESS

The last line surprises people: default-deny-all isolates egress too, so the api pod also needs an egress rule to the db (policy api-egress in the manifests). Remove the egress half of the default-deny (use default-deny-ingress only) to see the allowed 200 from api and the timeout from other. Expected results: timeouts (not refusals) for denied pods, 200 for allowed ones. On a cluster whose CNI does not enforce policy, every command returns 200.

Common misconceptions ​

BeliefReality
NAT is a firewallNAT blocks unsolicited inbound by accident (no table row). RFC 4864: "IPv4 NAT was not developed as a security mechanism"
ufw deny protects Docker published portsDocker's DNAT sends them through FORWARD; ufw owns INPUT. Use 127.0.0.1: binds or DOCKER-USER
A NetworkPolicy always restricts trafficOnly if the CNI enforces it; otherwise "no effect"
Security groups and NACLs are the sameSG: stateful, allow-only, per ENI. NACL: stateless, ordered allow and deny, per subnet
Stateful firewalls need rules for repliesReplies match the tracked flow; stateless ones (NACL) need an ephemeral-port rule
Block all ICMP for safetyDestination unreachable and Packet Too Big make PMTUD work; blocking them causes black holes
iptables and nftables are separate firewallsUsually the same kernel engine; iptables-nft writes nftables rules
DROP is better than REJECT everywhereDROP hides ports from scanners but slows legitimate failures; use REJECT internally
Closing a port in the firewall stops the process listeningThe socket still exists; any other path can reach it. Bind to loopback too
IPv6 is covered by my IPv4 rulesSeparate rules or an inet table are required; with no NAT every host is reachable
A rate limit after the established rule limits pingsAfter the first reply, later echo requests are ESTABLISHED and skip it; place guards earlier
Source-IP allow-lists are authenticationAddresses are shared (CGNAT, proxies, VPN) and spoofable behind trustProxies('*'); combine with identity
NetworkPolicy has deny rules and orderingIt is allow-only and additive; use CNI extensions for deny
Egress does not matter if ingress is lockedCompromise starts outbound: downloads, reverse shells, exfiltration

Cheat sheet ​

TopicWhat to remember
Rule inputs5-tuple, interface, direction, conntrack state; clouds add tags, SG references, labels
Stateless vs statefulStateful (conntrack, SG, NSG, NetworkPolicy): replies free. Stateless (NACL): allow both directions
Default posturepolicy drop; established first, then specifics; keep your SSH rule in before enabling
Hooksprerouting, input, forward, output, postrouting; own packets: input/output; routed (containers): forward
Tablesraw (notrack), mangle, nat (first packet only), filter (verdicts)
Prioritiesraw -300, mangle -150, DNAT -100, filter 0, SNAT 100
iptablesiptables -S, -L -n -v --line-numbers, iptables-save, -A/-I/-D, -m conntrack --ctstate
nftablesnft list ruleset, nft -f file, nft -c -f file, inet family, sets @name, iptables-translate
Verdict semantics (nft)accept ends one base chain; drop anywhere ends everything
Logginglimit rate + log; log group N + tcpdump -i nflog:N; counters for volume
ICMPAllow dest-unreachable, time-exceeded, packet-too-big, NDP; rate-limit echo
IPv6No NAT, own rules or inet; use meta l4proto, not ip6 nexthdr, for TCP/UDP/ICMPv6
Docker-p bypasses ufw; use 127.0.0.1: or DOCKER-USER with --ctorigdstport; nftables backend has no DOCKER-USER
KubernetesDefault allow; default-deny + allow-DNS; AND within an item, OR between items; the CNI enforces
AWSSG: ENI, stateful, allow-only, SG references. NACL: subnet, stateless, numbered, ephemeral 1024-65535
GCP / AzureGCP priority 0-65535 (default 1000), tags; Azure priority 100-4096, defaults at 65000-65500
EgressAllow-list destinations; NAT gateway + domain filtering; Cilium toFQDNs; egress gateway for stable IPs
Listener binding127.0.0.1 or a Unix socket for anything that is not public on purpose
Auditnft list ruleset, counters, conntrack -L, ss -ltn, flow logs, nmap from outside

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Which five fields make up the 5-tuple, and name three other things a rule can match that are not in it. Must-know ​

Answer

Answer: Source IP, destination IP, protocol, source port, destination port. Also the interface the packet arrived on or leaves through, the connection state (ct state), TCP flags, marks, packet length, owner uid on the host, and in clouds tags, security-group references or pod labels.

2 — Why does a stateful firewall need no rule for the reply to a web request, and what does a NACL need instead? Must-know ​

Answer

Answer: The reply belongs to a tracked flow (conntrack, security group tracking), so it is allowed implicitly. A NACL is stateless: it needs an outbound rule that covers the client's ephemeral port range (1024-65535 to be safe) and, for the reverse direction, an inbound one.

3 — Decode iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT. Must-know ​

Answer

Answer: Append to the INPUT chain (filter table) a rule matching TCP packets to destination port 22 whose conntrack state is NEW or ESTABLISHED, with target ACCEPT. The -m conntrack loads the state-matching extension. iptables-translate prints nft 'add rule ip filter INPUT tcp dport 22 ct state new,established counter accept'.

4 — A Docker host runs ufw deny 5432 and a container published with -p 5432:5432 answers from the internet. Why, and name two fixes. Must-know ​

Answer

Answer: Docker's DNAT in nat PREROUTING rewrites the destination to the container, so the packet is routed to FORWARD and never reaches INPUT where ufw's rules live. Fix: publish to loopback (-p 127.0.0.1:5432:5432) or put a drop in DOCKER-USER matching -m conntrack --ctorigdstport 5432 (or do not publish at all and use a shared network).

5 — What does inet mean in table inet filter, and why does it matter for IPv6? Important ​

Answer

Answer: The inet family sees both IPv4 and IPv6 in one table. One ruleset covers both families, so you cannot lock IPv4 and forget IPv6 (with iptables that needs a separate ip6tables ruleset).

6 — You applied a NetworkPolicy and traffic is unchanged. Give two causes. Important ​

Answer

Answer: The CNI does not enforce NetworkPolicy (the resource is stored and ignored), or the selectors do not match the pods/namespace (for example namespaceSelector and podSelector written as two items, OR, instead of one item, AND). Also possible: another policy allows the traffic (policies are additive).

7 — Why is blocking all ICMP harmful, and which messages must pass? Important ​

Answer

Answer: Path MTU Discovery depends on ICMP "fragmentation needed" (IPv4 type 3 code 4) and ICMPv6 Packet Too Big. Without them oversized packets vanish silently: small requests work, large transfers hang. Destination unreachable and time exceeded also support error reporting; ICMPv6 neighbor discovery is needed for the LAN. Echo can be rate-limited.

8 — A request is ACCEPT in flow logs and its reply is REJECT. What is the likely cause and how do you fix it? Important ​

Answer

Answer: A stateless NACL on the subnet lacks an outbound (or inbound, for the reverse path) rule for the ephemeral port range. Add an allow rule for tcp 1024-65535 in the direction of the reply.

9 — Why must the ping rate limit sit before ct state established accept? Good to know ​

Answer

Answer: After the first reply conntrack marks later echo requests of that flow as established; a limit placed after the established rule is never evaluated for them. Placed before it, limit rate over 5/second drop applies to every echo request (lab: 85% loss under a flood).

10 — Give three reasons to control egress, and two ways to do it for a Kubernetes pod. Important ​

Answer

Answer: Stop data exfiltration, stop reverse shells and payload downloads after a compromise, narrow supply-chain exposure to your registries. In Kubernetes: a NetworkPolicy with egress (and an allow-DNS rule), or Cilium toFQDNs / an egress gateway / a proxy or network firewall that filters by domain.

11 — Why is a Unix-socket admin listener better than "an admin port restricted by firewall rule"? Important ​

Answer

Answer: There is no port: nothing to scan, nothing for a rule change to expose, and access is decided by file permissions (mode 0600 and a restrictive directory). A firewall rule is one more thing that can be wrong.

12 — What is the first thing to check when Request::ip() in Laravel returns the load balancer's address? Must-know ​

Answer

Answer: trustProxies in bootstrap/app.php: list the load balancer's CIDR (not *) and the X-Forwarded-* headers to believe. Without it Laravel uses the TCP peer address.

Glossary ​

TermMeaning
FirewallRules that accept or drop packets or flows by header fields and state
Packet filterA firewall that reads L3-L4 headers only
5-tupleSource IP, source port, destination IP, destination port, protocol
StatelessEvery packet is judged alone; replies need their own rules
StatefulFlows are tracked; replies of an allowed flow pass automatically
Default-deny / allow-listPolicy drop, then list what is allowed
Policy (chain policy)Verdict for packets that match no rule in a base chain
netfilterThe Linux kernel framework of packet hooks that iptables and nftables use
HookA point in the packet path: prerouting, input, forward, output, postrouting (and ingress)
TableA container of chains: iptables filter, nat, mangle, raw; nftables tables you name
ChainAn ordered list of rules; base chains attach to hooks
Base chainAn nftables chain with type, hook, priority
PriorityOrder among chains at one hook; lower number runs first
Verdictaccept, drop, reject, jump, return
iptablesThe classic command-line tool for netfilter rules
iptables-nftiptables syntax over the nftables backend
nftables / nftThe modern rule engine and its tool
Family (ip, ip6, inet, arp, bridge, netdev)Which protocols a table sees
Set / map / concatenationnftables data structures: list of values, key-to-value lookup, pairs
Meter / dynamic setA set filled from traffic, with per-element rate limits
conntrackThe kernel's connection-tracking table
ct stateConnection state: new, established, related, invalid, untracked
ESTABLISHED,RELATEDStates for replies and flows tied to an existing flow (ICMP errors, FTP data)
ctorigdstportconntrack match on the destination port before DNAT
notrackRaw-table action that skips conntrack
DNAT / SNAT / MASQUERADEDestination, source and dynamic-source address rewriting
REJECT vs DROPAnswer with an error vs silently discard
LOG / NFLOGWrite a matched packet to the kernel log or to a userspace group
ufwUbuntu's front-end for netfilter
firewalldZone-based firewall daemon with nftables backend
fail2ban / CrowdSecTools that turn log patterns into temporary block rules
ICMP / ICMPv6Control protocol for errors and diagnostics (and NDP in IPv6)
PMTUDPath MTU Discovery: finding the smallest MTU on a path using ICMP
MTU black holeA path where oversized packets are dropped and no ICMP reaches the sender
MSS clampingRewriting the TCP MSS so segments fit the path MTU
NDPIPv6 neighbor discovery (ICMPv6 133-137), the ARP replacement
DOCKER-USERiptables chain where user rules run before Docker's own
Published portA container port mapped to a host port with -p
Direct routingSending packets to a container's address instead of a published port
NetworkPolicyKubernetes resource defining allowed pod traffic by label, namespace or CIDR
CNIContainer Network Interface plugin that implements pod networking and enforces policy
Calico, CiliumCNIs that enforce NetworkPolicy (iptables or eBPF datapath)
eBPFIn-kernel programs used by Cilium for policy and load balancing
ipBlockNetworkPolicy peer defined by a CIDR
Security groupAWS stateful, allow-only firewall attached to a network interface
Network ACL (NACL)AWS stateless, ordered, allow-and-deny firewall attached to a subnet
ENIElastic Network Interface: the virtual NIC an SG is attached to
Ephemeral portsShort-lived client-side ports (1024-65535 in AWS guidance) used for replies
Prefix listA named set of CIDRs reusable across rules
VPC Flow LogsPer-flow records with ACCEPT or REJECT
GCP firewall ruleVPC-level rule with priority, direction, tags or service accounts
Azure NSGNetwork security group with priorities 100-4096
Service tag / ASGAzure label for a service's prefixes / for a group of VMs
Egress controlRestricting outbound connections
NAT gatewayManaged SNAT for private subnets
Egress gatewayA fixed exit point for pod traffic
FQDN ruleRule that allows a domain name, resolved to addresses by the enforcer
Host firewallRules on the machine itself
PerimeterRules at the edge of a network, subnet or instance
WAFWeb application firewall: L7 filtering of HTTP content
Defense in depthSeveral independent controls so one mistake is not a breach
TrustProxiesLaravel middleware that decides which proxies' X-Forwarded-* headers to believe
Unix domain socketA local socket addressed by a file path

References ​

Every URL was fetched with curl and its text saved under scratchpad/sources/firewalls-iptables-nftables-security-groups/; HTTP status was 200 unless stated.

Built by Morteza Negahi