fix(honeypot): 取证记精确地址、封禁用 /64 键,并补建封与拦截日志

线上实测:IPv6 访问蜜罐后收到「你的 IP 已被封禁」,邮件里却是
`2408:…::/64` —— 既不像自己的地址,也说不清封了多大范围;同时用户自己
仍能正常访问,看日志也无从判断到底有没有封。

根因是「取证地址」与「封禁键」混用同一个变量(都取 LimitKey 的折叠值):
- 取证丢掉精确 IPv6 后 64 位,事后无法定位到具体主机、没法和其他日志对账;
- 邮件只给聚合键,运维第一反应是「不是我」,排查方向直接被带偏。

改动:
- Serve 拆 clientIP(ResolveClientIP,精确)与 banKey(LimitKey,/64):
  DB / 凭据文件 / 告警邮件用前者,封禁 / 探测采样 / 告警去重用后者;
- autoban.Options 新增 OnBan 回调(保持纯标准库、不引入 logrus),
  route.newBanner 注入后每次建封打 WARN:ban_key / reason / duration / expires_at;
  中间件 403 分支加 Debug 日志(被封者会持续请求,Info 会被刷屏);
- 告警邮件新增「封禁范围」行,仅 ip != ban_key 时渲染(IPv4 不重复显示),
  顺带把过时的「已入库」改为「写入取证文件」——凭据早就外置了;
- honeypot stats 的来源排行改按 LimitKey 合并,否则 IPv6 轮换地址会把
  排行碎成几十条各 1 次的记录;合并口径与封禁完全一致。

测试(每项都做了变异验证:改坏→确认变红→恢复):
- TestHoneypotRecordsExactIPv6ButBansByPrefix:精确地址进 DB 与凭据文件、
  /64 才是封禁键、同 /64 换地址仍 403;
- TestOnBanCallback:建封回调带键/时长/原因,封禁期内重复命中不重复回调;
- TestHoneypotAlertTemplateRenders:IPv6 渲染封禁范围、IPv4 不重复;
- TestMergeSourcesByKey:同 /64 合并、IPv4 原样、limit 与空输入。
This commit is contained in:
tamakyi
2026-10-23 10:53:03 +08:00
parent aa758884f9
commit 818fa74160
13 changed files with 511 additions and 38 deletions
+56 -2
View File
@@ -7,6 +7,7 @@ package cmd
import (
"context"
"fmt"
"sort"
"strings"
"time"
@@ -16,6 +17,7 @@ import (
"github.com/tamakyi/TamaBox/internal/conf"
"github.com/tamakyi/TamaBox/internal/db"
"github.com/tamakyi/TamaBox/internal/security/honeypot"
"github.com/tamakyi/TamaBox/internal/shared"
)
// Honeypot 提供蜜罐取证命令(只读 + 一条显式清理)。
@@ -193,10 +195,18 @@ func runHoneypotStats(ctx *cli.Context) error {
if err != nil {
return errors.Wrap(err, "count honeypot hits")
}
sources, err := store.TopSources(cctx, since, ctx.Int("limit"))
// 元数据表存的是精确地址(取证需要),但 IPv6 攻击者常在一个 /64 内轮换地址:
// 直接按精确 IP 排行会碎成几十条各 1 次的记录,看不出「其实是同一个人」。
// 多取一些再按封禁同口径(/64)合并,见 mergeSourcesByKey。
limit := ctx.Int("limit")
if limit <= 0 {
limit = 20
}
sources, err := store.TopSources(cctx, since, limit*4)
if err != nil {
return errors.Wrap(err, "query top sources")
}
sources = mergeSourcesByKey(sources, limit)
paths, err := store.TopPaths(cctx, since, ctx.Int("limit"))
if err != nil {
return errors.Wrap(err, "query top paths")
@@ -213,7 +223,7 @@ func runHoneypotStats(ctx *cli.Context) error {
fmt.Printf("蜜罐统计:近 %d 天,共 %d 次命中\n", days, total)
fmt.Println(strings.Repeat("-", 72))
fmt.Println("来源 IP 排行:")
fmt.Println("来源排行(IPv6 按 /64 聚合,与封禁口径一致):")
if len(sources) == 0 {
fmt.Println(" 无")
}
@@ -495,3 +505,47 @@ func maskSecret(s string) string {
return string(r[0]) + strings.Repeat("*", 6) + string(r[len(r)-1])
}
}
// mergeSourcesByKey 按「封禁 / 限流」的同一口径合并来源排行。
//
// 元数据表存的是精确地址(取证需要,见 db.HoneypotHit.IP),但 IPv6 攻击者
// 通常在一个 /64 内轮换地址:直接按精确 IP 排行会碎成几十条各 1 次的记录,
// 看不出「其实是同一台机器」。这里用 shared.LimitKey 折成 /64 ——
// 与 autoban 判定、限流的键完全一致,看到的排行就是「谁在被封」。
//
// 代价:SQL 只取了前 limit*4 条精确地址,极端长尾可能漏算,排行本身是近似展示。
func mergeSourcesByKey(rows []*db.HoneypotSourceStat, limit int) []*db.HoneypotSourceStat {
if len(rows) == 0 {
return rows
}
type agg struct {
count int64
provider string
}
merged := make(map[string]*agg, len(rows))
for _, r := range rows {
key := shared.LimitKey(r.IP)
if a, ok := merged[key]; ok {
a.count += r.Count
if a.provider == "" {
a.provider = r.Provider
}
continue
}
merged[key] = &agg{count: r.Count, provider: r.Provider}
}
out := make([]*db.HoneypotSourceStat, 0, len(merged))
for key, a := range merged {
out = append(out, &db.HoneypotSourceStat{IP: key, Count: a.count, Provider: a.provider})
}
sort.Slice(out, func(i, j int) bool {
if out[i].Count != out[j].Count {
return out[i].Count > out[j].Count
}
return out[i].IP < out[j].IP // 同次数时稳定排序,避免每次输出顺序抖动
})
if limit > 0 && len(out) > limit {
out = out[:limit]
}
return out
}
+46
View File
@@ -0,0 +1,46 @@
// 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 cmd
import (
"testing"
"github.com/tamakyi/TamaBox/internal/db"
)
// TestMergeSourcesByKey 验证来源排行按「封禁口径」合并(IPv6 折成 /64)。
//
// 元数据表存的是精确地址(取证需要),若排行榜也按精确地址分组,
// 一个在 /64 内轮换地址的扫描器会碎成几十条各 1 次的记录 ——
// 看起来像「很多人在扫」,其实只有一台机器。合并口径必须与 autoban 一致。
func TestMergeSourcesByKey(t *testing.T) {
rows := []*db.HoneypotSourceStat{
{IP: "2408:8207:1234:5678::1", Count: 5, Provider: "联通"},
{IP: "2408:8207:1234:5678::2", Count: 3},
{IP: "1.2.3.4", Count: 4, Provider: "Azure"},
{IP: "2408:8207:9999:0001::1", Count: 2},
}
got := mergeSourcesByKey(rows, 10)
if len(got) != 3 {
t.Fatalf("合并后条目数 = %d, want 3(同 /64 必须合并)", len(got))
}
if got[0].IP != "2408:8207:1234:5678::/64" || got[0].Count != 8 {
t.Errorf("第一名 = %s / %d, want 2408:8207:1234:5678::/64 / 8", got[0].IP, got[0].Count)
}
if got[0].Provider != "联通" {
t.Errorf("合并后应保留首个非空归属,got %q", got[0].Provider)
}
if got[1].IP != "1.2.3.4" || got[1].Count != 4 {
t.Errorf("第二名 = %s / %d, want 1.2.3.4 / 4(IPv4 原样保留)", got[1].IP, got[1].Count)
}
if limited := mergeSourcesByKey(rows, 1); len(limited) != 1 {
t.Errorf("limit=1 时条目数 = %d, want 1", len(limited))
}
if out := mergeSourcesByKey(nil, 10); len(out) != 0 {
t.Errorf("空输入应返回空,got %d", len(out))
}
}