Files
deploy.stack/etc/fail2ban/README.md
T
cnphpbb a7395afd4f fix(etc): 修复 Fail2ban 双链配置冲突
- 为 Gitea SSH 的 input 和 forward action 设置独立名称
- 固定 sshd 过滤器的 publickey=invalid 语义
- 补充 jail 数量检查、action 重名检测和实测说明
2026-11-09 00:04:54 +08:00

126 lines
8.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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、攻击者照样能连容器端口」。 |
| 两个 action 必须写**不同的 `name=`** | fail2ban 的 `ActionReader` 里 `name` 不写时默认取 **jail 名**,`actname` 只在 `name != jailName` 时才加后缀去重。两个 action 同名 → 撞成同一个 `actname` → `Actions.add()` 抛 `ValueError('Action nftables already exists')` → **整个 server-stream 中断**(实测 fail2ban 1.1.0)。`name` 同时决定 nft set 名(`addr-set-<name>`),不同 `name` 才能落在不同 set。 |
| `gitea-ssh` 的 `logpath` 指向稳定文件 | docker json-file 路径内嵌容器 ID,容器一重建就静默失效。 |
| `recidive` 读 `logpath=/var/log/fail2ban.log` | 默认 `logtarget` 是文件,`Ban`/`Unban` 行**只进文件不进 journal**,用 systemd backend 会收不到。 |
| 过滤器只匹配 `sshConnectionFailed()` | 旧版 `publicKeyHandler()` 的同类日志是「单次公钥尝试失败」,用户随后可能登录成功,属误报。 |
| `sshd` 显式写 `publickey=invalid` | 锁定语义:只把「对不存在用户名的公钥尝试」计为失败。实测与默认值 `nofail` 的**封禁集合相同**,区别是「有效用户用错 key」那行从 NOFAIL 记录变成完全不匹配。**不要用 `any`**(有效用户用错 key 3 次即被封),**不要用 `ignore`**(漏掉 invalid user 的公钥爆破)。 |
## 部署
```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 # Number of jail 必须是 3(sshd / gitea-ssh / recidive)
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 链。
### ⚠ 一个 jail 挂掉 = 全部失守
实测:某个 jail 初始化失败(例:`backend = systemd` 但 `python3-systemd` 缺失或与 python 版本不匹配,
报 `Backend 'systemd' failed to initialize`)会**直接中断整个 server-stream**,
结果是 **0 个 jail 启动**(`fail2ban-client status` 显示 `Number of jail: 0`)——
不是「少一个 jail」,而是**全都不封**。
因此部署后**必须**确认 `fail2ban-client status` 的 jail 数量符合预期,
并把这条纳入监控(`Number of jail: 0` 应当告警)。
### 关于 `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 过滤器实测行为(fail2ban 1.1.0)
用 `fail2ban-regex` 对 8 行典型日志实测,**计入失败**(触发封禁)的行:
| 日志行 | 是否计失败 | 说明 |
| --- | --- | --- |
| `Failed password for invalid user X from IP` | ✅ | 密码爆破主路径 |
| `Failed publickey for invalid user X from IP` | ✅ | **用户名枚举/公钥爆破**(默认 `nofail` 就已计入) |
| `Invalid user X from IP` | ✅ | 用户名枚举 |
| `User X from IP not allowed because not listed in AllowUsers` | ✅ | 唯一在**只开公钥**机器上稳定的触发点 |
| `maximum authentication attempts exceeded for X from IP` | ✅ | 单连接多次尝试 |
**不计入失败**(NOFAIL / ignored)的行:
| 日志行 | 说明 |
| --- | --- |
| `Failed publickey for <有效用户> from IP` | 用户名真实但 key 不对 —— 不封(避免误封正常用户) |
| `pam_unix(sshd:auth): authentication failure; ... rhost=IP` | PAM 层失败已被 sshd 自身总结过,重复计数无意义 |
| `Connection closed by authenticating user ... [preauth]` | 正常客户端抖动 |
| `Accepted publickey for ...` | 登录成功 |
> 注意:`publickey` 参数的四种取值实测对比(命中行数 / 8 行样本)——
> `nofail` 6、`invalid` 6、`any` 7、`ignore` 4。
> 本目录取 `invalid`(与默认 `nofail` 同效但语义明确);`any` 会误封有效用户,`ignore` 会漏防。
## 已知限制
- **密码登录关闭后 sshd jail 触发场景变少**:只开公钥时,真正稳定的触发点是
「用非 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`,它会覆盖本目录的公共白名单,需要合并。
- `blocktype = reject` 会向对端回 RST,等于告知攻击者「你被封了」。
追求隐蔽可改 `blocktype = drop`(代价是连接直接超时)。
- `ignoreip` 含全部 RFC1918(10/8、172.16/12、192.168/16),内网扫描与监控全部豁免;
若内网也有暴破场景,需要单独收敛。