How to configure nftables in Linux
How to Configure nftables in Linux
nftables is the modern Linux kernel firewall framework that serves as the successor to iptables, ip6tables, arptables, and ebtables. Introduced in Linux kernel 3.13, nftables provides a unified interface for packet filtering and classification with improved performance, simplified syntax, and enhanced flexibility. This comprehensive guide will walk you through everything you need to know about configuring nftables in Linux, from basic concepts to advanced implementations.
Table of Contents
1. [Introduction to nftables](#introduction-to-nftables)
2. [Prerequisites and Requirements](#prerequisites-and-requirements)
3. [Understanding nftables Architecture](#understanding-nftables-architecture)
4. [Installation and Setup](#installation-and-setup)
5. [Basic Configuration](#basic-configuration)
6. [Creating Tables and Chains](#creating-tables-and-chains)
7. [Writing Rules](#writing-rules)
8. [Practical Examples](#practical-examples)
9. [Advanced Configuration](#advanced-configuration)
10. [Troubleshooting Common Issues](#troubleshooting-common-issues)
11. [Best Practices](#best-practices)
12. [Conclusion](#conclusion)
Introduction to nftables
nftables represents a significant evolution in Linux firewall technology. Unlike its predecessors, nftables uses a single framework to handle all packet filtering tasks, eliminating the need for separate tools for different protocols. The framework introduces several key improvements:
- Unified syntax: One consistent command-line interface for all protocols
- Better performance: More efficient rule processing and reduced kernel overhead
- Improved scalability: Better handling of large rule sets
- Enhanced flexibility: More powerful rule matching and actions
- Atomic rule updates: Rules can be updated atomically without disrupting traffic
Prerequisites and Requirements
Before diving into nftables configuration, ensure your system meets the following requirements:
System Requirements
- Linux kernel version 3.13 or later (recommended: 4.17+)
- Root or sudo privileges for configuration
- Basic understanding of networking concepts
- Familiarity with command-line interface
Software Dependencies
Most modern Linux distributions include nftables by default. Verify installation with:
```bash
Check if nftables is installed
which nft
Check kernel support
lsmod | grep nf_tables
Verify nftables version
nft --version
```
Distribution-Specific Notes
Different Linux distributions may have varying default configurations:
- Ubuntu/Debian: nftables is available but may not be the default firewall
- CentOS/RHEL 8+: nftables is the default firewall framework
- Fedora: Uses nftables by default since version 29
- Arch Linux: nftables is available in the official repositories
Understanding nftables Architecture
nftables follows a hierarchical structure that's crucial to understand before configuration:
Core Components
1. Tables: Top-level containers that hold chains
2. Chains: Containers for rules, can be base chains or regular chains
3. Rules: Individual filtering statements with match criteria and actions
Address Families
nftables supports multiple address families:
- ip: IPv4 packets
- ip6: IPv6 packets
- inet: Both IPv4 and IPv6 packets
- arp: ARP packets
- bridge: Packets traversing bridge devices
- netdev: Packets from ingress
Hook Types
Base chains are attached to netfilter hooks:
- prerouting: Packets before routing decision
- input: Packets destined for local system
- forward: Packets being routed through the system
- output: Packets originating from local system
- postrouting: Packets after routing decision
Installation and Setup
Installing nftables
Ubuntu/Debian
```bash
sudo apt update
sudo apt install nftables
```
CentOS/RHEL/Fedora
```bash
CentOS/RHEL 8+
sudo dnf install nftables
Older versions
sudo yum install nftables
```
Arch Linux
```bash
sudo pacman -S nftables
```
Starting nftables Service
```bash
Enable and start nftables service
sudo systemctl enable nftables
sudo systemctl start nftables
Check service status
sudo systemctl status nftables
```
Initial Configuration Check
```bash
List current ruleset (should be empty initially)
sudo nft list ruleset
Check if any legacy iptables rules exist
sudo iptables -L
sudo ip6tables -L
```
Basic Configuration
Creating Your First Table
Tables are the top-level containers in nftables. Create a basic table:
```bash
Create a table for IPv4 filtering
sudo nft add table ip filter
Create a table for both IPv4 and IPv6
sudo nft add table inet firewall
List all tables
sudo nft list tables
```
Understanding Chain Types and Priorities
Chains define where and when rules are processed:
```bash
Create an input chain for incoming packets
sudo nft add chain inet firewall input { type filter hook input priority 0 \; policy accept \; }
Create an output chain for outgoing packets
sudo nft add chain inet firewall output { type filter hook output priority 0 \; policy accept \; }
Create a forward chain for routed packets
sudo nft add chain inet firewall forward { type filter hook forward priority 0 \; policy drop \; }
```
Basic Rule Structure
nftables rules follow this general syntax:
```
nft [add|insert|replace] rule [family] [table] [chain] [matches] [statement]
```
Creating Tables and Chains
Comprehensive Table Setup
Let's create a complete table structure for a typical firewall:
```bash
#!/bin/bash
Complete nftables setup script
Flush existing rules
nft flush ruleset
Create main firewall table
nft add table inet firewall
Create base chains
nft add chain inet firewall input {
type filter hook input priority 0 \;
policy drop \;
}
nft add chain inet firewall forward {
type filter hook forward priority 0 \;
policy drop \;
}
nft add chain inet firewall output {
type filter hook output priority 0 \;
policy accept \;
}
Create custom chains for organization
nft add chain inet firewall tcp_chain
nft add chain inet firewall udp_chain
nft add chain inet firewall icmp_chain
```
Chain Policies
Chain policies determine default behavior:
- accept: Allow packets by default
- drop: Silently discard packets by default
- reject: Reject packets with error message
```bash
Set different policies
nft add chain inet firewall input { type filter hook input priority 0 \; policy accept \; }
nft add chain inet firewall input { type filter hook input priority 0 \; policy drop \; }
```
Writing Rules
Basic Rule Examples
Allow Loopback Traffic
```bash
Allow all loopback traffic
nft add rule inet firewall input iif lo accept
nft add rule inet firewall output oif lo accept
```
Allow Established Connections
```bash
Allow established and related connections
nft add rule inet firewall input ct state established,related accept
nft add rule inet firewall forward ct state established,related accept
```
Allow SSH Access
```bash
Allow SSH on port 22
nft add rule inet firewall input tcp dport 22 accept
Allow SSH from specific subnet
nft add rule inet firewall input ip saddr 192.168.1.0/24 tcp dport 22 accept
```
Advanced Rule Matching
Port Ranges
```bash
Allow port range
nft add rule inet firewall input tcp dport 8000-8080 accept
Allow multiple specific ports
nft add rule inet firewall input tcp dport { 80, 443, 8080 } accept
```
IP Address Matching
```bash
Block specific IP address
nft add rule inet firewall input ip saddr 192.168.1.100 drop
Allow subnet access to web services
nft add rule inet firewall input ip saddr 10.0.0.0/8 tcp dport { 80, 443 } accept
```
Protocol-Specific Rules
```bash
ICMP rules
nft add rule inet firewall input icmp type echo-request accept
nft add rule inet firewall input icmpv6 type { echo-request, nd-neighbor-solicit, nd-neighbor-advert } accept
UDP rules
nft add rule inet firewall input udp dport 53 accept # DNS
nft add rule inet firewall input udp dport 123 accept # NTP
```
Practical Examples
Web Server Configuration
Here's a complete configuration for a web server:
```bash
#!/bin/bash
Web server nftables configuration
Flush existing rules
nft flush ruleset
Create table and chains
nft add table inet firewall
nft add chain inet firewall input { type filter hook input priority 0 \; policy drop \; }
nft add chain inet firewall forward { type filter hook forward priority 0 \; policy drop \; }
nft add chain inet firewall output { type filter hook output priority 0 \; policy accept \; }
Allow loopback
nft add rule inet firewall input iif lo accept
Allow established connections
nft add rule inet firewall input ct state established,related accept
Allow SSH (change port as needed)
nft add rule inet firewall input tcp dport 22 accept
Allow HTTP and HTTPS
nft add rule inet firewall input tcp dport 80 accept
nft add rule inet firewall input tcp dport 443 accept
Allow ICMP
nft add rule inet firewall input icmp type echo-request limit rate 1/second accept
nft add rule inet firewall input icmpv6 type { echo-request, nd-neighbor-solicit, nd-neighbor-advert } accept
Log dropped packets
nft add rule inet firewall input log prefix \"nftables-dropped: \" drop
```
Database Server Configuration
For a database server that needs to be accessible from application servers:
```bash
#!/bin/bash
Database server nftables configuration
nft flush ruleset
nft add table inet firewall
nft add chain inet firewall input { type filter hook input priority 0 \; policy drop \; }
nft add chain inet firewall output { type filter hook output priority 0 \; policy accept \; }
Basic rules
nft add rule inet firewall input iif lo accept
nft add rule inet firewall input ct state established,related accept
SSH access from management network
nft add rule inet firewall input ip saddr 10.0.100.0/24 tcp dport 22 accept
Database access from application servers
nft add rule inet firewall input ip saddr 10.0.1.0/24 tcp dport 5432 accept # PostgreSQL
nft add rule inet firewall input ip saddr 10.0.1.0/24 tcp dport 3306 accept # MySQL
Monitoring access
nft add rule inet firewall input ip saddr 10.0.200.0/24 tcp dport { 9100, 9187 } accept
ICMP
nft add rule inet firewall input icmp type echo-request accept
```
Router/Gateway Configuration
For a system acting as a router or gateway:
```bash
#!/bin/bash
Router/Gateway nftables configuration
nft flush ruleset
nft add table inet firewall
Input chain
nft add chain inet firewall input { type filter hook input priority 0 \; policy drop \; }
Forward chain for routing
nft add chain inet firewall forward { type filter hook forward priority 0 \; policy drop \; }
Output chain
nft add chain inet firewall output { type filter hook output priority 0 \; policy accept \; }
NAT table for masquerading
nft add table nat
nft add chain nat postrouting { type nat hook postrouting priority 100 \; }
Basic input rules
nft add rule inet firewall input iif lo accept
nft add rule inet firewall input ct state established,related accept
SSH access
nft add rule inet firewall input tcp dport 22 accept
Forward rules
nft add rule inet firewall forward ct state established,related accept
nft add rule inet firewall forward iifname "eth1" oifname "eth0" accept # LAN to WAN
nft add rule inet firewall forward iifname "eth0" oifname "eth1" ct state established,related accept
NAT masquerading
nft add rule nat postrouting oifname "eth0" masquerade
ICMP
nft add rule inet firewall input icmp type echo-request accept
nft add rule inet firewall forward icmp type echo-request accept
```
Advanced Configuration
Sets and Maps
Sets allow efficient matching against multiple values:
```bash
Create a set of allowed IPs
nft add set inet firewall allowed_ips { type ipv4_addr \; flags interval \; }
Add IPs to the set
nft add element inet firewall allowed_ips { 192.168.1.0/24, 10.0.0.0/8 }
Use the set in a rule
nft add rule inet firewall input ip saddr @allowed_ips accept
```
Maps provide key-value associations:
```bash
Create a map for port forwarding
nft add map inet firewall port_forward { type inet_service : ipv4_addr . inet_service \; }
Add mappings
nft add element inet firewall port_forward { 80 : 192.168.1.10 . 8080 }
Use in DNAT rule
nft add rule nat prerouting dnat tcp dport map @port_forward
```
Rate Limiting
Implement rate limiting to prevent abuse:
```bash
Limit SSH connection attempts
nft add rule inet firewall input tcp dport 22 ct state new limit rate 3/minute accept
Limit ICMP ping
nft add rule inet firewall input icmp type echo-request limit rate 1/second accept
Limit HTTP connections per IP
nft add rule inet firewall input tcp dport 80 ct state new limit rate over 20/minute drop
```
Logging and Monitoring
Configure logging for security monitoring:
```bash
Log all dropped packets
nft add rule inet firewall input log prefix \"INPUT-DROP: \" level info drop
Log specific events
nft add rule inet firewall input tcp dport 22 ct state new log prefix \"SSH-LOGIN: \" accept
Log with rate limiting
nft add rule inet firewall input log prefix \"SCAN-ATTEMPT: \" limit rate 1/minute drop
```
Connection Tracking
Leverage connection tracking for stateful filtering:
```bash
Allow related connections (like FTP data channels)
nft add rule inet firewall input ct state related accept
Drop invalid packets
nft add rule inet firewall input ct state invalid drop
Track connection states
nft add rule inet firewall input tcp dport 80 ct state new,established accept
```
Troubleshooting Common Issues
Rule Not Working
Problem: Rules don't seem to have any effect.
Solutions:
```bash
Check if rules are in the correct table and chain
nft list ruleset
Verify chain policy
nft list chain inet firewall input
Check rule order (rules are processed sequentially)
nft list chain inet firewall input -nn
Add logging to debug
nft insert rule inet firewall input position 1 log prefix \"DEBUG: \"
```
Performance Issues
Problem: nftables causing network slowdown.
Solutions:
```bash
Use sets for large lists instead of multiple rules
nft add set inet firewall blocked_ips { type ipv4_addr \; flags interval \; }
Optimize rule order (most frequent matches first)
Use connection tracking to avoid re-evaluating established connections
nft add rule inet firewall input ct state established,related accept
Monitor performance
nft monitor
```
Service Won't Start
Problem: nftables service fails to start.
Solutions:
```bash
Check service status
systemctl status nftables
Validate configuration file
nft -c -f /etc/nftables.conf
Check for syntax errors
journalctl -u nftables
Test configuration manually
nft -f /etc/nftables.conf
```
Locked Out of System
Problem: Firewall rules blocking SSH access.
Prevention and Solutions:
```bash
Always test rules before making permanent
nft -f test-rules.conf
Use at command for automatic rule removal
echo "nft flush ruleset" | at now + 10 minutes
Keep a console session open when testing
Use rescue mode or physical access if locked out
```
IPv6 Issues
Problem: IPv6 traffic not working correctly.
Solutions:
```bash
Use inet family for dual-stack rules
nft add table inet firewall
Add specific IPv6 rules if needed
nft add rule inet firewall input icmpv6 type { echo-request, nd-neighbor-solicit, nd-neighbor-advert } accept
Check IPv6 forwarding
sysctl net.ipv6.conf.all.forwarding
```
Best Practices
Configuration Management
1. Use Configuration Files: Store rules in `/etc/nftables.conf` for persistence
2. Version Control: Keep firewall configurations in version control
3. Testing Environment: Test rules in a non-production environment first
4. Documentation: Comment your rules and maintain documentation
Security Considerations
```bash
Always use default deny policies
nft add chain inet firewall input { type filter hook input priority 0 \; policy drop \; }
Log suspicious activity
nft add rule inet firewall input tcp flags syn tcp dport { 22, 23, 80, 443 } ct state new limit rate over 10/minute log prefix \"Port scan: \"
Use fail2ban integration
Configure fail2ban to work with nftables for automated blocking
Regular security audits
nft list ruleset > firewall-audit-$(date +%Y%m%d).txt
```
Performance Optimization
```bash
Use sets for multiple values
nft add set inet firewall web_ports { type inet_service \; }
nft add element inet firewall web_ports { 80, 443, 8080, 8443 }
nft add rule inet firewall input tcp dport @web_ports accept
Order rules by frequency (most common first)
Use connection tracking effectively
Minimize logging in production
```
Maintenance Procedures
1. Regular Backups:
```bash
Backup current ruleset
nft list ruleset > /backup/nftables-$(date +%Y%m%d).conf
```
2. Monitoring:
```bash
Monitor rule hits
nft list ruleset -a
Watch for changes
nft monitor
```
3. Updates and Patches:
```bash
Keep nftables updated
apt update && apt upgrade nftables # Debian/Ubuntu
dnf update nftables # Fedora/RHEL
```
Configuration File Structure
Create a well-organized `/etc/nftables.conf`:
```bash
#!/usr/sbin/nft -f
Clear existing rules
flush ruleset
Include external files for organization
include "/etc/nftables.d/defines.conf"
include "/etc/nftables.d/filter.conf"
include "/etc/nftables.d/nat.conf"
table inet firewall {
# Sets and maps
set allowed_ips {
type ipv4_addr
flags interval
elements = { 192.168.1.0/24, 10.0.0.0/8 }
}
# Chains
chain input {
type filter hook input priority 0; policy drop;
# Basic rules
iif lo accept
ct state established,related accept
# Service-specific rules
tcp dport 22 accept comment "SSH"
tcp dport { 80, 443 } accept comment "Web services"
# ICMP
icmp type echo-request limit rate 1/second accept
# Log and drop
log prefix "nftables-input-drop: " drop
}
chain forward {
type filter hook forward priority 0; policy drop;
}
chain output {
type filter hook output priority 0; policy accept;
}
}
```
Conclusion
nftables represents a significant advancement in Linux firewall technology, offering improved performance, flexibility, and ease of use compared to legacy iptables. This comprehensive guide has covered the essential aspects of nftables configuration, from basic concepts to advanced implementations.
Key takeaways include:
- Architecture Understanding: Master the hierarchical structure of tables, chains, and rules
- Practical Implementation: Use real-world examples as starting points for your configurations
- Security Focus: Always implement defense-in-depth strategies with proper logging and monitoring
- Performance Optimization: Leverage sets, maps, and proper rule ordering for optimal performance
- Maintenance: Establish proper backup, testing, and update procedures
Next Steps
To continue your nftables journey:
1. Practice: Set up a test environment and experiment with different configurations
2. Integration: Integrate nftables with other security tools like fail2ban and intrusion detection systems
3. Automation: Develop scripts and automation tools for rule management
4. Monitoring: Implement comprehensive logging and monitoring solutions
5. Advanced Features: Explore advanced features like traffic shaping and load balancing
Additional Resources
- Official nftables documentation: https://netfilter.org/projects/nftables/
- nftables wiki: https://wiki.nftables.org/
- Linux netfilter documentation
- Distribution-specific firewall guides
By following this guide and implementing the best practices outlined, you'll have a solid foundation for managing network security with nftables in Linux environments. Remember to always test configurations thoroughly and maintain proper documentation for your firewall rules.