-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathtest_rule.py
1647 lines (1397 loc) · 49.6 KB
/
test_rule.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pytest
from datetime import date, datetime
from uuid import UUID
from sigma import conditions
from sigma.rule import (
SigmaRuleTag,
SigmaLogSource,
SigmaDetectionItem,
SigmaDetection,
SigmaDetections,
SigmaStatus,
SigmaLevel,
SigmaRule,
)
from sigma.types import (
SigmaBool,
SigmaExpansion,
SigmaString,
SigmaNumber,
SigmaNull,
SigmaRegularExpression,
SigmaTimestampPart,
TimestampPart,
)
from sigma.modifiers import (
SigmaBase64Modifier,
SigmaBase64OffsetModifier,
SigmaContainsModifier,
SigmaRegularExpressionModifier,
SigmaAllModifier,
)
from sigma.conditions import (
ConditionFieldEqualsValueExpression,
ConditionValueExpression,
SigmaCondition,
ConditionAND,
ConditionOR,
)
import sigma.exceptions as sigma_exceptions
from tests.test_processing_conditions import detection_item
from tests.test_processing_pipeline import processing_item
from yaml.error import YAMLError
### SigmaLevel and SigmaStatus tests ###
def test_sigmalevel_str():
assert str(SigmaLevel.MEDIUM) == "medium"
def test_sigmalevel_comparation():
assert SigmaLevel.HIGH == SigmaLevel.HIGH
assert SigmaLevel.HIGH >= SigmaLevel.LOW
assert SigmaLevel.HIGH > SigmaLevel.LOW
assert SigmaLevel.HIGH != SigmaLevel.LOW
assert SigmaLevel.LOW <= SigmaLevel.HIGH
assert SigmaLevel.LOW < SigmaLevel.HIGH
def test_sigmalevel_comparation_invalid():
with pytest.raises(sigma_exceptions.SigmaTypeError, match="Must be a SigmaLevel .*"):
assert SigmaLevel.HIGH == "HIGH"
assert SigmaLevel.HIGH >= "LOW"
assert SigmaLevel.HIGH > "LOW"
assert SigmaLevel.HIGH != "LOW"
assert SigmaLevel.LOW <= "HIGH"
assert SigmaLevel.LOW < "HIGH"
def test_sigmastatus_str():
assert str(SigmaStatus.STABLE) == "stable"
def test_sigmastatus_comparation():
assert SigmaStatus.STABLE == SigmaStatus.STABLE
assert SigmaStatus.STABLE >= SigmaStatus.EXPERIMENTAL
assert SigmaStatus.STABLE > SigmaStatus.EXPERIMENTAL
assert SigmaStatus.STABLE != SigmaStatus.EXPERIMENTAL
assert SigmaStatus.EXPERIMENTAL <= SigmaStatus.STABLE
assert SigmaStatus.EXPERIMENTAL < SigmaStatus.STABLE
def test_sigmastatus_comparation_invalid():
with pytest.raises(sigma_exceptions.SigmaTypeError, match="Must be a SigmaStatus .*"):
assert SigmaStatus.STABLE == "STABLE"
assert SigmaStatus.STABLE >= "EXPERIMENTAL"
assert SigmaStatus.STABLE > "EXPERIMENTAL"
assert SigmaStatus.STABLE != "EXPERIMENTAL"
assert SigmaStatus.EXPERIMENTAL <= "STABLE"
assert SigmaStatus.EXPERIMENTAL < "STABLE"
### SigmaRuleTag tests ###
def test_sigmaruletag_fromstr():
assert SigmaRuleTag.from_str("namespace.name") == SigmaRuleTag("namespace", "name")
def test_sigmaruletag_fromstr_nodot():
with pytest.raises(sigma_exceptions.SigmaValueError, match="must start with namespace"):
SigmaRuleTag.from_str("tag")
def test_sigmaruletag_fromstr_3dots():
assert SigmaRuleTag.from_str("namespace.subnamespace.tag") == SigmaRuleTag(
"namespace", "subnamespace.tag"
)
### SigmaLogSource tests ###
def test_sigmalogsource_fromdict():
logsource = SigmaLogSource.from_dict(
{
"category": "category-id",
"product": "product-id",
"service": "service-id",
}
)
assert logsource == SigmaLogSource("category-id", "product-id", "service-id")
def test_sigmalogsource_fromdict_no_category():
logsource = SigmaLogSource.from_dict(
{
"product": "product-id",
"service": "service-id",
}
)
assert logsource == SigmaLogSource(None, "product-id", "service-id")
def test_sigmalogsource_fromdict_no_product():
logsource = SigmaLogSource.from_dict(
{
"category": "category-id",
"service": "service-id",
}
)
assert logsource == SigmaLogSource("category-id", None, "service-id")
def test_sigmalogsource_fromdict_no_service():
logsource = SigmaLogSource.from_dict(
{
"category": "category-id",
"product": "product-id",
}
)
assert logsource == SigmaLogSource("category-id", "product-id", None)
def test_sigmalogsource_fromdict_definition():
logsource = SigmaLogSource.from_dict(
{"category": "category-id", "product": "product-id", "definition": "use it"}
)
assert logsource == SigmaLogSource("category-id", "product-id", None, "use it")
def test_sigmalogsource_fromdict_category_not_str():
with pytest.raises(sigma_exceptions.SigmaLogsourceError):
SigmaLogSource.from_dict({"category": 1234, "product": "product-id"})
def test_sigmalogsource_fromdict_product_not_str():
with pytest.raises(sigma_exceptions.SigmaLogsourceError):
SigmaLogSource.from_dict({"category": "category-id", "product": {"a": "b"}})
def test_sigmalogsource_fromdict_service_not_str():
with pytest.raises(sigma_exceptions.SigmaLogsourceError):
SigmaLogSource.from_dict({"category": "category-id", "service": ["1", "2", "3"]})
def test_sigmalogsource_empty():
with pytest.raises(sigma_exceptions.SigmaLogsourceError, match="can't be empty.*test.yml"):
SigmaLogSource(None, None, None, source=sigma_exceptions.SigmaRuleLocation("test.yml"))
def test_sigmalogsource_fromdict_definition_not_str():
with pytest.raises(sigma_exceptions.SigmaLogsourceError):
SigmaLogSource.from_dict(
{"category": "category-id", "definition": ["sysmon", "edr", "siem"]}
)
def test_sigmalogsource_str():
with pytest.raises(
sigma_exceptions.SigmaLogsourceError,
match="Sigma logsource must be a valid YAML map.*test.yml",
):
SigmaRule.from_dict(
{"title": "test", "logsource": "windows"},
source=sigma_exceptions.SigmaRuleLocation("test.yml"),
)
def test_sigmalogsource_eq():
assert SigmaLogSource("category", "product", "service") == SigmaLogSource(
"category", "product", "service"
)
def test_sigmalogsource_neq():
assert SigmaLogSource("category", "product", None) != SigmaLogSource(
"category", "product", "service"
)
def test_sigmalogsource_in_eq():
assert SigmaLogSource("category", "product", "service") in SigmaLogSource(
"category", "product", "service"
)
def test_sigmalogsource_in():
assert SigmaLogSource("category", "product", "service") in SigmaLogSource(
"category", "product", None
)
def test_sigmalogsource_not_in():
assert SigmaLogSource("category", None, "service") not in SigmaLogSource(
None, "product", "service"
)
def test_sigmalogsource_in_invalid():
with pytest.raises(TypeError):
assert 123 in SigmaLogSource("category", "product", "service")
# SigmaDetectionItem
def test_sigmadetectionitem_keyword_single():
"""Single keyword detection."""
assert SigmaDetectionItem.from_mapping(None, "value") == SigmaDetectionItem(
None, [], [SigmaString("value")]
)
def test_sigmadetectionitem_value_cleanup_single():
"""Single value cleanup."""
assert SigmaDetectionItem(None, [], "value") == SigmaDetectionItem(
None, [], [SigmaString("value")]
)
def test_sigmadetectionitem_value_cleanup_multi():
"""Multiple value cleanup."""
assert SigmaDetectionItem(None, [], ["value", 123]) == SigmaDetectionItem(
None, [], [SigmaString("value"), SigmaNumber(123)]
)
def test_sigmadetectionitem_keyword_single_to_plain():
"""Single keyword detection."""
assert SigmaDetectionItem(None, [], [SigmaString("value*")]).to_plain() == "value*"
def test_sigmadetectionitem_disabled_to_plain():
detection_item = SigmaDetectionItem(
None,
[],
[SigmaString("value*")],
source=sigma_exceptions.SigmaRuleLocation("test.yml"),
)
detection_item.disable_conversion_to_plain()
with pytest.raises(
sigma_exceptions.SigmaValueError,
match="can't be converted to plain data type.*test.yml",
):
detection_item.to_plain()
def test_sigmadetectionitem_is_keyword():
assert SigmaDetectionItem.from_mapping(None, "value").is_keyword() == True
def test_sigmadetectionitem_is_not_keyword():
assert SigmaDetectionItem.from_mapping("field", "value").is_keyword() == False
def test_sigmadetectionitem_keyword_list():
"""Keyword list detection."""
assert SigmaDetectionItem.from_mapping(None, ["string", 123]) == SigmaDetectionItem(
None, [], [SigmaString("string"), SigmaNumber(123)]
)
def test_sigmadetectionitem_keyword_list_to_plain():
"""Keyword list detection."""
assert SigmaDetectionItem(None, [], [SigmaString("string"), SigmaNumber(123)]).to_plain() == [
"string",
123,
]
def test_sigmadetectionitem_keyword_modifiers():
"""Keyword detection with modifier chain."""
assert SigmaDetectionItem.from_mapping("key|re", "reg.*exp") == SigmaDetectionItem(
"key",
[SigmaRegularExpressionModifier],
[SigmaRegularExpression("reg.*exp")],
auto_modifiers=False,
)
def test_sigmadetectionitem_keyword_modifiers_to_plain():
"""Keyword detection with modifier chain."""
detection_item = SigmaDetectionItem(
None, [SigmaBase64Modifier, SigmaContainsModifier], [SigmaString("foobar")]
)
assert detection_item.to_plain() == {"|base64|contains": "foobar"}
def test_sigmadetectionitem_unknown_modifier():
"""Keyword detection with modifier chain."""
with pytest.raises(sigma_exceptions.SigmaModifierError, match="Unknown modifier.*test.yml"):
SigmaDetectionItem.from_mapping(
"|foobar", "foobar", source=sigma_exceptions.SigmaRuleLocation("test.yml")
)
def test_sigmadetectionitem_key_value_single_string():
"""Key-value detection with one value."""
assert SigmaDetectionItem.from_mapping("key", "value") == SigmaDetectionItem(
"key", [], [SigmaString("value")]
)
def test_sigmadetectionitem_key_value_single_string_to_plain():
"""Key-value detection with one value."""
assert SigmaDetectionItem("key", [], [SigmaString("value")]).to_plain() == {"key": "value"}
def test_sigmadetectionitem_key_value_single_string_modifier_to_plain():
"""
Key-value detection with one value and contains modifier converted to plain. Important: the
original value should appear instead of the modified.
"""
detection_item = SigmaDetectionItem("key", [SigmaContainsModifier], [SigmaString("value")])
detection_item.apply_modifiers()
assert detection_item.to_plain() == {"key|contains": "value"}
def test_sigmadetectionitem_key_value_single_int():
"""Key-value detection with one integer value."""
assert SigmaDetectionItem.from_mapping("key", 123) == SigmaDetectionItem(
"key", [], [SigmaNumber(123)]
)
def test_sigmadetectionitem_key_value_single_float():
"""Key-value detection with one integer value."""
assert SigmaDetectionItem.from_mapping("key", 12.34) == SigmaDetectionItem(
"key", [], [SigmaNumber(12.34)]
)
def test_sigmadetectionitem_key_value_none():
"""Key-value detection with none value."""
assert SigmaDetectionItem.from_mapping("key", None) == SigmaDetectionItem(
"key", [], [SigmaNull()]
)
def test_sigmadetectionitem_key_value_single_regexp():
"""Key-value detection with one value."""
assert SigmaDetectionItem.from_mapping("key|re", "reg.*exp") == SigmaDetectionItem(
"key",
[SigmaRegularExpressionModifier],
[SigmaRegularExpression("reg.*exp")],
auto_modifiers=False,
)
def test_sigmadetectionitem_key_value_single_regexp_to_plain():
"""Key-value detection with one value."""
assert SigmaDetectionItem.from_mapping("key|re", "reg.*exp").to_plain() == {
"key|re": "reg.*exp"
}
def test_sigmadetectionitem_key_value_single_regexp_trailing_backslashes_to_plain():
"""Key-value detection with one value."""
assert SigmaDetectionItem.from_mapping("key|re", "reg.*exp\\\\").to_plain() == {
"key|re": "reg.*exp\\\\"
}
def test_sigmadetectionitem_key_value_list():
"""Key-value detection with value list."""
assert SigmaDetectionItem.from_mapping("key", ["string", 123]) == SigmaDetectionItem(
"key", [], [SigmaString("string"), SigmaNumber(123)]
)
def test_sigmadetectionitem_key_value_list_to_plain():
"""Key-value detection with value list."""
assert SigmaDetectionItem.from_mapping("key", ["string", 123]).to_plain() == {
"key": ["string", 123]
}
def test_sigmadetectionitem_key_value_modifiers():
"""Key-value detection with modifier chain with first modifier expanding value to multiple values"""
assert SigmaDetectionItem.from_mapping(
"key|base64offset|contains|all", "foobar"
) == SigmaDetectionItem(
"key",
[SigmaBase64OffsetModifier, SigmaContainsModifier, SigmaAllModifier],
[
SigmaExpansion(
[
SigmaString("*Zm9vYmFy*"),
SigmaString("*Zvb2Jhc*"),
SigmaString("*mb29iYX*"),
]
)
],
ConditionAND,
auto_modifiers=False,
)
def test_sigmadetectionitem_key_value_modifiers_to_plain():
"""Key-value detection with modifier chain with first modifier expanding value to multiple values"""
assert SigmaDetectionItem.from_mapping(
"key|base64offset|contains|all", "foobar"
).to_plain() == {"key|base64offset|contains|all": "foobar"}
def test_sigmadetectionitem_key_value_modifiers_invalid_re():
"""Invalid regular expression modifier chain."""
with pytest.raises(sigma_exceptions.SigmaValueError, match="only applicable.*test.yml"):
SigmaDetectionItem.from_mapping(
"key|base64|re",
"value",
source=sigma_exceptions.SigmaRuleLocation("test.yml"),
)
def test_sigmadetectionitem_fromvalue():
SigmaDetectionItem.from_value("test") == SigmaDetectionItem(None, [], [SigmaString("test")])
def test_sigmadetectionitem_processing_item_tracking(processing_item):
"""Key-value detection with one value."""
detection_item = SigmaDetectionItem.from_mapping("key", "value")
detection_item.add_applied_processing_item(processing_item)
assert detection_item.was_processed_by("test")
### SigmaDetection tests ###
def test_sigmadetection_items():
assert (
SigmaDetection(
[
SigmaDetectionItem("key_1", [], [SigmaString("value_1")]),
SigmaDetectionItem("key_2", [], [SigmaString("value_2")]),
]
).item_linking
== ConditionAND
)
def test_sigmadetection_detections():
assert (
SigmaDetection(
[
SigmaDetection([SigmaDetectionItem("key_1", [], [SigmaString("value_1")])]),
SigmaDetection([SigmaDetectionItem("key_2", [], [SigmaString("value_2")])]),
]
).item_linking
== ConditionOR
)
def test_sigmadetection_mixed():
assert SigmaDetection(
[
SigmaDetectionItem("key_1", [], [SigmaString("value_1")]),
SigmaDetection([SigmaDetectionItem("key_2", [], [SigmaString("value_2")])]),
]
)
def test_sigmadetection_to_plain():
assert SigmaDetection(
[
SigmaDetectionItem("test_str", [], [SigmaString("test")]),
SigmaDetectionItem("test_num", [], [SigmaNumber(123)]), # Issue #56
SigmaDetectionItem("test_bool", [], [SigmaBool(True)]),
SigmaDetectionItem("test_null", [], [SigmaNull()]),
]
).to_plain() == {
"test_str": "test",
"test_num": 123,
"test_bool": True,
"test_null": None,
}
### SigmaDetections tests ###
def test_sigmadetections_fromdict():
detections = {
"keyword_list": [
"keyword_1",
"keyword_2",
3,
],
"test_list_of_maps": [
{"key1": "value1"},
{"key2": 2},
],
"test_map": {
"key1": "value1",
"key2": 2,
},
"single_keyword": "keyword",
}
condition = "1 of them"
sigma_detections = SigmaDetections.from_dict(
{
**detections,
"condition": condition,
}
)
assert sigma_detections == SigmaDetections(
detections={
"keyword_list": SigmaDetection(
[
SigmaDetectionItem(
None,
[],
[
SigmaString("keyword_1"),
SigmaString("keyword_2"),
SigmaNumber(3),
],
),
]
),
"test_list_of_maps": SigmaDetection(
[
SigmaDetection([SigmaDetectionItem("key1", [], [SigmaString("value1")])]),
SigmaDetection([SigmaDetectionItem("key2", [], [SigmaNumber(2)])]),
]
),
"test_map": SigmaDetection(
[
SigmaDetectionItem("key1", [], [SigmaString("value1")]),
SigmaDetectionItem("key2", [], [SigmaNumber(2)]),
]
),
"single_keyword": SigmaDetection(
[SigmaDetectionItem(None, [], [SigmaString("keyword")])]
),
},
condition=[condition],
)
assert isinstance(sigma_detections.parsed_condition[0], SigmaCondition)
def test_sigmadetections_to_dict_single_condition():
assert SigmaDetections(
detections={
"test": SigmaDetection([SigmaDetectionItem("field", [], SigmaString("value"))])
},
condition=["test"],
).to_dict() == {"test": {"field": "value"}, "condition": "test"}
def test_sigmadetections_to_dict_single_condition():
assert SigmaDetections(
detections={
"test": SigmaDetection([SigmaDetectionItem("field", [], SigmaString("value"))])
},
condition=["test", "all of them"],
).to_dict() == {"test": {"field": "value"}, "condition": ["test", "all of them"]}
def test_sigmadetections_index():
assert SigmaDetections(
detections={
"foo": SigmaDetection(
[
SigmaDetectionItem(None, [], [SigmaString("keyword_1")]),
]
),
"bar": SigmaDetection(
[
SigmaDetectionItem(None, [], [SigmaString("keyword_2")]),
]
),
},
condition=["1 of them"],
)["foo"] == SigmaDetection(
[
SigmaDetectionItem(None, [], [SigmaString("keyword_1")]),
]
)
def test_sigmadetections_fromdict_no_detections():
with pytest.raises(sigma_exceptions.SigmaDetectionError, match="No detections.*test.yml"):
SigmaDetections.from_dict(
{"condition": ["selection"]}, sigma_exceptions.SigmaRuleLocation("test.yml")
)
def test_sigmadetections_fromdict_no_condition():
with pytest.raises(
sigma_exceptions.SigmaConditionError, match="at least one condition.*test.yml"
):
SigmaDetections.from_dict(
{"selection": {"key": "value"}},
sigma_exceptions.SigmaRuleLocation("test.yml"),
)
def test_detectionitem_all_modified_key_plain_values_postprocess():
"""
Test if postprocessed condition result of an all-modified field-bound value list results in an
AND condition linking all listed values.
"""
detections = SigmaDetections.from_dict(
{"selection": {"field|all": ["val1", "val2", 123]}, "condition": "selection"}
)
assert detections.parsed_condition[0].parsed == ConditionAND(
[
ConditionFieldEqualsValueExpression("field", SigmaString("val1")),
ConditionFieldEqualsValueExpression("field", SigmaString("val2")),
ConditionFieldEqualsValueExpression("field", SigmaNumber(123)),
]
)
def test_detectionitem_all_modified_unbound_plain_values_postprocess():
"""
Test if postprocessed condition result of an all-modified not field-bound value list results in an
AND condition linking all listed values.
"""
detections = SigmaDetections.from_dict(
{"selection": {"|all": ["val1", "val2", 123]}, "condition": "selection"}
)
assert detections.parsed_condition[0].parsed == ConditionAND(
[
ConditionValueExpression(SigmaString("val1")),
ConditionValueExpression(SigmaString("val2")),
ConditionValueExpression(SigmaNumber(123)),
]
)
def test_detectionitem_all_modified_key_special_values_postprocess():
"""
Test if postprocessed condition result of an all-modified field-bound value list containing
strings with wildcards results in an AND condition linking all listed values.
"""
detections = SigmaDetections.from_dict(
{"selection": {"field|all": ["val1*", "val2", 123]}, "condition": "selection"}
)
assert detections.parsed_condition[0].parsed == ConditionAND(
[
ConditionFieldEqualsValueExpression("field", SigmaString("val1*")),
ConditionFieldEqualsValueExpression("field", SigmaString("val2")),
ConditionFieldEqualsValueExpression("field", SigmaNumber(123)),
]
)
def test_sigmadetection_processing_item_tracking(processing_item):
"""Key-value detection with one value."""
detection = SigmaDetection(
[
SigmaDetectionItem("field1", [], SigmaString("value1")),
SigmaDetectionItem("field2", [], SigmaString("value2")),
SigmaDetection(
[
SigmaDetectionItem("field3", [], SigmaString("value3")),
SigmaDetectionItem("field4", [], SigmaString("value4")),
]
),
]
)
detection.add_applied_processing_item(processing_item)
assert all(
[
(
detection_item.was_processed_by("test")
if isinstance(detection_item, SigmaDetectionItem)
else all(
[
sub_detection_item.was_processed_by("test")
for sub_detection_item in detection_item.detection_items
]
)
)
for detection_item in detection.detection_items
]
)
def test_sigmadetection_single_to_plain():
assert SigmaDetection(
detection_items=[SigmaDetectionItem("field", [], SigmaString("value"))]
).to_plain() == {"field": "value"}
def test_sigmadetection_multi_dict_to_plain():
assert SigmaDetection(
detection_items=[
SigmaDetectionItem("field1", [], SigmaString("value1")),
SigmaDetectionItem("field2", [], SigmaString("value2")),
]
).to_plain() == {
"field1": "value1",
"field2": "value2",
}
def test_sigmadetection_multi_dict_to_plain_key_collision():
"""Two field names exist in distinct detection items and have to be merged."""
assert SigmaDetection(
detection_items=[
SigmaDetectionItem("field", [], SigmaString("value1")),
SigmaDetectionItem("field", [], SigmaString("value2")),
]
).to_plain() == {"field|all": ["value1", "value2"]}
def test_sigmadetection_multi_dict_to_plain_all_key_collision():
"""Two field names exist in distinct detection items and have to be merged."""
assert SigmaDetection(
detection_items=[
SigmaDetectionItem("field|all", [], SigmaString("value1")),
SigmaDetectionItem("field|all", [], SigmaString("value2")),
]
).to_plain() == {"field|all": ["value1", "value2"]}
def test_sigmadetection_multi_dict_to_plain_all_key_collision_list_values():
"""Two field names exist in distinct detection items and have to be merged."""
assert SigmaDetection(
detection_items=[
SigmaDetectionItem("field|all", [], [SigmaString("value1"), SigmaString("value2")]),
SigmaDetectionItem("field|all", [], [SigmaString("value3"), SigmaString("value4")]),
]
).to_plain() == {"field|all": ["value1", "value2", "value3", "value4"]}
def test_sigmadetection_multi_dict_to_plain_key_collision_all():
assert SigmaDetection(
detection_items=[
SigmaDetectionItem("field", [], SigmaString("value1")),
SigmaDetectionItem("field|all", [], [SigmaString("value2"), SigmaString("value3")]),
]
).to_plain() == {
"field": "value1",
"field|all": ["value2", "value3"],
}
def test_sigmadetection_multi_dict_to_plain_key_collision_lists():
"""
Two items with the same field value and multiple values can't be merged, because both items are
implicitely and-linked, while the list items are or-linked. Merging them would cause a semantic
change because all items must have the same logical linking.
"""
with pytest.raises(
sigma_exceptions.SigmaValueError, match="different logical linking.*test.yml"
):
SigmaDetection(
detection_items=[
SigmaDetectionItem("field", [], [SigmaString("value1"), SigmaString("value2")]),
SigmaDetectionItem("field", [], [SigmaString("value3"), SigmaString("value4")]),
],
source=sigma_exceptions.SigmaRuleLocation("test.yml"),
).to_plain()
def test_sigmadetection_multi_dict_to_plain_key_collision_all_2single():
assert SigmaDetection(
detection_items=[
SigmaDetectionItem("field|all", [], [SigmaString("value1"), SigmaString("value2")]),
SigmaDetectionItem("field", [], [SigmaString("value3")]),
SigmaDetectionItem("field", [], [SigmaString("value4")]),
]
).to_plain() == {
"field|all": [
SigmaString("value1"),
SigmaString("value2"),
SigmaString("value3"),
SigmaString("value4"),
]
}
def test_sigmadetection_lists_and_plain_to_plain():
assert SigmaDetection(
detection_items=[
SigmaDetectionItem(None, [], SigmaString("value1")),
SigmaDetectionItem(None, [], [SigmaString("value2"), SigmaString("value3")]),
SigmaDetectionItem(None, [], [SigmaString("value4"), SigmaString("value5")]),
]
).to_plain() == ["value1", "value2", "value3", "value4", "value5"]
def test_sigmadetection_dict_and_keyword_to_plain():
with pytest.raises(sigma_exceptions.SigmaValueError, match="Can't convert detection.*test.yml"):
SigmaDetection(
detection_items=[
SigmaDetectionItem("field", [], SigmaString("value")),
SigmaDetectionItem(None, [], SigmaString("keyword")),
],
source=sigma_exceptions.SigmaRuleLocation("test.yml"),
).to_plain()
### SigmaRule tests ###
def test_sigmarule_fields_not_list():
with pytest.raises(sigma_exceptions.SigmaFieldsError, match="must be a list.*test.yml"):
SigmaRule.from_dict(
{"fields": "test"}, source=sigma_exceptions.SigmaRuleLocation("test.yml")
)
def test_sigmarule_bad_uuid():
with pytest.raises(sigma_exceptions.SigmaIdentifierError, match="must be an UUID.*test.yml"):
SigmaRule.from_dict(
{"id": "no-uuid"}, source=sigma_exceptions.SigmaRuleLocation("test.yml")
)
def test_sigmarule_bad_name():
with pytest.raises(sigma_exceptions.SigmaTypeError, match="must be a string.*test.yml"):
SigmaRule.from_dict({"name": 123}, source=sigma_exceptions.SigmaRuleLocation("test.yml"))
def test_sigmarule_empty_name():
with pytest.raises(sigma_exceptions.SigmaNameError, match="must not be empty.*test.yml"):
SigmaRule.from_dict({"name": ""}, source=sigma_exceptions.SigmaRuleLocation("test.yml"))
def test_sigmarule_bad_description():
with pytest.raises(sigma_exceptions.SigmaDescriptionError, match="must be a string.*test.yml"):
SigmaRule.from_dict(
{"description": ["1", "2"]}, source=sigma_exceptions.SigmaRuleLocation("test.yml")
)
def test_sigmarule_bad_level():
with pytest.raises(
sigma_exceptions.SigmaLevelError, match="not a valid Sigma rule level.*test.yml"
):
SigmaRule.from_dict({"level": "bad"}, source=sigma_exceptions.SigmaRuleLocation("test.yml"))
def test_sigmarule_bad_status():
with pytest.raises(
sigma_exceptions.SigmaStatusError, match="not a valid Sigma rule status.*test.yml"
):
SigmaRule.from_dict(
{"status": "bad"}, source=sigma_exceptions.SigmaRuleLocation("test.yml")
)
def test_sigmarule_bad_status_type():
with pytest.raises(
sigma_exceptions.SigmaStatusError, match="Sigma rule status cannot be a list.*test.yml"
):
SigmaRule.from_dict(
{"status": ["test"]}, source=sigma_exceptions.SigmaRuleLocation("test.yml")
)
def test_sigmarule_bad_date():
"""This test uses string data type as date representation in yaml"""
bad_string_dates = (
"bad",
" 2024-11-24",
"2024-11-24 ",
"2024 11-24",
"24-11-24",
"02-02-02",
"4000-01-01",
"10000-01-01",
"2022-01/01",
"2022/01-01",
)
for test_string in bad_string_dates:
match_string = f"Rule date '{test_string}' is invalid, use yyyy-mm-dd"
with pytest.raises(sigma_exceptions.SigmaDateError, match=match_string) as ex:
SigmaRule.from_yaml(
f"""
title: Test
date: '{test_string}' # try a string
logsource:
product: foobar
detection:
selection_1:
fieldA: valueA
condition: selection_1
"""
)
assert False, f"Did not throw SigmaDateError on date {test_string}"
def test_sigmarule_bad_modified():
"""
This test uses yaml ability to recognize dates.
Therefore, here 4000-01-01 will be interpreted as a correct yaml date.
"""
bad_dates = (
"bad",
"24-11-24",
"02-02-02",
"2024-5-5",
"10000-01-01",
"2022-01/01",
"2022/01-01",
"2022 01/01",
)
for test_string in bad_dates:
match_string = f"Rule modified '{test_string}' is invalid, use yyyy-mm-dd"
with pytest.raises(sigma_exceptions.SigmaModifiedError, match=match_string) as ex:
SigmaRule.from_yaml(
f"""
title: Test
modified: {test_string} # this can be recognized as date by yaml parser
logsource:
product: foobar
detection:
selection_1:
fieldA: valueA
condition: selection_1
"""
)
assert False, f"Did not throw SigmaModifiedError on date {test_string}"
def test_sigmarule_bad_falsepositives():
with pytest.raises(
sigma_exceptions.SigmaFalsePositivesError,
match="Sigma rule falsepositives must be a list.*test.yml",
):
SigmaRule.from_dict(
{"falsepositives": "bad"}, source=sigma_exceptions.SigmaRuleLocation("test.yml")
)
def test_sigmarule_bad_references():
with pytest.raises(
sigma_exceptions.SigmaReferencesError,
match="Sigma rule references must be a list.*test.yml",
):
SigmaRule.from_dict(
{"references": "bad"}, source=sigma_exceptions.SigmaRuleLocation("test.yml")
)
def test_sigmarule_date():
expected_date = date(3000, 1, 2)
rule = SigmaRule.from_yaml(
"""
title: Test
id: cafedead-beef-0000-1111-0123456789ab
level: medium
status: test
date: 3000-01-02
logsource:
product: foobar
detection:
selection_1:
fieldA: valueA
condition: selection_1
"""
)
assert rule is not None
assert rule.date == expected_date
def test_modified_date():
validDates = {
"3000-12-31": date(3000, 12, 31), # can appear as a generic date in the future
"2999-04-04": date(2999, 4, 4),
"2024-11-22": date(2024, 11, 22),
"1970-01-01": date(1970, 1, 1), # can appear as a generic date in the past
"1900-12-31": date(1900, 12, 31), # not much useful, but correct
"2024/11/22": date(2024, 11, 22), # US-based sigmas have such dates
"2024/1/2": date(2024, 1, 2),
"1970/1/1": date(1970, 1, 1),
}
for test_string, expected_date in validDates.items():