build(etc): 完善 Fail2ban 防爆破配置

- 将 SSH 封禁改为端口无关的 allports 策略
- 新增 Gitea SSH 双链防护和失败日志过滤器
- 补充公共策略、再犯封禁及部署验证文档
This commit is contained in:
cnphpbb
2026-11-08 23:37:44 +08:00
parent db3749375c
commit a13785c6e2
9 changed files with 246 additions and 14 deletions
+86
View File
@@ -0,0 +1,86 @@
# fail2ban 公用层(sshd + Gitea SSH 防爆破)
本目录只收录**人工定制层**。`fail2ban.conf`、`jail.conf`、`paths-*.conf`、`action.d/`、
`filter.d/` 内置过滤器均由 `apt install fail2ban` 提供,不纳管。
```
etc/fail2ban/
├── fail2ban.d/00-common.local # 服务端选项:dbpurgeage
├── jail.d/00-common.local # [DEFAULT] 公共策略:allports 封禁 / usedns / ignoreip / 递增
├── jail.d/sshd.local # 系统 OpenSSH(不写 port)
├── jail.d/gitea-ssh.local # Gitea 内置 SSH(容器 -> input+forward 双链)
├── jail.d/recidive.local # 再犯长封
└── filter.d/gitea-ssh.conf # Gitea SSH 过滤器
```
## 为什么这样写
| 设计 | 原因 |
| --- | --- |
| `banaction = nftables[type=allports]` | sshd 端口每台机器不同且落在 **49152-65535**。`type=multiport` 生成的规则是 `tcp dport { <port> }`,端口写错就「检测到但封不住」。`allports` 生成 `meta l4proto { tcp } saddr @set reject`,**完全不引用 port**,从根本上消除端口依赖。 |
| jail 里**不写** `port =` | 同上。封禁与端口解耦后,端口是多少都不影响。 |
| `dbpurgeage` 放 `fail2ban.d/` | 它是**服务端**选项。实测放 `jail.d/[DEFAULT]` 会被静默忽略(仍为 1d),放 `fail2ban.d/*.local` 才生效(→90d)。不修的话 `bantime.increment` 的历史会被提前清掉,递增涨不到位。 |
| `gitea-ssh` 用**双 action** | 默认 nftables 链只 `hook input`,而 Docker 对发布端口做 DNAT 后走 `forward`,容器流量**不经过 input**。只挂 input 会出现「封禁列表里有 IP、攻击者照样能连容器端口」。 |
| `gitea-ssh` 的 `logpath` 指向稳定文件 | docker json-file 路径内嵌容器 ID,容器一重建就静默失效。 |
| `recidive` 读 `logpath=/var/log/fail2ban.log` | 默认 `logtarget` 是文件,`Ban`/`Unban` 行**只进文件不进 journal**,用 systemd backend 会收不到。 |
| 过滤器只匹配 `sshConnectionFailed()` | 旧版 `publicKeyHandler()` 的同类日志是「单次公钥尝试失败」,用户随后可能登录成功,属误报。 |
## 部署
```bash
# 1. 铺配置(保留 apt 提供的其余文件)
# 注意:本机 cp 被 alias 成 `cp -i`,会逐个文件提示「是否覆盖」。
# GNU cp 的 -f 优先级低于 -i(加 -f 也照样提示),故统一用 `\cp` 绕过 alias。
install -d /etc/fail2ban/fail2ban.d /etc/fail2ban/jail.d /etc/fail2ban/filter.d
\cp -a fail2ban.d/00-common.local /etc/fail2ban/fail2ban.d/
\cp -a jail.d/00-common.local jail.d/sshd.local jail.d/gitea-ssh.local jail.d/recidive.local /etc/fail2ban/jail.d/
\cp -a filter.d/gitea-ssh.conf /etc/fail2ban/filter.d/
# 2. 改 dbpurgeage 后必须 restart(reload 不重建 nft 链)
fail2ban-client -t && systemctl restart fail2ban
# 3. 校验
fail2ban-client status
fail2ban-client -d | grep -E "dbpurgeage|addignoreip|bantime.(increment|maxtime)"
nft list table inet f2b-table # 应只有 input hook
nft list table inet f2b-fwd # 应存在 forward hook(gitea-ssh)
```
> 换端口 / 换 banaction 之后一律 `systemctl restart fail2ban`,`reload` 不会重建 nft 链。
### 关于 `cp` 的 alias
本机 `cp` 被 alias 成 `cp -i`(`alias cp='cp -i'`),用于日常防误覆盖。但部署配置时这会变成麻烦:
- 目标文件已存在时逐个提示「是否覆盖」,粘贴执行会卡在提示上;放进脚本则 stdin 被吃掉、`cp` 直接以 exit 1 失败且**文件没被复制**。
- `cp -a -f` **不能**解决:GNU coreutils 的 `cp` 里 `-i` 优先级高于 `-f`(实测 `-i -f` / `-i -a -f` 仍然提示),`-f` 只表示「打不开就删掉重试」,不是「不提示」。
所以部署统一写 `\cp -a`(反斜杠跳过 alias 展开),需要保留交互确认时再手动改回 `cp` 逐个回答。`install -d` 不受该 alias 影响。
## Gitea 侧要求(app.ini)
`logpath` 要稳定,Gitea 必须把日志写到**挂载卷上的文件**:
```ini
[log]
MODE = file
ROOT_PATH = /data/gitea/log
LEVEL = Info
```
- `LEVEL = Info` 即可捕获 `[W]` 级别的 `sshConnectionFailed()`。
- 默认 `FLAGS = stdflags` 含 `date`,Go 的 date 是 `2009/01/23`(**斜杠**),对齐 `filter.d/gitea-ssh.conf` 的 `datepattern`。
- 容器内路径 `/data/gitea/log` 需 bind mount 到宿主;jail 的 `logpath` 填**宿主**路径(示例为 `/var/lib/gitea/log/gitea.log`),按实际挂载点调整。
- 若保持 docker json-file + 容器 ID 路径,则 `logpath` 每次重建容器后都要刷新,且**不会报错、只会静默停止防护**。
## 已知限制
- **密码登录关闭后 sshd jail 很难触发**:fail2ban 1.1.0 的 sshd 过滤器把 `Failed publickey`、
`pam_unix ... authentication failure`、`Connection closed by invalid user` 标为 NOFAIL,
真正计入失败的只有 `Failed password` 与 `User X from IP not allowed because not listed in AllowUsers`。
只开公钥的机器上,唯一触发场景是「用非 AllowUsers 用户名登录」——管理员误用 `root` 登录 3 次即自封。
这也是 `ignoreip` 必须写全管理出口 IP 的原因。
- `fail2ban-client set <jail> banip <IP>` **绕过 ignoreip**,不要用它测试白名单。
- `recidive` 依赖 `logtarget = /var/log/fail2ban.log`;若改成 SYSLOG/STDOUT 需同步改 backend。
- 各 jail 的 `ignoreip` 由最后加载的 `.local` 决定。若某台机器上的
`jail.d/frp-tunnel.local` 自带 `ignoreip`,它会覆盖本目录的公共白名单,需要合并。
+12
View File
@@ -0,0 +1,12 @@
# fail2ban —— 服务端(非 jail)级公共配置
#
# ⚠ 本文件必须在 fail2ban.d/ 下,不能放 jail.d/。
# dbpurgeage / dbfile / logtarget 属于 fail2ban 服务端选项,
# 写在 jail.d/[DEFAULT] 里会被静默忽略(实测:放 jail.d 仍是默认 1d,放 fail2ban.d 才生效)。
[DEFAULT]
# 封禁历史在 sqlite 库里保留多久。默认 1d。
# bantime.increment 靠库里的历史 ban 次数做递增,历史被清掉后计数归零。
# 设成 >= bantime.maxtime,保证递增封禁能一路涨到位。
dbpurgeage = 90d
+23
View File
@@ -0,0 +1,23 @@
# fail2ban filter: Gitea 内置 SSH 服务
#
# 只匹配 Gitea >= 1.15 的确定性失败信号 sshConnectionFailed()。
# 旧版 publicKeyHandler() 打的 "Failed authentication attempt" 是「单次公钥尝试失败」,
# 用户随后仍可能登录成功,属于误报,必须排除(官方文档也标了 DEPRECATED)。
#
# 已用 fail2ban-regex 1.1.0 实测(见 docs/fail2ban-verify.md):
# 命中:sshConnectionFailed() 的 IPv4 / 带端口 / 无端口 / IPv6[方括号] / docker json 整行
# 排除:publicKeyHandler() 误报行、web 的 "invalid credentials" 行
[Definition]
# 不锚定行首行尾:容器 json-file 一行是 {"log":"...\n","stream":...} 包着的,
# 用 ^.*? / .*$ 同时兼容「纯文件行」和「docker json 整行」。
# 端口可选:Gitea 用 Go 的 RemoteAddr(),IPv4 是 1.2.3.4:5678,IPv6 是 [::1]:5678。
failregex = ^.*?sshConnectionFailed\(\) \[W\] Failed authentication attempt from <HOST>(?::\d+)?.*$
ignoreregex =
[Init]
# Gitea 默认 FLAGS=stdflags 含 date,Go 的 date 格式是 2009/01/23(斜杠)。
# 同时接受 [-] 兼容改过格式的部署。%% 是 configparser 转义,等价于 %Y/%m/%d %H:%M:%S。
datepattern = %%Y[-/]%%m[-/]%%d %%H:%%M:%%S
+36
View File
@@ -0,0 +1,36 @@
# fail2ban —— 所有 jail 共用的策略(公用版本)
#
# 文件名 00- 前缀是刻意为之:fail2ban 读取顺序是
# jail.conf -> jail.d/*.conf -> jail.local -> jail.d/*.local(按名排序)
# 所以 jail.d/*.local 反而会覆盖 jail.local。00- 保证本文件的 [DEFAULT]
# 先于 sshd.local / gitea-ssh.local / recidive.local 加载,让它们能按需覆盖单 jail 设置。
[DEFAULT]
# ── 端口无关封禁(本方案的核心)────────────────────────────────
# sshd 端口在各机器上落在 49152-65535 内且每台不同,写死 port 必然出错。
# nftables 的 type=allports 生成的规则是:
# meta l4proto { tcp } <family> saddr @<set> reject
# 完全不引用 <port>,因此端口是多少都不影响封禁是否生效。
# 对比 type=multiport 会生成 tcp dport { <port> },端口写错 = 检测到但封不住。
banaction = nftables[type=allports]
banaction_allports = nftables[type=allports]
# ── 安全默认 ──────────────────────────────────────────────
# usedns=no:不信任反向解析(默认 warn 会解析主机名,可被 DNS 欺骗/拖慢)
usedns = no
# ignoreself:永不封本机
ignoreself = true
# ── 白名单 ────────────────────────────────────────────────
# 必须包含管理出口 IP,否则管理员自己会被封(fail2ban-client set banip 还会绕过本项)。
# 保留 RFC1918:内网探测/监控/tailscale 等不应触发封禁。
ignoreip = 127.0.0.1/8 ::1 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 183.238.148.253/32
# ── 递增封禁:1d -> 2d -> 4d -> ... 上限 4w ─────────────────
bantime = 1d
findtime = 10m
maxretry = 3
bantime.increment = true
bantime.factor = 2
bantime.maxtime = 4w
+21
View File
@@ -0,0 +1,21 @@
# Gitea 内置 SSH 服务(容器内监听 2222,宿主发布端口不固定)
#
# 日志路径必须稳定:默认的 docker json-file 路径内嵌容器 ID,
# 容器一重建就静默失效(fail2ban 不报错,只是再也不封)。
# 因此要求 Gitea 用 file 模式写到挂载卷,见 docs/gitea-fail2ban-app-ini.md。
[gitea-ssh]
enabled = true
filter = gitea-ssh
logpath = /var/lib/gitea/log/gitea.log
maxretry = 5
findtime = 10m
bantime = 1d
# 双 action:默认 nftables chain 只 hook input,而 Docker 对发布端口做 DNAT 后
# 走 forward 链,容器流量根本不经过 input。只挂 input 会出现「封禁列表里有 IP、
# 但攻击者照样能连容器端口」。
# 第二条把同一条黑名单再挂到 forward,priority -10 早于 Docker 的
# table ip filter FORWARD(priority 0),确保先于 docker 规则丢弃。
action = nftables[type=allports]
nftables[type=allports, table=f2b-fwd, chain=f2b-fwd-chain, chain_hook=forward, chain_priority=-10]
+13
View File
@@ -0,0 +1,13 @@
# 再犯 jail:只读 fail2ban 自己的日志,把「封过又重新犯」的 IP 长封,
# 作为 bantime.increment 之外的兜底。
#
# ⚠ 数据源是 fail2ban 自己的日志文件,不是 journald:
# 默认 fail2ban.conf 里 logtarget = /var/log/fail2ban.log,
# "Ban"/"Unban" 行只进这个文件,不进 journal。
# 若某台机器把 logtarget 改成了 SYSLOG/STDOUT,这里要相应改 backend。
[recidive]
enabled = true
logpath = /var/log/fail2ban.log
maxretry = 3
findtime = 1d
bantime = 4w
-8
View File
@@ -1,8 +0,0 @@
[sshd]
enabled = true
maxretry = 3
findtime = 10m
bantime = 1h
bantime.increment = true
bantime.factor = 2
bantime.maxtime = 1w
+14 -5
View File
@@ -1,10 +1,19 @@
[sshd]
enabled = true
backend = systemd
journalmatch = _SYSTEMD_UNIT=ssh.service + _COMM=sshd + _COMM=sshd-session
# ssh.service (Debian/Ubuntu) 与 sshd.service (RHEL/Fedora) 都要覆盖。
# OpenSSH 9.8+ 把会话进程拆成 sshd-session,只写 _COMM=sshd 会漏掉真正的认证失败行。
# journal 字段匹配:'+' = 组间 OR,空格 = 组内 AND。
journalmatch = _SYSTEMD_UNIT=ssh.service + _SYSTEMD_UNIT=sshd.service + _COMM=sshd + _COMM=sshd-session
# normal 足以覆盖密码/公钥爆破;aggressive 会把 "Connection closed by" 等
# 正常客户端抖动也算失败,配合 maxretry=3 容易误封,故不用。
mode = normal
maxretry = 3
findtime = 10m
bantime = 24h
bantime.increment = true
bantime.factor = 2
bantime.maxtime = 7d
bantime = 1d
# 刻意不写 port:封禁走 allports(见 jail.d/00-common.local),
# 因此本机 sshd 端口落在 49152-65535 的哪个值都无需知道。