Introduction
fail2ban works by tailing log files, matching regex patterns, then shelling out to iptables (or nftables) to insert a ban rule. That chain of dependencies (Python runtime, log parsing, regex maintenance, jail configs, action scripts) adds moving parts that break in quiet ways: a rotated log file, a changed syslog format, a Python upgrade that breaks a plugin. On Debian 12, nftables ships as the default packet filter and includes native rate limiting primitives (meters, ct count, dynamic sets with timeouts) that handle the same job inside the kernel, with zero log parsing and zero userspace daemons.
This guide removes fail2ban from a Debian 12 server and replaces it with a pure nftables ruleset that rate-limits SSH and HTTP connections, auto-blocks repeat offenders using dynamic sets with expiration, and logs drops for auditing. Every rule, every test command, and every failure mode described here was verified on Debian 12.8 (Bookworm) with nftables 1.0.6 and kernel 6.1.
Why Replace fail2ban
fail2ban is a reactive tool. It waits for a failed login to appear in a log, parses the line, then adds a firewall rule after the damage attempt already happened. The delay between the attack and the block depends on log flush intervals, inotify responsiveness, and the findtime/maxretry window you configure. On a busy server, that window can be seconds or minutes.
nftables rate limiting is proactive. The kernel evaluates every incoming packet against your meter or set rule before the connection reaches sshd or nginx. There is no log to parse, no regex to maintain, no Python process consuming memory. The rate decision happens in the netfilter hook, at wire speed relative to what the kernel network stack can process.
There are real trade-offs. fail2ban gives you granular control per application: you can write a jail for Postfix SASL failures, another for Apache 404 floods, another for Dovecot auth failures, each with different thresholds and ban durations. nftables rate limiting operates at layer 3/4 (IP addresses, ports, connection rates). It cannot distinguish between a failed SSH password and a successful one at the packet level. If you need application-layer log analysis (for example, blocking IPs that trigger specific HTTP 401 responses), nftables alone will not replace that. You would need to combine nftables with a lighter log watcher, or accept that layer-4 rate limiting is sufficient for your threat model.
For the common case of SSH brute-force protection and HTTP connection flooding, nftables rate limiting is more than sufficient and removes an entire class of failure modes.
Prerequisites
Before starting, confirm your Debian 12 system meets these conditions:
# Verify Debian versioncat /etc/debian_version# Expected: 12.x
# Verify nftables is installed (it should be by default)dpkg -l nftables# Expected: ii nftables 1.0.6-...
# Verify kernel supports nftables (Debian 12 kernel 6.1 does)uname -r# Expected: 6.1.x-amd64
# Check if nftables service existssystemctl status nftablesYou need root access or sudo privileges. Every command below assumes root unless noted otherwise.
If you are running this on a remote server, keep a second SSH session open or have out-of-band console access (IPMI, VNC, cloud provider console). A firewall misconfiguration can lock you out.
Step 1: Audit Your Current fail2ban Configuration
Before removing fail2ban, document what it protects. You need to replicate the relevant protections in nftables.
# List active jailsfail2ban-client status
# For each jail, check its configfail2ban-client status sshdTypical output:
Status for the jail: sshd|- Filter| |- Currently failed: 3| |- Total failed: 1847| `- File list: /var/log/auth.log`- Actions |- Currently banned: 2 |- Total banned: 156 `- Banned IP list: 203.0.113.45 198.51.100.12Write down:
- Which jails are active (sshd, apache-auth, postfix, etc.)
- The
maxretryandfindtimevalues for each - The
bantimefor each - Any currently banned IPs you want to keep blocked
For the SSH jail specifically, the defaults on Debian 12 are typically maxretry = 5, findtime = 10m, bantime = 10m. We will replicate equivalent behavior in nftables.
# Export currently banned IPs if you want to seed your nftables blocklistfail2ban-client status sshd | grep "Banned IP" | sed 's/.*Banned IP list:\s*//' | tr ' ' '\n' > /tmp/banned_ips.txtStep 2: Build the nftables Ruleset
Create the ruleset file. Debian 12 reads /etc/nftables.conf on service start.
Back up the existing config first:
cp /etc/nftables.conf /etc/nftables.conf.bak.$(date +%Y%m%d)Now write the new ruleset. Here is the complete file, explained section by section afterward:
cat > /etc/nftables.conf << 'NFTEOF'#!/usr/sbin/nft -f
flush ruleset
table inet filter {
# Dynamic set: IPs that exceeded the rate limit get added here # and auto-expire after 1 hour set blocklist_v4 { type ipv4_addr flags dynamic, timeout timeout 1h }
set blocklist_v6 { type ipv6_addr flags dynamic, timeout timeout 1h }
# Persistent manual blocklist (no timeout, survives reload) set denylist_v4 { type ipv4_addr flags interval }
set denylist_v6 { type ipv6_addr flags interval }
chain input { type filter hook input priority filter; policy drop;
# Loopback: accept all iif "lo" accept
# Drop anything from dynamic or manual blocklists immediately ip saddr @blocklist_v4 drop ip6 saddr @blocklist_v6 drop ip saddr @denylist_v4 drop ip6 saddr @denylist_v6 drop
# Allow established and related connections ct state established,related accept
# Drop invalid connection tracking states ct state invalid drop
# ICMP: allow ping but rate limit it ip protocol icmp icmp type echo-request limit rate 5/second accept ip6 nexthdr ipv6-icmp icmpv6 type echo-request limit rate 5/second accept
# ICMPv6 neighbor discovery (required for IPv6 to function) ip6 nexthdr ipv6-icmp icmpv6 type { nd-neighbor-solicit, nd-neighbor-advert, nd-router-solicit, nd-router-advert } accept
# SSH rate limiting (port 22) tcp dport 22 ct state new meter ssh_meter { ip saddr limit rate over 4/minute burst 6 packets } add @blocklist_v4 { ip saddr } log prefix "nft-ssh-block: " drop tcp dport 22 ct state new accept
# HTTP/HTTPS rate limiting (ports 80, 443) tcp dport { 80, 443 } ct state new meter http_meter { ip saddr limit rate over 30/second burst 50 packets } add @blocklist_v4 { ip saddr } log prefix "nft-http-block: " drop tcp dport { 80, 443 } ct state new accept
# Log and drop everything else log prefix "nft-drop: " limit rate 5/minute counter drop }
chain forward { type filter hook forward priority filter; policy drop; }
chain output { type filter hook output priority filter; policy accept; }}NFTEOFRuleset Walkthrough
The ruleset uses table inet filter, which handles both IPv4 and IPv6 in a single table. The inet family is the correct choice on dual-stack systems and avoids maintaining separate ip and ip6 tables.
Dynamic sets with timeouts. The blocklist_v4 and blocklist_v6 sets use flags dynamic, timeout with a timeout 1h. When a rate-limiting rule adds an IP to this set, the kernel automatically removes it after one hour. No cron job, no cleanup script, no daemon. The kernel handles expiration internally using a timer wheel.
Manual denylist. The denylist_v4 and denylist_v6 sets use flags interval, which allows CIDR ranges (e.g., 198.51.100.0/24). These have no timeout; entries persist until you remove them or flush the set. Use these for known-bad networks.
Connection tracking. The ct state established,related accept rule is critical. Without it, every packet in an existing connection would hit the rate-limiting rules. This rule ensures only new connection attempts (SYN packets, effectively) are evaluated against the meters.
The SSH meter rule, dissected:
tcp dport 22 ct state new meter ssh_meter { ip saddr limit rate over 4/minute burst 6 packets } add @blocklist_v4 { ip saddr } log prefix "nft-ssh-block: " dropReading left to right:
tcp dport 22matches TCP packets to port 22ct state newmatches only new connections (SYN)meter ssh_meter { ip saddr limit rate over 4/minute burst 6 packets }creates a per-source-IP rate counter. Each unique source IP gets its own counter in the meter. The threshold is 4 new connections per minute, with a burst allowance of 6 packets. The burst handles legitimate reconnections (e.g., an admin opening multiple terminals)add @blocklist_v4 { ip saddr }when the rate is exceeded, the source IP is added to the dynamic blocklistlog prefix "nft-ssh-block: "logs the event to the kernel log (dmesg/journald)dropdrops the packet
The next line, tcp dport 22 ct state new accept, catches all SSH connections that did NOT exceed the rate limit and accepts them. Rule order matters: nftables evaluates rules top to bottom within a chain, and the first terminal action (accept, drop) wins.
The HTTP meter rule follows the same pattern but with higher thresholds: 30 new connections per second with a burst of 50. These numbers are starting points. A single browser loading a page with 20 assets will open 20 connections. Adjust based on your traffic patterns.
IPv6 Rate Limiting Gap
You may have noticed the meter rules use ip saddr (IPv4 only). To add IPv6 rate limiting, duplicate the meter rules with ip6 saddr and the v6 blocklist:
tcp dport 22 ct state new meter ssh_meter_v6 { ip6 saddr limit rate over 4/minute burst 6 packets } add @blocklist_v6 { ip6 saddr } log prefix "nft-ssh6-block: " dropAdd this line directly after the IPv4 SSH meter rule, before the tcp dport 22 ct state new accept line. Do the same for HTTP. The accept rule at the end covers both address families since the table is inet.
Step 3: Validate the Ruleset Syntax
Before applying, check for syntax errors:
nft -c -f /etc/nftables.confThe -c flag runs a dry check without loading the rules into the kernel. If the command returns silently (exit code 0), the syntax is valid. If there is an error, nft prints the line number and a description:
/etc/nftables.conf:35:28-31: Error: syntax error, unexpected dport tcp dport 22 ct state new meter ssh_meter { ip saddr limit rate over 4/minute burst 6 packets } add @blocklist_v4 { ip saddr } log prefix "nft-ssh-block: " drp ^^^Common syntax mistakes:
- Missing semicolons after
policy droporpolicy accept - Using
iptables-style syntax (-A INPUT -p tcp) instead of nftables syntax - Forgetting the
flags dynamic, timeouton a set that receives dynamic additions - Using
meterwith a set type that does not match (e.g., putting anipv6_addrinto anipv4_addrset)
Step 4: Apply the Ruleset
If you are on a remote server, set a safety net first. This cron job will flush all rules after 5 minutes, restoring connectivity if you lock yourself out:
echo "$(date -d '+5 minutes' '+%M %H %d %m') * root /usr/sbin/nft flush ruleset" >> /etc/crontabNow apply:
nft -f /etc/nftables.confVerify the rules loaded:
nft list rulesetYou should see the full ruleset printed back. Verify you can still SSH in by opening a new terminal and connecting. If the new connection works, remove the safety cron entry:
# Edit /etc/crontab and remove the flush line you addednano /etc/crontabEnable the nftables service so the ruleset loads on boot:
systemctl enable nftablessystemctl restart nftablesVerify the service loaded the rules after restart:
systemctl status nftablesnft list ruleset | head -20Step 5: Remove fail2ban
Only do this after confirming nftables is working and you can still access the server:
# Stop and disable fail2bansystemctl stop fail2bansystemctl disable fail2ban
# Remove the packageapt purge fail2ban
# Clean up leftover configrm -rf /etc/fail2banCheck that no iptables rules were left behind by fail2ban’s actions:
iptables -L -nip6tables -L -nOn a clean Debian 12 system with nftables as the backend, these commands should show empty chains or the nftables-translated output. If you see leftover fail2ban chains (like f2b-sshd), flush them:
iptables -F f2b-sshd 2>/dev/nulliptables -X f2b-sshd 2>/dev/nullStep 6: Testing the Rate Limiting
Testing is the part most guides skip. You need to verify that the rate limiting actually triggers, that the blocklist gets populated, and that legitimate traffic still passes.
Test SSH Rate Limiting
From a test machine (not your production SSH session), use a loop to rapidly attempt SSH connections:
# Run this from a DIFFERENT machine, not the server itselffor i in $(seq 1 15); do ssh -o ConnectTimeout=2 -o StrictHostKeyChecking=no user@your-server-ip exit 2>/dev/null echo "Attempt $i: exit code $?"doneAfter the burst threshold (6 packets) is consumed and the rate (4/minute) is exceeded, subsequent connections should hang or be refused. On the server, check:
# Check if the test IP was added to the blocklistnft list set inet filter blocklist_v4
# Expected output includes the test IP:# set blocklist_v4 {# type ipv4_addr# flags dynamic,timeout# timeout 1h# elements = { 203.0.113.99 timeout 1h expires 59m45s }# }Check the kernel log for the log prefix:
journalctl -k --since "5 minutes ago" | grep "nft-ssh-block"# Expected:# Nov 26 09:15:23 server kernel: nft-ssh-block: IN=eth0 OUT= MAC=... SRC=203.0.113.99 DST=192.0.2.1 ... DPT=22 ...Test HTTP Rate Limiting
Use ab (Apache Bench) or hey from a test machine:
# Install ab if needed (on the test machine, not the server)apt install apache2-utils
# Send 200 concurrent requestsab -n 200 -c 50 http://your-server-ip/Or with curl in a loop:
for i in $(seq 1 100); do curl -s -o /dev/null -w "%{http_code} " http://your-server-ip/ &donewaitOn the server, verify the blocklist:
nft list set inet filter blocklist_v4journalctl -k --since "5 minutes ago" | grep "nft-http-block"Test Blocklist Expiration
After adding a test IP to the blocklist, you can watch the timeout count down:
# Check remaining timenft list set inet filter blocklist_v4# elements = { 203.0.113.99 timeout 1h expires 58m12s }
# Or manually add a test entry with a short timeout to verify expiration worksnft add element inet filter blocklist_v4 { 192.0.2.99 timeout 30s }
# Wait 30 seconds, then check againsleep 35nft list set inet filter blocklist_v4# 192.0.2.99 should be goneTest Manual Denylist
# Add a single IPnft add element inet filter denylist_v4 { 198.51.100.50 }
# Add a CIDR rangenft add element inet filter denylist_v4 { 198.51.100.0/24 }
# Verifynft list set inet filter denylist_v4
# Remove an entrynft delete element inet filter denylist_v4 { 198.51.100.50 }Verify Legitimate Traffic Still Works
This is as important as testing the blocks. From your normal workstation:
# SSH should work normally (single connection)ssh user@your-server-ip "echo 'SSH works'"
# HTTP should work normally (single request)curl -I http://your-server-ip/If legitimate traffic is getting blocked, your rate thresholds are too aggressive. See the Tuning section below.
Step 7: Seeding the Blocklist with Previously Banned IPs
If you exported banned IPs from fail2ban in Step 1:
# Add each previously banned IP to the manual denylistwhile read -r ip; do [ -n "$ip" ] && nft add element inet filter denylist_v4 { "$ip" }done < /tmp/banned_ips.txtIf you want these in the auto-expiring blocklist instead (so they expire after 1 hour):
while read -r ip; do [ -n "$ip" ] && nft add element inet filter blocklist_v4 { "$ip" timeout 1h }done < /tmp/banned_ips.txtTo make manual denylist entries persist across reboots, add them to /etc/nftables.conf inside the set definition:
set denylist_v4 { type ipv4_addr flags interval elements = { 198.51.100.0/24, 203.0.113.45 }}Tuning Rate Limit Thresholds
The thresholds in the example ruleset (4/minute for SSH, 30/second for HTTP) are starting points. Here is how to decide on values for your environment.
SSH Tuning
Legitimate SSH usage patterns:
- A sysadmin opens 1-3 sessions in quick succession (terminal, scp, rsync). That is 3 new connections in a few seconds.
- Automated tools (Ansible, rsync cron jobs) might open 1 connection per run.
- Git over SSH (if you host repos) might open 1 connection per push/pull.
A rate of 4/minute with a burst of 6 means: the first 6 connections are always allowed (burst), then after that, a maximum of 4 new connections per minute per source IP. An admin opening 5 terminals in 10 seconds will use 5 of the 6 burst tokens and be fine. A brute-force bot sending 100 connection attempts per minute will burn through the burst in under a second and get blocklisted.
If you use Ansible or other automation that opens many parallel SSH connections, raise the burst:
meter ssh_meter { ip saddr limit rate over 4/minute burst 20 packets }If your server is a Git host with many developers, consider rate limiting per subnet instead of per IP, or raise the rate:
meter ssh_meter { ip saddr limit rate over 10/minute burst 15 packets }HTTP Tuning
HTTP is harder to tune because legitimate traffic varies enormously. A single page load can generate 1 request (API call) or 80 requests (page with many assets, before HTTP/2 multiplexing reduces connection count).
With HTTP/2 and HTTP/3, most browsers multiplex requests over a single TCP connection. The ct state new filter means your meter only counts new TCP connections (SYN packets), not individual HTTP requests within a connection. So 30 new connections per second is actually quite generous for browser traffic.
For API servers where each request opens a new connection (common with some HTTP clients that do not reuse connections), you may need to raise this:
meter http_meter { ip saddr limit rate over 100/second burst 200 packets }For static sites behind a CDN where direct hits should be rare:
meter http_meter { ip saddr limit rate over 10/second burst 20 packets }Monitoring to Inform Tuning
Watch the meters to see actual traffic patterns:
# List meter contents (shows per-IP counters)nft list meter inet filter ssh_meternft list meter inet filter http_meter
# Watch blocklist additions in real timejournalctl -kf | grep "nft-ssh-block\|nft-http-block"If you see legitimate IPs appearing in the blocklist, your thresholds need adjustment. Check the meter to see what rate they were hitting:
nft list meter inet filter ssh_meterThis shows each tracked IP and its current token bucket state.
Advanced: Per-Port and Per-Service Rate Limiting
The basic ruleset covers SSH and HTTP. Here are patterns for other services.
SMTP Rate Limiting (Port 25)
Mail servers need careful rate limiting. Legitimate mail servers retry on temporary failures, so blocking too aggressively causes mail loss.
# Allow 5 new SMTP connections per minute per source IPtcp dport 25 ct state new meter smtp_meter { ip saddr limit rate over 5/minute burst 10 packets } add @blocklist_v4 { ip saddr timeout 30m } log prefix "nft-smtp-block: " droptcp dport 25 ct state new acceptNote the shorter timeout (30 minutes instead of 1 hour). Legitimate mail servers will retry after the block expires. Spambots typically move on.
DNS Rate Limiting (Port 53, UDP)
DNS is UDP, so connection tracking works differently. Use packet rate instead:
udp dport 53 meter dns_meter { ip saddr limit rate over 50/second burst 100 packets } add @blocklist_v4 { ip saddr timeout 10m } log prefix "nft-dns-block: " dropudp dport 53 acceptProtecting Multiple Ports with a Single Meter
If you want a single rate limit across all services for a given IP (total connection rate regardless of port):
ct state new meter global_meter { ip saddr limit rate over 60/second burst 100 packets } add @blocklist_v4 { ip saddr } log prefix "nft-global-block: " dropPlace this before the per-service rules. An IP that exceeds 60 new connections per second across all ports gets blocklisted regardless of which service it targets.
Advanced: Longer Ban Durations with Recidivism Detection
fail2ban has a recidive jail that increases ban duration for repeat offenders. You can replicate this in nftables with a second set and a second timeout.
The concept: when an IP is added to blocklist_v4 (1-hour ban), also check if it is already in a repeat_offenders set. If it is, add it to a longban_v4 set with a 24-hour timeout instead.
# Add these sets to the tableset repeat_offenders_v4 { type ipv4_addr flags dynamic, timeout timeout 2h}
set longban_v4 { type ipv4_addr flags dynamic, timeout timeout 24h}Then modify the input chain to check for repeat offenders before the regular blocklist:
# Drop long-banned IPs firstip saddr @longban_v4 drop
# Check if incoming blocked IP is a repeat offenderip saddr @repeat_offenders_v4 ip saddr @blocklist_v4 add @longban_v4 { ip saddr } log prefix "nft-longban: " drop
# Drop blocklisted IPsip saddr @blocklist_v4 dropAnd in the meter rules, add the IP to repeat_offenders_v4 as well:
tcp dport 22 ct state new meter ssh_meter { ip saddr limit rate over 4/minute burst 6 packets } add @blocklist_v4 { ip saddr } add @repeat_offenders_v4 { ip saddr } log prefix "nft-ssh-block: " dropThe flow: first offense puts the IP in blocklist_v4 (1h) and repeat_offenders_v4 (2h). If the IP comes back within 2 hours and triggers the rate limit again, it is already in repeat_offenders_v4, so it gets added to longban_v4 (24h).
This is not as granular as fail2ban’s recidive jail with its escalating ban times, but it covers the common case of persistent attackers.
Persisting Dynamic Set Contents Across Reboots
One limitation of nftables dynamic sets: their contents live in kernel memory and are lost on reboot. The timeout flag means entries expire anyway, so for the auto-expiring blocklist_v4, this is usually fine. But if you want to preserve blocklist entries across reboots (for example, the longban_v4 set), you need a save/restore mechanism.
Create a systemd service that dumps set contents on shutdown and restores them on startup:
cat > /etc/systemd/system/nftables-sets-persist.service << 'EOF'[Unit]Description=Persist nftables dynamic sets across rebootsAfter=nftables.serviceRequires=nftables.service
[Service]Type=oneshotRemainAfterExit=yesExecStart=/usr/local/sbin/nft-sets-restore.shExecStop=/usr/local/sbin/nft-sets-save.sh
[Install]WantedBy=multi-user.targetEOFcat > /usr/local/sbin/nft-sets-save.sh << 'SAVEOF'#!/bin/bash# Save dynamic set contentsfor setname in blocklist_v4 blocklist_v6 longban_v4 repeat_offenders_v4; do nft list set inet filter "$setname" > "/var/lib/nftables/${setname}.nft" 2>/dev/nulldoneSAVEOF
cat > /usr/local/sbin/nft-sets-restore.sh << 'RESTEOF'#!/bin/bash# Restore dynamic set contentsDIR="/var/lib/nftables"[ -d "$DIR" ] || exit 0for f in "$DIR"/*.nft; do [ -f "$f" ] || continue # Extract elements and add them back grep -oP 'elements = \{[^}]+\}' "$f" | while read -r line; do setname=$(basename "$f" .nft) elements=$(echo "$line" | sed 's/elements = { //;s/ }//') IFS=',' read -ra ADDR <<< "$elements" for elem in "${ADDR[@]}"; do elem=$(echo "$elem" | xargs) [ -n "$elem" ] && nft add element inet filter "$setname" { "$elem" } 2>/dev/null done donedoneRESTEOF
chmod +x /usr/local/sbin/nft-sets-save.sh /usr/local/sbin/nft-sets-restore.shmkdir -p /var/lib/nftables
systemctl daemon-reloadsystemctl enable nftables-sets-persistThis is a pragmatic approach. The save script runs on service stop (which happens during shutdown), and the restore script runs after nftables loads the base ruleset on startup. Entries that had already expired will fail to re-add silently, which is the correct behavior.
Troubleshooting
Problem: Locked Out of SSH After Applying Rules
Symptom: Cannot SSH into the server after loading the nftables ruleset.
Cause 1: The ct state established,related accept rule is missing or misordered. Without it, existing SSH sessions are dropped because return packets do not match any accept rule.
Fix: Use out-of-band console access and check:
nft list chain inet filter input | head -20Verify ct state established,related accept appears before the rate-limiting rules.
Cause 2: The policy drop is active but the SSH accept rule is missing or has a syntax error.
Fix: From the console:
# Emergency: flush all rules (allows all traffic)nft flush ruleset
# Then fix /etc/nftables.conf and re-applyProblem: Legitimate Users Getting Blocked
Symptom: Users report intermittent connection failures. Their IPs appear in blocklist_v4.
Diagnosis:
nft list set inet filter blocklist_v4# Check if the user's IP is listed
journalctl -k | grep "nft-ssh-block" | grep "SRC=<user-ip>"# Check how many times they triggered the rate limitCause: Rate thresholds too low for the usage pattern. Common with offices sharing a single NAT IP (many users behind one public IP).
Fix: Either raise the rate/burst for that service, or add the office IP to an allowlist set:
set allowlist_v4 { type ipv4_addr flags interval elements = { 203.0.113.0/24 }}Add this rule before the rate-limiting rules:
ip saddr @allowlist_v4 acceptProblem: Meter Not Counting Connections
Symptom: nft list meter inet filter ssh_meter shows no entries even though SSH connections are happening.
Cause 1: The ct state new condition is filtering out packets you expect to match. If connection tracking is not loaded or is broken, no packets have ct state new.
Diagnosis:
# Check if conntrack module is loadedlsmod | grep nf_conntrack# If empty:modprobe nf_conntrackCause 2: SSH is on a non-standard port but the rule matches port 22.
Fix: Change tcp dport 22 to match your actual SSH port.
Problem: Log Messages Not Appearing
Symptom: journalctl -k | grep nft- shows nothing, even though the blocklist is getting populated.
Cause: The log statement might be rate-limited by the kernel’s net.core.message_burst setting, or rsyslog/journald is filtering kernel messages.
Diagnosis:
# Check kernel log rate limitingsysctl net.core.message_burstsysctl net.core.message_cost
# Temporarily disable kernel log rate limitingsysctl -w net.core.message_burst=1000sysctl -w net.core.message_cost=0Also check if the log rule is placed correctly. In the example ruleset, the log action is part of the meter rule (same line as drop). If you split them into separate rules, make sure the log rule fires before the drop.
Problem: nftables Service Fails to Start on Boot
Symptom: systemctl status nftables shows failure after reboot.
Diagnosis:
journalctl -u nftables --no-pagerCommon error:
Error: Could not process rule: No such file or directory/etc/nftables.conf:12:4-20: Error: Could not process rule: No such file or directory meter ssh_meter { ip saddr limit rate over 4/minute burst 6 packets }Cause: The meter feature requires kernel module nft_meter (or nft_limit depending on kernel version). On minimal Debian installs, this module might not auto-load.
Fix:
modprobe nft_limitecho "nft_limit" >> /etc/modules-load.d/nftables.confProblem: High Memory Usage from Meter/Set
Symptom: Under a DDoS with millions of source IPs, the meter and dynamic sets consume significant kernel memory.
Diagnosis:
# Check set sizesnft list meter inet filter ssh_meter | wc -lnft list set inet filter blocklist_v4 | wc -lMitigation: Add a size limit to your sets and meters:
set blocklist_v4 { type ipv4_addr flags dynamic, timeout timeout 1h size 65536}When the set reaches 65536 entries, new additions silently fail. This caps memory usage at a predictable level. For serious DDoS, you need upstream mitigation (provider-level null routing, BGP blackholing) anyway. nftables rate limiting protects against brute-force and small-scale abuse, not volumetric DDoS.
Comparing fail2ban and nftables Rate Limiting
| Aspect | fail2ban | nftables rate limiting |
|---|---|---|
| Detection layer | Application logs (layer 7) | Packet filter (layer 3/4) |
| Reaction time | Seconds to minutes (log parse delay) | Immediate (kernel evaluates every SYN) |
| Resource usage | Python daemon, inotify watches, regex engine | Zero userspace, kernel memory for sets/meters |
| Granularity | Per-application, per-failure-type | Per-IP, per-port, per-connection-rate |
| Auth failure detection | Yes (reads failed password from log) | No (cannot distinguish auth success/failure) |
| Configuration complexity | Jail files, filter files, action files | Single nftables.conf |
| IPv6 support | Partial (requires separate config) | Native (inet family handles both) |
| Ban persistence | SQLite database survives reboot | Dynamic sets lost on reboot without custom persistence |
| Custom application rules | Write a regex filter for any log format | Not possible at layer 4 |
The right choice depends on what you are protecting against. For SSH brute-force and HTTP connection floods, nftables rate limiting is simpler, faster, and has fewer failure modes. For application-specific abuse detection (failed logins to a web app, repeated 404 scanning, SMTP auth failures), fail2ban or a similar log analyzer still has a role.
A hybrid approach works too: use nftables rate limiting as the first layer (catch the obvious floods at the kernel level) and keep a lightweight fail2ban with only the application-specific jails you actually need. Remove the sshd jail since nftables handles that, and keep only jails for services where log-level detection matters.
Monitoring and Maintenance
Daily Check Script
cat > /usr/local/sbin/nft-status.sh << 'EOF'#!/bin/bashecho "=== nftables blocklist (IPv4) ==="nft list set inet filter blocklist_v4 2>/dev/null | grep -c "expires"echo "entries currently blocked"echo ""echo "=== Recent blocks (last hour) ==="journalctl -k --since "1 hour ago" --no-pager 2>/dev/null | grep -c "nft-ssh-block"echo "SSH blocks"journalctl -k --since "1 hour ago" --no-pager 2>/dev/null | grep -c "nft-http-block"echo "HTTP blocks"echo ""echo "=== Meter sizes ==="echo -n "SSH meter entries: "nft list meter inet filter ssh_meter 2>/dev/null | grep -c "limit"echo -n "HTTP meter entries: "nft list meter inet filter http_meter 2>/dev/null | grep -c "limit"EOFchmod +x /usr/local/sbin/nft-status.shLog Rotation
Kernel log messages from nftables go through journald on Debian 12. If you forward them to syslog, make sure /var/log/kern.log is rotated. The limit rate 5/minute on the catch-all drop rule prevents log flooding, but the per-service block logs do not have a rate limit. Under sustained attack, these can fill disk. Add rate limiting to the log statements:
tcp dport 22 ct state new meter ssh_meter { ip saddr limit rate over 4/minute burst 6 packets } add @blocklist_v4 { ip saddr } log prefix "nft-ssh-block: " limit rate 10/minute dropThe limit rate 10/minute on the log action means at most 10 log entries per minute for SSH blocks, regardless of how many IPs trigger the rule.
Manually Unblocking an IP
# Remove from dynamic blocklistnft delete element inet filter blocklist_v4 { 203.0.113.99 }
# Remove from manual denylistnft delete element inet filter denylist_v4 { 203.0.113.99 }
# Remove from longbannft delete element inet filter longban_v4 { 203.0.113.99 }Flushing All Dynamic Entries
# Clear all auto-blocked IPs (keeps the set, removes all entries)nft flush set inet filter blocklist_v4nft flush set inet filter blocklist_v6
# Clear meters (resets all per-IP rate counters)nft flush meter inet filter ssh_meternft flush meter inet filter http_meterComplete Production Ruleset
Here is the full production-ready /etc/nftables.conf incorporating all the features discussed, including IPv6 rate limiting, allowlists, recidivism detection, and rate-limited logging:
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
set allowlist_v4 { type ipv4_addr flags interval # Add your trusted IPs/ranges here # elements = { 203.0.113.0/24 } }
set allowlist_v6 { type ipv6_addr flags interval }
set blocklist_v4 { type ipv4_addr flags dynamic, timeout timeout 1h size 65536 }
set blocklist_v6 { type ipv6_addr flags dynamic, timeout timeout 1h size 65536 }
set longban_v4 { type ipv4_addr flags dynamic, timeout timeout 24h size 65536 }
set repeat_offenders_v4 { type ipv4_addr flags dynamic, timeout timeout 2h size 65536 }
set denylist_v4 { type ipv4_addr flags interval }
set denylist_v6 { type ipv6_addr flags interval }
chain input { type filter hook input priority filter; policy drop;
# Loopback iif "lo" accept
# Allowlists (skip all rate limiting) ip saddr @allowlist_v4 accept ip6 saddr @allowlist_v6 accept
# Blocklists (longest ban first) ip saddr @denylist_v4 drop ip6 saddr @denylist_v6 drop ip saddr @longban_v4 drop ip saddr @blocklist_v4 drop ip6 saddr @blocklist_v6 drop
# Connection tracking ct state established,related accept ct state invalid drop
# ICMP ip protocol icmp icmp type echo-request limit rate 5/second accept ip6 nexthdr ipv6-icmp icmpv6 type echo-request limit rate 5/second accept ip6 nexthdr ipv6-icmp icmpv6 type { nd-neighbor-solicit, nd-neighbor-advert, nd-router-solicit, nd-router-advert } accept
# SSH rate limiting (IPv4) tcp dport 22 ct state new meter ssh_meter { ip saddr limit rate over 4/minute burst 6 packets } add @blocklist_v4 { ip saddr } add @repeat_offenders_v4 { ip saddr } log prefix "nft-ssh-block: " limit rate 10/minute drop
# SSH rate limiting (IPv6) tcp dport 22 ct state new meter ssh_meter_v6 { ip6 saddr limit rate over 4/minute burst 6 packets } add @blocklist_v6 { ip6 saddr } log prefix "nft-ssh6-block: " limit rate 10/minute drop
# SSH accept (both families, covers connections that passed rate check) tcp dport 22 ct state new accept
# HTTP/HTTPS rate limiting (IPv4) tcp dport { 80, 443 } ct state new meter http_meter { ip saddr limit rate over 30/second burst 50 packets } add @blocklist_v4 { ip saddr } add @repeat_offenders_v4 { ip saddr } log prefix "nft-http-block: " limit rate 10/minute drop
# HTTP/HTTPS rate limiting (IPv6) tcp dport { 80, 443 } ct state new meter http_meter_v6 { ip6 saddr limit rate over 30/second burst 50 packets } add @blocklist_v6 { ip6 saddr } log prefix "nft-http6-block: " limit rate 10/minute drop
# HTTP/HTTPS accept tcp dport { 80, 443 } ct state new accept
# Catch-all: log and drop log prefix "nft-drop: " limit rate 5/minute counter drop }
chain forward { type filter hook forward priority filter; policy drop; }
chain output { type filter hook output priority filter; policy accept; }}Validate before applying:
nft -c -f /etc/nftables.conf && echo "Syntax OK" || echo "Syntax error"Kernel Parameters Worth Tuning
A few sysctl values affect how nftables connection tracking and rate limiting behave under load:
# Maximum tracked connections (default 65536, raise for busy servers)sysctl -w net.netfilter.nf_conntrack_max=262144
# Timeout for established TCP connections (default 432000 = 5 days, lower saves memory)sysctl -w net.netfilter.nf_conntrack_tcp_timeout_established=86400
# Hash table size for conntrack (set before loading nf_conntrack, or in modprobe.d)echo "options nf_conntrack hashsize=32768" > /etc/modprobe.d/nf_conntrack.confMake persistent:
cat >> /etc/sysctl.d/99-nftables.conf << EOFnet.netfilter.nf_conntrack_max = 262144net.netfilter.nf_conntrack_tcp_timeout_established = 86400EOFsysctl --systemFinal Verification Checklist
Run through this list after completing the migration:
# 1. nftables service is enabled and runningsystemctl is-enabled nftables && systemctl is-active nftables
# 2. Ruleset is loadednft list ruleset | grep -q "chain input" && echo "Ruleset loaded"
# 3. fail2ban is removed! systemctl is-active fail2ban 2>/dev/null && echo "fail2ban stopped"! dpkg -l fail2ban 2>/dev/null | grep -q "^ii" && echo "fail2ban removed"
# 4. SSH works (test from another machine)# ssh user@server "echo OK"
# 5. Rate limiting triggers (test from another machine)# Run the SSH loop test from Step 6
# 6. Blocked IPs expire (add test entry with short timeout)nft add element inet filter blocklist_v4 { 192.0.2.99 timeout 10s }sleep 15nft list set inet filter blocklist_v4 | grep -q "192.0.2.99" && echo "FAIL: entry did not expire" || echo "OK: entry expired"
# 7. Rules survive reboot# reboot# nft list ruleset | grep -q "chain input" && echo "Rules survived reboot"This migration removes a Python daemon, its log-parsing regex engine, its SQLite database, its jail configuration files, and its action scripts. What remains is a single configuration file, evaluated by the kernel, with no userspace dependencies. The server’s attack surface shrinks, its memory footprint drops, and the rate limiting happens before a connection reaches any listening service.