diff --git a/AGENTS.md b/AGENTS.md index 0bb7f1f..3628f6a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,7 +23,7 @@ | `webout/` | Caddy 反向代理配置,面向外部服务 | | `crontab/` | 定时任务脚本(硬盘巡检、apt 更新、时间同步) | | `apt.list/` | 国内镜像 APT 源配置(阿里云、中科大、华为)及 Docker 安装脚本 | -| `etc/` | 系统级配置(sysctl 内核调优) | +| `etc/` | 系统级配置(sysctl 内核调优、SSH 加固、fail2ban) | | `config/` | 共享配置片段(haproxy、gitea、proxy) | | `shell/` | 辅助 Shell 脚本 | | `i2c.py/` | 树莓派 I2C OLED 显示屏脚本 | @@ -143,6 +143,46 @@ docker compose -p <名称> --env-file ./builder/golang/env.cfg -f ./builder/gola - 内存管理(swappiness、脏页阈值) - 安全加固(ICMP 重定向拒绝、反向路径过滤、kptr_restrict) +### fail2ban(`etc/fail2ban/`) + +**只收录人工定制层**:`/etc/fail2ban` 下其余文件(`fail2ban.conf`、`jail.conf`、`paths-*.conf`、`action.d/`、`filter.d/` 内置过滤器)由 `apt install fail2ban` 提供,不纳管。 + +| 文件 | 作用 | +| --- | --- | +| `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/gitea-ssh.local` | Gitea 内置 SSH jail(input + forward 双链) | +| `etc/fail2ban/jail.d/recidive.local` | 再犯长封 | +| `etc/fail2ban/filter.d/gitea-ssh.conf` | Gitea SSH 过滤器 | + +设计说明与验证过程见 `etc/fail2ban/README.md`。 + +关键约定与坑: + +- **不要写死 `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、攻击者照样能连容器端口」。 +- **改配置后必须 `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 次即会被自封。 +- **`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。 +- **`recidive` 读的是文件不是 journal**:默认 `logtarget = /var/log/fail2ban.log`,`Ban`/`Unban` 行只进文件,用 systemd backend 收不到。 +- `filter.d/gitea-ssh.conf` 只匹配 `sshConnectionFailed()`。旧版 `publicKeyHandler()` 的同类日志是「单次公钥尝试失败」,用户随后可能登录成功,属误报,必须排除。 + +验证命令: + +```bash +fail2ban-client -t # 配置校验 +fail2ban-client status # 已启用 jail +fail2ban-client status sshd # 单 jail 状态 +fail2ban-client -d | grep dbpurgeage # 确认服务端选项真的生效 +fail2ban-client -d | grep -c dport # 应为 0(说明走的是 allports) +nft list table inet f2b-table # input 链 + IP 集合 +nft list table inet f2b-fwd # forward 链(仅 Docker 场景) +``` + ## Git 提交规范 ### Commit Message 格式 diff --git a/etc/fail2ban/README.md b/etc/fail2ban/README.md new file mode 100644 index 0000000..1a758d9 --- /dev/null +++ b/etc/fail2ban/README.md @@ -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 { }`,端口写错就「检测到但封不住」。`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 banip ` **绕过 ignoreip**,不要用它测试白名单。 +- `recidive` 依赖 `logtarget = /var/log/fail2ban.log`;若改成 SYSLOG/STDOUT 需同步改 backend。 +- 各 jail 的 `ignoreip` 由最后加载的 `.local` 决定。若某台机器上的 + `jail.d/frp-tunnel.local` 自带 `ignoreip`,它会覆盖本目录的公共白名单,需要合并。 diff --git a/etc/fail2ban/fail2ban.d/00-common.local b/etc/fail2ban/fail2ban.d/00-common.local new file mode 100644 index 0000000..64ddcca --- /dev/null +++ b/etc/fail2ban/fail2ban.d/00-common.local @@ -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 diff --git a/etc/fail2ban/filter.d/gitea-ssh.conf b/etc/fail2ban/filter.d/gitea-ssh.conf new file mode 100644 index 0000000..6b91188 --- /dev/null +++ b/etc/fail2ban/filter.d/gitea-ssh.conf @@ -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 (?::\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 diff --git a/etc/fail2ban/jail.d/00-common.local b/etc/fail2ban/jail.d/00-common.local new file mode 100644 index 0000000..bbc03de --- /dev/null +++ b/etc/fail2ban/jail.d/00-common.local @@ -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 } saddr @ reject +# 完全不引用 ,因此端口是多少都不影响封禁是否生效。 +# 对比 type=multiport 会生成 tcp dport { },端口写错 = 检测到但封不住。 +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 diff --git a/etc/fail2ban/jail.d/gitea-ssh.local b/etc/fail2ban/jail.d/gitea-ssh.local new file mode 100644 index 0000000..a4b1a80 --- /dev/null +++ b/etc/fail2ban/jail.d/gitea-ssh.local @@ -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] diff --git a/etc/fail2ban/jail.d/recidive.local b/etc/fail2ban/jail.d/recidive.local new file mode 100644 index 0000000..826e5e7 --- /dev/null +++ b/etc/fail2ban/jail.d/recidive.local @@ -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 diff --git a/etc/fail2ban/jail.d/sshd-hardening.local b/etc/fail2ban/jail.d/sshd-hardening.local deleted file mode 100644 index aa3d49e..0000000 --- a/etc/fail2ban/jail.d/sshd-hardening.local +++ /dev/null @@ -1,8 +0,0 @@ -[sshd] -enabled = true -maxretry = 3 -findtime = 10m -bantime = 1h -bantime.increment = true -bantime.factor = 2 -bantime.maxtime = 1w diff --git a/etc/fail2ban/jail.d/sshd.local b/etc/fail2ban/jail.d/sshd.local index efe4a16..97c63ae 100644 --- a/etc/fail2ban/jail.d/sshd.local +++ b/etc/fail2ban/jail.d/sshd.local @@ -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 的哪个值都无需知道。