diff --git a/AGENTS.md b/AGENTS.md index 3628f6a..d6f0137 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -151,7 +151,7 @@ docker compose -p <名称> --env-file ./builder/golang/env.cfg -f ./builder/gola | --- | --- | | `etc/fail2ban/fail2ban.d/00-common.local` | 服务端选项:`dbpurgeage` | | `etc/fail2ban/jail.d/00-common.local` | `[DEFAULT]` 公共策略:allports 封禁 / usedns / ignoreip / 递增封禁 | -| `etc/fail2ban/jail.d/sshd.local` | 系统 OpenSSH jail(**不写 `port`**) | +| `etc/fail2ban/jail.d/sshd.local` | 系统 OpenSSH jail(**不写 `port`**,`publickey=invalid`) | | `etc/fail2ban/jail.d/gitea-ssh.local` | Gitea 内置 SSH jail(input + forward 双链) | | `etc/fail2ban/jail.d/recidive.local` | 再犯长封 | | `etc/fail2ban/filter.d/gitea-ssh.conf` | Gitea SSH 过滤器 | @@ -163,8 +163,11 @@ docker compose -p <名称> --env-file ./builder/golang/env.cfg -f ./builder/gola - **不要写死 `port`**。sshd 端口每台机器不同、落在 49152-65535。`banaction = nftables[type=allports]` 生成 `meta l4proto { tcp } saddr @ reject`,**完全不引用 ``**,从根上消除端口依赖;反过来 `type=multiport` 生成 `tcp dport { }`,端口写错就是「检测得到、封不到」。 - **`dbpurgeage` 必须放 `fail2ban.d/`**。它是服务端选项,写在 `jail.d/[DEFAULT]` 里会被**静默忽略**(实测仍为 `1d`),只有 `fail2ban.d/*.local` 生效。默认 1d 会让 `bantime.increment` 的历史被提前清掉,递增涨不到位。 - **Docker 里的 Gitea 必须再挂一条 forward 链**。默认 nftables 链只 `hook input`,而 Docker 对发布端口做 DNAT 后走 `forward`,容器流量**不经过 input**;只挂 input 会出现「封禁列表里有 IP、攻击者照样能连容器端口」。 +- **同一 jail 里的多个 action 必须写不同的 `name=`**。fail2ban 的 `ActionReader` 中 `name` 不写时默认取 **jail 名**,而 `actname` 只在 `name != jailName` 时才加后缀去重——两个 action 同名会撞成同一个 `actname`,`Actions.add()` 直接抛 `ValueError('Action nftables already exists')`,**整个 server-stream 中断**(实测 fail2ban 1.1.0),forward 链根本不会建出来,且现象极隐蔽:`fail2ban-client status` 里 jail 仍在运行。`name` 同时决定 nft set 名(`addr-set-`),不同 `name` 才能落在不同 set。写法:`nftables[type=allports, name=gitea-ssh-in]` + `nftables[type=allports, name=gitea-ssh-fwd, ...]`。 +- **一个 jail 初始化失败 = 全部 jail 都不启动**。实测 `backend = systemd` 但 `python3-systemd` 缺失或与 python 版本不匹配时报 `Backend 'systemd' failed to initialize`,会**直接中断整个 server-stream**,结果是 **0 个 jail 运行**(`fail2ban-client status` 显示 `Number of jail: 0`)——不是少一个 jail,而是全都不封。部署后必须核对 jail 数量,并把 `Number of jail: 0` 纳入告警。 - **改配置后必须 `systemctl restart fail2ban`**,`reload` 不会重建 nftables 链。 -- **`ignoreip` 必须包含管理出口 IP**(`183.238.148.253/32`)。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**(`183.238.148.253/32`)。fail2ban 1.1.0 的 sshd 过滤器实测:**计入失败**的有 `Failed password for ...`、`Failed publickey for invalid user ...`、`Invalid user ...`、`User X ... not allowed because not listed in AllowUsers`、`maximum authentication attempts exceeded ...`;**标为 NOFAIL**(不计失败)的有 `Failed publickey for <有效用户>`、`pam_unix ... authentication failure`、`Connection closed by invalid user`。在密码登录关闭后,触发点是「用非 AllowUsers 用户名登录」和「对不存在用户名的公钥尝试」——管理员误用 `root` 登录 3 次即会被自封。 +- **`sshd.local` 显式写 `filter = sshd[mode=normal, publickey=invalid]`**。`publickey` 四种取值的实测命中数(8 行样本):`nofail` 6、**`invalid` 6**、`any` 7、`ignore` 4。`invalid` 与默认值 `nofail` 封禁集合相同(两者都把 `Failed publickey for invalid user` 计入失败),区别只是「有效用户用错 key」那行从 NOFAIL 记录变成完全不匹配;显式写是为了锁定语义、防上游改默认值。**不要用 `any`**(有效用户用错 key 3 次即被封),**不要用 `ignore`**(漏掉 invalid user 的公钥爆破)。 - **`fail2ban-client set banip ` 会绕过 `ignoreip`**(管理员强制操作)。切勿用它测试白名单,否则会把管理出口直接封死。验证白名单请用 `fail2ban-client -d | grep ignoreip`。 - `journalmatch = _SYSTEMD_UNIT=ssh.service + _SYSTEMD_UNIT=sshd.service + _COMM=sshd + _COMM=sshd-session`:systemd 对同一字段的多个值按 **OR** 合并(不同字段之间才是 AND)。`ssh.service`/`sshd.service` 覆盖 Debian/RHEL 差异;OpenSSH 9.8+ 把会话进程拆成 `sshd-session`,只写 `_COMM=sshd` 会漏掉真正的认证失败行。 - **`gitea-ssh.local` 的 `logpath` 必须指向稳定文件**。docker json-file 路径内嵌容器 ID,容器重建后**静默失效**(不报错,只是不再封)。要求 Gitea 用 `[log] MODE=file` 写到挂载卷,见 README。 @@ -175,10 +178,11 @@ docker compose -p <名称> --env-file ./builder/golang/env.cfg -f ./builder/gola ```bash fail2ban-client -t # 配置校验 -fail2ban-client status # 已启用 jail +fail2ban-client status # 已启用 jail(Number of jail 应为 3:sshd / gitea-ssh / recidive) fail2ban-client status sshd # 单 jail 状态 fail2ban-client -d | grep dbpurgeage # 确认服务端选项真的生效 fail2ban-client -d | grep -c dport # 应为 0(说明走的是 allports) +fail2ban-client -d | grep -c "already exists" # 应为 0(多 action 同名会导致 server-stream 中断) nft list table inet f2b-table # input 链 + IP 集合 nft list table inet f2b-fwd # forward 链(仅 Docker 场景) ``` diff --git a/etc/fail2ban/README.md b/etc/fail2ban/README.md index 1a758d9..4534373 100644 --- a/etc/fail2ban/README.md +++ b/etc/fail2ban/README.md @@ -21,9 +21,11 @@ etc/fail2ban/ | 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` 才能落在不同 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 的公钥爆破)。 | ## 部署 @@ -40,7 +42,7 @@ install -d /etc/fail2ban/fail2ban.d /etc/fail2ban/jail.d /etc/fail2ban/filter.d fail2ban-client -t && systemctl restart fail2ban # 3. 校验 -fail2ban-client status +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) @@ -48,6 +50,16 @@ 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'`),用于日常防误覆盖。但部署配置时这会变成麻烦: @@ -73,14 +85,41 @@ LEVEL = Info - 容器内路径 `/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 很难触发**: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 的原因。 +- **密码登录关闭后 sshd jail 触发场景变少**:只开公钥时,真正稳定的触发点是 + 「用非 AllowUsers 用户名登录」和「对不存在用户名的公钥尝试」——后者实测**确实计入失败**。 + 管理员误用 `root` 登录 3 次即自封,这也是 `ignoreip` 必须写全管理出口 IP 的原因。 - `fail2ban-client set banip ` **绕过 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),内网扫描与监控全部豁免; + 若内网也有暴破场景,需要单独收敛。 diff --git a/etc/fail2ban/filter.d/gitea-ssh.conf b/etc/fail2ban/filter.d/gitea-ssh.conf index 6b91188..3c0f68e 100644 --- a/etc/fail2ban/filter.d/gitea-ssh.conf +++ b/etc/fail2ban/filter.d/gitea-ssh.conf @@ -4,7 +4,7 @@ # 旧版 publicKeyHandler() 打的 "Failed authentication attempt" 是「单次公钥尝试失败」, # 用户随后仍可能登录成功,属于误报,必须排除(官方文档也标了 DEPRECATED)。 # -# 已用 fail2ban-regex 1.1.0 实测(见 docs/fail2ban-verify.md): +# 已用 fail2ban-regex 1.1.0 实测: # 命中:sshConnectionFailed() 的 IPv4 / 带端口 / 无端口 / IPv6[方括号] / docker json 整行 # 排除:publicKeyHandler() 误报行、web 的 "invalid credentials" 行 [Definition] diff --git a/etc/fail2ban/jail.d/gitea-ssh.local b/etc/fail2ban/jail.d/gitea-ssh.local index a4b1a80..2a9762a 100644 --- a/etc/fail2ban/jail.d/gitea-ssh.local +++ b/etc/fail2ban/jail.d/gitea-ssh.local @@ -2,7 +2,7 @@ # # 日志路径必须稳定:默认的 docker json-file 路径内嵌容器 ID, # 容器一重建就静默失效(fail2ban 不报错,只是再也不封)。 -# 因此要求 Gitea 用 file 模式写到挂载卷,见 docs/gitea-fail2ban-app-ini.md。 +# 因此要求 Gitea 用 file 模式写到挂载卷,app.ini 配置见 README.md 的「Gitea 侧要求(app.ini)」。 [gitea-ssh] enabled = true filter = gitea-ssh @@ -17,5 +17,12 @@ bantime = 1d # 但攻击者照样能连容器端口」。 # 第二条把同一条黑名单再挂到 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] +# +# ⚠ 两个 action 必须写不同的 name=: +# ActionReader 里 name 不指定时默认取 jail 名(都是 gitea-ssh),而 actname 只在 +# name != jailName 时才加后缀去重 —— 两者同名会撞成同一个 actname "nftables", +# Actions.add() 直接抛 ValueError('Action nftables already exists'), +# 整个 server-stream 中断(实测 fail2ban 1.1.0),forward 链根本不会建出来。 +# name 同时决定 nft set 名(addr-set-),不同 name 才能落在不同 set。 +action = nftables[type=allports, name=gitea-ssh-in] + nftables[type=allports, name=gitea-ssh-fwd, table=f2b-fwd, chain=f2b-fwd-chain, chain_hook=forward, chain_priority=-10] diff --git a/etc/fail2ban/jail.d/sshd.local b/etc/fail2ban/jail.d/sshd.local index 97c63ae..1f68971 100644 --- a/etc/fail2ban/jail.d/sshd.local +++ b/etc/fail2ban/jail.d/sshd.local @@ -11,6 +11,18 @@ journalmatch = _SYSTEMD_UNIT=ssh.service + _SYSTEMD_UNIT=sshd.service + _COMM=ss # 正常客户端抖动也算失败,配合 maxretry=3 容易误封,故不用。 mode = normal +# publickey=invalid:只把「对不存在用户名的公钥尝试」计为失败。 +# filter 自带默认值 publickey=nofail,封禁集合与 invalid 实测一致 +# (两者都把 "Failed publickey for invalid user ..." 计入失败,均为 6/8 行命中)。 +# 显式写 invalid 的意义: +# 1. 锁定语义 —— 上游改默认值时行为不变; +# 2. "Failed publickey for <有效用户>" 从 NOFAIL 记录变成完全不匹配, +# 不再进入 fail2ban 的统计管道。 +# 不要用 publickey=any:那会把有效用户用错 key 也计成失败, +# 正常用户 3 次输错就被封(实测命中数 6 -> 7)。 +# 也不要用 publickey=ignore:那会漏掉 invalid user 的公钥爆破(实测命中 6 -> 4)。 +filter = sshd[mode=normal, publickey=invalid] + maxretry = 3 findtime = 10m bantime = 1d