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
+57 -30
View File
@@ -131,7 +131,16 @@ func newHoneypotHandler(hp *honeypot.Honeypot, ab *autoban.Banner, store db.Hone
// Serve 处理一次蜜罐命中。
func (h *honeypotHandler) Serve(ctx flamego.Context) {
req := ctx.Request().Request
ip := shared.LimitKey(shared.ResolveClientIP(req))
// 两个不同的东西,必须分开用:
//
// clientIP —— 精确客户端地址(IPv6 保留完整地址),取证与告警展示用;
// banKey —— 聚合键(shared.LimitKey,IPv6 折成 /64),封禁与采样去重用。
//
// 曾经两者混用(都取 banKey),后果是取证只留下 /64 前缀:运维收到
// 「你的 IP 已被封禁」时发现邮件里那个地址根本不是自己的,排查方向直接被带偏;
// 而且精确地址一丢,拿去查其他日志或做 abuse 投诉就再也对不上了。
clientIP := shared.ResolveClientIP(req)
banKey := shared.LimitKey(clientIP)
// 反代/网关可能把 URI 带上首尾空白:实测 Cloudflare → nginx → 源站 链路上
// 出现过 ` /wp-login.php`。Match 内部会 normalize(含 TrimSpace),所以能命中,
// 但落库与假表单的 action 用的是原始值 —— 会留下脏取证数据,
@@ -141,9 +150,10 @@ func (h *honeypotHandler) Serve(ctx flamego.Context) {
// 这类字符肉眼不可见,裸打印会看不出哪里不同(曾经为此排查了一轮)。
if raw := req.URL.Path; raw != path {
logrus.WithFields(logrus.Fields{
"ip": ip,
"raw": fmt.Sprintf("%q", raw),
"used": fmt.Sprintf("%q", path),
"ip": clientIP,
"ban_key": banKey,
"raw": fmt.Sprintf("%q", raw),
"used": fmt.Sprintf("%q", path),
}).Warn("蜜罐路径含上游注入的空白/零宽字符,已清洗后使用")
}
@@ -151,7 +161,7 @@ func (h *honeypotHandler) Serve(ctx flamego.Context) {
// 典型信号。此时所有访客在源站眼里都是同一个 IP:
// 取证数据失去意义,且一次封禁会连带封掉整站(包括普通访客)。
// 只告警不改变行为 —— 本地直连调试时回环 IP 是正常的。
if ip != "" && !conf.Security.TrustProxy && isLoopbackIP(ip) {
if clientIP != "" && !conf.Security.TrustProxy && isLoopbackIP(clientIP) {
if h.dedup.first("warn:loopback", 24*time.Hour) {
logrus.Warn("蜜罐记录的来源 IP 是回环地址(127.0.0.1 / ::1):站点很可能在反向代理后面," +
"[security] trust_proxy 未开启。此时所有访客共享同一个 IP —— 取证失去意义," +
@@ -173,11 +183,11 @@ func (h *honeypotHandler) Serve(ctx flamego.Context) {
//
// 纯探测不封也不会被刷爆:落库有「每 IP 每分钟一条」的采样(见 record)。
banned := false
if h.ab != nil && ip != "" {
if h.ab != nil && banKey != "" {
if creds.HadFields {
banned = h.ab.RecordHoneypot(ip, path)
banned = h.ab.RecordHoneypot(banKey, path)
} else {
h.ab.Record(ip, path, autoban.KindSensitive)
h.ab.Record(banKey, path, autoban.KindSensitive)
}
}
@@ -192,7 +202,7 @@ func (h *honeypotHandler) Serve(ctx flamego.Context) {
}
// 落库留证。落库失败只记日志,绝不影响已写出的响应。
h.record(ip, req, path, creds, banned)
h.record(clientIP, banKey, req, path, creds, banned)
}
// cleanPath 去掉路径首尾的空白与零宽字符,并保证前导斜杠。
@@ -266,12 +276,14 @@ func (h *honeypotHandler) writeLogin(ctx flamego.Context, path, notice string) {
// record 追加一条命中记录(列宽对齐 + 探测采样都在这里收口)。
//
// clientIP 是精确客户端地址(写进取证数据),banKey 是聚合键(只用于采样去重)。
// 采样理由:honeypot_hits 的写入完全由外部流量驱动,一个诱饵 404 就 INSERT
// 一行,等于把「零成本探测」放大成数据库写压力;而 20 万行的数量闸每小时
// 才跑一轮,挡不住短时洪泛。提交了凭据的请求才是高价值证据(必须一条不漏),
// 纯路径探测按 IP + 窗口采样即可 —— 路径分布仍然保留。
func (h *honeypotHandler) record(ip string, req *http.Request, path string, creds honeypot.Credentials, banned bool) {
if !creds.HadFields && !h.dedup.first("probe:"+ip, probeSampleWindow) {
// 纯路径探测按来源 + 窗口采样即可 —— 路径分布仍然保留。
func (h *honeypotHandler) record(clientIP, banKey string, req *http.Request, path string, creds honeypot.Credentials, banned bool) {
// 采样按聚合键:同一 /64 内轮换地址的探测属于同一个来源,不必各存一条。
if !creds.HadFields && !h.dedup.first("probe:"+banKey, probeSampleWindow) {
return
}
@@ -283,10 +295,10 @@ func (h *honeypotHandler) record(ip string, req *http.Request, path string, cred
// 凭据先落文件:这是不可再生的证据,优先级高于元数据入库。
// 写失败只告警 —— 响应已经发出去了,取证失败不能反过来影响请求。
if creds.HadFields {
h.saveCredential(ip, req, path, query, creds, banned)
h.saveCredential(clientIP, req, path, query, creds, banned)
}
provider, proxied := ipinfo.Lookup(ip)
provider, proxied := ipinfo.Lookup(clientIP)
// 元数据入库。这里刻意只有「发生过一次带凭据的提交」这个事实(HadFields),
// 不含任何凭据内容 —— 见 db.HoneypotHit.HadFields 的注释。
@@ -294,7 +306,7 @@ func (h *honeypotHandler) record(ip string, req *http.Request, path string, cred
// 以 `value too long for type character varying(N)` 整条插入失败 ——
// 取证记录静默丢失,而攻击者只要发一个超长 URL 就能稳定触发。
hit := &db.HoneypotHit{
IP: truncate(ip, 64),
IP: truncate(clientIP, 64),
Method: truncate(req.Method, 16),
Path: truncate(path, 500),
Query: truncate(query, 1000),
@@ -311,13 +323,14 @@ func (h *honeypotHandler) record(ip string, req *http.Request, path string, cred
// 只有真的提交了凭据才告警:纯路径探测(GET)没有取证价值,
// 而爆破脚本往往在封禁前反复 POST,只告警一次即可。
if creds.HadFields {
h.alert(ip, req, path, creds, provider, proxied, banned)
h.alert(clientIP, banKey, req, path, creds, provider, proxied, banned)
}
// 有凭据的提交才是高价值证据,日志里点名;纯探测只记路径。
if creds.HadFields {
logrus.WithFields(logrus.Fields{
"ip": ip,
"ip": clientIP,
"ban_key": banKey,
"path": path,
"username": creds.Username,
"banned": banned,
@@ -331,7 +344,7 @@ func (h *honeypotHandler) record(ip string, req *http.Request, path string, cred
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := h.store.Create(ctx, hit); err != nil {
logrus.WithError(err).WithField("ip", ip).WithField("path", path).
logrus.WithError(err).WithField("ip", clientIP).WithField("path", path).
Warn("honeypot: failed to persist hit")
}
}
@@ -345,15 +358,17 @@ func (h *honeypotHandler) record(ip string, req *http.Request, path string, cred
//
// 文件写入失败只告警不重试:蜜罐是尽力而为的取证,不能因为磁盘满
// 反过来影响已经发出的响应;而且重试会放大攻击者的写入能力。
func (h *honeypotHandler) saveCredential(ip string, req *http.Request, path, query string, creds honeypot.Credentials, banned bool) {
// clientIP 必须是精确地址(不是 shared.LimitKey 折叠后的 /64 键):
// 这份文件是取证物,IPv6 只留前缀等于把「哪台主机」永久丢掉了。
func (h *honeypotHandler) saveCredential(clientIP string, req *http.Request, path, query string, creds honeypot.Credentials, banned bool) {
if h.cstore == nil {
logrus.WithField("ip", ip).
logrus.WithField("ip", clientIP).
Warn("蜜罐捕获到凭据,但凭据目录不可用,本条凭据未被保存")
return
}
rec := honeypot.CredRecord{
Time: time.Now(),
IP: truncate(ip, 64),
IP: truncate(clientIP, 64),
Method: truncate(req.Method, 16),
Path: truncate(path, 500),
Query: truncate(query, 1000),
@@ -365,18 +380,26 @@ func (h *honeypotHandler) saveCredential(ip string, req *http.Request, path, que
Banned: banned,
}
if err := h.cstore.Append(rec); err != nil {
logrus.WithError(err).WithField("ip", ip).Warn("蜜罐凭据写入文件失败")
logrus.WithError(err).WithField("ip", clientIP).Warn("蜜罐凭据写入文件失败")
}
}
// alert 发送一次告警邮件(每个 IP 只发一次)。
func (h *honeypotHandler) alert(ip string, req *http.Request, path string, creds honeypot.Credentials, provider string, proxied, banned bool) {
if h.sendAlert == nil || ip == "" {
// alert 发送一次告警邮件(同一来源在冷却期内只发一封)。
//
// clientIP 进正文(人要看的是「谁来了」,必须是精确地址);
// banKey 用作去重键,同时也让邮件能说清「实际被封的是哪个键」——
// IPv6 下两者不同(键是 /64 前缀),邮件只给其中一个都会让人误判。
func (h *honeypotHandler) alert(clientIP, banKey string, req *http.Request, path string, creds honeypot.Credentials, provider string, proxied, banned bool) {
if h.sendAlert == nil || clientIP == "" {
return
}
// 同一 IP 在冷却期内只发一封:爆破脚本会在封禁前反复 POST,
// 不去重会把邮箱打爆(且每个源 IP 都是一封)。
if !h.dedup.first("alert:"+ip, alertDedupTTL) {
dedupKey := banKey
if dedupKey == "" {
dedupKey = clientIP
}
// 同一来源在冷却期内只发一封:爆破脚本会在封禁前反复 POST,
// 不去重会把邮箱打爆。按聚合键去重 —— 同一 /64 内换地址仍是同一个人。
if !h.dedup.first("alert:"+dedupKey, alertDedupTTL) {
return
}
@@ -391,7 +414,8 @@ func (h *honeypotHandler) alert(ip string, req *http.Request, path string, creds
}
go func() {
if err := h.sendAlert(mail.HoneypotAlert{
IP: ip,
IP: clientIP,
BanKey: banKey,
Provider: provider,
Proxied: proxied,
Path: path,
@@ -400,7 +424,10 @@ func (h *honeypotHandler) alert(ip string, req *http.Request, path string, creds
Banned: banned,
DurationMin: durationMin,
}); err != nil {
logrus.WithError(err).WithField("ip", ip).Warn("honeypot: failed to send alert mail")
logrus.WithError(err).WithFields(logrus.Fields{
"ip": clientIP,
"ban_key": banKey,
}).Warn("honeypot: failed to send alert mail")
}
}()
}