github.com/runreveal/sigmalitesigmalite 包提供了 Sigma 检测格式 的解析器和执行引擎。
rule, err := sigmalite.ParseRule([]byte(`
title: My example rule
detection:
keywords:
- foo
- bar
selection:
EventId: 1234
condition: keywords and selection
`))
if err != nil {
return err
}
entry := &sigmalite.LogEntry{
Message: "Hello foo",
Fields: map[string]string{
"EventId": "1234",
},
}
isMatch := rule.Detection.Matches(entry, nil)
go get github.com/runreveal/sigmalite
规则以 YAML 格式编写,且至少必须包含 title 和 detection:
title: My example rule
detection:
keywords:
- foo
- bar
selection:
EventId: 1234
condition: keywords and selection
detection 块中的 condition 字段是一个逻辑表达式,用于连接 detection 块中的其他字段选择器。在此示例中,该规则将匹配任何满足以下条件的日志条目:EventId 字段正好是 1234,并且其消息中包含 "foo" 或 "bar"。
字段也可以通过 正则表达式 进行匹配:
title: My example rule with a timestamp
detection:
selection:
Timestamp|re: ^2024-06-01T(01|02|03):[0-5][0-9]:[0-5][0-9]$
condition: selection
以及 CIDR:
title: My example rule with IP addresses
detection:
local:
DestinationIp|cidr:
- "127.0.0.0/8"
- "10.0.0.0/8"
- "172.16.0.0/12"
- "192.168.0.0/16"
- "169.254.0.0/16"
- "::1/128" # IPv6 回环地址
- "fe80::/10" # IPv6 链路本地地址
- "fc00::/7" # IPv6 私有地址
condition: not local
更多信息请参见 官方 Sigma 规则文档。
本库支持以下 字段修饰符:
FieldResolver 接口扩展了标准 Sigma 规范,以支持超越简单键/值对的复杂字段查找场景。这允许您实现自定义的字段解析逻辑,用于:
event.process.user)process.*.user 或 network[*].ip 等字段模式type FieldResolver interface {
Resolve(fieldName string, entry *LogEntry) []string
}
Resolve 方法接收来自您 Sigma 规则的字段名称,并返回所有匹配的值,作为字符串切片。如果未找到匹配项,则返回 nil 或空切片。
// CustomResolver 演示了为结构化日志进行字段解析的示例
type CustomResolver struct{}
func (r *CustomResolver) Resolve(fieldName string, entry *sigma.LogEntry) []string {
switch fieldName {
case "process.users":
// 从多个来源聚合用户字段
var users []string
if user, ok := entry.Fields["Event.Process.User"]; ok {
users = append(users, user)
}
if user, ok := entry.Fields["Event.Login.User"]; ok {
users = append(users, user)
}
if user, ok := entry.Fields["Event.Session.User"]; ok {
users = append(users, user)
}
return users
case "network.internal_ips":
// 从所有与网络相关的字段中提取 IP 地址
var ips []string
for fieldName, value := range entry.Fields {
if strings.Contains(strings.ToLower(fieldName), "ip") {
// 简单的 IP 验证(实际使用中请使用合适的验证方法)
if strings.Contains(value, ".") {
ips = append(ips, value)
}
}
}
return ips
default:
return nil
}
}
func matches(detection *sigmalite.Detection) bool {
opts := &sigmalite.MatchOptions{
FieldResolver: CustomResolver{},
},
entry := &sigmalite.LogEntry{
Message: string("Message Text"),
Fields: nil, // 使用解析器,因此此处可以为空
}
return detection.Matches(entry, opts)
}
字段解析器与所有字段修饰符无缝协作,允许您将正则表达式模式、不区分大小写的匹配以及其他转换应用于解析后的值。