VPS Tutorials
Configure Fail2Ban: SSH jails, repeat bans and firewall checks
Configure local Fail2Ban overrides, ban thresholds, escalating durations and a narrow allowlist. Verify log backends, filters and real enforcement; add Nginx and application jails, coordinate UFW and Docker, and understand CDN and database-persistence limits.

An internet-facing SSH service will often receive automated login attempts. Inspect the records rather than assuming a particular daily volume:
grep "Failed password" /var/log/auth.log | wc -l
SSH keys reduce the chance of a guessed password succeeding. Fail2Ban can additionally detect repeated failures and ask a firewall or another supported action to temporarily block the source. It complements authentication and port filtering; it does not prevent a distributed flood from reaching your network.
- A filter reads a log file or the system journal.
- Failures attributed to an address reach
maxretrywithinfindtime. - An action applies a ban for
bantime.
Fail2Ban delegates enforcement to an action, commonly iptables or nftables. Legacy hosts.deny actions only work with services that actually support TCP wrappers. A detected failure and an effective network block are separate things to verify.
sudo grep -c "Failed password" /var/log/auth.log
sudo grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -10
The second command groups a particular Failed password log format by address. Field positions vary; inspect sample lines first. If auth.log is absent, use the journal rather than concluding that nobody is probing SSH.
sudo apt update
sudo apt install -y fail2ban
Package versions depend on the distribution release and repositories. Version numbers such as 1.0.2 or 1.1.1 are examples, not a universal current Ubuntu/upstream combination. Check fail2ban-client --version and the package's security support before choosing another source.
sudo systemctl enable --now fail2ban
sudo systemctl status fail2ban
Whether sshd is enabled after installation depends on package defaults. Confirm the active jails; do not assume an installed service is protecting SSH.
| File | Role |
|---|---|
/etc/fail2ban/jail.conf | Base configuration maintained by the package |
/etc/fail2ban/jail.d/*.conf | Additional configuration read after the base |
/etc/fail2ban/jail.local | Your local overrides |
Avoid editing jail.conf; use jail.local or an appropriate local drop-in. The load order also includes jail.d/*.local after jail.local, so inspect the effective configuration instead of assuming jail.local always wins.
Before writing this example, save any existing local configuration, insert your real management allowlist and adapt the SSH port. The tee command replaces the named file:
sudo tee /etc/fail2ban/jail.local > /dev/null <<'EOF'
[DEFAULT]
# 封禁时长(首次)
bantime = 1h
# 统计窗口
findtime = 10m
# 窗口内失败多少次就封
maxretry = 5
# 递增封禁:反复来的 IP 越封越久
bantime.increment = true
bantime.factor = 1
bantime.maxtime = 1w
# 白名单:自己的固定 IP 写这里,避免把自己封了
ignoreip = 127.0.0.1/8 ::1
[sshd]
enabled = true
backend = systemd
EOF
Keep an authenticated session and provider console available. Validate with sudo fail2ban-client -t before restarting:
sudo systemctl restart fail2ban
sudo fail2ban-client status
| Setting | Common reference value | Meaning |
|---|---|---|
bantime | 10m | Ban duration |
findtime | 10m | Observation window |
maxretry | 5 | Failure threshold |
ignoreip | 127.0.0.1/8 ::1 | Addresses exempt from bans |
bantime = 10m may be short for a repeat offender, but longer bans also increase the cost of a false positive. A 1-hour initial ban is a starting policy, not protection against attackers rotating addresses.
| Policy | Example | Tradeoff |
|---|---|---|
| Forgiving | maxretry=10, findtime=10m, bantime=30m | Lower lockout risk; tolerates more failures |
| Balanced starting point | maxretry=5, findtime=10m, bantime=1h | Moderate threshold and ban duration |
| Strict | maxretry=3, findtime=1h, bantime=1d | Greater lockout risk on shared/dynamic networks |
Avoid the strict example if your own address changes frequently or many legitimate users share an egress address.
bantime.increment = true
bantime.factor = 1
bantime.maxtime = 1w
The default exponential formula can increase bans roughly 1, 2, 4, 8 and 16 times; stored history, factors and alternative multipliers affect the result. bantime.maxtime caps the duration:
bantime.formula = ban.Time * (1<<(ban.Count if ban.Count<20 else 20)) * banFactor
The sample formula itself limits its shift count; do not interpret an unset maximum as literally unlimited doubling. Keep usable history long enough for your escalation policy. bantime.rndtime can add random time variation, without making an address-based defense effective against every botnet.
ignoreip = 127.0.0.1/8 ::1 203.0.113.5 198.51.100.0/24
The addresses shown are documentation examples: substitute yours. The setting accepts IPs, CIDR ranges and supported hostname resolution. Space-separate values; keep hostname/DNS trust and changing addresses in mind.
- Your fixed management address, if you have one.
- The administration jump host.
- Monitoring sources that genuinely require the protected service.
- Only the trusted internal subnets that need exemption.
Do not exempt broad private or shared ranges without checking who can use them. ignoreself commonly defaults to true, ignoring the server's own addresses; verify the effective setting.
If you lock yourself out, use the provider console and fail2ban-client set sshd unbanip 你的IP, replacing the placeholder with your address. See the lockout recovery guide.
[sshd]
backend = systemd
| Backend | Source | Considerations |
|---|---|---|
systemd | system journal | Requires the journal integration and appropriate filter match |
auto | Automatic file backend selection | Choice depends on installed modules/version |
pyinotify | File change notifications | Requires the relevant Python integration |
polling | Polled log files | Broad compatibility, with polling delay |
systemd is useful when SSH logs are in the journal rather than /var/log/auth.log. auto does not automatically turn a missing log path into journal monitoring; inspect startup errors and the actual source.
With systemd, use journalmatch rather than logpath. Built-in filters normally provide a match, but the illustrative _SYSTEMD_UNIT=sshd.service must match the real unit name; some systems use ssh.service. Verify a backend change against recorded failures.
sudo fail2ban-client status
# 应该列出 sshd
sudo fail2ban-client status sshd
# 会显示当前封禁数量、总封禁数、以及被封的 IP 列表
# 用 systemd journal
sudo fail2ban-regex systemd-journal /etc/fail2ban/filter.d/sshd.conf
# 或者指定日志文件
sudo fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf
Inspect Lines: ... matched. Zero matches can mean a bad filter/source, but also a sample containing no failures. Use a known failure and verify timestamps, journal selection and the recovered address.
sudo fail2ban-regex --print-all-matched systemd-journal /etc/fail2ban/filter.d/sshd.conf | head -30
# 看当前的 iptables 规则里有没有 f2b 链
sudo iptables -L -n | grep -A5 f2b
A chain such as f2b-sshd may be created only when a ban first occurs. A missing chain is therefore not sufficient proof of failure; nftables actions also need inspection in the nft ruleset. Verify the configured action, port, address family and packet path.
Use a separate test client with console access and a planned unban. This loop is interactive and must target your server, not an unrelated host:
# 在测试机上故意输错
for i in $(seq 1 6); do ssh wronguser@your-server; done
If password authentication is disabled, use failures recognized by the actual SSH filter rather than enabling passwords just to test a ban.
sudo fail2ban-client status sshd
# 应该能看到那个 IP 出现在 Banned IP list 里
Confirm both the ban list and a new test connection, then unban the test address.
sudo tail -f /var/log/fail2ban.log
journalctl -u fail2ban -f
Look for Ban, action errors and Unban, not just a running process.
sshd is one available jail. Inspect installed filters:
ls /etc/fail2ban/filter.d/ | head -40
[nginx-http-auth]
enabled = true
port = http,https
logpath = %(nginx_error_log)s
maxretry = 5
bantime = 1h
Verify the error-log path and a known authentication failure. Select a file backend for this file-based jail if your global default uses systemd.
[nginx-botsearch]
enabled = true
port = http,https
logpath = %(nginx_error_log)s
nginx-botsearch matches particular logged patterns. It is not general request-rate limiting; configure Nginx rate limits separately when needed.
[wordpress]
enabled = true
filter = wordpress
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 3
bantime = 2h
This requires a compatible wordpress filter and logs that actually identify failed logins. An ordinary access log with HTTP 200 for both success and failure is insufficient. Application login controls, such as a maintained attempt-limiting plugin, can supply more accurate context; test the integration before enabling a jail.
Inspect the trusted log format:
sudo tail -20 /var/log/myapp/auth.log
# 2026-09-29 10:23:11 FAILED login from 203.0.113.5 user=admin
Create /etc/fail2ban/filter.d/myapp.conf:
[Definition]
failregex = ^.*FAILED login from <HOST>.*$
ignoreregex =
<HOST> extracts a host/address, but it is not the only filter requirement. The broad sample regex must be narrowed to a trusted structured prefix; otherwise user-controlled text may name someone else's address. Check timestamps, IPv4/IPv6, genuine failures and negative examples such as successful logins.
sudo fail2ban-regex /var/log/myapp/auth.log /etc/fail2ban/filter.d/myapp.conf
Tune with fail2ban-regex before enabling the jail:
[myapp]
enabled = true
filter = myapp
port = http,https
logpath = /var/log/myapp/auth.log
maxretry = 5
findtime = 10m
bantime = 1h
For an existing UFW policy, inspect the effective banaction. iptables-multiport is a common example, not every distribution's current default. The enforcement chain and ordering depend on the chosen action and firewall backend.
UFW limit limits connection attempts, whereas Fail2Ban analyzes logged failures. They may complement each other. If deliberately replacing limit with allow, inspect the exact existing rule, custom SSH port and new allow rule first. The example may not match a rule originally created with a different spelling:
sudo ufw delete limit ssh
sudo ufw allow OpenSSH
Check the real iptables/nftables rules, including IPv6:
sudo iptables -L -n | grep f2b # 有输出说明 iptables 兼容层在工作
sudo nft list ruleset | grep f2b # 或者看 nftables 里有没有
Use a supported action such as nftables-multiport when appropriate. Some actions create rules lazily, so test a controlled ban before concluding they are missing. Do not use ufw disable as a blanket reset; changing UFW can disturb access and enforcement, with effects depending on the ruleset.
Docker-published traffic, for example -p 8080:8080, can use forwarding rules that a host-input ban never reaches. A useful private-application pattern binds to 127.0.0.1 and sends public requests through a host reverse proxy:
ports:
- "127.0.0.1:8080:8080"
Then read the correct proxy logs and enforce bans on the relevant path. This does not automatically solve a CDN boundary: the network peer can still be a CDN node rather than the visitor.
No bans: check jail state, a known matching failure and action records:
# 1. jail 启用了吗
sudo fail2ban-client status
# 2. 能匹配到日志吗(最可能的问题)
sudo fail2ban-regex systemd-journal /etc/fail2ban/filter.d/sshd.conf
# 3. server 和 jail 的日志
sudo tail -50 /var/log/fail2ban.log
Zero results from fail2ban-regex need diagnosis of input, timestamps and filter; they are not proof of a quiet server.
Bans end too quickly: inspect bantime and Unban. 10m is only a reference default; restarting/reloading policies and stored history can matter too.
The address still connects: inspect forwarding, IPv6, selected ports, established sessions and chain order. With a CDN, configure real_ip to trust headers only from known proxies, but remember that changing the logged address does not change the packet source. Blocking a visitor behind a CDN usually needs enforcement at the proxy/CDN layer; do not ban shared CDN nodes indiscriminately.
Failed to execute ban jail 'sshd' action ... 'iptables': if the configured action truly needs the missing command, install the supported package:
sudo apt install -y iptables
Alternatively select the correct nftables action; installing iptables alone does not correct every action mismatch.
A long ban list: inspect why it is growing before clearing it. The second command below unbans all jails, despite the illustrative comment suggesting one jail:
# 解封单个
sudo fail2ban-client set sshd unbanip 203.0.113.5
# 全部解封某个 jail
sudo fail2ban-client unban --all
Use a targeted unban when possible.
Persistence after restart: many packages already use /var/lib/fail2ban/fail2ban.sqlite3. Check dbfile and database permissions in fail2ban.conf/fail2ban.local. The following historical jail-style snippet does not itself enable the database:
[DEFAULT]
dbpurgeage = 1d
dbpurgeage belongs to the daemon's database configuration, and a 1-day history may be too short for a week-long escalation policy. Put an appropriate value in fail2ban.local, confirm it is loaded and test restoration. bantime.increment depends on usable stored history; do not assume every restart clears it or that every installation persists it correctly.
False positives: shared office, school or mobile egress addresses can represent many users. Increase maxretry or reduce bantime as appropriate, and use a narrow management exemption.
CrowdSec as well: it offers different detection and intelligence workflows and requires effective enforcement components. Choose from your actual workload and operational capacity; neither product guarantees complete protection. Fail2Ban's Python process and database are often modest, but memory/CPU depend on jail count and log volume, including on a 1 GB VPS.
- Use
jail.localor local drop-ins, preservingjail.conf. - Choose
bantimefor your lockout risk, rather than blindly retaining 10m. - Verify
bantime.incrementand suitable daemon-leveldbpurgeage. - Keep
ignoreipnarrow and current. - Verify
backend = systemdor the actual file source. - Test a known failure with
fail2ban-regex. - Inspect
iptables -L -n | grep f2bor the actual nftables action. - Confirm a controlled ban and a new test connection.
- Deliberately coordinate UFW
limitand log-based banning. - Keep private Docker application ports on
127.0.0.1where appropriate. - Configure trusted
real_ipheaders and enforcement at the correct proxy boundary.