Future firewalls: iptables vs. nftables
Just as iptables
replaced ipchains
, nftables
is here to supplant iptables
as the go-to firewall solution on Linux.
With it we must learn a new syntax and way of thinking, although all the familiar netfilter
framework hooks are still there:
input, postrouting, raw and so on.
The iptables
way
Sometimes it is useful to capture and log the packets sent by a specific user or program. With iptables
, we have been able to
use the NFLOG extension to pass packets to a netlink multicast group. Using tcpdump
, we can then capture those packets and log them
for analysis later.
Here is an example of doing just that, based on an example from the Wireshark wiki:
## Important: -m owner cannot be used with INPUT since it matches originating sockets only.
## To track responses to outgoing traffic, a connection mark has to be set in OUTPUT
## and matched in INPUT.
root@host:~# iptables -A OUTPUT -m owner --uid-owner 1000 -j CONNMARK --set-mark 1
root@host:~# iptables -A INPUT -m connmark --mark 1 -j NFLOG --nflog-group 30
root@host:~# iptables -A OUTPUT -m connmark --mark 1 -j NFLOG --nflog-group 30
root@host:~# tcpdump -i nflog:30 -w uid-1000-iptables.pcap
Modernizing with nftables
How can we implement a similar solution using newer tools? Below is an example of achieving the same thing with nftables
.
First we will add a table and input/output chains (in the previous example these were assumed to exist already).
The default policy is to accept which is fine for this example, thus I have omitted it. The same goes for the address family, which
defaults to ip
meaning IPv4. Other possibilities are ip6
for IPv6 or inet
to apply rules for both a families at once.
root@host:~# nft add table filter
root@host:~# nft add chain filter input { type filter hook input priority 0\; }
root@host:~# nft add chain filter output { type filter hook output priority 0\; }
## These four commands are exact translations of the iptables example
## using the same user ID and mark values.
root@host:~# nft add rule filter output skuid 1000 ct mark set 1
root@host:~# nft add rule filter input ct mark 1 log group 30
root@host:~# nft add rule filter output ct mark 1 log group 30
root@host:~# tcpdump -i nflog:30 -w uid-1000-nftables.pcap
Conclusion
As you can see, using nftables
is pretty straightforward and similar to the older iptables
commands which it replaces.
Benefits of using the newer tool include JSON output and a single unified utility for all types of firewalls, including ARP and bridge
rules.