forked from SigmaHQ/sigma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_rules.py
executable file
·2017 lines (1851 loc) · 86.3 KB
/
test_rules.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
#!/usr/bin/env python3
"""
Checks for noncompliance or common errors on all rules
Run using the command
# python test_rules.py
"""
import os
import unittest
import yaml
import re
import string
# from attackcti import attack_client
from colorama import init
from colorama import Fore
import collections
# Old Tests cover by pySigma 0.10.9 and simgma-cli 0.7.10
# Use sigma check --fail-on-error --fail-on-issues --validation-config tests/sigma_cli_conf.yml rules*
#
class TestRules(unittest.TestCase):
# @classmethod
# def setUpClass(cls):
# print("Calling get_mitre_data()")
# # Get Current Data from MITRE ATT&CK®
# cls.MITRE_ALL = get_mitre_data()
# print("Catched data - starting tests...")
# MITRE_TECHNIQUE_NAMES = [
# "process_injection",
# "signed_binary_proxy_execution",
# "process_injection",
# ] # incomplete list
# MITRE_TACTICS = [
# "initial_access",
# "execution",
# "persistence",
# "privilege_escalation",
# "defense_evasion",
# "credential_access",
# "discovery",
# "lateral_movement",
# "collection",
# "exfiltration",
# "command_and_control",
# "impact",
# "launch",
# ]
# # Don't use trademarks in rules - they require non-ASCII characters to be used on we don't want them in our rules
TRADE_MARKS = {"MITRE ATT&CK", "ATT&CK"}
path_to_rules = [
"rules",
"rules-emerging-threats",
"rules-placeholder",
"rules-threat-hunting",
"rules-compliance",
]
# Helper functions
def yield_next_rule_file_path(self, path_to_rules: list) -> str:
for path_ in path_to_rules:
for root, _, files in os.walk(path_):
for file in files:
if file.endswith(".yml"):
yield os.path.join(root, file)
def get_rule_part(self, file_path: str, part_name: str):
yaml_dicts = self.get_rule_yaml(file_path)
for yaml_part in yaml_dicts:
if part_name in yaml_part.keys():
return yaml_part[part_name]
return None
def get_rule_yaml(self, file_path: str) -> dict:
data = []
with open(file_path, encoding="utf-8") as f:
yaml_parts = yaml.safe_load_all(f)
for part in yaml_parts:
data.append(part)
return data
# Tests
def test_legal_trademark_violations(self):
# See Issue # https://github.com/SigmaHQ/sigma/issues/1028
files_with_legal_issues = []
for file in self.yield_next_rule_file_path(self.path_to_rules):
with open(file, "r", encoding="utf-8") as fh:
file_data = fh.read()
for tm in self.TRADE_MARKS:
if tm in file_data:
files_with_legal_issues.append(file)
self.assertEqual(
files_with_legal_issues,
[],
Fore.RED
+ "There are rule files which contains a trademark or reference that doesn't comply with the respective trademark requirements - please remove the trademark to avoid legal issues",
)
# sigma cli SigmahqFieldDuplicateValueIssue
# def test_look_for_duplicate_filters(self):
# def check_list_or_recurse_on_dict(item, depth: int, special: bool) -> None:
# if type(item) == list:
# check_if_list_contain_duplicates(item, depth, special)
# elif type(item) == dict and depth <= MAX_DEPTH:
# for keys, sub_item in item.items():
# if (
# "|base64" in keys or "|re" in keys
# ): # Covers both "base64" and "base64offset" modifiers, and "re" modifier
# check_list_or_recurse_on_dict(sub_item, depth + 1, True)
# else:
# check_list_or_recurse_on_dict(sub_item, depth + 1, special)
# def check_if_list_contain_duplicates(
# item: list, depth: int, special: bool
# ) -> None:
# try:
# # We use a list comprehension to convert all the element to lowercase. Since we don't care about casing in SIGMA except for the following modifiers
# # - "base64offset"
# # - "base64"
# # - "re"
# if special:
# item_ = item
# else:
# item_ = [i.lower() for i in item]
# if len(item_) != len(set(item_)):
# # We find the duplicates and then print them to the user
# duplicates = [
# i
# for i, count in collections.Counter(item_).items()
# if count > 1
# ]
# print(
# Fore.RED
# + "Rule {} has duplicate filters {}".format(file, duplicates)
# )
# files_with_duplicate_filters.append(file)
# except:
# # unhashable types like dictionaries
# for sub_item in item:
# if type(sub_item) == dict and depth <= MAX_DEPTH:
# check_list_or_recurse_on_dict(sub_item, depth + 1, special)
# MAX_DEPTH = 3
# files_with_duplicate_filters = []
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# detection = self.get_rule_part(file_path=file, part_name="detection")
# check_list_or_recurse_on_dict(detection, 1, False)
# self.assertEqual(
# files_with_duplicate_filters,
# [],
# Fore.RED + "There are rules with duplicate filters",
# )
#sigma cli SigmahqFieldWithSpaceIssue
# def test_field_name_with_space(self):
# def key_iterator(fields, faulty):
# for key, value in fields.items():
# if " " in key:
# faulty.append(key)
# print(
# Fore.YELLOW
# + "Rule {} has a space in field name ({}).".format(file, key)
# )
# if type(value) == dict:
# key_iterator(value, faulty)
# faulty_fieldnames = []
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# detection = self.get_rule_part(file_path=file, part_name="detection")
# key_iterator(detection, faulty_fieldnames)
# self.assertEqual(
# faulty_fieldnames,
# [],
# Fore.RED
# + "There are rules with an unsupported field name. Spaces are not allowed. (Replace space with an underscore character '_' )",
# )
#sigma cli AllOfThemConditionIssue
# def test_single_named_condition_with_x_of_them(self):
# faulty_detections = []
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# yaml = self.get_rule_yaml(file_path=file)
# detection = self.get_rule_part(file_path=file, part_name="detection")
# has_them_in_condition = "them" in detection["condition"]
# has_only_one_named_condition = len(detection) == 2
# not_multipart_yaml_file = len(yaml) == 1
# if (
# has_them_in_condition
# and has_only_one_named_condition
# and not_multipart_yaml_file
# ):
# faulty_detections.append(file)
# self.assertEqual(
# faulty_detections,
# [],
# Fore.RED
# + "There are rules using '1/all of them' style conditions but only have one condition",
# )
def test_duplicate_detections(self):
def compare_detections(detection1: dict, detection2: dict) -> bool:
# If they have different log sources. They can't be the same
# We first remove any definitions fields (if there are any) in the logsource to avoid typos
detection1["logsource"].pop("definition", None)
detection2["logsource"].pop("definition", None)
if detection1["logsource"] != detection2["logsource"]:
return False
# detections not the same count can't be the same
if len(detection1) != len(detection2):
return False
for named_condition in detection1:
# don't check timeframes
if named_condition == "timeframe":
continue
# condition clause must be the same too
if named_condition == "condition":
if detection1["condition"] != detection2["condition"]:
return False
else:
continue
# Named condition must exist in both rule files
if named_condition not in detection2:
return False
# can not be the same if len is not equal
if len(detection1[named_condition]) != len(detection2[named_condition]):
return False
for condition in detection1[named_condition]:
if type(condition) != str:
return False
if condition not in detection2[named_condition]:
return False
# We add this check in case of keyword rules. Where no field is used. The parser returns a list instead of a dict
# If the 2 list are different that means they aren't the same
if (type(detection1[named_condition]) == list) or (
type(detection2[named_condition]) == list
):
condition_value1 = detection1[named_condition]
condition_value2 = detection2[named_condition]
else:
condition_value1 = detection1[named_condition][condition]
condition_value2 = detection2[named_condition][condition]
if condition_value1 != condition_value2:
return False
return True
faulty_detections = []
files_and_their_detections = {}
for file in self.yield_next_rule_file_path(self.path_to_rules):
detection = self.get_rule_part(file_path=file, part_name="detection")
logsource = self.get_rule_part(file_path=file, part_name="logsource")
detection["logsource"] = {}
detection["logsource"].update(logsource)
yaml = self.get_rule_yaml(file_path=file)
is_multipart_yaml_file = len(yaml) != 1
if is_multipart_yaml_file:
continue
for key in files_and_their_detections:
if compare_detections(detection, files_and_their_detections[key]):
faulty_detections.append((key, file))
files_and_their_detections[file] = detection
self.assertEqual(
faulty_detections,
[],
Fore.YELLOW + "There are rule files with exactly the same detection logic.",
)
def test_source_eventlog(self):
faulty_detections = []
for file in self.yield_next_rule_file_path(self.path_to_rules):
detection = self.get_rule_part(file_path=file, part_name="detection")
detection_str = str(detection).lower()
if "'source': 'eventlog'" in detection_str:
faulty_detections.append(file)
self.assertEqual(
faulty_detections,
[],
Fore.YELLOW
+ "There are detections with 'Source: Eventlog'. This does not add value to the detection.",
)
def test_event_id_instead_of_process_creation(self):
faulty_detections = []
for file in self.yield_next_rule_file_path(self.path_to_rules):
with open(file, encoding="utf-8") as f:
for line in f:
if (
re.search(r".*EventID: (?:1|4688)\s*$", line)
and file not in faulty_detections
):
detection = self.get_rule_part(
file_path=file, part_name="detection"
)
if detection:
for search_identifier in detection:
if isinstance(detection[search_identifier], dict):
for field in detection[search_identifier]:
if "Provider_Name" in field:
if isinstance(
detection[search_identifier][
"Provider_Name"
],
list,
):
for value in detection[
search_identifier
]["Provider_Name"]:
if (
"Microsoft-Windows-Security-Auditing"
in value
or "Microsoft-Windows-Sysmon"
in value
):
if (
file
not in faulty_detections
):
faulty_detections.append(
file
)
else:
if (
"Microsoft-Windows-Security-Auditing"
in detection[search_identifier][
"Provider_Name"
]
or "Microsoft-Windows-Sysmon"
in detection[search_identifier][
"Provider_Name"
]
):
if file not in faulty_detections:
faulty_detections.append(file)
self.assertEqual(
faulty_detections,
[],
Fore.YELLOW
+ "There are rules still using Sysmon 1 or Event ID 4688. Please migrate to the process_creation category.",
)
def test_sysmon_rule_without_eventid(self):
faulty_rules = []
for file in self.yield_next_rule_file_path(self.path_to_rules):
logsource = self.get_rule_part(file_path=file, part_name="logsource")
if logsource:
service = logsource.get("service", "")
if service.lower() == "sysmon":
with open(file, encoding="utf-8") as f:
found = False
for line in f:
# might be on a single line or in multiple lines
if re.search(r".*EventID:.*$", line):
found = True
break
if not found:
faulty_rules.append(file)
self.assertEqual(
faulty_rules,
[],
Fore.RED
+ "There are rules using sysmon events but with no EventID specified",
)
# sigma cli SigmahqFalsepositivesCapitalIssue
# def test_optional_falsepositives_capital(self):
# faulty_rules = []
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# fps = self.get_rule_part(file_path=file, part_name="falsepositives")
# if fps:
# for fp in fps:
# # first letter should be capital
# try:
# if fp[0].upper() != fp[0]:
# print(
# Fore.YELLOW
# + "Rule {} defines a falsepositive that does not start with a capital letter: '{}'.".format(
# file, fp
# )
# )
# faulty_rules.append(file)
# except TypeError as err:
# print("TypeError Exception for rule {}".format(file))
# print("Error: {}".format(err))
# print("Maybe you created an empty falsepositive item?")
# self.assertEqual(
# faulty_rules,
# [],
# Fore.RED
# + "There are rules with false positives that don't start with a capital letter (e.g. 'unknown' should be 'Unknown')",
# )
# sigma cli SigmahqFalsepositivesBannedWordIssue
# def test_optional_falsepositives_blocked_content(self):
# faulty_rules = []
# banned_words = ["none", "pentest", "penetration test"]
# common_typos = ["unkown", "ligitimate", "legitim ", "legitimeate"]
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# fps = self.get_rule_part(file_path=file, part_name="falsepositives")
# if fps:
# for fp in fps:
# for typo in common_typos:
# if fp == "Unknow" or typo in fp.lower():
# print(
# Fore.YELLOW
# + "Rule {} defines a falsepositive with a common typo: '{}'.".format(
# file, typo
# )
# )
# faulty_rules.append(file)
# for banned_word in banned_words:
# if banned_word in fp.lower():
# print(
# Fore.YELLOW
# + "Rule {} defines a falsepositive with an invalid reason: '{}'.".format(
# file, banned_word
# )
# )
# faulty_rules.append(file)
# self.assertEqual(
# faulty_rules,
# [],
# Fore.RED
# + "There are rules with invalid false positive definitions (e.g. Pentest, None or common typos)",
# )
def test_optional_license(self):
faulty_rules = []
for file in self.yield_next_rule_file_path(self.path_to_rules):
license_str = self.get_rule_part(file_path=file, part_name="license")
if license_str:
if not isinstance(license_str, str):
print(
Fore.YELLOW
+ "Rule {} has a malformed 'license' (has to be a string).".format(
file
)
)
faulty_rules.append(file)
self.assertEqual(
faulty_rules,
[],
Fore.RED
+ "There are rules with malformed 'license' fields. (has to be a string )",
)
# sigma cli SigmaReferencesError
# def test_references(self):
# faulty_rules = []
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# references = self.get_rule_part(file_path=file, part_name="references")
# # Reference field doesn't exist
# # if not references:
# # print(Fore.YELLOW + "Rule {} has no field 'references'.".format(file))
# # faulty_rules.append(file)
# if references:
# # it exists but isn't a list
# if not isinstance(references, list):
# print(
# Fore.YELLOW
# + "Rule {} has a references field that isn't a list.".format(
# file
# )
# )
# faulty_rules.append(file)
# self.assertEqual(
# faulty_rules,
# [],
# Fore.RED
# + "There are rules with malformed 'references' fields. (has to be a list of values even if it contains only a single value)",
# )
# sigme cli SigmahqLinkDescriptionIssue
# def test_references_in_description(self):
# # This test checks for the presence of a links and special keywords in the "description" field while there is no "references" field.
# faulty_rules = []
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# references = self.get_rule_part(file_path=file, part_name="references")
# # Reference field doesn't exist
# if not references:
# descriptionfield = self.get_rule_part(
# file_path=file, part_name="description"
# )
# if descriptionfield:
# for i in [
# "http://",
# "https://",
# "internal research",
# ]: # Extends the list with other common references starters
# if i in descriptionfield.lower():
# print(
# Fore.RED
# + "Rule {} has a field that contains references to external links but no references set. Add a 'references' key and add URLs as list items.".format(
# file
# )
# )
# faulty_rules.append(file)
# self.assertEqual(
# faulty_rules,
# [],
# Fore.RED
# + "There are rules with malformed 'description' fields. (links and external references have to be in a seperate field named 'references'. see specification https://github.com/SigmaHQ/sigma-specification)",
# )
def test_file_names(self):
faulty_rules = []
name_lst = []
filename_pattern = re.compile(r"[a-z0-9_]{10,90}\.yml")
for file in self.yield_next_rule_file_path(self.path_to_rules):
filename = os.path.basename(file)
if filename in name_lst:
print(Fore.YELLOW + "Rule {} is a duplicate file name.".format(file))
faulty_rules.append(file)
elif filename[-4:] != ".yml":
print(
Fore.YELLOW + "Rule {} has a invalid extension (.yml).".format(file)
)
faulty_rules.append(file)
elif len(filename) > 90:
print(
Fore.YELLOW + "Rule {} has a file name too long >90.".format(file)
)
faulty_rules.append(file)
elif len(filename) < 14:
print(
Fore.YELLOW + "Rule {} has a file name too short <14.".format(file)
)
faulty_rules.append(file)
elif filename_pattern.match(filename) == None or not "_" in filename:
print(
Fore.YELLOW
+ "Rule {} has a file name that doesn't match our standard.".format(
file
)
)
faulty_rules.append(file)
else:
# This test make sure that every rules has a filename that corresponds to
# It's specific logsource.
# Fix Issue #1381 (https://github.com/SigmaHQ/sigma/issues/1381)
logsource = self.get_rule_part(file_path=file, part_name="logsource")
if logsource:
pattern_prefix = ""
os_infix = ""
os_bool = False
for key, value in logsource.items():
if key == "definition":
pass
else:
if key == "product":
# This is to get the OS for certain categories
if value == "windows":
os_infix = "win_"
elif value == "macos":
os_infix = "macos_"
elif value == "linux":
os_infix = "lnx_"
# For other stuff
elif value == "aws":
pattern_prefix = "aws_"
elif value == "azure":
pattern_prefix = "azure_"
elif value == "gcp":
pattern_prefix = "gcp_"
elif value == "m365":
pattern_prefix = "microsoft365_"
elif value == "okta":
pattern_prefix = "okta_"
elif value == "onelogin":
pattern_prefix = "onelogin_"
elif value == "github":
pattern_prefix = "github_"
elif key == "category":
if value == "process_creation":
pattern_prefix = "proc_creation_"
os_bool = True
elif value == "image_load":
pattern_prefix = "image_load_"
elif value == "file_event":
pattern_prefix = "file_event_"
os_bool = True
elif value == "registry_set":
pattern_prefix = "registry_set_"
elif value == "registry_add":
pattern_prefix = "registry_add_"
elif value == "registry_event":
pattern_prefix = "registry_event_"
elif value == "registry_delete":
pattern_prefix = "registry_delete_"
elif value == "registry_rename":
pattern_prefix = "registry_rename_"
elif value == "process_access":
pattern_prefix = "proc_access_"
os_bool = True
elif value == "driver_load":
pattern_prefix = "driver_load_"
os_bool = True
elif value == "dns_query":
pattern_prefix = "dns_query_"
os_bool = True
elif value == "ps_script":
pattern_prefix = "posh_ps_"
elif value == "ps_module":
pattern_prefix = "posh_pm_"
elif value == "ps_classic_start":
pattern_prefix = "posh_pc_"
elif value == "pipe_created":
pattern_prefix = "pipe_created_"
elif value == "network_connection":
pattern_prefix = "net_connection_"
os_bool = True
elif value == "file_rename":
pattern_prefix = "file_rename_"
os_bool = True
elif value == "file_delete":
pattern_prefix = "file_delete_"
os_bool = True
elif value == "file_change":
pattern_prefix = "file_change_"
os_bool = True
elif value == "file_access":
pattern_prefix = "file_access_"
os_bool = True
elif value == "create_stream_hash":
pattern_prefix = "create_stream_hash_"
elif value == "create_remote_thread":
pattern_prefix = "create_remote_thread_win_"
elif value == "dns":
pattern_prefix = "net_dns_"
elif value == "firewall":
pattern_prefix = "net_firewall_"
elif value == "webserver":
pattern_prefix = "web_"
elif key == "service":
if value == "auditd":
pattern_prefix = "lnx_auditd_"
elif value == "modsecurity":
pattern_prefix = "modsec_"
elif value == "diagnosis-scripted":
pattern_prefix = "win_diagnosis_scripted_"
elif value == "firewall-as":
pattern_prefix = "win_firewall_as_"
elif value == "msexchange-management":
pattern_prefix = "win_exchange_"
elif value == "security":
pattern_prefix = "win_security_"
elif value == "system":
pattern_prefix = "win_system_"
elif value == "taskscheduler":
pattern_prefix = "win_taskscheduler_"
elif value == "terminalservices-localsessionmanager":
pattern_prefix = "win_terminalservices_"
elif value == "windefend":
pattern_prefix = "win_defender_"
elif value == "wmi":
pattern_prefix = "win_wmi_"
elif value == "codeintegrity-operational":
pattern_prefix = "win_codeintegrity_"
elif value == "bits-client":
pattern_prefix = "win_bits_client_"
elif value == "applocker":
pattern_prefix = "win_applocker_"
elif value == "dns-server-analytic":
pattern_prefix = "win_dns_analytic_"
elif value == "bitlocker":
pattern_prefix = "win_bitlocker_"
elif value == "capi2":
pattern_prefix = "win_capi2_"
elif (
value
== "certificateservicesclient-lifecycle-system"
):
pattern_prefix = "win_certificateservicesclient_lifecycle_system_"
elif value == "pim":
pattern_prefix = "azure_pim_"
# This value is used to test if we should add the OS infix for certain categories
if os_bool:
pattern_prefix += os_infix
if pattern_prefix != "":
if not filename.startswith(pattern_prefix):
print(
Fore.YELLOW
+ "Rule {} has a file name that doesn't match our standard naming convention.".format(
file
)
)
faulty_rules.append(file)
name_lst.append(filename)
self.assertEqual(
faulty_rules,
[],
Fore.RED
+ r"There are rules with malformed file names (too short, too long, uppercase letters, a minus sign etc.). Please see the file names used in our repository and adjust your file names accordingly. The pattern for a valid file name is \'[a-z0-9_]{10,90}\.yml\' and it has to contain at least an underline character. It also has to follow the following naming convention https://github.com/SigmaHQ/sigma-specification/blob/main/sigmahq/Sigmahq_filename_rule.md",
)
# sigma cli sigmahq_title_caseIssue, sigmahq_title_endIssue, sigmahq_title_lengthIssue, sigmahq_title_startIssue
# def test_title(self):
# faulty_rules = []
# allowed_lowercase_words = [
# "the",
# "for",
# "in",
# "with",
# "via",
# "on",
# "to",
# "without",
# "of",
# "through",
# "from",
# "by",
# "as",
# "a",
# "or",
# "at",
# "and",
# "an",
# "over",
# "new",
# ]
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# title = self.get_rule_part(file_path=file, part_name="title")
# if not title:
# print(Fore.RED + "Rule {} has no field 'title'.".format(file))
# faulty_rules.append(file)
# continue
# elif len(title) > 110:
# print(
# Fore.YELLOW
# + "Rule {} has a title field with too many characters (>110)".format(
# file
# )
# )
# faulty_rules.append(file)
# if title.startswith("Detects "):
# print(
# Fore.RED
# + "Rule {} has a title that starts with 'Detects'".format(file)
# )
# faulty_rules.append(file)
# if title.endswith("."):
# print(Fore.RED + "Rule {} has a title that ends with '.'".format(file))
# faulty_rules.append(file)
# wrong_casing = []
# for word in title.split(" "):
# if (
# word.islower()
# and not word.lower() in allowed_lowercase_words
# and not "." in word
# and not "/" in word
# and not "_" in word
# and not word[0].isdigit()
# ):
# wrong_casing.append(word)
# if len(wrong_casing) > 0:
# print(
# Fore.RED
# + "Rule {} has a title that has not title capitalization. Words: '{}'".format(
# file, ", ".join(wrong_casing)
# )
# )
# faulty_rules.append(file)
# self.assertEqual(
# faulty_rules,
# [],
# Fore.RED
# + "There are rules with non-conform 'title' fields. Please check: https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide#title",
# )
def test_title_in_first_line(self):
faulty_rules = []
for file in self.yield_next_rule_file_path(self.path_to_rules):
yaml = self.get_rule_yaml(file)
# skip multi-part yaml
if len(yaml) > 1:
continue
# this probably is not the best way to check whether
# title is the attribute given in the 1st line
# (also assumes dict keeps the order from the input file)
if list(yaml[0].keys())[0] != "title":
print(
Fore.RED
+ "Rule {} does not have its 'title' attribute in the first line".format(
file
)
)
faulty_rules.append(file)
self.assertEqual(
faulty_rules,
[],
Fore.RED
+ "There are rules without the 'title' attribute in their first line.",
)
def test_selection_list_one_value(self):
def treat_list(file, values, valid_, selection_name):
# rule with only list of Keywords term
if len(values) == 1 and not isinstance(values[0], str):
print(
Fore.RED
+ "Rule {} has the selection ({}) with a list of only 1 element in detection".format(
file, selection_name
)
)
valid_ = False
elif isinstance(values[0], dict):
valid_ = treat_dict(file, values, valid_, selection_name)
return valid_
def treat_dict(file, values, valid_, selection_name):
if isinstance(values, list):
for dict_ in values:
for key_ in dict_.keys():
if isinstance(dict_[key_], list):
if len(dict_[key_]) == 1:
print(
Fore.RED
+ "Rule {} has the selection ({}/{}) with a list of only 1 value in detection".format(
file, selection_name, key_
)
)
valid_ = False
else:
dict_ = values
for key_ in dict_.keys():
if isinstance(dict_[key_], list):
if len(dict_[key_]) == 1:
print(
Fore.RED
+ "Rule {} has the selection ({}/{}) with a list of only 1 value in detection".format(
file, selection_name, key_
)
)
valid_ = False
return valid_
faulty_rules = []
for file in self.yield_next_rule_file_path(self.path_to_rules):
detection = self.get_rule_part(file_path=file, part_name="detection")
if detection:
valid = True
for key in detection:
values = detection[key]
if isinstance(detection[key], list):
valid = treat_list(file, values, valid, key)
if isinstance(detection[key], dict):
valid = treat_dict(file, values, valid, key)
if not valid:
faulty_rules.append(file)
self.assertEqual(
faulty_rules,
[],
Fore.RED + "There are rules using list with only 1 element",
)
# simga cli SigmahqSigmacIssue
# def test_selection_start_or_and(self):
# faulty_rules = []
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# detection = self.get_rule_part(file_path=file, part_name="detection")
# if detection:
# # This test is a best effort to avoid breaking SIGMAC parser. You could do more testing and try to fix this once and for all by modifiying the token regular expressions https://github.com/SigmaHQ/sigma/blob/b9ae5303f12cda8eb6b5b90a32fd7f11ad65645d/tools/sigma/parser/condition.py#L107-L127
# for key in detection:
# if key[:3].lower() == "sel":
# continue
# elif key[:2].lower() == "or":
# print(
# Fore.RED
# + "Rule {} has a selection '{}' that starts with the string 'or'".format(
# file, key
# )
# )
# faulty_rules.append(file)
# elif key[:3].lower() == "and":
# print(
# Fore.RED
# + "Rule {} has a selection '{}' that starts with the string 'and'".format(
# file, key
# )
# )
# faulty_rules.append(file)
# elif key[:3].lower() == "not":
# print(
# Fore.RED
# + "Rule {} has a selection '{}' that starts with the string 'not'".format(
# file, key
# )
# )
# faulty_rules.append(file)
# self.assertEqual(
# faulty_rules,
# [],
# Fore.RED
# + "There are rules with bad selection names. Can't start a selection name with an 'or*' or an 'and*' or a 'not*' ",
# )
# sigma validator dangling_detection
# def test_unused_selection(self):
# faulty_rules = []
# for file in self.yield_next_rule_file_path(self.path_to_rules):
# detection = self.get_rule_part(file_path=file, part_name="detection")
# condition = detection["condition"]
# wildcard_selections = re.compile(r"\sof\s([\w\*]+)(?:$|\s|\))")
# # skip rules containing aggregations
# if type(condition) == list:
# continue
# for selection in detection:
# if selection == "condition":
# continue
# if selection == "timeframe":
# continue
# # remove special keywords
# condition_list = (
# condition.replace("not ", "")
# .replace("1 of ", "")
# .replace("all of ", "")
# .replace(" or ", " ")
# .replace(" and ", " ")
# .replace("(", "")
# .replace(")", "")
# .split(" ")
# )
# if selection in condition_list:
# continue
# # find all wildcards in condition
# found = False
# for wildcard_selection in wildcard_selections.findall(condition):
# # wildcard matches selection
# if (
# re.search(wildcard_selection.replace(r"*", r".*"), selection)
# is not None
# ):
# found = True
# break
# # selection was not found in condition
# if not found:
# print(
# Fore.RED
# + "Rule {} has an unused selection '{}'".format(file, selection)
# )
# faulty_rules.append(file)
# self.assertEqual(
# faulty_rules, [], Fore.RED + "There are rules with unused selections"
# )