feat(honeypot): 蜜罐安全状况周期汇总(周报/月报 + 地图 + 邮件)

以周/月为单位汇总蜜罐命中,把来源 IP 通过公共服务查地理位置,画到地图上,
生成 HTML 报告并发邮件。同时补齐 ipinfo 无法回答「这个 IP 在哪儿」的问题。

新增 IP 地理定位层 internal/security/geoip:
- 与 internal/security/ipinfo 正交。ipinfo 走 cdncheck 离线指纹,只认云厂商/CDN/WAF,
  答的是「是不是代理」;肉鸡(家宽、企业宽带、移动网络)必然被判为
  「未识别(普通网络)」,所以「在哪儿」必须另建一套。
- ip-api.com 批量打底(100 个/请求、1.4s 节流)+ 腾讯位置服务精修国内
  (一 IP 一请求,只精修命中数最高的前 N 个,受 ip_geo_tencent_key 控制)。
- Result{Geo, Unresolved, Requests, Failures} 三态。服务明确回答「没有这个地址」
  才允许写失败缓存;请求超时/限流/5xx 一律不写 —— 否则一次抖动会把整批 IP
  钉成「查不到」三天,此后每份报告的定位覆盖率都莫名变成 0。
- addrs 按调用方给的顺序构建(不是 map 遍历):腾讯精修只取前 N 个,乱序会让
  每次运行精修到不同 IP,配额花在长尾上。

报告生成 internal/security/report:
- period:PreviousWeek / PreviousMonth,窗口一律 [start, end) 左闭右开,
  相邻两期不重叠也不漏边界整点;period_key(week:2026-W44)做幂等。
- aggregate:按 shared.LimitKey 合并(IPv4 精确 / IPv6 折 /64);国家、城市、
  路径、每日趋势;显式统计未定位命中数(覆盖率 60% 的图看起来和 100% 一样)。
- mapdraw:自绘等距圆柱投影气泡图。零海岸线零国界 —— 国界/台湾/南海诸岛绘制
  必须符合国家标准,自绘极易画错,真实底图交给腾讯。经纬网 + 度数刻度 +
  标签防重叠(同一都市圈两城市坐标差 0.01°,曾把「AU 55」和「AU 30」叠成
  看起来像 AU 305 的假数字)。
- html:自包含报告页,内嵌 SVG + 腾讯交互地图(无 key 时给申请指引,
  代码里不预置任何 key)。
- countryname:港澳台统一显示「中国香港/中国澳门/中国台湾」,常见国家用中文名。

存储与调度:
- ip_geo_cache(主键 = LimitKey,成功 TTL 90 天 / 明确无数据 TTL 3 天)
- security_report_logs(period_key 唯一索引 → 重启、错过时间窗都能正确补发,
  失败重试上限 5 次后停止)
- honeypot report --period week|month [--to] [--dir] [--no-email]
- web 启动时按配置挂 30 分钟一轮的调度器(与保留期清理共用停止信号,
  defer 移出 if 外,避免「清理关掉、报告开着」时 goroutine 泄漏)

配置([security]):ip_geo_provider=auto|ipapi|tencent|none、ip_geo_tencent_key、
honeypot_report_enabled / _weekly / _monthly / _email / _dir。

顺带修复:
- route/honeypot_test.go 的 captureStore 缺 AggregateSources/AggregatePaths/
  TimestampsBetween,整个 route 包编译不过。
- templates/render_test.go 的 mockLoggedUser 缺 TelegramChatID,3 个渲染测试失败。
This commit is contained in:
tamakyi
2026-10-30 16:40:44 +08:00
parent 08bbd17751
commit d690355cdc
33 changed files with 5198 additions and 1 deletions
+112
View File
@@ -10,6 +10,7 @@ import (
"embed"
"fmt"
"html/template"
"path/filepath"
"strings"
"time"
@@ -247,12 +248,54 @@ func sendTemplateMail(email, title string, templateFS embed.FS, templatePath str
}
func sendMail(to, title, content string) error {
return sendMailWith(to, title, content, nil, nil)
}
// MailAttachment 邮件附件。
type MailAttachment struct {
Path string
// Name 附件显示名,留空则用文件名。
Name string
}
// MailInlineImage 正文内嵌图片。
//
// CID 是 Content-ID:正文 HTML 里写 <img src="cid:xxx">,邮件客户端就会用
// 附件里的这张图渲染。这是让「地图不依赖任何外链、不依赖 JS」的唯一可靠办法 ——
// 直接放外链图片,Gmail 默认不加载远程图片;放内联 SVG,Gmail/Outlook 会剥掉。
type MailInlineImage struct {
Path string
CID string
}
// sendMailWith 发送一封带内嵌图片与附件的 HTML 邮件。
//
// 图片与附件都从本地路径读取(调用方负责把文件写到临时目录或报告目录)。
// 任何一步失败都向上返回错误:报告这种「发了就该完整」的邮件,
// 静默丢附件比直接报错更糟。
func sendMailWith(to, title, content string, inline []MailInlineImage, atts []MailAttachment) error {
m := gomail.NewMessage()
m.SetHeader("From", fmt.Sprintf("TamaBox <%s>", conf.Mail.Account))
m.SetHeader("To", to)
m.SetHeader("Subject", title)
m.SetBody("text/html", content)
for _, img := range inline {
// 显式指定 Content-ID:gomail 的 Embed 默认会给一个随机值,
// 那样正文里就没法引用它。
m.Embed(img.Path, gomail.SetHeader(map[string][]string{
"Content-ID": {"<" + img.CID + ">"},
"Content-Disposition": {`inline; filename="` + filepath.Base(img.Path) + `"`},
}))
}
for _, a := range atts {
opts := []gomail.FileSetting{}
if a.Name != "" {
opts = append(opts, gomail.Rename(a.Name))
}
m.Attach(a.Path, opts...)
}
d := gomail.NewDialer(
conf.Mail.SMTP,
conf.Mail.Port,
@@ -265,3 +308,72 @@ func sendMail(to, title, content string) error {
}
return d.DialAndSend(m)
}
// SecurityReportMail 周期安全汇总邮件的载荷。
//
// HTML 片段用 template.HTML 传:报告正文里有 KPI 卡片和表格,
// 走 string 会被 html/template 转义成源码文本,收件人看到的是一堆尖括号。
type SecurityReportMail struct {
// To 收件人,由调用方决定(honeypot_report_email / security_alert_email)。
To string
Title string
Period string
Generated string
// MapCID 正文内嵌地图的 Content-ID;为空则不发地图(报告无数据时)。
MapCID string
// SummaryHTML KPI 卡片片段。
SummaryHTML template.HTML
// CountriesHTML 国家排行表片段。
CountriesHTML template.HTML
// Notes 口径说明。用 template.HTML 传:里面有多行 <br/> 结构。
Notes template.HTML
// Attachments 附件(报告 HTML)。
Attachments []MailAttachment
// InlineImages 内嵌图片(地图 PNG),其 CID 必须与 MapCID 一致。
InlineImages []MailInlineImage
}
// securityReportData 是模板的渲染载荷(独立成一个类型,方便单独测渲染)。
type securityReportData struct {
Title string
Period string
Generated string
MapCID string
SummaryHTML template.HTML
CountriesHTML template.HTML
Notes template.HTML
}
// SendSecurityReportMail 发送周期安全汇总邮件。
func SendSecurityReportMail(r SecurityReportMail) error {
content, err := RenderSecurityReportMail(r)
if err != nil {
return err
}
return sendMailWith(r.To, r.Title, content, r.InlineImages, r.Attachments)
}
// RenderSecurityReportMail 只渲染邮件正文,不发信。
//
// 单独拆出来是为了能在没有 SMTP 的环境里验证模板:模板里的字段名写错一个字母,
// 生产上表现为「报告发出去了但正文是空的」,而这封邮件一周才发一次,
// 等发现时已经缺了好几期。
func RenderSecurityReportMail(r SecurityReportMail) (string, error) {
t, err := template.ParseFS(templates.FS, "mail/security-report.html")
if err != nil {
return "", errors.Wrap(err, "parse template file")
}
var content bytes.Buffer
if err := t.Execute(&content, securityReportData{
Title: r.Title,
Period: r.Period,
Generated: r.Generated,
MapCID: r.MapCID,
SummaryHTML: r.SummaryHTML,
CountriesHTML: r.CountriesHTML,
Notes: r.Notes,
}); err != nil {
return "", errors.Wrap(err, "execute template")
}
return content.String(), nil
}
+52
View File
@@ -0,0 +1,52 @@
// 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 mail
import (
"html/template"
"testing"
"github.com/stretchr/testify/require"
)
// TestRenderSecurityReportMail 钉住报告邮件模板本身。
//
// 这封邮件一周才发一次,模板字段名写错的表现是「发出去了但正文空/漏块」,
// 很难在第一时间发现。这里同时验证两件容易出错的事:
// 1. HTML 片段必须原样插入(走 template.HTML),不能被转义成源码文本;
// 2. 地图走 cid: 引用,邮件客户端才会把它当内嵌图而不是外链。
func TestRenderSecurityReportMail(t *testing.T) {
out, err := RenderSecurityReportMail(SecurityReportMail{
Title: "2026 年 10 月 第 43 周安全状况周报",
Period: "2026-10-19 ~ 2026-10-25",
Generated: "2026-10-30 16:16",
MapCID: "map-43",
SummaryHTML: template.HTML(`<div class="kpi">命中 <strong>554</strong> 次</div>`),
CountriesHTML: template.HTML(`<table><tr><td>美国</td><td>160</td></tr></table>`),
Notes: template.HTML(`口径一<br/>口径二`),
})
require.NoError(t, err)
// HTML 片段原样出现
require.Contains(t, out, "<strong>554</strong>")
require.Contains(t, out, "<td>美国</td>")
require.Contains(t, out, "口径一<br/>口径二")
require.NotContains(t, out, "&lt;strong&gt;", "片段被转义了,收件人只会看到一堆尖括号")
// 地图按 Content-ID 引用
require.Contains(t, out, "cid:map-43")
// 模板里的变量都应已展开
require.NotContains(t, out, "{{")
require.Contains(t, out, "2026-10-19 ~ 2026-10-25")
}
// TestRenderSecurityReportMailNoMap 没有命中时不发地图,也就不该留一个坏图位。
func TestRenderSecurityReportMailNoMap(t *testing.T) {
out, err := RenderSecurityReportMail(SecurityReportMail{Title: "空报告"})
require.NoError(t, err)
require.NotContains(t, out, "cid:", "无数据时不该引用不存在的地图")
require.NotContains(t, out, "{{")
}