fail2ban 入侵防护:SSH 爆破的自动封禁
SSH 暴露在公网就会被爆破,fail2ban 是最省心的自动应对:数失败次数、超阈值封 IP、到时间解封。这篇全按 Fedora 45 实测走。
sudo dnf install -y fail2ban-server fail2ban-firewalld实测版本 1.1.0。两个包的分工:fail2ban-server 是本体,fail2ban-firewalld 带来 firewalld 联动动作(firewallcmd-* 系列配置,实测 /etc/fail2ban/action.d/ 下有 allports/common 两个文件)。
最小配置:jail.local
Section titled “最小配置:jail.local”不要改 jail.conf(升级会覆盖),新建 /etc/fail2ban/jail.local:
[sshd]enabled = truebackend = systemdmaxretry = 5findtime = 10mbantime = 1h四个键的含义:
| 键 | 值 | 说明 |
|---|---|---|
backend | systemd | F45 必须。sshd 日志走 journal 不落文件,默认的 auto 找不到 /var/log/auth.log 会空转 |
maxretry | 5 | 10 分钟内失败 5 次即封 |
findtime | 10m | 计数窗口 |
bantime | 1h | 封禁时长,递增写法 1h 后可升 bantime.increment = true |
sudo systemctl enable --now fail2bansudo fail2ban-client status sshd实测输出(干净机器):
Status for the jail: sshd|- Filter| |- Currently failed: 0| `- Journal matches: _SYSTEMD_UNIT=sshd.service + _COMM=sshd + _COMM=sshd-session`- Actions |- Currently banned: 0Journal matches 一行是关键——它证明 filter 真的挂在 journal 上。
管理命令:手动封与解
Section titled “管理命令:手动封与解”sudo fail2ban-client set sshd banip 203.0.113.5 # 手动封sudo fail2ban-client set sshd unbanip 203.0.113.5 # 解封sudo fail2ban-client status sshd # 看计数与名单实测封禁后的状态:
|- Currently banned: 1`- Banned IP list: 203.0.113.5与 firewalld 的联动(实测验证)
Section titled “与 firewalld 的联动(实测验证)”ban 掉一个 IP 后,firewalld 里出现一条 rich rule:
rule family="ipv4" source address="203.0.113.5" port port="ssh" protocol="tcp" reject type="icmp-port-unreachable"nftables 规则集里同步可见该源地址。unban 后规则消失。这就是必须装 fail2ban-firewalld 的原因:封禁走 firewalld 的规则接口,与系统防火墙完全兼容,重启后不残留。
调试 filter:fail2ban-regex 的正确用法
Section titled “调试 filter:fail2ban-regex 的正确用法”filter 匹配不上时,用真实格式的一行去测:
printf "Oct 29 07:30:00 fd45-repo sshd[123]: Failed password for invalid user admin from 203.0.113.5 port 4242 ssh2\n" | \ sudo fail2ban-regex - /etc/fail2ban/filter.d/sshd.conf实测输出 1 matched。两个注意点:
- 行要带
sshd[pid]前缀——filter 的prefregex要求这个结构,裸的日志正文会0 matched [preauth]结尾的Connection closed by ...行在默认mode = normal下不算失败,jail.local里加mode = aggressive才计入(代价是误封率升高)
进阶:递增封禁与白名单
Section titled “进阶:递增封禁与白名单”[DEFAULT]bantime.increment = true # 屡犯者封禁时间翻倍bantime.maxtime = 1w
[sshd]enabled = truebackend = systemdignoreip = 127.0.0.1/8 192.168.2.0/24 # 自己的网段别封自己ignoreip 一定要先写再启用——否则一次配置失误+连续失败会把自己锁在门外。
| 现象 | 原因 |
|---|---|
| Total failed 一直是 0 | backend 不是 systemd(F45 没有 auth.log 文件) |
| 封了但还能连 | 没装 fail2ban-firewalld,动作落到不存在的 iptables |
| 自己被锁外面 | ignoreip 没配自家网段 |
| filter 匹配不上 | 测试行缺 sshd[pid] 前缀,或 preauth 行需要 aggressive 模式 |
| 重启后 jail 没起来 | enabled = true 只写在 [sshd] 节内,且文件名必须是 jail.local |
| fail2ban-regex 全 missed | 用裸文本行测试;带 journal 前缀结构才能过 prefregex |
- journalctl 日志 — fail2ban 的数据源
- 防火墙 firewalld — rich rule 的宿主
- SSH 与密钥 — 比封禁更根本的是只允许密钥登录
- 官方:fail2ban wiki