Writing Firewall and NAT Rules on Linux With nftables
A practical guide to nftables, Linux's packet-filtering framework: hooks and priorities, tables, chains, rules, sets and verdicts, a complete router rule set tested in a real lab, NAT rules, tracing a dropped packet, translating iptables rules, and keeping rules safe.
kvi5hnuCode Sprout team member16 min readOn this page
Articles 34 and 35 explained what firewalls and NATs do. This article shows how to configure them on Linux, which runs most routers, servers, cloud images and containers, with nftables, the kernel's packet-classification framework and its command-line tool, nft. nftables replaced iptables, ip6tables, arptables and ebtables with one tool and one syntax for IPv4, IPv6 and more.
The lab here is a small router, gw, with an inside interface lan (10.0.0.1, 2001:db8:a::1) and an outside interface wan (203.0.113.1, 2001:db8:f::1). A client (10.0.0.10) sits inside and a server (203.0.113.10) outside. The lab used nftables 1.1.3.
Where rules run: hooks and priorities
The Linux kernel's packet-processing framework is called netfilter. It has hooks, fixed points in a packet's path where code can inspect, change or drop it. nftables rules run at those hooks:

| Hook | Sees | Typical use |
|---|---|---|
prerouting | Every arriving packet, before routing | Destination NAT (port forwarding), early drops |
input | Packets addressed to this host | Protecting the host's own services |
forward | Packets being routed through this host | The firewall policy of a router |
output | Packets sent by this host | Restricting what the host sends |
postrouting | Every departing packet, after routing | Source NAT and masquerading |
Two more hooks exist: ingress (and, since kernel 5.16, egress) in the netdev family run on one interface before anything else, which suits very early filtering, such as dropping a flood.
Several chains can attach to the same hook. Each has a priority, and lower numbers run first. Named priorities make this readable: raw (−300) runs before connection tracking, dstnat (−100) for destination NAT, filter (0) for ordinary filtering, and srcnat (100) for source NAT.
Tables, chains and rules
An nftables configuration has three levels:

- A table groups chains and has a family that says which packets it sees:
ip(IPv4),ip6(IPv6),inet(both),arp,bridge(frames crossing a Linux bridge) ornetdev(one interface). Usinginetlets one rule set handle IPv4 and IPv6 together. - A chain holds rules. A base chain is attached to a hook with a type (
filter,natorroute), a priority and a policy, the verdict when no rule decides. A regular chain has no hook and is reached only byjumporgotofrom another chain, which is how you organize large rule sets. - A rule is a list of matches (
tcp dport 22,ip saddr 10.0.0.0/24,ct state new), statements (counter,log,limit,meta mark set) and usually a verdict:acceptanddrop;reject, which drops and tells the sender;jumpandgoto, which go to another chain;return, which goes back to the calling chain.
Rules run top to bottom. A verdict ends the chain, while statements don't. One detail surprises many people: accept ends only the current base chain. If another base chain is attached to the same hook with a later priority, the packet still goes through it, and a drop there wins. A drop is final everywhere.
Sets and maps are what make nftables efficient. A set is a named or anonymous group of addresses, ports or other values, matched with a single lookup instead of one rule per value. { 53, 67 } is an anonymous set, and @admin_hosts refers to a named one, which you can change at run time without reloading any rules. A verdict map (vmap) picks a verdict by value, for example iifname vmap { "lan" : jump from_lan, "wan" : jump from_wan }.
A complete router rule set
Here is the rule set the lab loaded on gw, as a file. Writing rules in a file, rather than as separate nft add commands, has a big advantage: nft -f loads the whole file as one atomic transaction, so the firewall never runs with half the rules.
#!/usr/sbin/nft -f
# Firewall and NAT for a small router: lan = inside, wan = Internet
flush ruleset
define LAN = "lan"
define WAN = "wan"
table inet filter {
set admin_hosts {
type ipv4_addr
elements = { 10.0.0.10 }
}
chain input {
type filter hook input priority filter; policy drop;
iif "lo" accept
ct state established,related accept
ct state invalid drop
# IPv6 needs ICMPv6 for neighbor discovery and path MTU discovery
meta l4proto ipv6-icmp accept
meta l4proto icmp icmp type { echo-request, destination-unreachable, time-exceeded } accept
iifname $LAN tcp dport 22 ip saddr @admin_hosts counter accept comment "admin SSH from listed hosts"
iifname $LAN udp dport { 53, 67 } accept comment "DNS and DHCP for the LAN"
counter limit rate 5/minute log prefix "gw input drop: "
}
chain forward {
type filter hook forward priority filter; policy drop;
ct state established,related accept
ct state invalid drop
meta l4proto ipv6-icmp accept
iifname $LAN oifname $WAN counter accept comment "LAN to Internet"
counter comment "dropped: not allowed to cross"
}
chain output {
type filter hook output priority filter; policy accept;
}
}
table ip nat {
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
oifname $WAN masquerade
}
}
Notes on the design:
flush rulesetat the top removes everything first, so reloading the file gives exactly this state.definecreates variables, so the interface names appear once.ct statematches use connection tracking (conntrack, article 34):establishedmeans a packet belongs to a flow already seen in both directions,relatedmeans it's tied to one (such as an ICMP error about it), andinvalidmeans it fits no known flow.- Order matters in input and forward.
established,relatedcomes first, because nearly every packet matches it, and theninvalidpackets are dropped before any rule can accept them. - ICMPv6 must be allowed for IPv6 to work at all. Neighbor discovery, the IPv6 equivalent of ARP, uses ICMPv6 (article 42), and so does path MTU discovery (article 47). Blocking all ICMPv6 breaks IPv6 in ways that are hard to diagnose.
- The last rule of input logs before the policy drops, with
limitbeforelog. Statements run in order, solimit rate 5/minute loglogs at most 5 drops a minute. Writinglog ... limit ...would log every dropped packet and then apply the limit to nothing useful, which is an easy mistake. - NAT is in its own table with the
ipfamily, because only IPv4 is masqueraded here. IPv6 is routed without translation, as article 35 recommends.
Before loading, nft -c checks the file without applying it:
nft -c -f gw.nft: syntax OK
Then the lab tested what's allowed and what isn't. To keep the tests simple, a small web server on gw listened on port 22 in place of SSH, so curl stands in for an SSH client, and the last line is a ping from the client to the outside server:
client: curl http://203.0.113.10/ -> HTTP 200
client: curl http://[2001:db8:f::10]/ -> HTTP 200
client: curl http://10.0.0.1:22/ -> HTTP 200
server: curl http://203.0.113.1:22/ -> timed out
1 packets transmitted, 1 received, 0% packet loss, time 0ms
- The client reached the outside web server over both IPv4 (masqueraded) and IPv6 (routed, no NAT).
- The client reached the router's own port 22, because it's in
admin_hosts. - The outside server's attempt to reach port 22 on the router's public address timed out: it's dropped by the input policy.
- The
pingfrom the client to the server worked because forwarding allows new connections from the LAN, which includes ICMP echo, and the replies areestablished.
Listing a chain shows its rules with counters:
table inet filter {
chain forward {
type filter hook forward priority filter; policy drop;
ct state established,related accept
ct state invalid drop
meta l4proto ipv6-icmp accept
iifname "lan" oifname "wan" counter packets 3 bytes 224 accept comment "LAN to Internet"
counter packets 0 bytes 0 comment "dropped: not allowed to cross"
}
}
Each counter shows packets and bytes matched so far. The "LAN to Internet" rule counted only 3 packets (the IPv4 and IPv6 connection attempts and the ping), because it sees only the first packet of each flow; every later packet was accepted by the established,related rule above it, which has no counter.
And this command pulls out every counter that has counted something, which is a quick way to see which rules traffic actually hit:
iifname "lan" tcp dport 22 ip saddr @admin_hosts counter packets 1 bytes 60 accept comment "admin SSH from listed hosts"
counter packets 2 bytes 120 limit rate 5/minute burst 5 packets log prefix "gw input drop: "
iifname "lan" oifname "wan" counter packets 3 bytes 224 accept comment "LAN to Internet"
The admin rule counted the client's one connection attempt (a 60-byte SYN, the TCP packet that opens a connection). The log rule counted 2 packets: the outside server's SYN and its retransmission, both of which then hit the drop policy. nft also filled in burst 5 packets, the default burst for limit.
NAT rules
NAT rules live in chains of type nat. The common forms:
| Purpose | Rule (in a chain at that hook) |
|---|---|
| Share the router's address, which may change | oifname "wan" masquerade (postrouting) |
| Share a fixed address, slightly faster | oifname "wan" snat to 203.0.113.1 (postrouting) |
| Port forwarding | iifname "wan" tcp dport 8080 dnat to 10.0.0.20:80 (prerouting) |
| Send traffic to a local port | tcp dport 80 redirect to :3128 (prerouting, for a transparent proxy) |
| Hairpin NAT | a dnat rule for inside traffic plus a masquerade for traffic that leaves on the inside interface (article 35) |
A NAT chain sees only the first packet of each connection. The translation is stored in the connection-tracking entry, and every later packet, in both directions, is translated from that entry without passing through the NAT rules again. That's why conntrack is the heart of both stateful filtering and NAT on Linux.
A filter rule in the forward chain sees packets after destination NAT. So to allow a port-forwarded connection, match the inside address and port (ip daddr 10.0.0.20 tcp dport 80 ct state new accept), or simply ct status dnat accept, which accepts anything that was port-forwarded.
Tracing why a packet was dropped
When something is blocked and you can't see why, nftables can trace a packet through every chain and rule it visits. You set the nftrace flag on the packets you care about, in a chain that runs early, and then watch with nft monitor trace. In the lab, a trace was set on TCP traffic from the outside server to port 22, and the server tried to connect:
trace inet filter trace_pre rule ip saddr 203.0.113.10 tcp dport 22 meta nftrace set 1 (verdict continue)
trace inet filter trace_pre policy accept
trace inet filter input rule counter packets 2 bytes 120 limit rate 5/minute burst 5 packets log prefix "gw input drop: " (verdict continue)
trace inet filter input policy drop
Each line names the family, table and chain, then the rule the packet matched and its verdict; (verdict continue) means the rule had no verdict, so evaluation went on. trace_pre is a small chain the lab added at the prerouting hook only to set nftrace. Read it line by line. The packet went through the tracing chain (trace_pre), into input, matched only the last counter-and-log rule, which has no verdict, and was then dropped by the chain's policy. That tells you no rule accepted it, rather than some rule dropping it on purpose.
Coming from iptables
You'll still meet iptables rules in older guides and scripts. On current distributions, the iptables command is usually iptables-nft: it accepts the old syntax but creates nftables rules in the kernel. iptables-translate converts a rule to nftables syntax:
nft 'add rule ip filter FORWARD iifname "lan" oifname "wan" ct state new counter accept'
nft 'add rule ip nat POSTROUTING oifname "wan" counter masquerade'
nft 'add rule ip nat PREROUTING iifname "wan" tcp dport 8080 counter dnat to 10.0.0.20:80'
The old iptables-legacy back end, which uses the original x_tables kernel code, is being retired. Since Linux 6.17, the kernel option it depends on (CONFIG_NETFILTER_XTABLES_LEGACY) is off by default, so distributions that still ship the legacy tools have to turn it back on explicitly. Mixing the legacy back end with nftables on one machine is a common source of confusion, because each shows only its own rules.
Many systems put a manager on top of nftables:
- firewalld is used by Fedora, RHEL (Red Hat Enterprise Linux) and openSUSE, with zones and services.
- ufw is used by Ubuntu.
- Container and Kubernetes networking (Docker, Podman, kube-proxy) adds its own tables. When a manager is in use, change rules through it, or it may overwrite yours.
Other systems have their own tools: Windows Defender Firewall (New-NetFirewallRule in PowerShell), and pf on macOS and the BSDs.
The lab's version:
nftables v1.1.3 (Commodore Bullmoose #4)
Keeping rules safe
- Make rules persistent. Rules in the kernel vanish on reboot. Most distributions load
/etc/nftables.confwith thenftablessystemd service. - Test before you lock yourself out. On a remote server, apply new rules with a safety net, for example
nft -f new.nft; sleep 60; nft -f old.nftin atmuxorscreensession, and cancel the restore once you've confirmed you can still log in. - Allow, then deny. Start with a drop policy and add accept rules for what's needed, rather than trying to list everything bad.
- Count and log what you drop (with a rate limit), so you can see what your policy is blocking.
Common questions
What's the difference between drop and reject in nftables?
drop discards silently, so the sender times out. reject discards and sends back an ICMP error (port unreachable by default) or, with reject with tcp reset, a TCP RST (a reset segment, which aborts the connection attempt), so the sender fails immediately. Use reject for traffic you expect from your own users, such as blocked outbound ports, and drop for unsolicited traffic from the Internet.
Why does my accept rule not work when another tool's chain drops the packet?
accept only ends evaluation of the current base chain. If, for example, firewalld or Docker has its own base chain on the same hook, the packet goes through that chain too, and a drop there is final. Check nft list ruleset for every chain on the hook, or add your rule through the tool that owns the other chain.
Should I use the inet family or separate ip and ip6 tables?
Use inet for filtering, so one rule set covers both protocols and you can't forget IPv6. Rules that are specific to one protocol still work inside it (ip saddr, ip6 saddr, meta nfproto ipv4). For NAT, inet tables have been supported since kernel 5.2, but many people keep an ip NAT table because they only translate IPv4.
How do I block a long list of addresses efficiently?
Put them in a named set with flags interval (so it can hold prefixes) and match with one rule: ip saddr @blocklist drop. A set lookup costs about the same for 10 elements as for 100,000, while 100,000 separate rules would be checked one by one. You can add and remove elements at run time with nft add element without reloading the rule set.
Do my rules see a forwarded packet before or after NAT?
At prerouting, destination NAT runs at priority dstnat (−100), so a filter chain at priority filter (0) on the same hook, and everything in forward and input, sees the translated destination. Source NAT runs at postrouting, after forward, so forward rules see the original inside source address. That's why forward rules match inside addresses in both directions.
Why can't I see my log messages?
Logged packets go to the kernel log, shown by journalctl -k or dmesg. Inside a container or a non-default network namespace, logging may be disabled unless the host allows it (net.netfilter.nf_log_all_netns). Also check that limit comes before log in the rule, and that a rule earlier in the chain didn't already give a verdict.
Summary
- nftables is Linux's packet filter, replacing iptables. Rules run at netfilter hooks (
prerouting,input,forward,output,postrouting, plusingressandegress), with priorities deciding the order of chains on the same hook. - A table has a family (
inetcovers IPv4 and IPv6). Base chains attach to hooks with a type, priority and policy, and regular chains are reached byjump. - Rules are matches, statements and a verdict, checked top to bottom. Statement order matters, so put
limitbeforelog.acceptends only the current base chain, whiledropis final. - Sets and verdict maps replace long lists of rules with one lookup, and named sets can change at run time.
- Load rule sets from a file with
nft -f(atomic), check them withnft -c, allow ICMPv6, and count and log what the policy drops. - NAT chains see only the first packet of a connection, and conntrack applies the translation to the rest. Forward rules see the translated destination and the original source.
nft monitor traceshows exactly which rules a packet visited.iptables-translateconverts old rules, and iptables-legacy is being phased out.
Practice questions
1. Write an nftables rule for the input chain that accepts SSH (TCP 22) only from the 192.0.2.0/24 network, and counts the packets it accepts.
Answer
ip saddr 192.0.2.0/24 tcp dport 22 counter accept. With a drop policy on the chain, SSH from anywhere else is dropped. To allow IPv6 as well, add a second rule with ip6 saddr and the IPv6 prefix.
2. A rule reads counter log prefix "drop: " limit rate 10/minute. What does it log, and how should it be written?
Answer
Statements run in order, so it logs every packet that reaches the rule, and only then applies the rate limit, which has no effect on logging. It should be counter limit rate 10/minute log prefix "drop: ", so the limit is checked first and at most 10 packets a minute are logged.
3. You add iifname "wan" tcp dport 8080 dnat to 10.0.0.20:80 in a prerouting NAT chain, but connections still fail. The forward chain has policy drop and only ct state established,related accept and a LAN-to-WAN rule. What rule is missing?
Answer
The first packet of a forwarded connection is new and arrives on wan, so the forward chain drops it. Add ip daddr 10.0.0.20 tcp dport 80 ct state new accept, matching the translated address, or ct status dnat accept. After that, replies are established and pass.
4. Why is nft -f rules.nft safer than running a list of nft add rule commands from a script?
Answer
nft -f loads the whole file as one atomic transaction. Either every rule is applied or, if any line has an error, none is, and the old rules stay in place. A script of separate commands applies rules one at a time, so the firewall passes through partial states, and an error halfway through leaves it half-configured.
5. In the lab's trace, the last lines were the log rule "(verdict continue)" and then "policy drop". What does that tell you about why the packet was dropped?
Answer
No rule in the input chain matched with a verdict for this packet. The log rule matched, but it has no verdict, so evaluation continued past the end of the chain and the chain's default policy, drop, decided. To allow the traffic, you'd add an accept rule above the log rule. Nothing explicitly blocked it.
6. Why should a firewall that handles IPv6 never drop all ICMPv6?
Answer
IPv6 depends on ICMPv6 for basic operation. Neighbor discovery, which resolves addresses on the local link and finds routers, uses ICMPv6 messages. Path MTU discovery relies on ICMPv6 Packet Too Big messages, because IPv6 routers never fragment. Dropping all ICMPv6 breaks address resolution and causes large packets to vanish. Allow at least the neighbor discovery types and Packet Too Big, or simply allow all ICMPv6, as the lab's rules did.
Previous: Getting Through NAT: Hole Punching, STUN, TURN, ICE, UPnP and PCP
Next: IPv4/IPv6 Coexistence: Dual Stack, DS-Lite, NAT64, DNS64, 464XLAT and Teredo

More in TCP/IP Course
Quiz: TCP/IP Delicate Details
Twenty-five questions on the details that catch out experienced engineers: sequence numbers for SYN and FIN, TIME_WAIT versus tcp_fin_timeout, Karn's algorithm, socket buffer doubling, even and odd ephemeral ports, IPv6 checksums and fragmentation, negative DNS caching, and capture filter traps.
Quiz: TCP/IP Interview Questions
Thirty-three networking questions of the kind asked in developer, SRE and network engineering interviews: what happens when you load a URL, TCP versus UDP, handshakes, closing and TIME_WAIT, subnetting, NAT, DNS, MTU problems, congestion, TLS and QUIC, and debugging slow or failing connections.
Quiz: TCP/IP Course Final Exam (All Parts)
The final exam for the TCP/IP course: thirty questions across all fourteen parts, from packets and addressing through Ethernet, ARP, IP, DHCP, NAT, ICMP, UDP, DNS, TCP connections, reliability, congestion control, security, QUIC and troubleshooting.
Quiz: Modern Transports and Troubleshooting (TCP/IP Part 14)
Review modern transports and troubleshooting: QUIC packets, handshakes, 0-RTT, streams and connection migration, HTTP/3, Multipath TCP, SCTP multihoming, and a layered method for diagnosing real network faults.
Discussion
Sign in to ask a question or share what you learned.