Skip to content
masdzub.com
~/articles/linux — one from the notebook

Rate-limiting SSH with nftables Meters: A High-Performance Alternative to Fail2ban

Replace Fail2ban with native nftables meters for kernel-level SSH rate-limiting. Reduce CPU overhead and eliminate log-parsing latency on Linux servers.

masdzub@website:~$ cat ~/articles/rate-limit-ssh-with-nftables-meters-instead-of-fail2ban.aspx.md
# 1 file · 11 min read · topic: linux · status: published

Introduction

Fail2ban is the traditional choice for protecting SSH from brute force attacks, but it relies on an inefficient architecture for modern high-traffic environments. It operates in userspace, constantly tailing log files, parsing strings with regular expressions, and calling external binaries to update firewall rules. This creates a latency gap between the attack and the block, often allowing hundreds of failed attempts before the ban takes effect. On low-resource systems like small VPS instances or embedded devices, the Python-based Fail2ban process can consume significant CPU and memory.

Nftables meters provide a native, kernel-level solution that handles rate-limiting entirely within the network stack. By using dynamic sets, nftables can track source IP addresses, count connection attempts in real-time, and apply temporary or permanent bans without ever leaving the kernel. This approach eliminates log-parsing overhead and ensures that a malicious actor is throttled or blocked at the very first packet that exceeds the defined threshold.

The Performance Cost of Log-Based Security

Log-based security tools like Fail2ban or SSHGuard work by reacting to historical data. When a user attempts to log in via SSH, the sshd daemon writes a line to /var/log/auth.log or the systemd journal. Fail2ban must wait for the disk I/O to complete, scan the new lines, match them against a regex pattern, and then execute an iptables or nft command. In a coordinated distributed brute force attack, this delay is a vulnerability.

The resource consumption of Fail2ban is also non-trivial. Python’s memory footprint and the CPU cycles required for regex matching on every log entry can lead to performance degradation during heavy attacks. If the log file grows rapidly, the parsing process slows down further, creating a feedback loop where the firewall becomes less responsive as the attack intensity increases.

Nftables moves this logic to the Netfilter subsystem. Instead of parsing “Failed password for root,” the kernel tracks the TCP SYN packets or the frequency of new connections to port 22. This is done using hash tables that are highly optimized for lookup speed. A system using nftables meters can handle thousands of connection attempts per second with negligible impact on system load, making it the superior choice for hardening public-facing servers.

Understanding Nftables Dynamic Sets and Meters

In older versions of nftables, the meter keyword was the primary way to handle rate-limiting. In modern versions (nftables 0.9.3 and later), meters have been unified with dynamic sets. A dynamic set is a collection of data, such as IP addresses, that can be updated automatically based on rule matches. These sets support timeouts, allowing the kernel to automatically remove an IP address after a specified duration.

The core mechanism involves the update keyword. When a packet matches a rule, the kernel looks up the source IP in a set. If the IP is not present, it is added. If it is present, its state (such as a packet counter or a timestamp) is updated. You can then apply a limit statement to that set. If the limit is exceeded, the rule performs an action, such as dropping the packet or logging the event.

This stateful tracking is stored in memory-efficient structures. Unlike static blacklists, dynamic sets are volatile by default, though they can be made persistent. For SSH protection, volatility is often desired because it prevents the firewall configuration from bloating over time with thousands of stale IP addresses that no longer pose a threat.

Implementing the Basic Rate Limiter

To replace Fail2ban, you must define a table and a chain that intercepts incoming SSH traffic. The following configuration creates an inet table (which covers both IPv4 and IPv6) and a set to track connection attempts.

Create or edit /etc/nftables.conf with the following structure:

table inet filter {
set ssh_meter {
type ipv4_addr
size 65535
flags dynamic, timeout
timeout 5m
}
chain input {
type filter hook input priority 0; policy accept;
# Allow established traffic
ct state established,related accept
# Rate limit new SSH connections
tcp dport 22 ct state new_update @ssh_meter { ip saddr timeout 1m limit rate over 2/minute } log prefix "SSH-REJECT: " reject
tcp dport 22 ct state new accept
}
}

In this configuration, the ssh_meter set tracks IPv4 addresses. The flags dynamic, timeout line is critical because it allows the set to be modified by rules and ensures entries expire. The rule checks for new TCP connections to port 22. If an IP address attempts more than two connections per minute, it is added to the set with a one-minute timeout, and the packet is rejected. The log statement ensures you can monitor these rejections in dmesg or your system logs.

Handling IPv6 Brute Force Attempts

IPv6 requires a different strategy than IPv4. Because an attacker can have an entire /64 subnet, banning a single IPv6 address is often useless; the attacker simply rotates to the next address in the block. To counter this, your nftables configuration should limit based on a prefix rather than a specific address.

Modify the set and the rule to handle IPv6 prefixes:

set ssh_meter6 {
type ipv6_addr
size 65535
flags dynamic, timeout
timeout 5m
}
# Inside the input chain
tcp dport 22 ct state new add @ssh_meter6 { ip6 saddr & ffff:ffff:ffff:ffff:: timeout 1m limit rate over 2/minute } log prefix "SSH6-REJECT: " reject

By applying the bitwise AND operator & ffff:ffff:ffff:ffff::, you mask the source address to its /64 prefix. Any connection attempt from any address within that /64 will count toward the same rate limit. This effectively neutralizes prefix-rotation attacks which are common in the IPv6 landscape.

Advanced Protection with Burst Limits

A simple “X per minute” limit can sometimes be too restrictive for legitimate users who might have multiple SSH sessions opening simultaneously (e.g., using Ansible or SCP). To solve this, nftables supports burst limits. This allows a user to open a few connections quickly but throttles them if they continue at that high rate.

tcp dport 22 ct state new update @ssh_meter { ip saddr timeout 5m limit rate over 5/minute burst 3 packets } reject

In this example, the burst 3 packets parameter allows a user to initiate three connections immediately. Once those three are used, the user is limited to five connections per minute. If they exceed this, the IP is throttled. The timeout is set to five minutes, meaning the “penalty” for exceeding the limit lasts long enough to discourage automated scripts.

Whitelisting Trusted Networks

One of the biggest risks of aggressive rate-limiting is locking yourself out. You should always include a whitelist of trusted IP addresses or networks that are exempt from the rate limits. This is best handled by a separate static set.

table inet filter {
set whitelist {
type ipv4_addr
elements = { 192.168.1.0/24, 203.0.113.50 }
}
chain input {
type filter hook input priority 0; policy accept;
# Whitelist check
ip saddr @whitelist tcp dport 22 accept
# Rate limiting logic follows...
}
}

By placing the whitelist check before the rate-limiting rule, packets from trusted sources are accepted immediately and never reach the update @ssh_meter logic. This ensures that your management workstation or internal automation tools are never accidentally banned during intensive operations.

Logging and Monitoring the Firewall

Unlike Fail2ban, which has its own log file (/var/log/fail2ban.log), nftables logs directly to the kernel ring buffer. You can view these logs using journalctl -k or dmesg. To make these logs more useful, use specific prefixes and limit the logging rate to prevent the firewall itself from flooding your disks during a massive attack.

tcp dport 22 ct state new update @ssh_meter { ip saddr limit rate over 2/minute } log prefix "NFT-SSH-BAN: " limit rate 1/second stop reject

The limit rate 1/second stop ensures that even if you are receiving 1,000 bad packets per second, only one log entry per second is written. This prevents an attacker from filling your disk space by intentionally triggering the rate limiter. For real-time monitoring, you can use the nft monitor command, which shows set updates and rule matches as they happen in the kernel.

Persistence and Systemd Integration

Nftables rules are not persistent by default. If the server reboots, the rules are lost unless they are loaded by a service. Most Linux distributions (Debian, Ubuntu, RHEL, Arch) use a systemd service that loads rules from /etc/nftables.conf.

To ensure your SSH protection is active on boot:

  1. Validate the syntax: nft -c -f /etc/nftables.conf
  2. Enable the service: systemctl enable nftables
  3. Start the service: systemctl start nftables

If you make changes to your rules, always use nft -f /etc/nftables.conf to reload them atomically. This replaces the entire ruleset in a single transaction, ensuring there is no window where the firewall is “open” during the reload process.

Comparison: Nftables vs. Fail2ban vs. Iptables

FeatureFail2banIptables (hashlimit)Nftables (Meters)
LayerUserspace (Python)KernelKernel
TriggerLog File ParsingPacket ArrivalPacket Arrival
LatencyHigh (Seconds)Low (Microseconds)Low (Microseconds)
IPv6 SupportGood (with backend)Separate (ip6tables)Native (inet table)
ComplexityHigh (Regex/Actions)ModerateLow (Integrated)
ResourcesHigh RAM/CPULowVery Low

Fail2ban remains useful for complex application-level protection (like WordPress logins or SMTP auth) where the kernel cannot see the “failure” inside the encrypted payload. However, for network-level services like SSH, where the failure is often visible through connection frequency, nftables is significantly more efficient.

Troubleshooting Common Issues

When moving away from Fail2ban, you might encounter issues where rules do not behave as expected. The most common error is related to the ct state (conntrack state). Nftables relies on the connection tracking module. If established,related packets are not accepted at the top of your chain, the rate-limiter will trigger on every packet of an active SSH session, cutting off your connection mid-stream.

Error: Could not process rule: No such file or directory This usually occurs if the table or chain you are trying to add a rule to does not exist. Ensure your script defines the table before adding sets or rules to it.

Problem: IPs are not being removed from the set Check the timeout flag. If you define a set without the timeout flag, entries are permanent until manually deleted. For SSH rate-limiting, always use flags dynamic, timeout.

Problem: Locked out after one failed attempt Verify your limit rate. If you set it to 1/hour, a single typo in your password might trigger the ban. Start with a more generous limit like 5/minute and tighten it as you confirm the rules are working correctly.

Case Study: Mitigating a High-Intensity Brute Force Attack

Consider a scenario where a public jump host is targeted by a botnet. The botnet uses 500 different IP addresses, each attempting to log in once every 10 seconds. Fail2ban would struggle here because the aggregate log volume is high, but the per-IP frequency is low.

With nftables, you can adjust the set’s memory size to accommodate thousands of IPs and extend the tracking window. By setting a timeout 24h and a limit rate over 10/day, you can catch “low and slow” attackers that Fail2ban might miss unless configured with very long findtimes (which increases memory usage significantly in Python).

set ssh_long_term {
type ipv4_addr
flags dynamic, timeout
timeout 24h
}
# In input chain
tcp dport 22 ct state new update @ssh_long_term { ip saddr limit rate over 10/day } reject

This kernel-native tracking allows you to maintain a massive “reputation” database of IPs without the performance penalty associated with userspace tools.

Conclusion

Transitioning from Fail2ban to nftables meters represents a shift toward a more modern, performance-oriented security architecture. By leveraging the power of the Linux kernel’s networking stack, you can protect your SSH daemon with minimal resource impact and near-zero latency. While Fail2ban is still a valuable tool for application-specific logic, nftables should be the first line of defense for any system administrator looking to harden their infrastructure against the constant noise of the public internet.

The efficiency of dynamic sets, combined with the flexibility of the inet table and IPv6 prefix masking, provides a robust framework that scales from small Raspberry Pi projects to large-scale enterprise gateways. As you implement these rules, remember to prioritize whitelisting and use the nft monitor tool to fine-tune your thresholds for the best balance between security and usability.---

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.