nftable
nftables: From Linux Firewall Fundamentals to Professional Administration
A practical, theory-driven guide to Linux packet filtering, firewall design, troubleshooting, and secure configuration.
Platform: Linux, with practical notes for Arch Linux and AlmaLinux.
Skill level: Beginner to advanced.
Main tool:
nftConfiguration file:
/etc/nftables.conf
Table of Contents
- Introduction to Linux Firewalls
- Understanding How Network Traffic Works
- What Is nftables?
- Installing and Preparing nftables
- Understanding the nftables Architecture
- How Packets Travel Through Netfilter
- Your First Firewall
- Understanding Rules and Expressions
- Building a Stateful Firewall
- Managing Tables, Chains, and Rules
- Working with TCP, UDP, ICMP, and Ports
- Interfaces, IP Addresses, and Networks
- IPv4 and IPv6
- Named Sets and Dynamic Rules
- Logging, Counters, and Rate Limiting
- NAT, Masquerading, and Port Forwarding
- Permanent Configuration and systemd
- Testing Rules Safely
- Troubleshooting Network Connectivity
- Recovering from a Broken Firewall
- Practical Firewall Configurations
- Advanced Concepts
- Common Mistakes and Security Considerations
- Essential Command Reference
- Hands-On Labs
- Professional Troubleshooting Workflow
- Learning Roadmap
- Official Documentation
1. Introduction to Linux Firewalls
1.1 What is a firewall?
A firewall is a system that decides which network traffic is allowed to pass and which traffic must be rejected or discarded.
Imagine a Linux server running three services:
- SSH on TCP port
22 - HTTP on TCP port
80 - HTTPS on TCP port
443
Without appropriate filtering, these services might accept connections from any network that can reach the server, subject to the services’ own configuration and other network controls.
A firewall lets you express a policy such as:
- Allow SSH from your trusted administration network.
- Allow HTTP and HTTPS from the Internet.
- Allow replies to connections that the server initiated.
- Drop unsolicited incoming traffic to other ports.
- Allow necessary network-control traffic.
A firewall is therefore not simply a list of open ports. It is a collection of rules that implement a security policy.
1.2 Why do we need firewalls?
A Linux machine can expose network services even when you did not intend to make them publicly accessible.
For example, a service might listen on:
0.0.0.0:8080
This means that the service listens on all local IPv4 addresses, subject to the machine’s network configuration.
If the machine has a reachable network interface, clients may be able to attempt connections to that service.
A firewall adds a separate layer of control over whether those packets are permitted.
Firewalls are useful for:
- Reducing the attack surface.
- Restricting administration access.
- Isolating services.
- Limiting communication between networks.
- Controlling traffic forwarded through a router.
- Protecting test environments.
- Enforcing network segmentation.
1.3 Firewall versus service security
These are different layers of defense.
Suppose SSH listens on TCP port 22.
The SSH daemon decides whether the SSH connection is accepted and whether a user may authenticate.
The firewall decides whether the relevant network traffic is allowed to reach the host or service.
You generally want both:
Network packet
|
v
Firewall policy
|
v
SSH service
|
v
Authentication and authorization
A firewall does not replace strong passwords, SSH keys, software updates, or least-privilege access.
2. Understanding How Network Traffic Works
Before writing firewall rules, understand what a network connection actually means.
2.1 IP addresses
An IP address identifies a network-layer endpoint.
Example:
192.168.1.50
A server might have this address on its LAN interface.
Another example:
10.10.20.15
This might be the address of an application server inside a private network.
Private IPv4 ranges include:
| Range | Typical use |
|---|---|
10.0.0.0/8 |
Large private networks |
172.16.0.0/12 |
Private networks |
192.168.0.0/16 |
Home and small office networks |
An address alone does not determine whether traffic is trusted. A private network can contain compromised machines, and a public address can belong to a trusted monitoring service.
2.2 Ports
A port identifies a transport-layer endpoint associated with a service.
Common examples:
| Port | Protocol | Typical service |
|---|---|---|
| 22 | TCP | SSH |
| 53 | TCP and UDP | DNS |
| 67/68 | UDP | DHCPv4 |
| 80 | TCP | HTTP |
| 123 | UDP | NTP |
| 443 | TCP | HTTPS |
| 443 | UDP | HTTP/3 over QUIC |
| 3306 | TCP | MySQL |
| 5432 | TCP | PostgreSQL |
| 6443 | TCP | Kubernetes API server |
A port number does not prove which application is running there. It is simply a number used by a transport protocol.
To inspect listening sockets:
sudo ss -lntup
Useful options:
-l: listening sockets.-n: numeric addresses and ports.-t: TCP.-u: UDP.-p: process information where available.
For TCP listening sockets only:
sudo ss -lntp
2.3 TCP connections
TCP provides a connection-oriented transport.
A typical TCP connection begins with a three-way handshake:
Client Server
| |
| -------- SYN ---------------> |
| |
| <------ SYN-ACK ------------- |
| |
| -------- ACK ---------------> |
| |
| Connection ready |
For example, an SSH client initiates a TCP connection to the server’s port 22.
The firewall can distinguish an initial connection attempt from packets belonging to an established connection by using connection tracking.
2.4 UDP traffic
UDP is connectionless at the transport-protocol level.
DNS queries, DHCP traffic, and some real-time applications use UDP.
Linux connection tracking can nevertheless associate UDP packets with tracked flows and classify them as new, established, or other states. These labels do not mean that UDP has a TCP-style handshake.
2.5 Inbound, outbound, and forwarded traffic
This distinction is fundamental to firewall design.
Input
Traffic addressed to the local machine.
Example:
Remote administrator ---> Linux server port 22
This traffic traverses the input hook.
Output
Traffic generated by the local machine.
Example:
Linux server ---> Remote DNS server
This traffic traverses the output hook.
Forward
Traffic passing through the machine to another destination.
Example:
Client ---> Linux router ---> Internet
This traffic traverses the forward hook.
Important: Allowing traffic in input does not automatically allow traffic to be routed through forward.
3. What Is nftables?
3.1 The Linux Netfilter framework
Linux implements packet filtering and related network functions through a kernel framework called Netfilter.
Netfilter provides hooks at different stages of packet processing. Firewall software registers rules and operations at those stages.
nftables is the modern packet-filtering framework used with Netfilter.
It includes:
- Kernel-side rule evaluation.
- The
nftuserspace command-line utility. - Stateful filtering through connection tracking.
- NAT support.
- Sets, maps, counters, logging, and other rule-building features.
The architecture is roughly:
Administrator
|
v
nft command
|
| Netlink
v
Linux kernel
|
v
Netfilter hooks
|
v
Packet filtering and other actions
The nft command configures rules. The Linux kernel evaluates those rules when relevant packets arrive.
3.2 nftables versus iptables
iptables is the older rule-management interface traditionally used with Netfilter.
nftables provides a more unified framework for defining IPv4, IPv6, and other types of packet filtering.
On modern Linux distributions, the iptables command may use an nftables compatibility backend. This does not mean every firewall management tool is interchangeable.
A machine can also have multiple firewall managers or legacy rule systems, which can make troubleshooting confusing.
Useful inspection commands:
sudo nft list ruleset
iptables --version
If iptables --version contains:
(nf_tables)
the iptables command is using the nftables backend.
Rule of thumb: Choose one primary firewall management method and understand which other tools may alter the ruleset.
4. Installing and Preparing nftables
4.1 Arch Linux
Install the package:
sudo pacman -S nftables
Check the version:
nft --version
Inspect the service:
systemctl status nftables.service
4.2 AlmaLinux
On AlmaLinux, install the package if it is not already present:
sudo dnf install nftables
Check the version:
nft --version
Inspect the service:
systemctl status nftables.service
The package and service are not necessarily the only components managing the firewall. AlmaLinux systems may also use firewalld, depending on the installation and configuration.
Check for it:
systemctl status firewalld.service
Do not casually enable a second firewall manager alongside an existing one. First determine which service is responsible for the active firewall policy.
4.3 Check the current firewall
Before changing anything, inspect the system:
sudo nft list ruleset
Check the active services:
systemctl --type=service --state=running
Check the network interfaces:
ip -br address
Check the routes:
ip route
ip -6 route
Check the listening services:
sudo ss -lntup
These commands answer four essential questions:
- What firewall rules are already active?
- Which services might manage those rules?
- Which network interfaces and addresses exist?
- Which applications are listening for connections?
4.4 Save a backup before changing rules
Create a backup directory:
sudo install -d -m 700 /root/firewall-backups
Save the current ruleset:
sudo sh -c 'nft list ruleset > /root/firewall-backups/ruleset-before.nft'
Inspect the backup:
sudo less /root/firewall-backups/ruleset-before.nft
The output of nft list ruleset is generally valid nftables input. However, it does not preserve every aspect of your original configuration, such as comments or shell variables that existed only in the source file.
Warning: A backup is useful only if you know how to restore it. Test restoration procedures in a disposable VM before relying on them in production.
5. Understanding the nftables Architecture
The core concepts are:
- Family
- Table
- Chain
- Hook
- Rule
- Expression
- Statement
- Verdict
Understanding these concepts is more important than memorizing commands.
5.1 Families
A family determines what type of traffic a table handles.
| Family | Purpose |
|---|---|
ip |
IPv4 |
ip6 |
IPv6 |
inet |
IPv4 and IPv6 |
arp |
ARP traffic |
bridge |
Bridged Ethernet traffic |
netdev |
Interface-level packet processing |
For ordinary host firewalls, inet is often a good starting point because it lets one ruleset cover both IPv4 and IPv6.
Example:
table inet firewall {
}
This creates a table named firewall in the inet family.
5.2 Tables
A table groups related firewall objects.
A table can contain:
- Chains
- Sets
- Maps
- Flowtables and other supported objects
A table is a container, not a rule that automatically filters packets.
Example:
table inet firewall {
# Firewall objects belong here.
}
You may encounter names such as filter, nat, or firewall. These are names chosen by the administrator; they do not automatically assign filtering behavior.
5.3 Chains
A chain contains rules.
There are two important types.
Base chains
A base chain is attached to a Netfilter hook.
Example:
chain input {
type filter hook input priority filter;
policy drop;
}
This chain participates in processing traffic destined for the local host.
Regular chains
A regular chain is a reusable collection of rules that another chain can call with jump or goto.
Example:
chain allow_web {
tcp dport { 80, 443 } accept
}
This chain does not automatically receive traffic. It must be called from a base chain or another reachable chain.
5.4 Hooks
A hook determines where a base chain participates in packet processing.
Common hooks:
| Hook | Meaning |
|---|---|
prerouting |
Before the routing decision |
input |
Traffic destined for the local host |
forward |
Traffic routed through the host |
output |
Traffic generated locally |
postrouting |
After the routing decision, before transmission |
Filtering and NAT commonly use these hooks.
5.5 Priority
Priority determines when a chain runs relative to other Netfilter operations and chains at the same hook.
For example:
type filter hook input priority filter;
The symbolic priority filter corresponds to the conventional filter priority.
NAT chains use different conventional priorities.
If multiple base chains are attached to the same hook, their order matters. An accept verdict in one base chain does not necessarily prevent a later base chain from dropping the packet.
For that reason, understanding all active firewall managers and chains matters when debugging a surprising packet drop.
5.6 Policy
A base chain can have a default policy:
policy accept;
or:
policy drop;
The policy applies when packet processing reaches the end of the base chain without a terminating verdict.
accept: allow the packet to continue through normal processing.drop: silently discard the packet.
A restrictive policy is useful for an inbound firewall, but only if you have explicitly allowed the traffic your machine needs.
5.7 Rules, expressions, and statements
Consider:
tcp dport 22 accept
This contains two conceptual parts:
- Expression:
tcp dport 22 - Statement:
accept
The expression matches TCP packets whose destination port is 22.
The statement allows matching packets to continue.
Another example:
ip saddr 192.168.1.0/24 tcp dport 22 accept
This matches packets from the specified IPv4 network destined for TCP port 22.
The order of expressions and statements is significant in complex rules.
6. How Packets Travel Through Netfilter
Understanding packet flow is one of the most useful skills in firewall administration.
6.1 Local traffic
Suppose a remote machine connects to SSH on your Linux server.
Network interface
|
v
prerouting
|
v
Routing decision
|
v
input
|
v
Local SSH service
The input chain is the main filtering point for traffic addressed to the local host.
6.2 Locally generated traffic
Suppose your server runs:
curl https://example.com
The request is generated locally.
Local application
|
v
output
|
v
Routing decision
|
v
postrouting
|
v
Network interface
An outbound firewall can restrict this traffic at the output hook.
6.3 Forwarded traffic
Suppose your Linux machine acts as a router.
Incoming interface
|
v
prerouting
|
v
Routing decision
|
v
forward
|
v
postrouting
|
v
Outgoing interface
Forwarded traffic is not automatically allowed merely because the destination is reachable.
You generally need:
- IP forwarding enabled.
- Appropriate routing.
- Firewall rules permitting the forwarded traffic.
- NAT, if required by the network design.
6.4 A critical distinction: host firewall versus router firewall
For a typical server:
input: Protect the server itself.
output: Control traffic generated by the server.
forward: Usually drop unsolicited routed traffic.
For a router:
input: Protect the router's own services.
output: Control traffic generated by the router.
forward: Control traffic passing between networks.
Do not copy a router ruleset onto a normal server without understanding the consequences.
7. Your First Firewall
We will build a basic stateful firewall for a single Linux server.
The example assumes:
- You administer the server over SSH.
- SSH listens on TCP port 22.
- The machine needs outbound connectivity.
- You want to permit established connections.
- You want to drop unsolicited inbound connections.
- The machine is not acting as a router.
Do not apply this example blindly to a remote machine. Confirm the SSH port, current network requirements, and existing firewall manager first.
7.1 Create a minimal configuration
Create or edit the configuration file:
sudo vim /etc/nftables.conf
Use this example as a starting point:
##!/usr/bin/nft -f
flush ruleset
table inet firewall {
chain input {
type filter hook input priority filter;
policy drop;
# Accept loopback traffic.
iifname "lo" accept
# Drop invalid connection-tracking states.
ct state invalid drop
# Accept traffic belonging to existing connections.
ct state established,related accept
# Permit essential ICMP and ICMPv6 traffic.
meta l4proto { icmp, ipv6-icmp } accept
# Permit SSH.
tcp dport 22 ct state new accept
}
chain forward {
type filter hook forward priority filter;
policy drop;
}
chain output {
type filter hook output priority filter;
policy accept;
}
}
7.2 Understand every part
Flush the existing ruleset
flush ruleset
This removes the entire current nftables ruleset when the file is loaded.
That includes tables created by other software. It can break Docker networking, VPNs, container networking, or rules managed by another firewall service.
Use it only when you intentionally own the complete ruleset.
If multiple applications manage firewall rules, do not assume this is safe.
Create a table
table inet firewall {
The inet family allows rules to cover IPv4 and IPv6.
Create the input chain
chain input {
type filter hook input priority filter;
policy drop;
This attaches the chain to the input hook and establishes a default-deny policy.
Allow loopback
iifname "lo" accept
Loopback traffic is local traffic using the loopback interface, usually lo and address 127.0.0.1 or ::1.
Many applications rely on local communication.
Drop invalid packets
ct state invalid drop
Connection tracking classifies packets that do not fit a valid tracked flow as invalid.
Dropping them is a common defensive measure.
Allow established and related traffic
ct state established,related accept
This is a fundamental stateful-firewall rule.
It allows traffic associated with connections that are already tracked as established, along with traffic classified as related to an existing connection.
For example, the reply packets for an outbound HTTPS connection can be permitted without opening every possible remote source port.
Permit ICMP and ICMPv6
meta l4proto { icmp, ipv6-icmp } accept
ICMP supports diagnostics and network operation. ICMPv6 is also essential to IPv6 functionality, including Neighbor Discovery and Path MTU Discovery.
This broad rule is easy to understand for a lab. In a stricter production firewall, consider which ICMP types and rates you want to permit rather than blocking all ICMP traffic.
Allow SSH
tcp dport 22 ct state new accept
This permits new TCP connections to port 22.
It allows SSH from any source address that can reach the host. A production system may need a more restrictive source-address rule.
Drop forwarded traffic
chain forward {
type filter hook forward priority filter;
policy drop;
}
This is appropriate for a host that should not route traffic between networks.
Allow outgoing traffic
chain output {
type filter hook output priority filter;
policy accept;
}
This permits traffic generated by the host.
It is a common starting point for a server firewall, but it does not restrict outbound communication.
7.3 A note about IPv6
Using the inet family means the SSH rule applies to both IPv4 and IPv6.
That is often desirable, but it means IPv6 SSH access is also allowed when IPv6 is available.
If you intend to restrict SSH to a particular address family or network, make that restriction explicit.
8. Understanding Rules and Expressions
A firewall rule is a logical test followed by one or more actions.
For example:
ip saddr 192.168.1.10 tcp dport 22 accept
The rule matches traffic when both conditions are true:
- The source IPv4 address is
192.168.1.10. - The TCP destination port is
22.
If both conditions match, the packet is accepted at this chain.
8.1 Common match expressions
| Expression | Meaning |
|---|---|
ip saddr 192.168.1.10 |
IPv4 source address |
ip daddr 192.168.1.20 |
IPv4 destination address |
ip6 saddr 2001:db8::10 |
IPv6 source address |
tcp dport 443 |
TCP destination port |
tcp sport 50000 |
TCP source port |
udp dport 53 |
UDP destination port |
iifname "eth0" |
Incoming interface |
oifname "eth0" |
Outgoing interface |
ct state established |
Established connection state |
ct state new |
New tracked connection |
ct state related |
Related tracked connection |
meta l4proto tcp |
TCP at the transport layer |
ip protocol icmp |
IPv4 ICMP |
ip6 nexthdr ipv6-icmp |
IPv6 ICMP header match; use protocol-aware expressions carefully |
limit rate 10/second |
Rate limit |
For most mixed IPv4/IPv6 rulesets, meta l4proto is a useful way to match the transport-layer protocol.
8.2 Multiple conditions
Expressions within a rule normally combine as logical AND conditions.
Example:
ip saddr 192.168.1.0/24 tcp dport 22 accept
The packet must match both the source network and the TCP destination port.
8.3 Multiple possible values
Use a set:
tcp dport { 22, 80, 443 } accept
This matches TCP packets destined for any of the listed ports.
For UDP:
udp dport { 53, 123 } accept
8.4 Port ranges
You can match a range of ports:
tcp dport 8000-8100 accept
Opening a range is convenient, but it can expose many services. Prefer specific ports whenever possible.
8.5 Verdicts
The most common verdicts are:
| Verdict | Meaning |
|---|---|
accept |
Accept the packet at this point |
drop |
Discard the packet silently |
reject |
Refuse the packet, usually with an error response |
jump |
Call another chain and return when appropriate |
goto |
Transfer control to another chain without the same return behavior as jump |
return |
Return from a regular chain or end processing in a base chain according to its policy |
continue |
Continue evaluating the current chain |
drop versus reject
drop silently discards a packet.
reject sends an appropriate rejection response where supported.
Example:
tcp dport 23 reject with tcp reset
This rejects matching TCP traffic using a TCP reset.
Use reject when explicit failure is desirable. Use drop when silent discard is appropriate.
9. Building a Stateful Firewall
A stateful firewall tracks flows and makes decisions based on their connection state.
This is one of the most important concepts in practical Linux firewall management.
9.1 Connection tracking states
Common states include:
| State | Meaning |
|---|---|
new |
A packet is starting a new tracked connection or flow |
established |
Traffic belongs to a connection that has already been established in connection tracking |
related |
Traffic is associated with another tracked connection |
invalid |
Traffic does not fit a valid tracked connection |
untracked |
Traffic has not been tracked by connection tracking |
These states are assigned by the connection-tracking subsystem, not by the application itself.
9.2 Why established traffic matters
Imagine the server initiates an HTTPS connection to a remote website.
Server Website
| |
| -------- TCP SYN ------------>|
| |
|<------- TCP SYN-ACK ----------|
| |
| -------- TCP ACK ------------>|
| |
| HTTPS traffic |
A stateful firewall can allow the outbound connection and its replies without requiring a separate rule for every remote source port.
For an inbound SSH connection, however, the initial connection is initiated by the remote client. A restrictive inbound policy needs a rule that permits that new connection.
9.3 A typical stateful pattern
ct state invalid drop
ct state established,related accept
These rules are normally placed early in the input chain.
They are not a complete firewall by themselves. You still need rules that permit the new connections you actually want.
9.4 Connection tracking is not authentication
Allowing:
ct state established,related accept
does not mean the remote user is authenticated.
It means the packet matches a state recognized by connection tracking.
Application authentication remains a separate security layer.
10. Managing Tables, Chains, and Rules
This section covers the most useful commands for inspecting and modifying a live ruleset.
Most changes require root privileges.
10.1 List the complete ruleset
sudo nft list ruleset
This is the first command to run when troubleshooting an nftables firewall.
10.2 List tables
sudo nft list tables
Example output:
table inet firewall
10.3 List a table
sudo nft list table inet firewall
10.4 Add a table
sudo nft add table inet lab
10.5 Delete a table
sudo nft delete table inet lab
Be careful: deleting a table removes its chains and associated rules.
10.6 Add a base chain
sudo nft 'add chain inet lab input { type filter hook input priority filter; policy drop; }'
This creates an input base chain with a default-drop policy.
Do not create a restrictive base chain on a remote host until you have added and tested the required access rules.
10.7 Add a regular chain
sudo nft add chain inet lab ssh_rules
A regular chain does not have a hook or policy.
10.8 Add a rule
sudo nft add rule inet lab input tcp dport 22 accept
This appends the rule to the specified chain.
10.9 Insert a rule at the beginning
sudo nft insert rule inet lab input tcp dport 22 accept
Rule order matters, so insertion and appending are not equivalent.
10.10 Display rule handles
sudo nft -a list chain inet firewall input
The -a option displays rule handles.
Example:
tcp dport 22 accept # handle 5
A handle identifies a rule in that chain.
10.11 Delete a rule
sudo nft delete rule inet firewall input handle 5
Use the handle from your own current ruleset. Do not assume that a handle will remain the same after the ruleset is rebuilt.
10.12 Flush a chain
sudo nft flush chain inet lab ssh_rules
This removes the rules from the specified chain while leaving the chain itself in place.
10.13 Flush the entire ruleset
sudo nft flush ruleset
Danger: This removes all nftables tables and their contents, including rules that may have been created by other applications.
It does not mean “temporarily disable only my firewall.” It is a global operation.
Use it only when you intentionally want to clear the entire nftables ruleset.
10.14 Inspect counters
sudo nft list ruleset
If rules contain counter, the output can show packet and byte counts.
Counters help determine whether traffic is reaching a rule.
11. Working with TCP, UDP, ICMP, and Ports
11.1 Allow SSH
tcp dport 22 accept
If your SSH daemon uses a different port, replace 22 with the actual port.
Confirm the listener:
sudo ss -lntp
11.2 Restrict SSH to a trusted IPv4 network
Suppose your administration network is 192.168.1.0/24.
ip saddr 192.168.1.0/24 tcp dport 22 accept
This allows SSH only from that source network, provided no other applicable rule or firewall path allows it.
Use your actual trusted network. Do not copy the example network without checking your addresses.
11.3 Allow HTTP and HTTPS
tcp dport { 80, 443 } accept
This opens TCP ports 80 and 443.
If you serve HTTP/3, which uses QUIC over UDP, you may also need:
udp dport 443 accept
Open UDP 443 only if your service actually needs it.
11.4 Allow DNS
For a DNS server that accepts incoming client queries:
udp dport 53 accept
tcp dport 53 accept
Both protocols can be needed.
A machine that merely uses an external DNS resolver usually needs to initiate outbound DNS queries and accept the corresponding replies. It does not necessarily need to accept unsolicited inbound DNS queries.
11.5 Allow ICMP
For a simple lab:
meta l4proto { icmp, ipv6-icmp } accept
A more restrictive policy may select particular ICMP and ICMPv6 message types.
Be careful not to block essential IPv6 Neighbor Discovery or ICMP errors needed for Path MTU Discovery.
11.6 Avoid unnecessary open ports
Before allowing a port, ask:
- Is there a service listening on it?
- Does the service need to be reachable from this network?
- Should access be restricted to particular source addresses?
- Is the service authenticated and updated?
- Does it need both TCP and UDP?
- Does the service also have an application-level access policy?
A firewall rule should express an actual requirement, not merely make a connection test succeed.
12. Interfaces, IP Addresses, and Networks
A firewall can match traffic by interface as well as by address.
12.1 Find interface names
ip -br link
Example:
lo UNKNOWN
enp1s0 UP
Your actual interface names may differ.
12.2 Find addresses
ip -br address
Example:
enp1s0 UP 192.168.1.50/24
12.3 Match an incoming interface
iifname "enp1s0" tcp dport 22 accept
This permits SSH arriving through enp1s0.
12.4 Match an outgoing interface
oifname "enp1s0" accept
This matches traffic leaving through that interface.
Be careful when using interface rules on systems whose network interfaces can be renamed, created dynamically, or removed.
12.5 Match a source network
ip saddr 192.168.1.0/24 accept
This matches IPv4 packets whose source address belongs to the specified network.
12.6 Match a destination network
ip daddr 10.10.0.0/16 accept
This matches IPv4 packets destined for that network.
The meaning of a rule depends on the chain where it appears. For example, a destination-address match in an input chain is evaluated against traffic addressed to the local machine, while a match in a forward chain concerns routed traffic.
13. IPv4 and IPv6
IPv6 must be considered explicitly in a modern firewall.
13.1 Why use the inet family?
A table in the inet family supports combined IPv4 and IPv6 filtering.
Example:
table inet firewall {
chain input {
type filter hook input priority filter;
policy drop;
iifname "lo" accept
ct state invalid drop
ct state established,related accept
meta l4proto { icmp, ipv6-icmp } accept
tcp dport 22 accept
}
}
This is simpler than maintaining separate IPv4 and IPv6 filter tables for every common rule.
13.2 IPv4-specific rules
Use ip expressions:
ip saddr 192.168.1.10 tcp dport 22 accept
13.3 IPv6-specific rules
Use ip6 expressions:
ip6 saddr 2001:db8:1234::/48 tcp dport 22 accept
2001:db8::/32 is reserved for documentation. Replace it with your real IPv6 network.
13.4 Why ICMPv6 matters
IPv6 uses ICMPv6 for functions including:
- Neighbor Discovery.
- Router Discovery.
- Error reporting.
- Path MTU Discovery.
A policy that blocks all ICMPv6 traffic can break connectivity in ways that are difficult to diagnose.
A working IPv6 firewall needs to permit the relevant control traffic while still applying an intentional security policy.
13.5 Check both address families
ip address
ip -6 address
ip route
ip -6 route
sudo ss -lntup
A service listening on an IPv6 wildcard address may also accept IPv4 connections, depending on its configuration and the system’s socket behavior.
Do not assume IPv4 rules protect IPv6 traffic. A unified inet table is a convenient way to apply common policy to both.
14. Named Sets and Dynamic Rules
Sets let you group addresses or ports and reference them in multiple rules.
They are especially useful when a firewall policy contains many trusted networks or services.
14.1 Why use sets?
Without a set, you might write separate rules for several trusted addresses:
ip saddr 192.168.1.10 tcp dport 22 accept
ip saddr 192.168.1.11 tcp dport 22 accept
ip saddr 192.168.1.12 tcp dport 22 accept
A set is more manageable.
14.2 Create a set of trusted IPv4 addresses
table inet firewall {
set trusted_admins {
type ipv4_addr
elements = {
192.168.1.10,
192.168.1.11,
192.168.1.12
}
}
chain input {
type filter hook input priority filter;
policy drop;
iifname "lo" accept
ct state invalid drop
ct state established,related accept
ip saddr @trusted_admins tcp dport 22 accept
}
}
The expression:
ip saddr @trusted_admins
matches a source address contained in the named set.
14.3 Add an element to a set
For a set called trusted_admins:
sudo nft add element inet firewall trusted_admins '{ 192.168.1.20 }'
14.4 Remove an element
sudo nft delete element inet firewall trusted_admins '{ 192.168.1.20 }'
14.5 Inspect a set
sudo nft list set inet firewall trusted_admins
14.6 Sets versus inline lists
An inline list is useful for a small, fixed group:
tcp dport { 22, 80, 443 } accept
A named set is useful when the list must be maintained independently of the rules that reference it.
For larger deployments, sets can simplify configuration management and automated updates.
15. Logging, Counters, and Rate Limiting
A firewall should be observable. When traffic is blocked, you want a way to investigate why.
15.1 Add a counter
tcp dport 22 counter accept
A counter records matching packet and byte counts.
Use counters to answer questions such as:
- Is traffic reaching this rule?
- Are clients actually connecting to this port?
- Is a rule being used?
- Does a rule match more traffic than expected?
15.2 Add logging
Example:
ct state invalid log prefix "nft-invalid: " drop
This logs matching packets and then drops them.
Logs are useful for troubleshooting, but excessive logging can create large amounts of data or consume resources.
15.3 Limit log volume
limit rate 5/second burst 10 packets log prefix "nft-drop: " drop
This limits the rate at which the rule logs matching traffic.
The precise behavior of rate limits depends on where and how the limit expression is applied. Test the rule before relying on it.
15.4 Inspect kernel messages
sudo journalctl -k
Filter for a particular prefix:
sudo journalctl -k | grep 'nft-drop'
You can also follow new kernel messages:
sudo journalctl -kf
Logging is not a replacement for counters, packet captures, or application logs. Use the evidence source that best answers the question.
15.5 Avoid indiscriminate logging
Do not automatically log every packet that reaches a default-drop policy.
Internet-facing machines can receive a large volume of unwanted traffic. Logging every packet may overwhelm useful logs.
Prefer targeted logging, sensible rate limits, and counters.
16. NAT, Masquerading, and Port Forwarding
NAT stands for Network Address Translation.
It changes address information in packets, often so private hosts can communicate through a router.
NAT and filtering are related but distinct operations.
16.1 Source NAT
Source NAT changes the source address of a packet.
A common example is a private machine accessing the Internet through a router.
Private client
192.168.1.20
|
v
Linux router
|
v
Internet
The router translates the client’s private source address to an address used on the outgoing network.
16.2 Masquerading
Masquerading is a form of source NAT that uses the address of the outgoing interface.
A typical rule is:
oifname "wan0" masquerade
This belongs in an appropriate NAT postrouting chain.
Replace wan0 with your actual outgoing interface.
16.3 Destination NAT
Destination NAT changes the destination address, often to forward a connection to another machine.
Example:
Internet client
|
v
Public router address
|
v
Private web server
192.168.1.20:443
A DNAT rule can translate the public destination to the private server.
16.4 Port forwarding example
A router forwards incoming TCP port 443 to a private server at 192.168.1.20.
Illustrative NAT rules:
table ip nat {
chain prerouting {
type nat hook prerouting priority dstnat;
policy accept;
iifname "wan0" tcp dport 443 dnat to 192.168.1.20:443
}
chain postrouting {
type nat hook postrouting priority srcnat;
policy accept;
oifname "wan0" masquerade
}
}
This is only the NAT portion of a router configuration. It is not a complete firewall.
You also need a suitable forward chain permitting the intended traffic.
The exact NAT and forwarding rules depend on the network layout and whether the router uses IPv4, IPv6, or both.
16.5 Enable IPv4 forwarding
On a Linux router, check:
sysctl net.ipv4.ip_forward
Enable forwarding temporarily:
sudo sysctl -w net.ipv4.ip_forward=1
To make it persistent, create a file such as:
/etc/sysctl.d/90-ip-forwarding.conf
With:
net.ipv4.ip_forward = 1
Then apply the configuration:
sudo sysctl --system
Only enable forwarding if the machine is intended to route packets.
IPv6 forwarding is controlled separately. Its configuration also interacts with router advertisements and the host’s IPv6 network design.
17. Permanent Configuration and systemd
Rules added interactively with nft affect the running kernel ruleset. They do not automatically become permanent across reboot.
A configuration file lets you manage a repeatable firewall policy.
17.1 Main configuration file
On typical Arch Linux and AlmaLinux installations using the nftables service, the configuration file is:
/etc/nftables.conf
Check the service definition and package documentation if your installation uses a customized path.
17.2 Validate the configuration
Before loading a configuration, test its syntax:
sudo nft -c -f /etc/nftables.conf
The -c option checks the configuration without applying it.
A successful syntax check does not prove that the firewall will preserve your SSH connection or permit every required service. It checks whether the configuration can be processed.
17.3 Load the configuration
sudo nft -f /etc/nftables.conf
This applies the file to the running ruleset.
Remember that the file is not automatically a replacement for everything currently in the kernel. Its behavior depends on the commands it contains.
If it starts with flush ruleset, it removes the current ruleset before defining the new one.
17.4 Enable the service at boot
sudo systemctl enable nftables.service
17.5 Start the service
sudo systemctl start nftables.service
17.6 Enable and start it together
sudo systemctl enable --now nftables.service
17.7 Check service status
systemctl status nftables.service
17.8 Reload the service
sudo systemctl restart nftables.service
On common installations, the service loads the configured ruleset when started. A restart may therefore disrupt existing firewall rules and connectivity, particularly if the configuration is incomplete.
Validate the configuration before restarting.
17.9 Inspect service logs
sudo journalctl -u nftables.service -b
For recent messages:
sudo journalctl -u nftables.service -n 100
17.10 The difference between active and persistent rules
There are two related states:
Runtime ruleset: The rules currently loaded into the kernel.
Persistent configuration: The rules stored in configuration files and loaded during startup.
A rule can exist at runtime but disappear after reboot. A rule can also exist in a configuration file but fail to load because of a syntax error or service problem.
Always verify both.
18. Testing Rules Safely
A correct firewall is not just one that loads. It is one that permits the intended traffic and blocks everything else.
18.1 Inspect before changing
Run:
sudo nft list ruleset
ip -br address
ip route
sudo ss -lntup
These establish the current state.
18.2 Test syntax
sudo nft -c -f /etc/nftables.conf
Do this after every significant configuration edit.
18.3 Back up the current rules
sudo nft list ruleset | sudo tee /root/firewall-backup.nft >/dev/null
This backs up the current runtime ruleset.
Keep a separate copy of the source configuration as well.
18.4 Keep an existing SSH session open
When changing the firewall remotely:
- Keep your current SSH connection open.
- Prepare the new ruleset.
- Validate it.
- Apply the changes.
- Open a second SSH session.
- Verify the new session works.
- Inspect the rules and logs.
- Only then close the original session.
An existing SSH session may survive a new rule that blocks new connections, because the connection is already established. That is not proof that new SSH connections will work.
18.5 Use a second terminal
In terminal A:
ssh user@server
In terminal B, apply and inspect the firewall changes.
Then test a new connection from terminal C, or from a separate client machine.
18.6 Test from the right network
Testing SSH from the same machine or from an unrelated network may not reflect the real access path.
Verify from the actual administration client or a client in the relevant network segment.
18.7 Prefer a disposable VM for learning
A lab VM is an ideal environment for experimenting with:
- Default-drop policies.
- SSH restrictions.
- ICMP rules.
- NAT.
- Forwarding.
- Logging.
- Rule ordering.
- Recovery procedures.
Take a VM snapshot before major experiments if your virtualization setup supports it.
19. Troubleshooting Network Connectivity
When a connection fails, do not immediately assume the firewall is responsible.
A failure can occur at several layers.
19.1 Check whether the service is listening
sudo ss -lntup
If SSH is not listening, opening port 22 will not make SSH work.
Check the service:
systemctl status sshd
The service name varies by distribution and application.
19.2 Check the address
ip -br address
Confirm the server has the expected IP address.
19.3 Check routing
ip route
For IPv6:
ip -6 route
A missing or incorrect route can prevent traffic from reaching its destination or prevent replies from returning.
19.4 Inspect firewall rules
sudo nft list ruleset
Look for:
- A default-drop policy.
- A missing allow rule.
- A source-address restriction.
- A rule that appears earlier than the intended allow rule.
- A different table or base chain that also processes the traffic.
- Rules created by a separate firewall manager.
19.5 Inspect the SSH service
On many Linux distributions:
sudo journalctl -u sshd.service -b
Also inspect the SSH daemon’s effective configuration when necessary:
sudo sshd -T
Use the service name appropriate to your distribution.
19.6 Test connectivity from the client
ssh -vvv user@server
Verbose SSH output can reveal whether the problem occurs during name resolution, TCP connection establishment, host-key verification, or authentication.
19.7 Check TCP connectivity
If nc is installed:
nc -vz server.example.com 22
This tests whether a TCP connection can be established. It does not verify that SSH authentication will succeed.
19.8 Capture packets
Use tcpdump to determine whether packets arrive and whether replies leave.
Example:
sudo tcpdump -ni any 'tcp port 22'
Interpretation:
- No incoming SYN packets: investigate routing, upstream firewalls, addressing, and the client.
- Incoming SYN packets but no reply: inspect local filtering, service listeners, routing, and kernel behavior.
- SYN followed by SYN-ACK: the server is responding; investigate the return path and subsequent connection behavior.
- TCP handshake succeeds but SSH fails: investigate the SSH service, authentication, and protocol logs.
Packet captures are often more informative than repeatedly changing firewall rules.
19.9 Trace nftables packet processing
For advanced troubleshooting, nftables supports packet tracing through nftrace and the monitor trace command.
First, inspect the existing ruleset and identify a narrowly scoped test packet.
For example, a temporary diagnostic rule might be:
sudo nft add rule inet firewall input ip saddr 192.168.1.10 tcp dport 22 meta nftrace set 1
Then run:
sudo nft monitor trace
Generate a test connection from the matching client and observe the trace.
The example assumes a table named firewall, an input chain, and the relevant source address. Adapt it to your own ruleset.
Remove the temporary tracing rule afterward. Use nft -a list chain inet firewall input to find its handle, then delete it by handle.
Tracing is powerful because it can reveal which rules and chains a packet traverses. Use it carefully, especially on busy systems.
20. Recovering from a Broken Firewall
This is essential knowledge for anyone learning firewall administration.
20.1 Why SSH can fail after a firewall change
Suppose you apply:
chain input {
type filter hook input priority filter;
policy drop;
}
If the chain contains no SSH allow rule, new inbound SSH connections can be dropped.
You may lose remote access before you have a chance to correct the configuration.
20.2 Use the VM console
For a virtual machine managed by libvirt, the serial console can provide a recovery path independent of the guest’s network connectivity.
On the host:
virsh list --all
Then:
virsh console almalinux10
The guest must have a working serial console configured. For example, its systemd serial-getty service and kernel console configuration must match the virtual machine’s serial device.
Press Enter if necessary.
To exit the console, use:
Ctrl + ]
This disconnects the console session without shutting down the VM.
20.3 Restore a known-good configuration
If the firewall is managed by /etc/nftables.conf, restore a verified backup of that file, validate it, and reload the service from the guest console.
For example:
sudo cp /root/nftables.conf.backup /etc/nftables.conf
sudo nft -c -f /etc/nftables.conf
sudo systemctl restart nftables.service
The backup path must refer to a real backup you created earlier.
Do not blindly copy a backup from another machine or assume the backup represents the current network environment.
20.4 If only runtime rules were changed
If you saved a valid runtime ruleset, it may be possible to restore it with:
sudo nft -f /root/firewall-backup.nft
This works only if the saved file represents the desired rules and is compatible with the current environment.
If the file does not clear conflicting existing rules, the result may differ from the original state. Review its contents before restoring.
20.5 Avoid relying on a single recovery path
A good recovery plan includes:
- A tested configuration backup.
- Access through a VM console or hypervisor.
- Knowledge of the active firewall manager.
- A second SSH connection for validation.
- A snapshot or other rollback mechanism where appropriate.
For remote production servers, use the provider’s documented out-of-band console or recovery mechanism as well.
21. Practical Firewall Configurations
The following examples illustrate different policies. Each is a starting point, not a universal drop-in configuration.
21.1 Workstation firewall
A workstation generally needs:
- Loopback.
- Established and related traffic.
- Appropriate ICMP and ICMPv6.
- New inbound connections only for services that should be reachable.
A simple policy might look like:
table inet workstation {
chain input {
type filter hook input priority filter;
policy drop;
iifname "lo" accept
ct state invalid drop
ct state established,related accept
meta l4proto { icmp, ipv6-icmp } accept
}
chain forward {
type filter hook forward priority filter;
policy drop;
}
chain output {
type filter hook output priority filter;
policy accept;
}
}
This example does not open SSH or any other unsolicited inbound service.
It also does not define exceptions for every possible workstation service. Depending on your environment, you may need to account for DHCP, VPN software, network discovery, local sharing, or other services.
21.2 SSH administration restricted to a LAN
Suppose you want SSH access only from 192.168.1.0/24.
The relevant input-chain rules could be:
iifname "lo" accept
ct state invalid drop
ct state established,related accept
meta l4proto { icmp, ipv6-icmp } accept
ip saddr 192.168.1.0/24 tcp dport 22 accept
Use this inside a properly defined base chain.
If the server also has IPv6 connectivity, define an intentional IPv6 administration policy too. Do not accidentally allow SSH from every IPv6 source simply because the IPv4 rule is restrictive.
21.3 Public web server
A public web server may need to accept:
- SSH from a restricted administration network.
- HTTP on TCP port 80.
- HTTPS on TCP port 443.
- Required ICMP and ICMPv6 traffic.
- Established and related traffic.
The following rules illustrate the intended access policy:
ct state invalid drop
ct state established,related accept
iifname "lo" accept
meta l4proto { icmp, ipv6-icmp } accept
ip saddr 192.168.1.0/24 tcp dport 22 accept
tcp dport { 80, 443 } accept
The first rule restricts SSH by IPv4 source network. Adjust the rule for your real administration network and IPv6 requirements.
21.4 Database server
A database should generally be reachable only from application hosts that require it.
Suppose an application server has IPv4 address 10.10.0.15, and the database listens on TCP port 5432.
A relevant allow rule is:
ip saddr 10.10.0.15 tcp dport 5432 accept
This belongs in the database server’s input chain.
Also ensure the database itself listens on the intended address and uses appropriate authentication.
A firewall rule does not replace database authorization.
21.5 A server with restricted inbound access
A useful baseline policy is:
table inet server_firewall {
chain input {
type filter hook input priority filter;
policy drop;
iifname "lo" accept
ct state invalid drop
ct state established,related accept
meta l4proto { icmp, ipv6-icmp } accept
# SSH from the trusted administration network.
ip saddr 192.168.1.0/24 tcp dport 22 accept
# Public web traffic.
tcp dport { 80, 443 } accept
}
chain forward {
type filter hook forward priority filter;
policy drop;
}
chain output {
type filter hook output priority filter;
policy accept;
}
}
This is an example of policy structure, not a complete production policy for every service.
Before loading it, identify the machine’s network requirements and the other software that manages firewall rules.
21.6 Docker and container hosts
Container runtimes may create firewall rules for bridge networks, port publishing, and NAT.
For example, a published container port may depend on rules that are not present in your hand-written host firewall configuration.
On a Docker host, inspect:
sudo nft list ruleset
docker ps
docker network ls
If container connectivity breaks after a firewall change, inspect the runtime’s network configuration before flushing or replacing rules.
Avoid using flush ruleset on a machine whose rules are partly managed by Docker, Kubernetes, or another network controller unless you fully understand the impact.
22. Advanced Concepts
22.1 Chain jumps
A jump allows one chain to call another chain.
Example:
table inet firewall {
chain input {
type filter hook input priority filter;
policy drop;
iifname "lo" accept
ct state established,related accept
tcp dport 22 jump ssh_policy
}
chain ssh_policy {
ip saddr 192.168.1.0/24 accept
drop
}
}
This is a structural illustration of chain reuse.
The ssh_policy chain evaluates the source address and drops packets that do not match the permitted network.
When designing chains, be careful about the difference between jump, goto, return, and the policy of the calling base chain.
22.2 Maps
Maps associate keys with values. They can help implement policies that would otherwise require many similar rules.
For example, a map can associate a destination address with a port or another value.
Maps are more advanced than simple sets and should be introduced when the configuration benefits from data-driven rule selection.
22.3 Dynamic sets
Dynamic sets can be useful for temporary bans, rate-limiting systems, and automated security tools.
For example, a set can have a timeout so an element expires automatically.
A simplified set definition is:
set temporary_blocks {
type ipv4_addr
flags timeout
timeout 10m
}
An address can be added with a timeout:
sudo nft add element inet firewall temporary_blocks '{ 192.0.2.10 timeout 10m }'
This assumes the table and set already exist. The example address is reserved for documentation and is not a real attacker address.
Dynamic blocking should be designed carefully. Automated bans can accidentally block legitimate clients or be abused to deny service to others.
22.4 Connection limits and rate limits
Rate limits can reduce the impact of bursts of traffic or excessive logging.
For example:
limit rate 10/second burst 20 packets accept
The meaning depends on the surrounding rule and whether the limit is applied globally or per source through an appropriate construct.
Do not assume a global limit automatically provides a separate allowance for every client.
For production systems, design and test rate limits according to the specific traffic pattern and threat model.
22.5 Flowtables and performance
Advanced nftables deployments may use flowtables and hardware offload to accelerate packet forwarding.
These mechanisms can change which paths packets traverse and can complicate observation and debugging.
Learn ordinary filtering, connection tracking, and packet flow first. Introduce flow offload only when you have a measurable performance requirement and understand the implications.
22.6 Firewall policy as code
For repeatable administration, treat the firewall configuration as code:
- Store it in version control.
- Review changes before deployment.
- Test syntax automatically.
- Apply it through a controlled process.
- Keep a known-good version for rollback.
- Verify behavior after deployment.
A firewall configuration should be understandable and reproducible, not merely a collection of commands that happen to work on one machine.
23. Common Mistakes and Security Considerations
23.1 Using flush ruleset without understanding it
This command removes all nftables tables and their contents.
It may disrupt:
- Container networking.
- NAT.
- VPN connectivity.
- Firewall rules managed by other software.
- Traffic forwarding.
- Security policies you did not create manually.
Use it only when you intend to manage the entire ruleset.
23.2 Forgetting the SSH allow rule
A default-drop input chain can block new SSH connections.
Always identify the actual SSH port and source network before applying a restrictive policy.
23.3 Assuming an existing SSH session proves access is safe
Established connections may continue working while new connections are blocked.
Test a new connection before closing your existing session.
23.4 Ignoring IPv6
An IPv4-only rule does not necessarily restrict IPv6 traffic.
Use inet when appropriate and verify both address families.
23.5 Opening every port
Avoid rules such as:
tcp dport 1-65535 accept
They defeat the purpose of a restrictive inbound firewall.
Open only the ports required by the intended services.
23.6 Blocking all ICMPv6
This can interfere with important IPv6 functions.
Build an IPv6 policy that permits necessary control traffic.
23.7 Running two firewall managers without understanding their interaction
If firewalld, Docker, Kubernetes, a VPN, or another application modifies the ruleset, your manually created rules may interact with those rules.
Determine which component owns each part of the policy.
23.8 Assuming a syntax check proves connectivity
A configuration can be syntactically valid and still block SSH or a required application.
Test both syntax and actual network behavior.
23.9 Treating NAT as a firewall
NAT changes address information. It does not replace an explicit filtering policy.
A router generally needs both suitable NAT configuration and suitable forwarding rules.
23.10 Making permanent changes before testing
Do not save an untested restrictive policy as the only startup configuration on a remote machine.
Keep backups and a recovery path.
24. Essential Command Reference
This is the practical command sheet to keep nearby.
Inspect
## Show the complete ruleset.
sudo nft list ruleset
## List tables.
sudo nft list tables
## List chains.
sudo nft list chains
## List a particular table.
sudo nft list table inet firewall
## List a particular chain.
sudo nft list chain inet firewall input
## Show rule handles.
sudo nft -a list chain inet firewall input
## Show nftables version.
nft --version
## Show network interfaces and addresses.
ip -br address
## Show IPv4 routes.
ip route
## Show IPv6 routes.
ip -6 route
## Show listening sockets.
sudo ss -lntup
Validate and load
## Validate configuration syntax without applying it.
sudo nft -c -f /etc/nftables.conf
## Load the configuration file.
sudo nft -f /etc/nftables.conf
## Enable nftables at boot.
sudo systemctl enable nftables.service
## Enable and start the service.
sudo systemctl enable --now nftables.service
## Check service status.
systemctl status nftables.service
## Read service logs from this boot.
sudo journalctl -u nftables.service -b
Modify
## Create a table.
sudo nft add table inet lab
## Create a regular chain.
sudo nft add chain inet lab ssh_rules
## Add a rule.
sudo nft add rule inet lab ssh_rules tcp dport 22 accept
## Delete a table.
sudo nft delete table inet lab
## Flush a regular chain's rules.
sudo nft flush chain inet lab ssh_rules
## Delete a rule by its handle.
sudo nft delete rule inet firewall input handle 5
Always adapt table names, chain names, and handles to the ruleset you actually have.
Backup and restore
## Back up the runtime ruleset.
sudo nft list ruleset | sudo tee /root/firewall-backup.nft >/dev/null
## Validate a configuration file.
sudo nft -c -f /etc/nftables.conf
## Restore a previously saved ruleset, after reviewing it.
sudo nft -f /root/firewall-backup.nft
Monitor and troubleshoot
## Follow kernel messages.
sudo journalctl -kf
## Follow nftables service messages.
sudo journalctl -fu nftables.service
## Capture SSH packets.
sudo tcpdump -ni any 'tcp port 22'
## Monitor nftables trace events.
sudo nft monitor trace
## Test SSH with verbose output from the client.
ssh -vvv user@server
nft monitor trace is most useful after an appropriate nftrace rule has been configured to mark the traffic you want to inspect.
25. Hands-On Labs
The best way to learn nftables is to experiment in a virtual machine where mistakes are recoverable.
Use a disposable Linux VM and ensure you have console access before starting.
Lab 1: Explore the current ruleset
Objectives:
- Learn how to inspect nftables.
- Identify existing tables and chains.
- Understand the current network layout.
Commands:
sudo nft list ruleset
sudo nft list tables
ip -br address
ip route
sudo ss -lntup
Questions:
- Which tables exist?
- Which base chains are present?
- Which chains have a default-drop policy?
- Which ports have listening services?
- Is another firewall manager active?
Lab 2: Build a small test ruleset
Perform this only in a disposable VM where replacing the existing ruleset is safe.
Create /tmp/nft-lab.nft:
flush ruleset
table inet lab {
chain input {
type filter hook input priority filter;
policy drop;
iifname "lo" accept
ct state invalid drop
ct state established,related accept
meta l4proto { icmp, ipv6-icmp } accept
}
chain forward {
type filter hook forward priority filter;
policy drop;
}
chain output {
type filter hook output priority filter;
policy accept;
}
}
Validate it:
sudo nft -c -f /tmp/nft-lab.nft
If the configuration is valid and you are certain the VM is safe to modify, load it:
sudo nft -f /tmp/nft-lab.nft
Inspect the result:
sudo nft list ruleset
Observe that outbound traffic is permitted by the output chain, while unsolicited inbound traffic is dropped by the input policy unless it matches an explicit rule.
This lab does not permit new SSH connections. Do not use it on a remote machine unless you have another reliable access method.
Lab 3: Add a restricted SSH rule
First determine the real administration network.
Suppose it is 192.168.1.0/24. Add:
sudo nft add rule inet lab input ip saddr 192.168.1.0/24 tcp dport 22 accept
Inspect the chain:
sudo nft -a list chain inet lab input
Test SSH from a client in that network.
If the VM uses another network, substitute the actual trusted network.
Lab 4: Add counters
Add a counter to the SSH rule in a test ruleset, or create a dedicated test rule:
sudo nft add rule inet lab input tcp dport 22 counter
Inspect counters:
sudo nft list chain inet lab input
This example is for learning only. Because the test rule has no explicit verdict, matching packets continue to subsequent rules and eventually reach the chain policy if no later rule accepts them.
Use the counter to observe matching traffic, then remove the test rule when finished.
Lab 5: Restrict a service by source address
Create a rule permitting a test TCP service only from a trusted source address.
For example:
ip saddr 192.168.1.10 tcp dport 8080 accept
Test from both the permitted client and another client.
Observe the difference between:
- The service listening.
- The packet reaching the host.
- The firewall allowing the packet.
- The application accepting the connection.
Lab 6: Practice recovery
Objectives:
- Create a known-good configuration.
- Make a restrictive change.
- Observe the impact.
- Recover through the VM console.
Procedure:
- Save a known-good configuration.
- Confirm the VM console works.
- Apply a test rule that blocks a new test connection.
- Observe the connection failure.
- Use the console to inspect the ruleset.
- Restore the known-good configuration.
- Validate and reload it.
- Verify connectivity again.
Do not experiment with your only SSH access to a remote production server.
Lab 7: Explore packet tracing
In a test VM:
- Identify the relevant base chain.
- Add a narrowly scoped
meta nftrace set 1rule. - Run
sudo nft monitor trace. - Generate matching traffic.
- Observe the rules and verdicts.
- Remove the temporary trace rule.
The goal is to understand why a packet is accepted or dropped, not merely to keep changing rules until the connection works.
26. Professional Troubleshooting Workflow
When a connection fails, follow a repeatable sequence rather than making random firewall changes.
Step 1: Define the problem
Record:
- Source IP address.
- Destination IP address.
- Protocol.
- Destination port.
- Network interface.
- Expected behavior.
- Actual behavior.
For example:
Source: 192.168.1.25
Destination: 192.168.1.50
Protocol: TCP
Port: 22
Expected: SSH connection succeeds
Actual: Connection times out
Step 2: Confirm the service
sudo ss -lntup
Is the expected service listening on the correct address and port?
Step 3: Confirm addressing and routing
ip -br address
ip route
ip -6 route
Can the client reach the destination? Is there a return route?
Step 4: Inspect the active ruleset
sudo nft list ruleset
Identify the relevant base chain and the rules that may match the packet.
Step 5: Check the firewall manager
systemctl status nftables.service
systemctl status firewalld.service
Also consider container runtimes, VPN software, and other components that modify firewall state.
Step 6: Capture packets
sudo tcpdump -ni any 'tcp port 22'
Determine whether packets arrive and whether replies leave.
Step 7: Trace the packet if necessary
Use nftrace and nft monitor trace to observe the rule path.
Step 8: Make one controlled change
Modify one relevant part of the policy.
Validate syntax before applying the change.
Step 9: Verify the result
Test from the actual client and inspect the ruleset again.
Step 10: Make the fix persistent
Once the fix is verified:
- Update the source configuration.
- Validate it.
- Apply it through the intended management process.
- Verify the runtime rules.
- Confirm it survives the expected reload or reboot procedure.
This workflow scales from a lab VM to a production server.
27. Learning Roadmap
To progress from beginner to confident firewall administrator, learn the topics in this order.
Stage 1: Linux networking fundamentals
Understand:
- IP addresses and CIDR notation.
- TCP and UDP.
- Ports and listening sockets.
- Routing tables.
- Default gateways.
- DNS.
- Network interfaces.
- IPv4 and IPv6.
Practice:
ip -br address
ip route
ip -6 route
ss -lntup
ping
tracepath
Stage 2: Basic nftables
Understand:
- Tables.
- Chains.
- Hooks.
- Priorities.
- Rules.
- Verdicts.
- Policies.
Practice building a small ruleset in a disposable VM.
Stage 3: Stateful filtering
Understand:
- Connection tracking.
new,established,related, andinvalid.- Inbound versus outbound traffic.
- Default-deny policies.
- Rule ordering.
Practice restricting SSH to a trusted network.
Stage 4: Persistent administration
Understand:
/etc/nftables.conf.nft -c -f.nft -f.- systemd service management.
- Runtime versus persistent rules.
- Backups and rollback.
Practice recovering from a deliberately broken test configuration.
Stage 5: Troubleshooting
Understand:
tcpdump.journalctl.ss.- Routing diagnostics.
- Packet tracing.
- Multiple firewall managers.
Practice diagnosing a connection failure without immediately changing the firewall.
Stage 6: Advanced firewalling
Learn:
- Named sets and maps.
- Timeouts and dynamic sets.
- Logging and rate limits.
- NAT and port forwarding.
- Router forwarding policies.
- IPv6 control traffic.
- Performance and flow offload.
Stage 7: Production operations
Develop habits around:
- Version-controlled configuration.
- Peer review.
- Automated validation.
- Change control.
- Monitoring.
- Rollback.
- Documentation.
- Least privilege.
- Testing from real client networks.
Professional skill comes from understanding the packet path and being able to prove why a connection succeeds or fails.
28. Official Documentation
Use these references to deepen your understanding and verify syntax.
-
ArchWiki — nftables
https://wiki.archlinux.org/title/NftablesPractical installation, configuration, examples, service management, and Arch-specific guidance.
-
Official nftables Wiki
https://wiki.nftables.org/wiki-nftables/index.php/Main_PageDetailed reference material on chains, expressions, sets, packet tracing, NAT, and connection tracking.
-
nftables Quick Reference
https://wiki.nftables.org/wiki-nftables/index.php/Quick_reference-nftables_in_10_minutesA concise reference for common commands and basic ruleset construction.
-
nft(8) manual page
https://man.archlinux.org/man/nft.8The command reference for
nft, including operations, rule syntax, and options. -
Netfilter documentation
https://www.netfilter.org/documentation/Background information on the Linux packet-filtering framework.
-
Red Hat Enterprise Linux security documentation
https://docs.redhat.com/Consult the relevant networking and security chapters for RHEL-family operational guidance, including AlmaLinux-compatible concepts.
Final Checklist
Before deploying a firewall, verify the following:
- I understand whether the machine is a server, workstation, or router.
- I know which interfaces, addresses, and routes it uses.
- I know which services are listening.
- I identified the active firewall manager.
- I reviewed the existing ruleset.
- I backed up the current configuration.
- I understand the consequences of
flush ruleset. - I have explicitly permitted the required inbound services.
- I have an intentional IPv4 and IPv6 policy.
- I have validated the configuration syntax.
- I have tested new connections, not just existing sessions.
- I have a recovery path if SSH stops working.
- I know how to inspect counters, logs, and packet traces.
- I have made the verified configuration persistent.
- I have documented the purpose of important rules.
The central principle: A good firewall is not a collection of commands copied from a tutorial. It is a deliberate, tested, observable, and recoverable security policy.
Learn what each packet should be allowed to do, understand where the kernel evaluates it, and use that knowledge to build the ruleset.