-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathtest_collection.py
417 lines (355 loc) · 10.3 KB
/
test_collection.py
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
from pathlib import Path
from uuid import UUID
import pytest
from sigma.collection import SigmaCollection, deep_dict_update
from sigma.correlations import (
SigmaCorrelationCondition,
SigmaCorrelationConditionOperator,
SigmaCorrelationRule,
SigmaCorrelationTimespan,
SigmaCorrelationType,
SigmaRuleReference,
)
from sigma.exceptions import (
SigmaCollectionError,
SigmaModifierError,
SigmaRuleLocation,
SigmaError,
SigmaRuleNotFoundError,
)
from sigma.rule import SigmaRule, SigmaLogSource
def test_single_rule():
rule = {
"title": "Test",
"logsource": {"category": "test"},
"detection": {
"test": {"field": "value"},
"condition": "test",
},
}
assert SigmaCollection.from_dicts([rule]) == SigmaCollection([SigmaRule.from_dict(rule)])
def test_merge():
rules = [
{
"title": "Test " + i,
"logsource": {"category": "test"},
"detection": {
"test": {"field" + i: "value" + i},
"condition": "test",
},
}
for i in ["1", "2"]
]
collection_1 = SigmaCollection.from_dicts([rules[0]])
collection_1.errors = [SigmaError("Test Error 1")]
collection_2 = SigmaCollection.from_dicts([rules[1]])
collection_2.errors = [SigmaError("Test Error 2")]
assert SigmaCollection.merge(
[
collection_1,
collection_2,
]
) == SigmaCollection(
[
SigmaRule.from_dict(rules[0]),
SigmaRule.from_dict(rules[1]),
],
errors=[
SigmaError("Test Error 1"),
SigmaError("Test Error 2"),
],
)
def test_deep_dict_update_disjunct():
assert deep_dict_update(
{
"key1": "val1",
},
{
"key2": "val2",
},
) == {
"key1": "val1",
"key2": "val2",
}
def test_deep_dict_update_overwrite():
assert deep_dict_update(
{
"key": "val1",
},
{
"key": "val2",
},
) == {
"key": "val2",
}
def test_deep_dict_update_subdict():
assert deep_dict_update(
{
"dict": {"key1": "val1"},
},
{
"dict": {"key2": "val2"},
},
) == {
"dict": {
"key1": "val1",
"key2": "val2",
}
}
def test_action_global():
c = SigmaCollection.from_dicts(
[
{
"action": "global",
"title": "Test",
"detection": {
"test": {"field": "value"},
"condition": "test",
},
},
{
"logsource": {"category": "test-1"},
},
{
"logsource": {"category": "test-2"},
},
]
)
assert (
len(c) == 2
and [r.title for r in c] == ["Test", "Test"]
and c[0].detection == c[1].detection
and [r.logsource.category for r in c] == ["test-1", "test-2"]
)
def test_action_reset():
c = SigmaCollection.from_dicts(
[
{
"title": "Reset Test",
"action": "global",
"logsource": {"category": "testcat"},
},
{"action": "reset"},
{
"title": "Test",
"logsource": {"service": "testsvc"},
"detection": {
"test": {"field": "value"},
"condition": "test",
},
},
]
)
assert (
len(c) == 1 and c[0].title == "Test" and c[0].logsource == SigmaLogSource(service="testsvc")
)
def test_action_repeat():
c = SigmaCollection.from_dicts(
[
{
"title": "Test",
"logsource": {"category": "testcat", "service": "svc-1"},
"detection": {
"test": {"field": "value"},
"condition": "test",
},
},
{
"action": "repeat",
"logsource": {"service": "svc-2"},
},
]
)
assert (
len(c) == 2
and [r.title for r in c] == ["Test", "Test"]
and c[0].detection == c[1].detection
and [r.logsource for r in c]
== [
SigmaLogSource(category="testcat", service="svc-1"),
SigmaLogSource(category="testcat", service="svc-2"),
]
)
def test_action_repeat_global():
c = SigmaCollection.from_dicts(
[
{
"action": "global",
"title": "Test",
"logsource": {"category": "testcat", "service": "svc-1"},
"detection": {
"test": {"field": "value"},
"condition": "test",
},
},
{
"action": "repeat",
"logsource": {"service": "svc-2"},
},
]
)
assert (
len(c) == 1
and c[0].title == "Test"
and c[0].logsource == SigmaLogSource(category="testcat", service="svc-2")
)
def test_action_unknown():
with pytest.raises(SigmaCollectionError, match="Unknown.*test.yml"):
SigmaCollection.from_dicts(
[
{
"action": "invalid",
}
],
source=SigmaRuleLocation("test.yml"),
)
def test_action_unknown_collect_errors():
assert (
len(
SigmaCollection.from_dicts(
[
{
"action": "invalid",
}
],
collect_errors=True,
).errors
)
> 0
)
@pytest.fixture
def ruleset():
return SigmaCollection.load_ruleset(["tests/files/ruleset"])
def test_load_ruleset(ruleset):
assert len(ruleset.rules) == 2
def test_load_ruleset_path():
assert (
SigmaCollection.load_ruleset([Path("tests/files/ruleset")]).rules
== SigmaCollection.load_ruleset(["tests/files/ruleset"]).rules
)
def test_load_ruleset_with_error():
with pytest.raises(SigmaModifierError, match="Unknown modifier.*test_rule_with_error.yml"):
SigmaCollection.load_ruleset([Path("tests/files/ruleset_with_errors")])
def test_load_ruleset_nolist():
with pytest.raises(TypeError, match="must be list"):
SigmaCollection.load_ruleset("tests/files/ruleset")
def test_load_ruleset_onbeforeload():
def onbeforeload(p):
if "2" in str(p):
return None
else:
return p
assert (
len(SigmaCollection.load_ruleset(["tests/files/ruleset"], on_beforeload=onbeforeload).rules)
== 1
)
def test_load_ruleset_onload():
def onload(p, sc):
if "2" in str(p):
return None
else:
sc.rules[0].title = "changed"
return sc
sigma_collection = SigmaCollection.load_ruleset(["tests/files/ruleset"], on_load=onload)
assert len(sigma_collection.rules) == 1 and sigma_collection.rules[0].title == "changed"
def test_index_rule_by_position(ruleset):
assert isinstance(ruleset[0], SigmaRule)
def test_index_rule_by_position_not_existing(ruleset):
with pytest.raises(
SigmaRuleNotFoundError, match="Rule at position 2 not found in rule collection"
):
ruleset[2]
def test_index_rule_by_id(ruleset):
rule_id = "240dbc26-8b19-4f5f-8972-fc3841f4185f"
assert ruleset[rule_id].id == UUID(rule_id)
assert ruleset[UUID(rule_id)].id == UUID(rule_id)
def test_index_rule_by_name(ruleset):
assert ruleset["test_rule"].name == "test_rule"
def test_index_rule_by_name_not_existing(ruleset):
with pytest.raises(
SigmaRuleNotFoundError, match="Rule 'test_rule_not_existing' not found in rule collection"
):
ruleset["test_rule_not_existing"]
@pytest.fixture
def rules_with_correlation():
rule_collection = SigmaCollection.from_yaml(
"""
title: Correlating 1+2
name: corr-1-2
correlation:
type: temporal
rules:
- rule-1
- rule-2
group-by: user
timespan: 5m
---
title: Rule 1
name: rule-1
logsource:
category: process_creation
product: windows
detection:
selection:
ImageFile|endswith: '\\\\a.exe'
condition: selection
---
title: Rule 2
name: rule-2
logsource:
category: process_creation
product: windows
detection:
selection:
ImageFile|endswith: '\\\\b.exe'
condition: selection
"""
)
rule_collection.resolve_rule_references()
return rule_collection
def test_load_ruleset_with_correlation(rules_with_correlation):
assert len(rules_with_correlation.rules) == 3
correlation_rule = rules_with_correlation.rules[2]
assert correlation_rule == SigmaCorrelationRule(
title="Correlating 1+2",
name="corr-1-2",
type=SigmaCorrelationType.TEMPORAL,
rules=[SigmaRuleReference("rule-1"), SigmaRuleReference("rule-2")],
group_by=["user"],
timespan=SigmaCorrelationTimespan("5m"),
condition=SigmaCorrelationCondition(SigmaCorrelationConditionOperator.GTE, 2),
)
assert correlation_rule.rules[0].rule == rules_with_correlation.rules[0]
def test_get_output_rules(rules_with_correlation):
output_rules = list(rules_with_correlation.get_output_rules())
assert len(output_rules) == 1
assert isinstance(output_rules[0], SigmaCorrelationRule)
def test_get_unreferenced_rules(rules_with_correlation):
output_rules = list(rules_with_correlation.get_unreferenced_rules())
assert len(output_rules) == 1
assert isinstance(output_rules[0], SigmaCorrelationRule)
def test_load_ruleset_with_correlation_referencing_nonexistent_rule():
with pytest.raises(SigmaRuleNotFoundError, match="Rule 'rule-2' not found in rule collection"):
SigmaCollection.from_yaml(
"""
title: Rule 1
name: rule-1
logsource:
category: process_creation
product: windows
detection:
selection:
ImageFile|endswith: '\\\\a.exe'
condition: selection
---
title: Correlating 1+2
name: corr-1-2
correlation:
type: temporal
rules:
- rule-1
- rule-2
group-by: user
timespan: 5m
"""
).resolve_rule_references()