How to use nftables → nft list ruleset; nft add rule ..
How to Use nftables: Complete Guide to nft list ruleset and nft add rule Commands
Table of Contents
1. [Introduction](#introduction)
2. [Prerequisites and Requirements](#prerequisites-and-requirements)
3. [Understanding nftables Architecture](#understanding-nftables-architecture)
4. [Using nft list ruleset Command](#using-nft-list-ruleset-command)
5. [Using nft add rule Command](#using-nft-add-rule-command)
6. [Practical Examples and Use Cases](#practical-examples-and-use-cases)
7. [Advanced Rule Management](#advanced-rule-management)
8. [Common Issues and Troubleshooting](#common-issues-and-troubleshooting)
9. [Best Practices and Professional Tips](#best-practices-and-professional-tips)
10. [Conclusion and Next Steps](#conclusion-and-next-steps)
Introduction
nftables is the modern Linux kernel firewall framework that replaces the legacy iptables, ip6tables, arptables, and ebtables tools. Introduced in Linux kernel 3.13, nftables provides a unified interface for packet filtering and classification, offering improved performance, simplified syntax, and enhanced flexibility for network administrators and security professionals.
This comprehensive guide focuses on two fundamental nftables commands: `nft list ruleset` and `nft add rule`. These commands form the foundation of nftables management, allowing you to view existing firewall configurations and add new rules to control network traffic. Whether you're a system administrator transitioning from iptables or a security professional implementing advanced firewall policies, mastering these commands is essential for effective network security management.
By the end of this article, you'll understand how to efficiently list and examine your current firewall configuration, add new rules with proper syntax, and implement complex filtering policies using nftables' powerful rule engine.
Prerequisites and Requirements
System Requirements
Before working with nftables, ensure your system meets the following requirements:
- Linux Kernel: Version 3.13 or later (recommended: 4.17+)
- Operating System: Modern Linux distribution with nftables support
- Root Access: Administrative privileges for firewall management
- Network Understanding: Basic knowledge of networking concepts (TCP/IP, ports, protocols)
Software Installation
Most modern Linux distributions include nftables by default. To verify installation or install nftables:
Ubuntu/Debian:
```bash
sudo apt update
sudo apt install nftables
```
CentOS/RHEL/Fedora:
```bash
sudo dnf install nftables
or for older versions
sudo yum install nftables
```
Arch Linux:
```bash
sudo pacman -S nftables
```
Verification Steps
Verify your nftables installation:
```bash
Check nftables version
nft --version
Check kernel support
lsmod | grep nf_tables
Verify nftables service status
systemctl status nftables
```
Important Considerations
Warning: Always test firewall rules in a safe environment before applying them to production systems. Incorrect rules can lock you out of remote systems.
Backup Recommendation: Before making changes, save your current configuration:
```bash
nft list ruleset > /backup/nftables-backup-$(date +%Y%m%d).conf
```
Understanding nftables Architecture
Core Concepts
nftables organizes firewall rules using a hierarchical structure:
1. Tables: Top-level containers that group chains and rules by protocol family
2. Chains: Collections of rules that process packets at specific network stack points
3. Rules: Individual statements that define packet matching criteria and actions
Protocol Families
nftables supports multiple protocol families:
- `ip`: IPv4 packets
- `ip6`: IPv6 packets
- `inet`: Both IPv4 and IPv6 packets
- `arp`: ARP packets
- `bridge`: Bridge packets
- `netdev`: Network device packets
Chain Types and Hooks
Different chain types serve specific purposes:
- filter: Standard packet filtering
- nat: Network Address Translation
- route: Routing decisions
- mangle: Packet modification
Basic Syntax Structure
nftables commands follow this general pattern:
```bash
nft [options] command [family] [table] [chain] [rule-specification]
```
Using nft list ruleset Command
Basic Usage
The `nft list ruleset` command displays the complete current nftables configuration, showing all tables, chains, and rules across all protocol families.
```bash
List complete ruleset
nft list ruleset
List ruleset with numeric output (ports/protocols as numbers)
nft -n list ruleset
List ruleset with handles (rule identifiers)
nft -a list ruleset
```
Understanding Output Format
A typical `nft list ruleset` output looks like this:
```bash
table inet filter {
chain input {
type filter hook input priority filter; policy accept;
iif "lo" accept
ct state established,related accept
tcp dport 22 accept
drop
}
chain forward {
type filter hook forward priority filter; policy drop;
}
chain output {
type filter hook output priority filter; policy accept;
}
}
```
Listing Specific Components
You can list specific parts of your configuration:
```bash
List all tables
nft list tables
List specific table
nft list table inet filter
List specific chain
nft list chain inet filter input
List rules in a chain with line numbers
nft -a list chain inet filter input
```
Advanced Listing Options
JSON Output: For programmatic processing:
```bash
nft -j list ruleset
```
Verbose Output: Shows additional details:
```bash
nft -v list ruleset
```
Stateless Output: Excludes stateful objects:
```bash
nft -s list ruleset
```
Filtering and Searching Output
Combine with standard Unix tools for specific information:
```bash
Find rules containing specific ports
nft list ruleset | grep "dport 80"
Count total number of rules
nft -a list ruleset | grep "handle" | wc -l
Find all DROP rules
nft list ruleset | grep -i "drop"
```
Using nft add rule Command
Basic Syntax
The `nft add rule` command adds new rules to existing chains:
```bash
nft add rule [family] [table] [chain] [rule-specification]
```
Essential Rule Components
Every rule consists of:
1. Match Criteria: Conditions packets must meet
2. Actions: What to do with matching packets (accept, drop, reject, etc.)
3. Optional Parameters: Additional rule modifiers
Basic Rule Examples
Allow SSH Access:
```bash
nft add rule inet filter input tcp dport 22 accept
```
Block Specific IP:
```bash
nft add rule inet filter input ip saddr 192.168.1.100 drop
```
Allow HTTP and HTTPS:
```bash
nft add rule inet filter input tcp dport { 80, 443 } accept
```
Rule Positioning
By default, rules are appended to the end of a chain. Control positioning with:
Insert at Beginning:
```bash
nft insert rule inet filter input tcp dport 22 accept
```
Add at Specific Position:
```bash
First, get handle numbers
nft -a list chain inet filter input
Insert after specific rule (handle 5)
nft add rule inet filter input position 5 tcp dport 80 accept
Insert before specific rule
nft insert rule inet filter input position 5 tcp dport 443 accept
```
Match Criteria Types
Protocol Matching:
```bash
TCP traffic
nft add rule inet filter input tcp dport 80 accept
UDP traffic
nft add rule inet filter input udp dport 53 accept
ICMP traffic
nft add rule inet filter input icmp type echo-request accept
```
Address Matching:
```bash
Source IP
nft add rule inet filter input ip saddr 10.0.0.0/8 accept
Destination IP
nft add rule inet filter input ip daddr 192.168.1.1 drop
IP ranges
nft add rule inet filter input ip saddr 192.168.1.10-192.168.1.20 accept
```
Interface Matching:
```bash
Input interface
nft add rule inet filter input iifname "eth0" accept
Output interface
nft add rule inet filter output oifname "wlan0" accept
```
Connection State Matching:
```bash
Established connections
nft add rule inet filter input ct state established,related accept
New connections only
nft add rule inet filter input ct state new tcp dport 80 accept
```
Actions and Verdicts
Basic Actions:
```bash
Accept packet
nft add rule inet filter input tcp dport 22 accept
Drop packet silently
nft add rule inet filter input ip saddr 10.0.0.1 drop
Reject with error message
nft add rule inet filter input tcp dport 23 reject
Log packet
nft add rule inet filter input tcp dport 80 log accept
```
Advanced Actions:
```bash
Jump to another chain
nft add rule inet filter input tcp dport 80 jump web_chain
Return from chain
nft add rule inet filter web_chain tcp sport 80 return
Counter with action
nft add rule inet filter input counter accept
```
Practical Examples and Use Cases
Basic Firewall Setup
Create a simple but effective firewall configuration:
```bash
Create table and chains
nft add table inet filter
nft add chain inet filter input { type filter hook input priority 0; policy drop; }
nft add chain inet filter forward { type filter hook forward priority 0; policy drop; }
nft add chain inet filter output { type filter hook output priority 0; policy accept; }
Allow loopback traffic
nft add rule inet filter input iif lo accept
Allow established connections
nft add rule inet filter input ct state established,related accept
Allow SSH
nft add rule inet filter input tcp dport 22 accept
Allow ping
nft add rule inet filter input icmp type echo-request accept
```
Web Server Configuration
Configure rules for a web server:
```bash
HTTP and HTTPS
nft add rule inet filter input tcp dport { 80, 443 } accept
Allow DNS queries (for outbound connections)
nft add rule inet filter output udp dport 53 accept
Rate limiting for HTTP connections
nft add rule inet filter input tcp dport 80 limit rate 25/minute accept
```
Advanced Security Rules
Implement sophisticated security measures:
```bash
Block common attack ports
nft add rule inet filter input tcp dport { 135, 139, 445, 1433, 3389 } drop
Geographic blocking (requires geoip module)
nft add rule inet filter input ip saddr @country_blocklist drop
Prevent port scanning
nft add rule inet filter input tcp flags syn limit rate 1/second accept
```
NAT Configuration
Set up Network Address Translation:
```bash
Create NAT table
nft add table nat
Create postrouting chain for masquerading
nft add chain nat postrouting { type nat hook postrouting priority 100; }
Masquerade outgoing traffic
nft add rule nat postrouting oifname "eth0" masquerade
Port forwarding
nft add chain nat prerouting { type nat hook prerouting priority -100; }
nft add rule nat prerouting tcp dport 8080 dnat to 192.168.1.100:80
```
Load Balancing Rules
Distribute traffic across multiple servers:
```bash
Create custom chain for load balancing
nft add chain inet filter lb_web
Distribute based on source IP hash
nft add rule inet filter input tcp dport 80 jump lb_web
nft add rule inet filter lb_web numgen random mod 3 0 dnat to 192.168.1.10:80
nft add rule inet filter lb_web numgen random mod 3 1 dnat to 192.168.1.11:80
nft add rule inet filter lb_web numgen random mod 3 2 dnat to 192.168.1.12:80
```
Advanced Rule Management
Using Sets and Maps
Sets allow efficient matching against multiple values:
```bash
Create a set of blocked IPs
nft add set inet filter blocked_ips { type ipv4_addr; }
Add IPs to the set
nft add element inet filter blocked_ips { 192.168.1.100, 10.0.0.50 }
Use set in rules
nft add rule inet filter input ip saddr @blocked_ips drop
```
Maps provide key-value relationships:
```bash
Create port forwarding map
nft add map inet nat port_forwards { type inet_service : ipv4_addr . inet_service; }
Populate map
nft add element inet nat port_forwards { 8080 : 192.168.1.10 . 80, 8443 : 192.168.1.10 . 443 }
Use map in rules
nft add rule nat prerouting tcp dport map @port_forwards
```
Rule Modification and Deletion
Replace Rules:
```bash
Get rule handle
nft -a list chain inet filter input
Replace rule by handle
nft replace rule inet filter input handle 5 tcp dport 80 accept
```
Delete Rules:
```bash
Delete by handle
nft delete rule inet filter input handle 5
Delete entire chain
nft delete chain inet filter input
Flush chain (remove all rules)
nft flush chain inet filter input
```
Configuration Management
Save Configuration:
```bash
Save to file
nft list ruleset > /etc/nftables.conf
Save with timestamp
nft list ruleset > /backup/nftables-$(date +%Y%m%d-%H%M%S).conf
```
Load Configuration:
```bash
Load from file
nft -f /etc/nftables.conf
Test configuration before applying
nft -c -f /etc/nftables.conf
```
Common Issues and Troubleshooting
Connection Problems
Issue: Rules blocking legitimate traffic
Solution: Check rule order and add necessary allow rules:
```bash
List rules with handles to see order
nft -a list chain inet filter input
Insert allow rule at correct position
nft insert rule inet filter input position 1 ct state established,related accept
```
Issue: Can't connect after applying rules
Solution: Add explicit allow rules for your management connection:
```bash
Allow SSH from specific IP
nft insert rule inet filter input ip saddr YOUR_IP tcp dport 22 accept
```
Syntax Errors
Issue: Command syntax errors
Common Problems and Solutions:
```bash
Wrong: Missing table specification
nft add rule input tcp dport 22 accept
Correct: Include full path
nft add rule inet filter input tcp dport 22 accept
Wrong: Incorrect protocol family
nft add rule ip6 filter input tcp dport 22 accept # for IPv4 rule
Correct: Use appropriate family
nft add rule inet filter input tcp dport 22 accept # for both IPv4/IPv6
```
Performance Issues
Issue: Slow packet processing
Solution: Optimize rule order and use sets:
```bash
Instead of multiple individual rules
nft add rule inet filter input ip saddr 1.1.1.1 drop
nft add rule inet filter input ip saddr 2.2.2.2 drop
... many more
Use a set for better performance
nft add set inet filter blocked_ips { type ipv4_addr; }
nft add element inet filter blocked_ips { 1.1.1.1, 2.2.2.2, 3.3.3.3 }
nft add rule inet filter input ip saddr @blocked_ips drop
```
Rule Conflicts
Issue: Conflicting rules causing unexpected behavior
Solution: Review rule order and use specific matching:
```bash
Problem: Generic rule before specific rule
nft add rule inet filter input drop # This blocks everything
nft add rule inet filter input tcp dport 22 accept # This never matches
Solution: Specific rules first
nft add rule inet filter input tcp dport 22 accept
nft add rule inet filter input drop
```
Debugging Techniques
Enable Logging:
```bash
Add logging to troublesome rules
nft add rule inet filter input tcp dport 80 log prefix "HTTP: " accept
Check logs
journalctl -f | grep "HTTP:"
```
Use Counters:
```bash
Add counters to track rule usage
nft add rule inet filter input counter tcp dport 22 accept
Check counter values
nft list chain inet filter input
```
Best Practices and Professional Tips
Security Best Practices
Default Deny Policy: Always start with a restrictive default policy:
```bash
nft add chain inet filter input { type filter hook input priority 0; policy drop; }
```
Principle of Least Privilege: Only allow necessary traffic:
```bash
Instead of allowing all HTTP
nft add rule inet filter input tcp dport 80 accept
Allow HTTP only from specific networks
nft add rule inet filter input ip saddr 192.168.0.0/16 tcp dport 80 accept
```
Rate Limiting: Protect against abuse:
```bash
Limit SSH connections
nft add rule inet filter input tcp dport 22 limit rate 3/minute accept
Limit ping responses
nft add rule inet filter input icmp type echo-request limit rate 1/second accept
```
Performance Optimization
Rule Ordering: Place most common matches first:
```bash
High-traffic rules first
nft add rule inet filter input ct state established,related accept
nft add rule inet filter input tcp dport { 80, 443 } accept
Less common rules later
nft add rule inet filter input tcp dport 22 accept
```
Use Sets for Multiple Values: More efficient than multiple rules:
```bash
nft add set inet filter web_ports { type inet_service; }
nft add element inet filter web_ports { 80, 443, 8080, 8443 }
nft add rule inet filter input tcp dport @web_ports accept
```
Maintenance Practices
Regular Backups: Automate configuration backups:
```bash
#!/bin/bash
Add to crontab for daily backups
nft list ruleset > /backup/nftables-$(date +%Y%m%d).conf
find /backup -name "nftables-*.conf" -mtime +30 -delete
```
Documentation: Comment your rules:
```bash
Use descriptive set and chain names
nft add set inet filter trusted_networks { type ipv4_addr; }
nft add chain inet filter wan_input
Keep external documentation of rule purposes
```
Testing: Always test in safe environments:
```bash
Test configuration syntax
nft -c -f /etc/nftables.conf
Use atomic loading to prevent lockouts
nft -f /tmp/test-rules.conf && echo "Rules loaded successfully"
```
Monitoring and Alerting
Log Important Events:
```bash
Log dropped packets for analysis
nft add rule inet filter input counter log prefix "DROPPED: " drop
Log successful SSH connections
nft add rule inet filter input tcp dport 22 log prefix "SSH: " accept
```
Performance Monitoring:
```bash
Monitor rule hit counts
watch -n 5 'nft list chain inet filter input'
Check for unused rules
nft list ruleset | grep "counter 0"
```
Conclusion and Next Steps
Mastering the `nft list ruleset` and `nft add rule` commands provides the foundation for effective nftables management. The `nft list ruleset` command serves as your primary tool for examining and understanding current firewall configurations, while `nft add rule` enables you to implement precise traffic control policies.
Key Takeaways
1. Understanding Structure: nftables' hierarchical organization of tables, chains, and rules provides flexibility and clarity in firewall management
2. Command Mastery: Proficiency with listing and adding rules enables effective firewall administration
3. Security Focus: Always implement security best practices, including default deny policies and principle of least privilege
4. Performance Awareness: Optimize rule order and use advanced features like sets and maps for better performance
5. Maintenance Importance: Regular backups, testing, and monitoring ensure reliable firewall operation
Next Steps for Advanced Usage
Explore Advanced Features:
- Learn about nftables scripting and automation
- Implement complex NAT and load balancing scenarios
- Master named objects and variables for better organization
- Study integration with configuration management tools
Deepen Security Knowledge:
- Investigate DDoS protection techniques
- Learn about application-layer filtering
- Explore integration with intrusion detection systems
- Study compliance requirements for your environment
Operational Excellence:
- Develop change management procedures
- Implement monitoring and alerting systems
- Create disaster recovery procedures
- Build automation for common tasks
Resources for Continued Learning:
- Official nftables documentation and wiki
- Linux networking and security courses
- Community forums and discussion groups
- Hands-on practice in lab environments
By mastering these fundamental commands and following the practices outlined in this guide, you'll be well-equipped to manage sophisticated firewall configurations that protect your systems while maintaining optimal performance. Remember that firewall management is an ongoing process requiring continuous learning, testing, and adaptation to evolving security requirements.
The transition from legacy iptables to nftables represents a significant advancement in Linux firewall technology. Embracing these modern tools and techniques will serve you well in current and future network security challenges.