新增:安全告警邮件展示来源 IP 网络归属(CDN/云厂商/WAF)

- 新增 internal/security/ipinfo:基于 projectdiscovery/cdncheck v1.3.0
  (离线指纹、零外部请求)识别来源 IP 归属,识别失败折叠为展示标签,
  不中断告警链路
- autoban 告警回调注入归属识别;告警邮件新增「网络归属」行,
  命中 CDN/代理网络时提示「封禁可能无法拦截真实来源」
- 新增邮件模板渲染回归测试 internal/mail/mail_alert_test.go
- dev/s3stub:webp(cgo) 本地类型检查桩,替换 s3.go 做全模块编译验证,
  生产 Linux 构建不受影响;dev/overlay.json 指向该桩
- go mod tidy 顺带升级共享依赖(lipgloss/xid/testify 等),
  全模块类型检查与相关包测试通过
This commit is contained in:
tamakyi
2026-09-08 13:25:20 +08:00
parent 35a846ea40
commit e94c2b57ce
12 changed files with 350 additions and 342 deletions
+13 -5
View File
@@ -94,12 +94,20 @@ func SendNewVoteSubmissionMail(email, voteTitle string, voteID uint) error {
}
// SendSecurityAlertMail 发送安全告警:检测到疑似批量扫描/探测并触发自动封禁时通知管理员。
func SendSecurityAlertMail(ip string, samplePaths []string, durationMinutes int) error {
// provider 为来源 IP 的网络归属标签(见 internal/security/ipinfo),proxied 表示
// IP 属于 CDN/WAF/代理网络(此时封禁出口 IP 可能无法拦截真实攻击者,邮件中额外提示)。
func SendSecurityAlertMail(ip, provider string, proxied bool, samplePaths []string, durationMinutes int) error {
proxyHint := ""
if proxied {
proxyHint = "1"
}
params := map[string]string{
"ip": ip,
"paths": strings.Join(samplePaths, "、"),
"duration": fmt.Sprintf("%d", durationMinutes),
"time": time.Now().Format("2006-01-02 15:04:05"),
"ip": ip,
"provider": provider,
"proxy_hint": proxyHint,
"paths": strings.Join(samplePaths, "、"),
"duration": fmt.Sprintf("%d", durationMinutes),
"time": time.Now().Format("2006-01-02 15:04:05"),
}
return sendTemplateMail(conf.Security.SecurityAlertEmail, "【狼的提问箱】检测到疑似批量扫描,已自动封禁 IP", templates.FS, "mail/security-alert.html", params)
}
+59
View File
@@ -0,0 +1,59 @@
package mail
import (
"bytes"
"html/template"
"testing"
"github.com/tamakyi/TamaBox/templates"
)
// TestSecurityAlertTemplateRenders 保证 security-alert.html 模板可解析,
// 且新增的「网络归属 / 代理网络提示」字段在参数齐全时正确渲染、
// proxy_hint 为空时不渲染提示块。
func TestSecurityAlertTemplateRenders(t *testing.T) {
tmpl, err := template.ParseFS(templates.FS, "mail/security-alert.html")
if err != nil {
t.Fatalf("parse template: %v", err)
}
base := map[string]string{
"ip": "203.0.113.7",
"provider": "Cloudflare(CDN)",
"paths": "/admin、/.env",
"duration": "15",
"time": "2026-09-08 12:00:00",
"year": "2026",
}
// 1. 代理网络命中:应有归属行 + 代理提示
var withHint bytes.Buffer
params := cloneParams(base)
params["proxy_hint"] = "1"
if err := tmpl.Execute(&withHint, params); err != nil {
t.Fatalf("execute with proxy_hint: %v", err)
}
out := withHint.String()
for _, want := range []string{"203.0.113.7", "网络归属", "Cloudflare(CDN)", "代理网络"} {
if !bytes.Contains([]byte(out), []byte(want)) {
t.Errorf("rendered mail missing %q", want)
}
}
// 2. 普通网络:不应出现代理提示块
var noHint bytes.Buffer
if err := tmpl.Execute(&noHint, cloneParams(base)); err != nil {
t.Fatalf("execute without proxy_hint: %v", err)
}
if bytes.Contains(noHint.Bytes(), []byte("代理网络")) {
t.Errorf("proxy hint rendered without proxy_hint param")
}
}
func cloneParams(src map[string]string) map[string]string {
dst := make(map[string]string, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
+7 -1
View File
@@ -31,6 +31,7 @@ import (
"github.com/tamakyi/TamaBox/internal/mail"
"github.com/tamakyi/TamaBox/internal/route/chat" // 私聊路由
"github.com/tamakyi/TamaBox/internal/security/autoban"
"github.com/tamakyi/TamaBox/internal/security/ipinfo"
"github.com/tamakyi/TamaBox/internal/shared"
templatepkg "github.com/tamakyi/TamaBox/internal/template"
"github.com/tamakyi/TamaBox/route"
@@ -90,7 +91,12 @@ func New() *flamego.Flame {
Window: time.Duration(conf.Security.BanWindowSeconds) * time.Second,
Duration: time.Duration(conf.Security.BanDurationMinutes) * time.Minute,
AlertEmail: conf.Security.SecurityAlertEmail,
SendAlert: mail.SendSecurityAlertMail,
// 告警发送前先离线识别来源 IP 的网络归属(CDN/云厂商/WAF,零外部请求),
// 识别失败不影响告警发送(ipinfo.Lookup 内部已折叠错误)。
SendAlert: func(ip string, paths []string, durationMinutes int) error {
provider, proxied := ipinfo.Lookup(ip)
return mail.SendSecurityAlertMail(ip, provider, proxied, paths, durationMinutes)
},
})
// 需要输出详细日志时配置如下
// if conf.App.Production {
+84
View File
@@ -0,0 +1,84 @@
// Package ipinfo 识别 IP 的网络归属(CDN / 云厂商 / WAF)。
// 基于 projectdiscovery/cdncheck 的离线签名(编译期嵌入,上游每周更新指纹),
// 判定过程零外部网络请求,适合 1C1G 小型服务器与告警链路使用。
// 当前用于安全告警邮件:展示扫描来源的网络归属,帮助管理员判断告警严重性。
package ipinfo
import (
"fmt"
"net"
"strings"
"sync"
"github.com/projectdiscovery/cdncheck"
)
var (
clientOnce sync.Once
client *cdncheck.Client
)
// getClient 懒加载判定客户端(签名数据编译期嵌入,New 无错误返回)。
func getClient() *cdncheck.Client {
clientOnce.Do(func() {
client = cdncheck.New()
})
return client
}
// Lookup 判定 IP 的网络归属。
// 返回:
// - label:展示用标签,如 "Cloudflare(CDN)"、"亚马逊(云厂商)";
// 未命中返回 "未识别(普通网络)",输入非法或判定出错返回 "识别失败"。
// - proxied:IP 是否属于 CDN/WAF/代理网络(用于提示"封禁可能无法拦截真实来源")。
//
// 任何内部错误都被折叠为展示标签,不向调用方传播——告警链路不应因归属识别失败而中断。
func Lookup(ipStr string) (label string, proxied bool) {
ip := net.ParseIP(strings.TrimSpace(ipStr))
if ip == nil {
return "识别失败(IP 格式异常)", false
}
matched, value, itemType, err := getClient().Check(ip)
if err != nil {
return "识别失败", false
}
if !matched || value == "" {
return "未识别(普通网络)", false
}
return fmt.Sprintf("%s(%s)", title(value), typeLabel(itemType)), true
}
// typeLabel 将 cdncheck 的 itemType 翻译为中文展示。
func typeLabel(itemType string) string {
switch itemType {
case "cdn":
return "CDN"
case "waf":
return "WAF"
case "cloud":
return "云厂商"
default:
return "未知类型"
}
}
// acronymProviders 需要保持全大写的提供商缩写(cdncheck 返回全小写,如 aws → AWS)。
var acronymProviders = map[string]bool{
"aws": true, "gcp": true, "oci": true, "gds": true, "ovh": true,
}
// title 将提供商名转为展示形式:缩写全大写(aws → AWS),其余首字母大写
// (cloudflare → Cloudflare)。
func title(s string) string {
if s == "" {
return s
}
lower := strings.ToLower(s)
if acronymProviders[lower] {
return strings.ToUpper(lower)
}
r := []rune(lower)
return strings.ToUpper(string(r[0])) + string(r[1:])
}
+27
View File
@@ -0,0 +1,27 @@
package ipinfo
import "testing"
// TestLookupInvalidIP 非法输入必须折叠为展示标签且不 panic,proxied 恒为 false。
func TestLookupInvalidIP(t *testing.T) {
for _, in := range []string{"", "not-an-ip", "999.1.1.1", " "} {
label, proxied := Lookup(in)
if proxied {
t.Errorf("Lookup(%q) proxied = true, want false", in)
}
if label == "" {
t.Errorf("Lookup(%q) label is empty, want a fallback label", in)
}
}
}
// TestLookupReturnsLabel 合法 IP 应返回非空标签且不 panic(不锁定具体归属,
// 避免上游签名快照更新导致测试抖动)。
func TestLookupReturnsLabel(t *testing.T) {
for _, in := range []string{"1.1.1.1", "8.8.8.8", "2606:4700:4700::1111"} {
label, _ := Lookup(in)
if label == "" {
t.Errorf("Lookup(%q) label is empty", in)
}
}
}