Repository navigation
Expand file tree
/
Copy pathcondition_parser.go
More file actions
355 lines (306 loc) · 8.35 KB
/
Copy pathcondition_parser.go
File metadata and controls
355 lines (306 loc) · 8.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package sigma
import (
"fmt"
"sort"
"strings"
)
// condNode is the interface for condition AST nodes.
type condNode interface {
condNode()
}
// condNodeRef references a named detection item.
type condNodeRef struct {
name string
}
func (condNodeRef) condNode() {}
// condNodeAnd represents an AND expression.
type condNodeAnd struct {
children []condNode
}
func (condNodeAnd) condNode() {}
// condNodeOr represents an OR expression.
type condNodeOr struct {
children []condNode
}
func (condNodeOr) condNode() {}
// condNodeNot represents a NOT expression.
type condNodeNot struct {
child condNode
}
func (condNodeNot) condNode() {}
// condNodeQuantifier represents "X of Y" expressions.
type condNodeQuantifier struct {
quantifier string // "1", "all", or a number
pattern string // detection name pattern (may contain wildcards) or "them"
}
func (condNodeQuantifier) condNode() {}
// conditionParser is a recursive descent parser for Sigma condition expressions.
type conditionParser struct {
tokens []token
pos int
errors []string
}
// parseConditionExpr parses a condition expression string and returns the AST
// plus any aggregation expression (text after |).
func parseConditionExpr(condStr string) (condNode, string, []string) {
lexer := newConditionLexer(condStr)
p := &conditionParser{tokens: lexer.tokens}
node := p.parseOr()
if next := p.peek(); next.typ != tokEOF && next.typ != tokPipe {
p.errors = append(p.errors, fmt.Sprintf("unexpected token after condition expression: %q", next.val))
}
// Check for aggregation after pipe
var aggExpr string
if p.peek().typ == tokPipe {
p.advance() // consume |
// Collect rest of tokens as aggregation expression
start := p.peek().pos
aggExpr = strings.TrimSpace(condStr[start:])
}
return node, aggExpr, p.errors
}
func (p *conditionParser) peek() token {
if p.pos >= len(p.tokens) {
return token{typ: tokEOF}
}
return p.tokens[p.pos]
}
func (p *conditionParser) advance() token {
t := p.peek()
if p.pos < len(p.tokens) {
p.pos++
}
return t
}
// parseOr: orExpr := andExpr ("or" andExpr)*
func (p *conditionParser) parseOr() condNode {
left := p.parseAnd()
children := []condNode{left}
for p.peek().typ == tokOr {
p.advance()
children = append(children, p.parseAnd())
}
if len(children) == 1 {
return children[0]
}
return condNodeOr{children: children}
}
// parseAnd: andExpr := notExpr ("and" notExpr)*
func (p *conditionParser) parseAnd() condNode {
left := p.parseNot()
children := []condNode{left}
for p.peek().typ == tokAnd {
p.advance()
children = append(children, p.parseNot())
}
if len(children) == 1 {
return children[0]
}
return condNodeAnd{children: children}
}
// parseNot: notExpr := "not" notExpr | atom
func (p *conditionParser) parseNot() condNode {
if p.peek().typ == tokNot {
p.advance()
return condNodeNot{child: p.parseNot()}
}
return p.parseAtom()
}
// parseAtom: atom := "(" orExpr ")" | quantifier "of" pattern | identifier
func (p *conditionParser) parseAtom() condNode {
t := p.peek()
switch t.typ {
case tokLParen:
p.advance()
node := p.parseOr()
if p.peek().typ == tokRParen {
p.advance()
} else {
p.errors = append(p.errors, "expected closing parenthesis")
}
return node
case tokAll:
// "all of ..."
p.advance()
if p.peek().typ == tokOf {
p.advance()
pattern := p.parsePattern()
return condNodeQuantifier{quantifier: "all", pattern: pattern}
}
// If no "of", treat as identifier
return condNodeRef{name: t.val}
case tokNumber:
// Could be "N of ..." quantifier
num := t.val
p.advance()
if p.peek().typ == tokOf {
p.advance()
pattern := p.parsePattern()
return condNodeQuantifier{quantifier: num, pattern: pattern}
}
// Just a number reference (unusual but handle)
return condNodeRef{name: num}
case tokIdent:
p.advance()
// Check for "of" — handles "selection of them" (1 of pattern == any)
if p.peek().typ == tokOf {
// Treat identifier as quantifier (e.g., "selection" is just a ref, not quantifier)
// Only valid quantifiers are numbers and "all"
// Revert: this is a regular identifier
return condNodeRef{name: t.val}
}
return condNodeRef{name: t.val}
case tokEOF:
p.errors = append(p.errors, "unexpected end of condition expression")
return condNodeRef{name: ""}
default:
p.errors = append(p.errors, fmt.Sprintf("unexpected token: %q", t.val))
p.advance()
return condNodeRef{name: ""}
}
}
// parsePattern parses the pattern after "of" — identifier, wildcard, or "them".
func (p *conditionParser) parsePattern() string {
t := p.peek()
switch t.typ {
case tokThem:
p.advance()
return "them"
case tokStar:
p.advance()
return "*"
case tokIdent:
p.advance()
// Could be "selection*" (identifier with wildcard)
if p.peek().typ == tokStar {
p.advance()
return t.val + "*"
}
return t.val
default:
p.errors = append(p.errors, fmt.Sprintf("expected pattern after 'of', got %q", t.val))
return ""
}
}
// evaluateAST walks the condition AST and emits Conditions by looking up
// detection items. The logicalOp and negated parameters are propagated down.
func evaluateAST(node condNode, items map[string]*detectionItem, negated bool) []Condition {
switch n := node.(type) {
case condNodeRef:
item, ok := items[n.name]
if !ok {
return nil
}
conds := make([]Condition, len(item.conditions))
copy(conds, item.conditions)
if negated {
for i := range conds {
conds[i].Negated = !conds[i].Negated
}
}
return conds
case condNodeAnd:
var result []Condition
logicalOp := "AND"
if negated {
logicalOp = "OR"
}
for i, child := range n.children {
childConds := evaluateAST(child, items, negated)
if i > 0 && len(childConds) > 0 {
childConds[0].LogicalOp = logicalOp
}
result = append(result, childConds...)
}
return result
case condNodeOr:
var result []Condition
logicalOp := "OR"
if negated {
logicalOp = "AND"
}
for i, child := range n.children {
childConds := evaluateAST(child, items, negated)
if i > 0 && len(childConds) > 0 {
childConds[0].LogicalOp = logicalOp
}
result = append(result, childConds...)
}
return result
case condNodeNot:
return evaluateAST(n.child, items, !negated)
case condNodeQuantifier:
return evaluateQuantifier(n, items, negated)
default:
return nil
}
}
// evaluateQuantifier handles "X of Y" by glob-matching detection item names.
func evaluateQuantifier(q condNodeQuantifier, items map[string]*detectionItem, negated bool) []Condition {
// Find matching detection items
matchingNames := matchDetectionItems(q.pattern, items)
if len(matchingNames) == 0 {
return nil
}
isAll := q.quantifier == "all"
var result []Condition
for i, name := range matchingNames {
item := items[name]
conds := make([]Condition, len(item.conditions))
copy(conds, item.conditions)
if negated {
for j := range conds {
conds[j].Negated = !conds[j].Negated
}
}
// Connect items: "all of" → AND, "1 of" / "N of" → OR.
// Under NOT, apply De Morgan for the compatibility Conditions slice.
if i > 0 && len(conds) > 0 {
if isAll != negated {
conds[0].LogicalOp = "AND"
} else {
conds[0].LogicalOp = "OR"
}
}
result = append(result, conds...)
}
return result
}
// matchDetectionItems returns detection item names matching a pattern, sorted
// for determinism. Without the sort, map iteration order made quantifier
// evaluation ("N of selection_*", "all of them") non-deterministic, which
// could reorder — and in turn drop — extracted conditions across runs.
func matchDetectionItems(pattern string, items map[string]*detectionItem) []string {
var names []string
if pattern == "them" || pattern == "*" {
// Match all detection items
names = make([]string, 0, len(items))
for name := range items {
names = append(names, name)
}
} else {
// Glob matching with * wildcard
for name := range items {
if globMatch(pattern, name) {
names = append(names, name)
}
}
}
sort.Strings(names)
return names
}
// globMatch performs simple glob matching (only * wildcard at end/start).
func globMatch(pattern, s string) bool {
if pattern == s {
return true
}
if strings.HasSuffix(pattern, "*") {
prefix := strings.TrimSuffix(pattern, "*")
return strings.HasPrefix(s, prefix)
}
if strings.HasPrefix(pattern, "*") {
suffix := strings.TrimPrefix(pattern, "*")
return strings.HasSuffix(s, suffix)
}
return false
}