From 7d52155411b4ac5cad62e5ad989f021b679d73e4 Mon Sep 17 00:00:00 2001 From: tamakyi Date: Wed, 21 Oct 2026 12:36:33 +0800 Subject: [PATCH] =?UTF-8?q?fix(honeypot):=20=E8=9C=9C=E7=BD=90=E5=B0=81?= =?UTF-8?q?=E7=A6=81=E4=B8=8E=20enable=5Fauto=5Fban=20=E8=A7=A3=E8=80=A6?= =?UTF-8?q?=20+=20=E6=B3=84=E9=9C=B2=E6=89=AB=E6=8F=8F=E5=90=8E=E7=BC=80?= =?UTF-8?q?=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - autoban: 新增 RecordHoneypot 独立通道(不受 enabled 约束)+ 独立阈值/时长; IsBanned 不再因 enable_auto_ban=false 而忽略已有封禁 - honeypot: 新增 honeypotSuffixes 后缀匹配,覆盖 /backup.zip、/db.sql、/id_rsa.pem - 新增配置 honeypot_threshold / honeypot_ban_minutes - 补测试:autoban/honeypot_test.go、route 侧禁用自动封禁仍封禁 --- .workbuddy/memory/2026-10-21.md | 45 +++++++ .workbuddy/memory/topics/misc.md | 6 + .workbuddy/memory/topics/review.md | 8 ++ conf/app.sample.ini | 5 + internal/conf/static.go | 6 + internal/route/autoban.go | 1 - internal/route/honeypot.go | 10 +- internal/route/honeypot_test.go | 74 +++++++++++- internal/security/autoban/autoban.go | 105 ++++++++++++++++- internal/security/autoban/honeypot_test.go | 123 ++++++++++++++++++++ internal/security/honeypot/honeypot.go | 23 +++- internal/security/honeypot/honeypot_test.go | 6 + 12 files changed, 402 insertions(+), 10 deletions(-) create mode 100644 internal/security/autoban/honeypot_test.go diff --git a/.workbuddy/memory/2026-10-21.md b/.workbuddy/memory/2026-10-21.md index 13556a1..1481b63 100644 --- a/.workbuddy/memory/2026-10-21.md +++ b/.workbuddy/memory/2026-10-21.md @@ -59,3 +59,48 @@ - 新增测试:`internal/security/honeypot/honeypot_test.go`(匹配/业务路由零交集/编码绕过/凭据提取)、 `internal/route/honeypot_test.go`(假页含 canary、业务路由不被劫持、关闭时回落 302、POST 返回失败页)、 `internal/db/honeypot_test.go`(写入/倒序/三张聚合表/保留期清理)。 + +## 测试站黑盒验证 + P0 缺陷修复(蜜罐封禁被 enable_auto_ban 连坐) + +测试站:`https://box-dev-api.337845818.best`(Cloudflare Tunnel + CF 边缘,`cf-cache-status: DYNAMIC`、无 `Age` → 不缓存,请求确实回源)。 +生产站 `https://box.tama.guru` 强制 301 → www,本机不可达,无法做对照。 + +### 黑盒验证结果(全部通过) +- 诱饵路径全部 200 + `text/html`:`/wp-login.php` 2529B、`/wp-admin/` 2517B、`/.ssh/id_rsa` 2525B、`/.env` 2497B、`/administrator` 2533B。 +- 响应体含 canary `tb-hp-7f3a1c9e`(2 处)、`Log In ‹ WordPress`、`name="log"`/`name="pwd"`/`name="redirect_to"`。 +- 响应头:`Cache-Control: no-store, no-cache, must-revalidate`、`x-robots-tag: noindex, nofollow`、`x-frame-options: DENY`。 +- POST 凭据提交 → 200 + `id="login_error">ERROR: Invalid username or password.`。 +- 路径变体全命中:`/WP-ADMIN`(大小写)、`/wp-admin%2f..%2fetc`(编码绕过)、`//wp-admin//x.php`(双斜杠)、`/.git/config`、`/.aws/credentials`、`/phpmyadmin/`、`/actuator/env`、`/xmlrpc.php`、`/vendor/phpunit/x.php`、`/console`、`/cgi-bin/test.cgi`、`/wp-content/plugins/x.php`、`/.env.bak`、`/wp-json/wp/v2/users`。 +- 凭据来源全覆盖:表单 POST、JSON body、BasicAuth、查询串、POST 到 `/.ssh/id_rsa`。 +- **业务路由零交集(红线)**:`/` 34192B、`/login` 23420B、`/register` 25194B、`/_/admin6` 39358B、`/user` 302、`/api/v1/questions` 302、`/robots.txt` 145B;非诱饵随机路径 `/nonexistent-random-xyz` 仍 302→`/`。 + +### P0 缺陷:蜜罐命中 70+ 次但站点零封禁 +- 根因:`autoban.Record()` 第一行 `if !b.enabled { return }`,`b.enabled` 来自 `enable_auto_ban`。 + 运维为避免共享出口误伤而关掉 `enable_auto_ban` → **蜜罐被另一个开关连坐**,只落库不封禁。 +- 对照组证明非蜜罐专属:`/index.php`(autoban 敏感、蜜罐不匹配)连打 40 次 + 30 并发同样零封禁。 +- 排除项:CF 缓存(DYNAMIC/无 Age)、flamego NotFound 链(源码确认全局 Use 链生效)、蜜罐匹配器、阈值配置。 + +**修复(已实施,测试全绿)**: +- `autoban.Options` 新增 `HoneypotEnabled` / `HoneypotThreshold`(默认 1)/ `HoneypotDuration`(默认复用常规)。 +- 新增 `Banner.RecordHoneypot(ip, path) bool`:独立计数、独立阈值,**不受 `enabled` 约束**;键与 `Record` 一致(同样 `shared.LimitKey` 归一化),否则 `IsBanned` 判不出来。 +- `IsBanned()` 移除 `!b.enabled` 早退 —— `enabled` 只控制「是否主动创建封禁」,不控制「是否尊重已有封禁」。 +- `internal/route/honeypot.go`:`banned = h.ab.RecordHoneypot(ip, path)`。 +- `internal/route/route.go`(CRLF)装配三个蜜罐字段;`conf/static.go` + `conf/app.sample.ini`(CRLF)新增 `honeypot_threshold` / `honeypot_ban_minutes`。 +- 告警:仍走既有 `sendAlert`(「已封禁」)+ 蜜罐自己的告警邮件(「捕获了什么凭据」),互补。 + +### 后缀匹配补缺 +- `/backup.zip`、`/db.sql`、`/id_rsa.pem` 这类泄露扫描文件名主体随机,**只有后缀稳定**。 +- 原 `honeypotFragments` 用 `"/.zip"` 子串匹配 → `.zip` 前是 `k` 不是 `/`,全漏网。 +- 新增 `honeypotSuffixes`(`.zip .tar .tar.gz .tgz .gz .rar .7z .bz2 .sql .sql.gz .dump .bak .old .orig .save .swp .env .env.bak .env.local .pem .key .p12 .pfx .jks .kdbx .ovpn`),按 `path.Base()` 结尾匹配。 + +### 踩坑 +- ⚠️ **测试里 `Duration: 60` = 60 纳秒**,封禁瞬间过期 → 表现为「时序巧合的 200/200/403」,测试假失败。一律写 `60 * time.Minute`。 +- ⚠️ 路由测试只注册路由 + NotFound 会被绕过:执行 `IsBanned` → 403 的是 **`autobanMiddleware`**,测试服务器必须 `f.Use(autobanMiddleware(ab, hp))`。 +- ⚠️ `internal/route/route.go`、`internal/conf/static.go`、`conf/app.sample.ini` **实际是全 CRLF**;`grep | cat -A` 不显示 `^M`,极易误判为 LF。Python 脚本按 `\n` 锚点替换会静默失败 → 用 `\r\n` 锚点 + 写后统计 `b'\r\n'` 复核。 +- 假页纯静态 HTML(内联 CSS,不落盘)、告警走 SMTP → **取证数据只在 `honeypot_hits` 一张表**,服务器无文件副本;autoban 封禁表是内存态(重启清零)。 +- 测试阶段产生的噪声凭据(`testadmin/S3cr3tP@ss` 等)可用 `TamaBox honeypot prune` 清理。 + +### 遗留(需用户侧) +- 本轮修复需**重新部署**才在测试站生效;部署后 `curl` 一次 `/wp-login.php` 应 200、再一次 403。 +- 需确认测试环境 `conf/app.ini` 的 `[security] enable_auto_ban`(零封禁直接原因)+ `enable_honeypot = true`。 +- 无法 SSH(`100.79.185.45:19999` 全部账号 Permission denied),落库验证需用户执行 `TamaBox honeypot hits --since 24h --show-password`。 diff --git a/.workbuddy/memory/topics/misc.md b/.workbuddy/memory/topics/misc.md index ae7b9bd..b8afd43 100644 --- a/.workbuddy/memory/topics/misc.md +++ b/.workbuddy/memory/topics/misc.md @@ -31,3 +31,9 @@ - 蜜罐 CLI:`TamaBox honeypot hits|stats|prune`(`--since 24h` / `--show-password` / `--yes`), 注册须在 `cmd/tamabox.go` + 根 `tamabox.go` 两处同步。 - 蜜罐配置:`[security] enable_honeypot` / `honeypot_paths` / `honeypot_retain_days`(默认全关)。 + +## 行尾与测试坑(2026-10-21 蜜罐轮) +- ⚠️ `internal/route/route.go`、`internal/conf/static.go`、`conf/app.sample.ini` **实际是全 CRLF**; + `grep | cat -A` 不显示 `^M` 极易误判 → Python 替换用 `\r\n` 锚点,写后统计 `b'\r\n'` 复核。 +- ⚠️ Go 里 `time.Duration(60)` = 60 **纳秒**,测试写裸数字会让封禁/冷却瞬间过期 → 一律 `60 * time.Minute`。 +- ⚠️ 测 `IsBanned` → 403 必须注册中间件(`f.Use(autobanMiddleware(ab, hp))`),只注册路由+NotFound 会被绕过。 diff --git a/.workbuddy/memory/topics/review.md b/.workbuddy/memory/topics/review.md index ace21f7..86f074e 100644 --- a/.workbuddy/memory/topics/review.md +++ b/.workbuddy/memory/topics/review.md @@ -37,3 +37,11 @@ - `HoneypotHit` 不嵌 `dbutil.Model`(审计证据只追加,不软删)。 - 假页只含 canary + 假信息;错误提示不区分「用户不存在」与「密码错误」(防用户名枚举)。 - 密码 CLI 默认脱敏;告警邮件含明文凭据 → 收件人只能是运维本人。 + +### 蜜罐封禁与 enable_auto_ban 解耦(2026-10-21 线上实测修复) +- ⚠️ **`Record()` 第一行 `if !b.enabled { return }` 会让 `enable_auto_ban=false` 连坐蜜罐** → + 蜜罐只落库不封禁(实测命中 70+ 次零封禁)。已修:新增 `RecordHoneypot()` 独立通道 + 独立阈值/时长。 +- `IsBanned()` 不得受 `enabled` 约束:`enabled` 只控制「是否主动创建封禁」,不控制「是否尊重已有封禁」。 +- `RecordHoneypot` 的键必须与 `Record` 一致(同样 `shared.LimitKey` 归一化),否则 `IsBanned` 判不出来。 +- 备份/配置/密钥泄露扫描(`/backup.zip`、`/db.sql`、`/id_rsa.pem`)文件名主体随机,**只有后缀稳定** + → 用 `path.Base()` 后缀匹配表,不能只靠子串(`"/.zip"` 匹配不到 `/backup.zip`)。 diff --git a/conf/app.sample.ini b/conf/app.sample.ini index 517fab7..ad6ec5d 100644 --- a/conf/app.sample.ini +++ b/conf/app.sample.ini @@ -80,6 +80,11 @@ enable_honeypot = false ; 开启后,扫描器探测后台路径( ; 假页面只含 canary 标记与假凭据,绝不含任何真实信息。 honeypot_paths = ; 追加自定义诱饵路径(逗号分隔),与内置清单取并集。 honeypot_retain_days = 30 ; 蜜罐命中记录的保留天数(取证用途),到期可用 CLI 清理。 +honeypot_threshold = 1 ; 窗口内蜜罐命中多少次即封禁。默认 1(一次即封):蜜罐路径 + ; 与真实业务路由零交集,正常访客不可能命中,一次即足以判定扫描器。 +honeypot_ban_minutes = ; 蜜罐封禁时长(分钟)。留空则复用 ban_duration_minutes(15)。 + ; ⚠️ 蜜罐封禁与 enable_auto_ban 相互独立:即使关掉自动封禁, + ; 只要 enable_honeypot = true,蜜罐命中仍会封禁并记录。 default_moderation_strictness = ; 站点默认「内容审核严格度」:lax(宽松)/ standard(标准)/ strict(严格)。 ; 仅对未单独设置档位的账号生效(账号在设置页选择后以账号设置为准)。 ; 留空回退 strict(最严档):保证升级不会放宽任何拦截。 diff --git a/internal/conf/static.go b/internal/conf/static.go index 2189c83..fbad9f8 100644 --- a/internal/conf/static.go +++ b/internal/conf/static.go @@ -87,6 +87,12 @@ var ( HoneypotPaths string `ini:"honeypot_paths"` // HoneypotRetainDays 蜜罐命中记录的保留天数,到期由 CLI 清理。 HoneypotRetainDays int `ini:"honeypot_retain_days"` + // HoneypotThreshold 窗口内蜜罐命中多少次即封禁。默认 1(一次即封): + // 蜜罐路径与真实业务路由零交集,正常访客不可能命中,一次即足以判定扫描器。 + // 留空回退 1。 + HoneypotThreshold int `ini:"honeypot_threshold"` + // HoneypotBanMinutes 蜜罐封禁时长(分钟)。留空则复用 ban_duration_minutes。 + HoneypotBanMinutes int `ini:"honeypot_ban_minutes"` SecurityAlertEmail string `ini:"security_alert_email"` // 触发封禁时告警收件人(留空不发送) } diff --git a/internal/route/autoban.go b/internal/route/autoban.go index cba5588..86952cc 100644 --- a/internal/route/autoban.go +++ b/internal/route/autoban.go @@ -43,7 +43,6 @@ func autobanMiddleware(b *autoban.Banner, hp *honeypot.Honeypot) flamego.Handler if kind != autoban.KindNone { defer b.Record(ip, path, kind) } - // 让下游业务路由先执行,敏感路径的计数延后到响应返回后记录。 ctx.Next() } diff --git a/internal/route/honeypot.go b/internal/route/honeypot.go index 17f797a..aa68082 100644 --- a/internal/route/honeypot.go +++ b/internal/route/honeypot.go @@ -63,12 +63,14 @@ func (h *honeypotHandler) Serve(ctx flamego.Context) { ip := shared.LimitKey(shared.ResolveClientIP(req)) path := req.URL.Path - // 记录与封禁:走既有 autoban 链路,复用阈值封禁与告警。 + // 封禁:走 autoban 的蜜罐独立通道(RecordHoneypot)。 + // + // 刻意不用常规的 Record:它受 enable_auto_ban 开关约束, + // 而蜜罐是显式开启的功能 —— 开了就该封禁,不该被另一个开关连坐。 + // 蜜罐路径与业务路由零交集,正常访客不可能命中,阈值取 1(一次即封)。 banned := false if h.ab != nil && ip != "" { - h.ab.Record(ip, path, autoban.KindSensitive) - // Record 内部在触发封禁时把 IP 写入 banned 表;此处再查一次得到确切状态。 - banned = h.ab.IsBanned(ip) + banned = h.ab.RecordHoneypot(ip, path) } // body 只能读一次:先提取凭据(POST 时读 body),再决定写哪种响应。 diff --git a/internal/route/honeypot_test.go b/internal/route/honeypot_test.go index 315bed3..4794adb 100644 --- a/internal/route/honeypot_test.go +++ b/internal/route/honeypot_test.go @@ -10,6 +10,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/flamego/flamego" @@ -22,17 +23,29 @@ import ( // 刻意不调用 route.New()(那会拉起 DB/Redis/session 依赖),而是复刻它的 // 关键结构:全局 Use 链 → 具体路由 → NotFound 蜜罐分流。 func newHoneypotTestServer(t *testing.T, enabled bool) *httptest.Server { + t.Helper() + return newHoneypotTestServerWith(t, enabled, true) +} + +// newHoneypotTestServerWith 可分别控制「蜜罐开关」与「常规自动封禁开关」, +// 用于验证两者相互独立(见 autoban.Options.HoneypotEnabled)。 +func newHoneypotTestServerWith(t *testing.T, enabled, autoBan bool) *httptest.Server { t.Helper() f := flamego.New() hp := honeypot.New(honeypot.Options{Enabled: enabled}) ab := autoban.New(autoban.Options{ - Enabled: true, + Enabled: autoBan, + HoneypotEnabled: enabled, ThresholdSensitive: 1, // 命中一次即封禁,便于断言 - Window: 60, - Duration: 60, + Window: 60 * time.Second, + Duration: 60 * time.Minute, // ⚠️ 必须是 time.Duration:写 60 是 60 纳秒,封禁瞬间即失效 }) hph := newHoneypotHandler(hp, ab, nil) // store=nil → 只走日志,不落库 + // 与 internal/route/route.go 一致:自动封禁中间件挂在全局 Use 链, + // 在业务路由与 NotFound 之前 —— 它负责检查「是否已封禁」并返回 403。 + f.Use(autobanMiddleware(ab, hp)) + f.Get("/login", func(ctx flamego.Context) { ctx.ResponseWriter().WriteHeader(http.StatusOK) _, _ = ctx.ResponseWriter().Write([]byte("REAL_LOGIN")) @@ -166,3 +179,58 @@ func TestHoneypotPostReturnsFailurePage(t *testing.T) { t.Error("提交凭据后应返回「用户名或密码无效」的假提示") } } + +// TestHoneypotBansEvenWhenAutoBanDisabled 是本次线上实测发现缺陷的回归测试。 +// +// 现象:蜜罐命中 70+ 次,站点一次都没封禁。 +// 根因:蜜罐复用了 autoban.Record,而 Record 受 enable_auto_ban 开关约束 —— +// 运维关掉自动封禁(它对共享出口误伤多)就连带让蜜罐只记录不封禁。 +// 修复:蜜罐走独立的 RecordHoneypot 通道,只看 enable_honeypot。 +func TestHoneypotBansEvenWhenAutoBanDisabled(t *testing.T) { + // 蜜罐开、常规自动封禁关 —— 这正是线上触发问题的组合 + ts := newHoneypotTestServerWith(t, true, false) + + // 第一次命中蜜罐 + resp, err := http.Get(ts.URL + "/wp-login.php") + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("首次命中 status = %d, want 200(应先返回假登录页)", resp.StatusCode) + } + + // 第二次:应已被蜜罐封禁 → 403 + resp2, err := http.Get(ts.URL + "/wp-login.php") + if err != nil { + t.Fatal(err) + } + defer resp2.Body.Close() + body, _ := io.ReadAll(resp2.Body) + if resp2.StatusCode != http.StatusForbidden { + t.Errorf("status = %d, want 403(蜜罐封禁不得被 enable_auto_ban 连坐)", resp2.StatusCode) + } + if !strings.Contains(string(body), "403 Forbidden") { + t.Errorf("body = %q, want 含 \"403 Forbidden\"", truncate(string(body), 80)) + } +} + +// TestHoneypotBanBlocksBusinessRoutes 验证:被蜜罐封禁的 IP 连正常业务路由也进不去。 +func TestHoneypotBanBlocksBusinessRoutes(t *testing.T) { + ts := newHoneypotTestServerWith(t, true, false) + + resp, err := http.Get(ts.URL + "/wp-login.php") + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + + resp2, err := http.Get(ts.URL + "/login") + if err != nil { + t.Fatal(err) + } + defer resp2.Body.Close() + if resp2.StatusCode != http.StatusForbidden { + t.Errorf("status = %d, want 403(被封禁的 IP 不应还能访问业务路由)", resp2.StatusCode) + } +} diff --git a/internal/security/autoban/autoban.go b/internal/security/autoban/autoban.go index c970939..a5a2bd8 100644 --- a/internal/security/autoban/autoban.go +++ b/internal/security/autoban/autoban.go @@ -37,6 +37,24 @@ type Options struct { Duration time.Duration // 封禁时长 AlertEmail string // 告警收件人(留空不发送) SendAlert func(ip string, paths []string, durationMinutes int) error // 告警发送函数(nil 则不发送) + + // HoneypotEnabled 独立于 Enabled:蜜罐(假后台登录页 + 破解凭据取证)是显式 + // 开启的功能,命中即应封禁,不应被 enable_auto_ban 连坐。 + // + // 为什么必须独立:蜜罐命中的是「有人在真的往假登录表单里填账号密码」, + // 证据强度远高于「访问了一个可疑路径」。若两者共用同一个 enabled 开关, + // 运维关掉 enable_auto_ban(因为它对共享出口误伤多)就会连带让蜜罐变成 + // 只记录不封禁的旁观者 —— 蜜罐的全部价值(威慑 + 阻断)就消失了。 + // + // 开启后蜜罐命中仍走同一套计数/阈值/告警机制,只是绕开 enabled 早退。 + HoneypotEnabled bool + // HoneypotThreshold 蜜罐独立阈值:窗口内蜜罐命中次数达到即封禁。 + // 默认 1(一次即封)—— 蜜罐路径与业务路由零交集,正常访客不可能命中, + // 一次命中就足以判定为扫描器,无需等 autoban 的 10 次阈值。 + // 留空或 <= 0 时兜底为 1。 + HoneypotThreshold int + // HoneypotDuration 蜜罐独立封禁时长,<= 0 时复用 Duration。 + HoneypotDuration time.Duration } // sensitivePaths 常见后台/配置/漏洞探测路径特征(忽略大小写,完整段前缀匹配)。 @@ -91,6 +109,11 @@ type Banner struct { alertEmail string sendAlert func(ip string, paths []string, durationMinutes int) error enabled bool + + // 蜜罐独立通道(见 Options.HoneypotEnabled 的说明)。 + honeypotEnabled bool + honeypotThreshold int + honeypotDuration time.Duration } // New 按配置创建封禁器并注册全局清理。 @@ -111,6 +134,14 @@ func New(opts Options) *Banner { if notFound <= 0 { notFound = DefaultThreshold404 } + honeypotThreshold := opts.HoneypotThreshold + if honeypotThreshold <= 0 { + honeypotThreshold = 1 + } + honeypotDuration := opts.HoneypotDuration + if honeypotDuration <= 0 { + honeypotDuration = duration + } b := &Banner{ probes: make(map[string]*probeStat), banned: make(map[string]time.Time), @@ -123,11 +154,79 @@ func New(opts Options) *Banner { alertEmail: strings.TrimSpace(opts.AlertEmail), sendAlert: opts.SendAlert, enabled: opts.Enabled, + honeypotEnabled: opts.HoneypotEnabled, + honeypotThreshold: honeypotThreshold, + honeypotDuration: honeypotDuration, } register(b) return b } +// RecordHoneypot 记录一次蜜罐命中,命中即封禁。 +// +// 与 Record 的区别: +// - 不受 enabled(enable_auto_ban)约束 —— 蜜罐是显式开启的功能, +// 开启即意味着要对命中者封禁(详见 Options.HoneypotEnabled); +// - 走独立的阈值(默认 1 次即封)与时长(默认复用常规时长); +// - 键与 Record 完全一致(同样经 shared.LimitKey 归一化), +// 否则 IsBanned 判不出来,封禁形同虚设。 +// +// 告警仍走既有的 sendAlert 通道(每 IP 一次),与蜜罐自己的告警邮件互补: +// 前者说明「已封禁」,后者说明「捕获到了什么凭据」。 +func (b *Banner) RecordHoneypot(ip, path string) bool { + if !b.honeypotEnabled || ip == "" { + return false + } + b.mu.Lock() + defer b.mu.Unlock() + + now := time.Now() + cutoff := now.Add(-b.window) + + st := b.probes[ip] + if st == nil { + st = &probeStat{} + b.probes[ip] = st + } + + // 滚动清理过期事件(只统计窗口内的蜜罐命中) + valid := st.events[:0] + hits := 0 + for _, e := range st.events { + if e.at.After(cutoff) { + valid = append(valid, e) + hits++ + } + } + valid = append(valid, probeEvent{at: now, kind: KindSensitive}) + hits++ + st.events = valid + st.sensitive = hits + if len(st.paths) < pathSampleMax && path != "" { + st.paths = append(st.paths, path) + } + + if hits < b.honeypotThreshold { + return false + } + // 已在封禁中则跳过 + if until, ok := b.banned[ip]; ok && until.After(now) { + return true + } + b.banned[ip] = now.Add(b.honeypotDuration) + + // 告警(每 IP 仅一次) + if b.alertEmail != "" && b.sendAlert != nil && !b.alerted[ip] { + b.alerted[ip] = true + sample := append([]string{}, st.paths...) + dur := int(b.honeypotDuration.Minutes()) + go func() { + _ = b.sendAlert(ip, sample, dur) + }() + } + return true +} + // Record 记录一次探测事件,达到阈值时封禁 IP 并触发一次告警。 func (b *Banner) Record(ip, path string, kind int) { if !b.enabled || ip == "" || kind == KindNone { @@ -199,8 +298,12 @@ func (b *Banner) Record(ip, path string, kind int) { } // IsBanned 判断 IP 是否处于封禁期;到期自动解除。 +// +// 注意:即使 enabled(enable_auto_ban)关闭,蜜罐通道写入的封禁依然生效 —— +// 否则「关了自动封禁就等于连蜜罐的封禁一起关了」,与 Options.HoneypotEnabled +// 的设计意图相悖。enabled 只控制「是否主动创建封禁」,不控制「是否尊重已有封禁」。 func (b *Banner) IsBanned(ip string) bool { - if !b.enabled || ip == "" { + if ip == "" { return false } b.mu.Lock() diff --git a/internal/security/autoban/honeypot_test.go b/internal/security/autoban/honeypot_test.go new file mode 100644 index 0000000..adfdf7b --- /dev/null +++ b/internal/security/autoban/honeypot_test.go @@ -0,0 +1,123 @@ +// Copyright 2026 tamakyi. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package autoban + +import ( + "testing" + "time" +) + +// TestHoneypotBanIndependentOfAutoBan 覆盖 P0:蜜罐封禁不得被 enable_auto_ban 连坐。 +// +// 背景(线上实测发现):蜜罐命中 70+ 次,站点一次都没封禁。 +// 根因是蜜罐复用了 Record(),而 Record() 第一行就 `if !b.enabled { return }` —— +// 运维一旦关掉 enable_auto_ban(它对共享出口误伤多,常被关掉), +// 蜜罐就退化成「只记录不封禁」的旁观者,全部价值(威慑 + 阻断)消失。 +// +// 修复:蜜罐走独立的 RecordHoneypot 通道,只看 HoneypotEnabled。 +func TestHoneypotBanIndependentOfAutoBan(t *testing.T) { + b := New(Options{ + Enabled: false, // 自动封禁关闭 + HoneypotEnabled: true, // 但蜜罐开启 + Window: 60 * time.Second, + Duration: 15 * time.Minute, + }) + + // 常规敏感路径不再计数(enable_auto_ban 关闭) + b.Record("1.2.3.4", "/wp-admin", KindSensitive) + if b.IsBanned("1.2.3.4") { + t.Error("enable_auto_ban 关闭时,常规敏感路径不应产生封禁") + } + + // 蜜罐命中必须立即封禁 + if !b.RecordHoneypot("5.6.7.8", "/wp-login.php") { + t.Error("RecordHoneypot 应在首次命中时封禁") + } + if !b.IsBanned("5.6.7.8") { + t.Error("蜜罐命中后 IsBanned 应为 true(蜜罐封禁不得被 enable_auto_ban 连坐)") + } + // 其它 IP 不受影响 + if b.IsBanned("9.9.9.9") { + t.Error("无关 IP 不应被封禁") + } +} + +// TestHoneypotDisabledNoBan 覆盖反向:蜜罐关闭时不应封禁。 +func TestHoneypotDisabledNoBan(t *testing.T) { + b := New(Options{ + Enabled: true, + HoneypotEnabled: false, + Window: 60 * time.Second, + Duration: 15 * time.Minute, + }) + if b.RecordHoneypot("1.2.3.4", "/wp-login.php") { + t.Error("蜜罐关闭时不应封禁") + } + if b.IsBanned("1.2.3.4") { + t.Error("蜜罐关闭时不应产生封禁") + } +} + +// TestHoneypotThreshold 覆盖蜜罐独立阈值:默认 1 次即封,可配为 N 次。 +func TestHoneypotThreshold(t *testing.T) { + b := New(Options{ + Enabled: false, + HoneypotEnabled: true, + HoneypotThreshold: 3, + Window: 60 * time.Second, + Duration: 15 * time.Minute, + }) + if b.RecordHoneypot("1.2.3.4", "/wp-login.php") { + t.Error("第 1 次不应封禁(阈值 3)") + } + if b.RecordHoneypot("1.2.3.4", "/wp-login.php") { + t.Error("第 2 次不应封禁(阈值 3)") + } + if !b.RecordHoneypot("1.2.3.4", "/wp-login.php") { + t.Error("第 3 次应封禁(阈值 3)") + } + if !b.IsBanned("1.2.3.4") { + t.Error("达到阈值后 IsBanned 应为 true") + } +} + +// TestHoneypotDurationIndependent 覆盖蜜罐独立封禁时长。 +func TestHoneypotDurationIndependent(t *testing.T) { + b := New(Options{ + Enabled: false, + HoneypotEnabled: true, + Duration: 15 * time.Minute, // 常规时长 + HoneypotDuration: 5 * time.Minute, // 蜜罐时长 + Window: 60 * time.Second, + }) + b.RecordHoneypot("1.2.3.4", "/wp-login.php") + + b.mu.Lock() + until := b.banned["1.2.3.4"] + b.mu.Unlock() + + if until.IsZero() { + t.Fatal("未写入封禁记录") + } + remaining := time.Until(until) + if remaining > 6*time.Minute { + t.Errorf("蜜罐封禁时长应约 5 分钟,实际剩余 %v", remaining) + } +} + +// TestIsBannedRespectsExistingBan 覆盖:enabled 关闭时,已有的封禁依然被尊重。 +// 这是蜜罐封禁能真正挡住后续请求的前提。 +func TestIsBannedRespectsExistingBan(t *testing.T) { + b := New(Options{ + Enabled: false, + HoneypotEnabled: true, + Window: 60 * time.Second, + Duration: 15 * time.Minute, + }) + b.RecordHoneypot("1.2.3.4", "/wp-login.php") + if !b.IsBanned("1.2.3.4") { + t.Error("enabled 关闭时仍应尊重已存在的蜜罐封禁") + } +} diff --git a/internal/security/honeypot/honeypot.go b/internal/security/honeypot/honeypot.go index 22b017a..cca071b 100644 --- a/internal/security/honeypot/honeypot.go +++ b/internal/security/honeypot/honeypot.go @@ -51,7 +51,21 @@ var honeypotFragments = []string{ "/wp-config", "/xmlrpc.php", "/wordpress", "/phpmyadmin", "/cgi-bin/", "/.git/", "/.env", "/.aws/", "/.ssh/", "/actuator/", "/swagger", "/druid/", "/solr/", "/nacos/", "/vuln", "/shell?", "/cmd?", - "/.bak", "/.old", "/.orig", "/.save", "/.swp", "/.zip", "/.tar.gz", "/.sql", + "/.bak", "/.old", "/.orig", "/.save", "/.swp", +} + +// honeypotSuffixes 是按「路径结尾」匹配的敏感文件后缀。 +// +// 为什么单独列:备份/配置类泄露扫描(/backup.zip、/db.sql、/site.tar.gz、/x.bak) +// 的文件名主体是随机的,只有后缀稳定。上一版用子串 "/.zip" 匹配, +// 结果 /backup.zip 命中不了(前面是 "k" 不是 "/"),而 /www.zip、/1.sql 全部漏网。 +// 结尾匹配既精确又不会误伤业务路由(业务 URL 空间里不存在这些后缀), +// 且 forbiddenPrefixes 仍会先剔除业务前缀。 +var honeypotSuffixes = []string{ + ".zip", ".tar", ".tar.gz", ".tgz", ".gz", ".rar", ".7z", ".bz2", + ".sql", ".sql.gz", ".dump", ".bak", ".old", ".orig", ".save", + ".swp", ".env", ".env.bak", ".env.local", + ".pem", ".key", ".p12", ".pfx", ".jks", ".kdbx", ".ovpn", } // forbiddenPrefixes 是业务路由前缀:即便有人往诱饵表里塞了这些前缀, @@ -161,6 +175,13 @@ func (h *Honeypot) Match(rawPath string) bool { return true } } + // 后缀匹配:备份/配置/密钥类泄露扫描(/backup.zip、/db.sql、/id_rsa.pem)。 + base := path.Base(p) + for _, s := range honeypotSuffixes { + if strings.HasSuffix(base, s) { + return true + } + } return false } diff --git a/internal/security/honeypot/honeypot_test.go b/internal/security/honeypot/honeypot_test.go index fa8add6..6a07a1d 100644 --- a/internal/security/honeypot/honeypot_test.go +++ b/internal/security/honeypot/honeypot_test.go @@ -16,6 +16,10 @@ func TestMatch(t *testing.T) { "/administrator", "/phpmyadmin", "/actuator/env", "/swagger-ui.html", "/xmlrpc.php", "/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php", "/wp-admin/../wp-content/x.php", + // 后缀匹配:备份/配置/密钥泄露扫描 + "/backup.zip", "/www.zip", "/site.tar.gz", "/db.sql", "/dump.sql", + "/x.bak", "/config.php.bak", "/.env.bak", "/id_rsa.pem", "/private.key", + "/server.jks", "/data.ovpn", } for _, p := range hit { if !h.Match(p) { @@ -29,6 +33,8 @@ func TestMatch(t *testing.T) { "/api/v1/questions", "/static/css/base.css", "/favicon.ico", "/robots.txt", "/about", "/rules", "/sponsor", "/change-logs.html", "/vote/abc", "/explore", "/i18n/en", + // 业务 URL 空间里不存在这些后缀 + "/_/admin.ini", "/api/v1/questions.json", "/user/settings.yaml", } for _, p := range miss { if h.Match(p) {