forked from ace-ecosystem/yara_scanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyara_scanner.py
executable file
·1814 lines (1480 loc) · 66.5 KB
/
yara_scanner.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
# vim: sw=4:ts=4:et:cc=120
__version__ = "1.1.3"
__doc__ = """
Yara Scanner
============
A wrapper around the yara library for Python. ::
scanner = YaraScanner()
# start tracking this yara file
scanner.track_yara_file('/path/to/yara_file.yar')
scanner.load_rules()
scanner.scan('/path/to/file/to/scan')
# check to see if your yara file changed
if scanner.check_rules():
scanner.load_rules()
# track an entire directory of yara files
scanner.track_yara_dir('/path/to/directory')
scanner.load_rules()
# did any of the yara files in this directory change?
if scanner.check_rules():
scanner.load_rules()
# track a git repository of yara rules
scanner.track_yara_repo('/path/to/git_repo')
scanner.load_rules()
# this only returns True if a new commit was added since the last check
if scanner.check_rules():
scanner.load_rules()
"""
import csv
import datetime
import functools
import io
import json
import logging
import multiprocessing
import os
import os.path
import pickle
import random
import re
import shutil
import signal
import socket
import struct
import sys
import threading
import time
import traceback
from operator import itemgetter
import hashlib
import tempfile
from subprocess import PIPE, Popen
from typing import Dict, List
import plyara, plyara.utils
import progress.bar
import yara
class RulesNotLoadedError(Exception):
"""Raised when a call is made to scan before any rules have been loaded."""
pass
# keys to the JSON dicts you get back from YaraScanner.scan_results
RESULT_KEY_TARGET = "target"
RESULT_KEY_META = "meta"
RESULT_KEY_NAMESPACE = "namespace"
RESULT_KEY_RULE = "rule"
RESULT_KEY_STRINGS = "strings"
RESULT_KEY_TAGS = "tags"
ALL_RESULT_KEYS = [
RESULT_KEY_TARGET,
RESULT_KEY_META,
RESULT_KEY_NAMESPACE,
RESULT_KEY_RULE,
RESULT_KEY_STRINGS,
RESULT_KEY_TAGS,
]
DEFAULT_YARA_EXTERNALS = {
"filename": "",
"filepath": "",
"extension": "",
"filetype": "",
}
yara.set_config(max_strings_per_rule=30720)
log = logging.getLogger("yara-scanner")
def get_current_repo_commit(repo_dir):
"""Utility function to return the current commit hash for a given repo directory. Returns None on failure."""
p = Popen(
["git", "-C", repo_dir, "log", "-n", "1", "--format=oneline"], stdout=PIPE, stderr=PIPE, universal_newlines=True
)
commit, stderr = p.communicate()
p.wait()
if len(stderr.strip()) > 0:
log.error("git reported an error: {}".format(stderr.strip()))
if len(commit) < 40:
log.error("got {} for stdout with git log".format(commit.strip()))
return None
return commit[0:40]
def get_rules_md5(namespaces: Dict[str, List[str]]) -> str:
"""Combine all of the rule files and hash. We can then store the compiled
rules to disk and reload on a later run if nothing has changed"""
m = hashlib.md5()
for namespace in sorted(namespaces):
for path in sorted(namespaces[namespace]):
with open(path, "rb") as fp:
while True:
chunk = fp.read(io.DEFAULT_BUFFER_SIZE)
if chunk == b"":
break
m.update(chunk)
return m.hexdigest()
class YaraJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, bytes):
return o.decode("utf-8", errors="backslashreplace")
return json.JSONEncoder.default(self, o)
class YaraScanner(object):
"""
The primary object used for scanning files and data with yara rules."""
def __init__(
self,
signature_dir=None,
thread_count=None,
test_mode=False,
auto_compile_rules=False,
auto_compiled_rules_dir=None,
default_timeout=5,
):
"""
Creates a new YaraScanner object.
:param signature_dir: A directory that contains one directory per set
of yara rules. Each subdirectory will get loaded into its own namespace
(named after the path to the directory.) This is for convenience. Also
see :func:`YaraScanner.track_yara_file`,
:func:`YaraScanner.track_yara_dir`, and
:func:`YaraScanner.track_yara_repo`.
:param compile_rules: Set to True to save and load compiled rules using
the compiled_rules_dir. Defaults to False.
:para compiled_rules_dir: A path to a directory to read/write compiled rules.
If this is left as None then the system temporary directory is used.
:type signature_dir: str or None
"""
self.rules = None
self._scan_results = []
# we can pass in a list of "blacklisted" rules
# this is a list of rule NAMES that are essentially ignored in the scan results (not output)
self._blacklisted_rules = set()
# we keep track of when the rules change and (optionally) automatically re-load the rules
self.tracked_files = {} # key = file_path, value = last modification time
self.tracked_dirs = {} # key = dir_path, value = {} (key = file_path, value = last mtime)
self.tracked_repos = {} # key = dir_path, value = current git commit
self.tracked_compiled_path = None
self.tracked_compiled_lastmtime = None
# both parameters to this function are for backwards compatibility
if thread_count is not None:
# TODO use warnings
log.warning("thread_count is no longer used in YaraScanner.__init__")
# we are reading/writing compiled rules?
self.auto_compile_rules = auto_compile_rules
# where to save/load compiled rules from
self.auto_compiled_rules_dir = auto_compiled_rules_dir
if not self.auto_compiled_rules_dir:
self.auto_compiled_rules_dir = os.path.join(tempfile.gettempdir(), "compiled_rules")
# if a "signature directory" is specific then we automatically start tracking rules
if signature_dir is not None and os.path.isdir(signature_dir):
for dir_path in os.listdir(signature_dir):
dir_path = os.path.join(signature_dir, dir_path)
if not os.path.isdir(dir_path):
continue
if os.path.exists(os.path.join(dir_path, ".git")):
self.track_yara_repository(dir_path)
else:
self.track_yara_dir(dir_path)
# the default amount of time (in seconds) a yara scan is allowed to take before it fails
self.default_timeout = default_timeout
@property
def scan_results(self):
"""Returns the scan results of the most recent scan.
This function returns a list of dict with the following format ::
{
'target': str,
'meta': dict,
'namespace': str,
'rule': str,
'strings': list,
'tags': list,
}
**target** is the target of the scane. In the case of file scans then target will be the path to the file that was scanned. In the case of data (raw binary) scans, this will be an empty string.
**meta** is the dict of meta directives of the matching rule.
**namespace** is the namespace the rule is in. In the case of repo and directory tracking, this will be the path of the directory. Otherwise it has a hard coded value of DEFAULT. *Setting the namespace to the path of the directory allows yara rules with duplicate names in different directories to be added to the same yara context.*
**rule** is the name of the matching yara rule.
**strings** is a list of tuples representing the individual string matches in the following format. ::
(position, string_name, content)
where **position** is the byte position of the match, **string_name** is the name of the yara string that matched, and **content** is the binary content it matched.
**tags** is a list of tags contained in the matching rule.
"""
return self._scan_results
@scan_results.setter
def scan_results(self, value):
self._scan_results = value
@property
def blacklist(self):
"""The list of yara rules configured as blacklisted. Rules that are blacklisted are not compiled and used."""
return list(self._blacklisted_rules)
@blacklist.setter
def blacklist(self, value):
assert isinstance(value, list)
self._blacklisted_rules = set(value)
def blacklist_rule(self, rule_name):
"""Adds the given rule to the list of rules that are blacklisted. See :func:`YaraScanner.blacklist`."""
self._blacklisted_rules.add(rule_name)
@property
def json(self):
"""Returns the current scan results as a JSON formatted string."""
return json.dumps(self.scan_results, indent=4, sort_keys=True, cls=YaraJSONEncoder)
@functools.lru_cache()
def git_available(self):
"""Returns True if git is available on the system, False otherwise."""
return shutil.which("git")
def track_compiled_yara_file(self, file_path):
"""Tracks the given file that contains compiled yara rules."""
self.tracked_compiled_path = file_path
if os.path.exists(file_path):
self.tracked_compiled_lastmtime = os.path.getmtime(file_path)
def track_yara_file(self, file_path):
"""Adds a single yara file. The file is then monitored for changes to mtime, removal or adding."""
if not os.path.exists(file_path):
self.tracked_files[file_path] = None # file did not exist when we started tracking
# we keep track of the path by keeping the key in the dictionary
# so that if the file comes back we'll reload it
else:
self.tracked_files[file_path] = os.path.getmtime(file_path)
log.debug("yara file {} tracked @ {}".format(file_path, self.tracked_files[file_path]))
def track_yara_dir(self, dir_path):
"""Adds all files in a given directory that end with .yar when converted to lowercase. All files are monitored for changes to mtime, as well as new and removed files."""
if not os.path.isdir(dir_path):
log.error("{} is not a directory".format(dir_path))
return
self.tracked_dirs[dir_path] = {}
for file_path in os.listdir(dir_path):
file_path = os.path.join(dir_path, file_path)
if file_path.lower().endswith(".yar") or file_path.lower().endswith(".yara"):
self.tracked_dirs[dir_path][file_path] = os.path.getmtime(file_path)
log.debug("tracking file {} @ {}".format(file_path, self.tracked_dirs[dir_path][file_path]))
log.debug("tracking directory {} with {} yara files".format(dir_path, len(self.tracked_dirs[dir_path])))
def track_yara_repository(self, dir_path):
"""Adds all files in a given directory **that is a git repository** that end with .yar when converted to lowercase. Only commits to the repository trigger rule reload."""
if not self.git_available():
log.warning("git cannot be found: defaulting to track_yara_dir")
return self.track_yara_dir(dir_path)
if not os.path.isdir(dir_path):
log.error("{} is not a directory".format(dir_path))
return False
if not os.path.exists(os.path.join(dir_path, ".git")):
log.error("{} is not a git repository (missing .git)".format(dir_path))
return False
# get the initial commit of this directory
self.tracked_repos[dir_path] = get_current_repo_commit(dir_path)
log.debug("tracking git repo {} @ {}".format(dir_path, self.tracked_repos[dir_path]))
def check_rules(self):
"""
Returns True if the rules need to be recompiled or reloaded, False
otherwise. The criteria that determines if the rules are recompiled
depends on how they are tracked.
:rtype: bool"""
if self.tracked_compiled_path:
# did the file come back?
if self.tracked_compiled_lastmtime is None and os.path.exists(self.tracked_compiled_path):
log.info(f"detected recreated compiled yara file {self.tracked_compiled_path}")
return True
# was the file deleted?
elif self.tracked_compiled_lastmtime is not None and not os.path.exists(self.tracked_compiled_path):
log.info(f"detected deleted compiled yara file {self.tracked_compiled_path}")
return False # no reason to reload if we have nothing to load
# was the file modified?
elif os.path.getmtime(self.tracked_compiled_path) != self.tracked_compiled_lastmtime:
log.info(f"detected change in compiled yara file {self.tracked_compiled_path}")
return True
else:
# nothing changed, nothing to compare
return False
reload_rules = False # final result to return
for file_path in self.tracked_files.keys():
# did the file come back?
if self.tracked_files[file_path] is None and os.path.exists(file_path):
log.info(f"detected recreated yara file {file_path}")
self.track_yara_file(file_path)
# was the file deleted?
elif self.tracked_files[file_path] is not None and not os.path.exists(file_path):
log.info(f"detected deleted yara file {file_path}")
self.track_yara_file(file_path)
reload_rules = True
# was the file modified?
elif os.path.getmtime(file_path) != self.tracked_files[file_path]:
log.info(f"detected change in yara file {file_path}")
self.track_yara_file(file_path)
reload_rules = True
for dir_path in self.tracked_dirs.keys():
reload_dir = False # set to True if we need to reload this directory
existing_files = set() # keep track of the ones we see
for file_path in os.listdir(dir_path):
file_path = os.path.join(dir_path, file_path)
if not (file_path.lower().endswith(".yar") or file_path.lower().endswith(".yara")):
continue
existing_files.add(file_path)
if file_path not in self.tracked_dirs[dir_path]:
log.info("detected new yara file {} in {}".format(file_path, dir_path))
reload_dir = True
reload_rules = True
elif os.path.getmtime(file_path) != self.tracked_dirs[dir_path][file_path]:
log.info("detected change in yara file {} dir {}".format(file_path, dir_path))
reload_dir = True
reload_rules = True
# did a file get deleted?
for file_path in self.tracked_dirs[dir_path].keys():
if file_path not in existing_files:
log.info("detected deleted yara file {} in {}".format(file_path, dir_path))
reload_dir = True
reload_rules = True
if reload_dir:
self.track_yara_dir(dir_path)
for repo_path in self.tracked_repos.keys():
current_repo_commit = get_current_repo_commit(repo_path)
# log.debug("repo {} current commit {} tracked commit {}".format(
# repo_path, self.tracked_repos[repo_path], current_repo_commit))
if current_repo_commit != self.tracked_repos[repo_path]:
log.info("detected change in git repo {}".format(repo_path))
self.track_yara_repository(repo_path)
reload_rules = True
# if we don't have a yara context yet then we def need to compile the rules
if self.rules is None:
return True
return reload_rules
def get_namespace_dict(self) -> Dict[str, List[str]]:
"""Returns a dictionary that contains lists of the tracked yara files organized by namespace."""
# if we're using pre-compiled yara rules then you don't need this
if self.tracked_compiled_path:
return {}
all_files = {} # key = "namespace", value = [] of file_paths
# XXX there's a bug in yara where using an empty string as the namespace causes a segfault
all_files["DEFAULT"] = [_ for _ in self.tracked_files.keys() if self.tracked_files[_] is not None]
for dir_path in self.tracked_dirs.keys():
all_files[dir_path] = self.tracked_dirs[dir_path]
for repo_path in self.tracked_repos.keys():
all_files[repo_path] = []
for file_path in os.listdir(repo_path):
file_path = os.path.join(repo_path, file_path)
if file_path.lower().endswith(".yar") or file_path.lower().endswith(".yara"):
all_files[repo_path].append(file_path)
return all_files
def test_rules(self, test_config):
if not test_config.test:
return False
if self.tracked_compiled_path:
raise RuntimeError("cannot test compiled rules -- you need the source code to test the performance")
all_files = self.get_namespace_dict()
file_count = 0
for namespace, file_list in all_files.items():
file_count += len(file_list)
# if we have no files to compile then we have nothing to do
if file_count == 0:
sys.stderr.write("ERROR: no yara files specified\n")
return False
# build the buffers we're going to use to test
buffers = [] # [(buffer_name, buffer)]
if test_config.test_data: # random data to scan
buffers.append(("random", test_config.test_data))
else:
buffers.append(("random", os.urandom(1024 * 1024)))
for x in range(255):
buffers.append((f"chr({x})", bytes([x]) * (1024 * 1024)))
execution_times = [] # of (total_seconds, buffer_type, file_name, rule_name)
execution_errors = [] # of (error_message, buffer_type, file_name, rule_name)
string_execution_times = []
string_errors = []
bar = progress.bar.Bar("decompiling rules", max=file_count)
parsed_rules = {} # key = rule_name, value = parsed_yara_rule
yara_sources = {} # key = rule_name, value = yara_source_string
yara_files = {} # key = rule_name, value = file it came from
for namespace, file_list in all_files.items():
for file_path in file_list:
if test_config.show_progress_bar:
bar.next()
with open(file_path, "r") as fp:
yara_source = fp.read()
parser = plyara.Plyara()
for parsed_rule in parser.parse_string(yara_source):
# if we specified a rule to test then discard the others
if test_config.test_rule and parsed_rule["rule_name"] != test_config.test_rule:
continue
parsed_rules[parsed_rule["rule_name"]] = parsed_rule
yara_sources[parsed_rule["rule_name"]] = yara_source
yara_files[parsed_rule["rule_name"]] = file_path
if test_config.show_progress_bar:
bar.finish()
steps = len(parsed_rules) * 256
class FancyBar(progress.bar.Bar):
message = "testing"
suffix = "%(percent).1f%% - %(eta_hms)s - %(rule)s (%(buffer)s)"
rule = None
buffer = None
@property
def eta_hms(self):
seconds = self.eta
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, seconds)
bar = FancyBar(max=steps)
for rule_name in parsed_rules.keys():
bar.rule = rule_name
# some rules depend on other rules, so we deal with that here
dependencies = [] # list of rule_names that this rule needs
rule_context = None
while True:
# compile all the rules we've collected so far as one
dep_source = "\n".join([plyara.utils.rebuild_yara_rule(parsed_rules[r]) for r in dependencies])
try:
rule_context = yara.compile(
source="{}\n{}".format(dep_source, plyara.utils.rebuild_yara_rule(parsed_rules[rule_name]))
)
break
except Exception as e:
# some rules depend on other rules
m = re.search(r'undefined identifier "([^"]+)"', str(e))
if m:
dependency = m.group(1)
if dependency in parsed_rules:
# add this rule to the compilation and try again
dependencies.insert(0, dependency)
continue
sys.stderr.write(
"rule {} in file {} does not compile by itself: {}\n".format(
rule_name, yara_files[rule_name], e
)
)
rule_context = None
break
if not rule_context:
continue
trigger_test_strings = False
for buffer_name, buffer in buffers:
try:
bar.buffer = buffer_name
if test_config.show_progress_bar:
bar.next()
start_time = time.time()
rule_context.match(data=buffer, timeout=5)
end_time = time.time()
total_seconds = end_time - start_time
execution_times.append([buffer_name, yara_files[rule_name], rule_name, total_seconds])
if test_config.test_strings_if and total_seconds > test_config.test_strings_threshold:
trigger_test_strings = True
except Exception as e:
execution_errors.append([buffer_name, yara_files[rule_name], rule_name, str(e)])
if test_config.test_strings_if:
trigger_test_strings = True
if test_config.test_strings or trigger_test_strings:
parser = plyara.Plyara()
parsed_rule = None
for _ in parser.parse_string(yara_sources[rule_name]):
if _["rule_name"] == rule_name:
parsed_rule = _
if not parsed_rule:
sys.stderr.write(f"no rule named {rule_name} in {yara_files[rule_name]}\n")
continue
string_count = 1
for string in parsed_rule["strings"]:
if string["type"] == "regex":
string_count += 1
class FancyStringBar(progress.bar.Bar):
message = "processing"
suffix = "%(percent).1f%% - %(eta_hms)s - %(rule)s %(string)s (%(buffer)s)"
rule = None
string = None
buffer = None
@property
def eta_hms(self):
seconds = self.eta
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, seconds)
string_bar = FancyStringBar(max=string_count * 256)
string_bar.rule = rule_name
for string in parsed_rule["strings"]:
if string["type"] == "regex":
string_bar.string = string["value"]
try:
string_name = string["name"]
string_value = string["value"]
temp_rule = f"""
rule temp_rule {{
strings:
$ = {string_value}
condition:
any of them
}}"""
string_rule_context = yara.compile(source=temp_rule)
for buffer_name, buffer in buffers:
string_bar.buffer = buffer_name
try:
start_time = time.time()
scan_result = string_rule_context.match(data=buffer, timeout=5)
end_time = time.time()
string_execution_times.append(
[
buffer_name,
yara_files[rule_name],
rule_name,
string_name,
len(scan_result),
end_time - start_time,
]
)
except Exception as e:
string_errors.append(
[buffer_name, yara_files[rule_name], rule_name, string_name, str(e)]
)
if test_config.show_progress_bar:
string_bar.next()
except Exception as e:
sys.stderr.write(f"failed to test string {string_name}: {e}\n")
string_errors.append(["N/A", yara_files[rule_name], rule_name, string_name, str(e)])
if test_config.show_progress_bar:
string_bar.finish()
if test_config.show_progress_bar:
bar.finish()
# order by execution time
execution_times = sorted(execution_times, key=itemgetter(3), reverse=True)
string_execution_times = sorted(string_execution_times, key=itemgetter(5), reverse=True)
if test_config.csv or test_config.performance_csv:
with open(test_config.csv or test_config.performance_csv, "w", newline="") as fp:
writer = csv.writer(fp)
writer.writerow(["buffer", "file", "rule", "time"])
for row in execution_times:
writer.writerow(row)
else:
print("BEGIN EXECUTION TIME")
for row in execution_times:
print(row)
print("END EXECUTION TIME")
if test_config.csv or test_config.failure_csv:
with open(test_config.csv or test_config.failure_csv, "a" if test_config.csv else "w", newline="") as fp:
writer = csv.writer(fp)
writer.writerow(["buffer", "file", "rule", "error"])
for row in execution_errors:
writer.writerow(row)
else:
print("BEGIN EXECUTION ERRORS")
for row in execution_errors:
print(row)
print("END EXECUTION ERRORS")
if test_config.csv or test_config.string_performance_csv:
with open(
test_config.csv or test_config.string_performance_csv, "a" if test_config.csv else "w", newline=""
) as fp:
writer = csv.writer(fp)
writer.writerow(["buffer", "file", "rule", "string", "hits", "time"])
for row in string_execution_times:
writer.writerow(row)
else:
print("BEGIN STRING EXECUTION TIME")
for row in string_execution_times:
print(row)
print("END STRING EXECUTION TIME")
if test_config.csv or test_config.string_failure_csv:
with open(
test_config.csv or test_config.string_failure_csv, "a" if test_config.csv else "w", newline=""
) as fp:
writer = csv.writer(fp)
writer.writerow(["buffer", "file", "rule", "string", "error"])
for row in string_errors:
writer.writerow(row)
else:
print("BEGIN STRING EXECUTION ERRORS")
for row in string_errors:
print(row)
print("END STRING EXECUTION ERRORS")
def load_rules(self, external_vars=DEFAULT_YARA_EXTERNALS):
if self.auto_compile_rules:
rules_hash = get_rules_md5(self.get_namespace_dict())
compiled_rules_path = os.path.join(self.auto_compiled_rules_dir, f"{rules_hash}.cyar")
if self.load_compiled_rules(compiled_rules_path):
return True
if self.compile_and_load_rules(external_vars=external_vars):
if self.auto_compile_rules:
self.save_compiled_rules(compiled_rules_path)
return True
else:
return False
def load_compiled_rules(self, path):
try:
if os.path.isfile(path):
log.debug(f"up to date compiled rules already exist at {path}")
self.rules = yara.load(path)
return True
except:
log.warning(f"failed to load compiled rules: {path}")
return False
def save_compiled_rules(self, path):
try:
self.rules.save(path)
os.chmod(path, 0o666) # XXX ???
return True
except Exception as e:
log.warning(f"failed to save compiled rules {path}: {e}")
return False
def compile_and_load_rules(self, external_vars=DEFAULT_YARA_EXTERNALS):
"""
Loads and compiles all tracked yara rules. Returns True if the rules were loaded correctly, False otherwise.
Scans can be performed only after the rules are loaded.
:rtype: bool"""
if self.tracked_compiled_path:
try:
self.tracked_compiled_lastmtime = os.path.getmtime(self.tracked_compiled_path)
self.rules = yara.load(self.tracked_compiled_path)
return True
except FileNotFoundError:
self.tracked_compiled_lastmtime = None
return False
except Exception as e:
log.error("unable to load {self.tracked_compiled_path}: {e}")
return False
# load and compile the rules
# we load all the rules into memory as a string to be compiled
sources = {}
rule_count = 0
file_count = 0
all_files = self.get_namespace_dict()
file_count = sum([len(_) for _ in all_files.values()])
# if we have no files to compile then we have nothing to do
if file_count == 0:
logging.debug("no files to compile")
self.rules = None
return False
for namespace in all_files.keys():
for file_path in all_files[namespace]:
with open(file_path, "r") as fp:
log.debug("loading namespace {} rule file {}".format(namespace, file_path))
data = fp.read()
try:
# compile the file as a whole first, make sure that works
rule_context = yara.compile(source=data, externals=external_vars)
rule_count += 1
except Exception as e:
log.error("unable to compile {}: {}".format(file_path, str(e)))
continue
# then we just store the source to be loaded all at once in the compilation that gets used
if namespace not in sources:
sources[namespace] = []
sources[namespace].append(data)
for namespace in sources.keys():
sources[namespace] = "\r\n".join(sources[namespace])
try:
log.info("loading {} rules".format(rule_count))
self.rules = yara.compile(sources=sources, externals=external_vars)
return True
except Exception as e:
log.error(f"unable to compile all yara rules combined: {e}")
self.rules = None
return False
# we're keeping things backwards compatible here...
def scan(self, file_path, yara_stdout_file=None, yara_stderr_file=None, external_vars={}, timeout=None):
"""
Scans the given file with the loaded yara rules. Returns True if at least one yara rule matches, False otherwise.
The ``scan_results`` property will contain the results of the scan.
:param file_path: The path to the file to scan.
:type file_path: str
:param yara_stdout_file: Ignored.
:param yara_stderr_file: Ignored.
:external_vars: dict of variables to pass to the scanner as external yara variables (typically used in the condition of the rule.)
:type external_vars: dict
:rtype: bool
"""
# default external variables
default_external_vars = {
"filename": os.path.basename(file_path),
"filepath": file_path,
"filetype": "", # get_the_file_type(),
"extension": file_path.rsplit(".", maxsplit=1)[1] if "." in file_path else "",
}
# update with whatever is passed in
default_external_vars.update(external_vars)
if not timeout:
timeout = self.default_timeout
if self.rules is None:
self.load_rules()
if self.rules is None:
raise RulesNotLoadedError()
# scan the file
# external variables come from the profile points added to the file
yara_matches = self.rules.match(file_path, externals=default_external_vars, timeout=timeout)
return self.filter_scan_results(
file_path, None, yara_matches, yara_stdout_file, yara_stderr_file, external_vars
)
def scan_data(self, data, yara_stdout_file=None, yara_stderr_file=None, external_vars={}, timeout=None):
"""
Scans the given data with the loaded yara rules. ``data`` can be either a str or bytes object. Returns True if at least one yara rule matches, False otherwise.
The ``scan_results`` property will contain the results of the scan.
:param data: The data to scan.
:type data: str or bytes
:param yara_stdout_file: Ignored.
:param yara_stderr_file: Ignored.
:external_vars: dict of variables to pass to the scanner as external yara variables (typically used in the condition of the rule.)
:type external_vars: dict
:rtype: bool
"""
assert self.rules is not None
if not timeout:
timeout = self.default_timeout
# scan the data stream
# external variables come from the profile points added to the file
yara_matches = self.rules.match(data=data, externals=external_vars, timeout=timeout)
return self.filter_scan_results(None, data, yara_matches, yara_stdout_file, yara_stderr_file, external_vars)
def filter_scan_results(
self, file_path, data, yara_matches, yara_stdout_file=None, yara_stderr_file=None, external_vars={}
):
# if we didn't specify a file_path then we default to an empty string
# that will be the case when we are scanning a data chunk
if file_path is None:
file_path = ""
# the mime type of the file
# we'll figure it out if we need to
mime_type = None
# the list of matches after we filter
self.scan_results = []
for match_result in yara_matches:
skip = False # state flag
# is this a rule we've blacklisted?
if match_result.rule in self.blacklist:
log.debug("rule {} is blacklisted".format(match_result.rule))
continue
for directive in match_result.meta:
value = match_result.meta[directive]
# everything we're looking for is a string
if not isinstance(value, str):
continue
# you can invert the logic by starting the value with !
inverted = False
if value.startswith("!"):
value = value[1:]
inverted = True
# you can use regex by starting string with re: (after optional negation)
use_regex = False
if value.startswith("re:"):
value = value[3:]
use_regex = True
# or you can use substring matching with sub:
use_substring = False
if value.startswith("sub:"):
value = value[4:]
use_substring = True
# figure out what we're going to compare against
compare_target = None
if directive.lower() == "file_ext":
if "." not in file_path:
compare_target = ""
else:
compare_target = file_path.rsplit(".", maxsplit=1)[1]
elif directive.lower() == "mime_type":
# have we determined the mime type for this file yet?
if mime_type is None:
if not file_path:
mime_type = ""
else:
p = Popen(["file", "-b", "--mime-type", file_path], stdout=PIPE)
mime_type = p.stdout.read().decode().strip()
log.debug("got mime type {} for {}".format(mime_type, file_path))
compare_target = mime_type
elif directive.lower() == "file_name":
compare_target = os.path.basename(file_path)
elif directive.lower() == "full_path":
compare_target = file_path
else:
# not a meta tag we're using
# log.debug("not a valid meta directive {}".format(directive))
continue
log.debug("compare target is {} for directive {}".format(compare_target, directive))
# figure out how to compare what is supplied by the user to the search target
if use_regex:
compare_function = lambda user_supplied, target: re.search(user_supplied, target)
elif use_substring:
compare_function = lambda user_supplied, target: user_supplied in target
else:
compare_function = lambda user_supplied, target: user_supplied.lower() == target.lower()
matches = False
for search_item in [x.strip() for x in value.lower().split(",")]:
matches = matches or compare_function(search_item, compare_target)
# log.debug("search item {} vs compare target {} matches {}".format(search_item, compare_target, matches))
if (inverted and matches) or (not inverted and not matches):
log.debug(
"skipping yara rule {} for file {} directive {} list {} negated {} regex {} subsearch {}".format(
match_result.rule, file_path, directive, value, inverted, use_regex, use_substring
)
)
skip = True
break # we are skipping so we don't need to check anything else
if not skip:
self.scan_results.append(match_result)
# get rid of the yara object and just return dict
# also includes a "target" (reference to what was scanned)
self.scan_results = [
{
"target": file_path,
"meta": o.meta,
"namespace": o.namespace,
"rule": o.rule,
"strings": o.strings,