Using Linux nftables
nftables is the new packet filtering framework built into the Linux kernel that replaces the older iptables technology. This tutorial will cover the basics of using nftables to configure a simple firewall on a Linux system.
Installing nftables
Most modern Linux distributions already have nftables installed and enabled by default.
On Debian/Ubuntu systems, you can install it with:
sudo apt install nftables
This will install the nft command line utility we will use to interact with nftables.
nft Command Syntax
The nft command allows us to add, delete, and list rules and sets for packet filtering. Some common syntax includes:
nft list ruleset- List all tables and chainsnft list table <table>- List all chains in a specific tablenft add rule <table> <chain> <rulespec>- Append a rule to a chainnft delete rule <table> <chain> <handle>- Delete a specific rule
The <rulespec> defines the matching criteria and actions for packets.
Creating Custom Chains
By default nftables includes some built-in tables like filter which contains chains like input, output, and forward.
We can create custom chains under these tables using the add chain command:
nft add chain filter input my_chain
This adds a new chain called my_chain under the input table. We can now add rules to this chain:
nft add rule filter input my_chain tcp dport { 22, 80 } accept
This will accept TCP traffic on ports 22 and 80.
Filtering Packets
nftables provides flexible syntax for matching packets and taking actions. Some examples:
- Match specific IP address
nft add rule filter input my_chain ip saddr 192.168.0.5 drop
- Match a port range
nft add rule filter input my_chain tcp dport {1024-65535} accept
- Match a network subnet
nft add rule filter input my_chain ip saddr 192.168.0.0/24 drop
- Match by protocol and limit rate
nft add rule filter input my_chain icmp limit rate 1/second accept
The nft man pages provide more detail on all the matching criteria and actions available.
Saving and Loading Rulesets
To persist rules between reboots, we can save our nftables configuration to a file:
nft list ruleset > /etc/nftables.conf
This will save the current nftables rules. We can load it on startup by adding:
nft -f /etc/nftables.conf
to our systemd unit file or init scripts.
This covers the basics of configuring a simple firewall with nftables on Linux. nftables provides a flexible and powerful framework for packet filtering and firewalling. As iptables is phased out, knowing how to use nftables will become an essential skill for Linux system administration.