Files
tamabox/internal/cmd/honeypot_test.go
T
tamakyi 818fa74160 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 与空输入。
2026-10-23 10:53:03 +08:00

47 lines
1.7 KiB
Go
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.
// 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))
}
}