forked from Neo23x0/yarGen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yarGen.py
2481 lines (2155 loc) · 105 KB
/
yarGen.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 python
# -*- coding: iso-8859-1 -*-
# -*- coding: utf-8 -*-
#
# yarGen
# A Rule Generator for YARA Rules
#
# Florian Roth
__version__ = "0.24.0"
import os
import sys
import argparse
import re
import traceback
import operator
import datetime
import time
import lief
import json
import gzip
import urllib.request
import binascii
import base64
import shutil
from collections import Counter
from hashlib import sha256
import signal as signal_module
from lxml import etree
import nltk
# Ensure that necessary NLTK resources are available
nltk.download('punkt')
nltk.download('punkt_tab')
nltk.download('words')
from nltk.corpus import words
from nltk.tokenize import word_tokenize
# A simple filter function to consider only meaningful words (ignoring non-English or arbitrary symbols)
def filter_meaningful_words(word_list):
# Only allow alphabetic, lowercase words
return [word for word in word_list if word.isalpha() and word.islower()]
# Load NLTK word corpus
nltk_words = set(words.words())
RELEVANT_EXTENSIONS = [".asp", ".vbs", ".ps", ".ps1", ".tmp", ".bas", ".bat", ".cmd", ".com", ".cpl",
".crt", ".dll", ".exe", ".msc", ".scr", ".sys", ".vb", ".vbe", ".vbs", ".wsc",
".wsf", ".wsh", ".input", ".war", ".jsp", ".php", ".asp", ".aspx", ".psd1", ".psm1", ".py"]
AI_COMMENT = """
The provided rule is a YARA rule, encompassing a wide range of suspicious strings. Kindly review the list and pinpoint the twenty strings that are most distinctive or appear most suited for a YARA rule focused on malware detection. Arrange them in descending order based on their level of suspicion. Then, swap out the current list of strings in the YARA rule with your chosen set and supply the revised rule.
---
"""
REPO_URLS = {
'good-opcodes-part1.db': 'https://www.bsk-consulting.de/yargen/good-opcodes-part1.db',
'good-opcodes-part2.db': 'https://www.bsk-consulting.de/yargen/good-opcodes-part2.db',
'good-opcodes-part3.db': 'https://www.bsk-consulting.de/yargen/good-opcodes-part3.db',
'good-opcodes-part4.db': 'https://www.bsk-consulting.de/yargen/good-opcodes-part4.db',
'good-opcodes-part5.db': 'https://www.bsk-consulting.de/yargen/good-opcodes-part5.db',
'good-opcodes-part6.db': 'https://www.bsk-consulting.de/yargen/good-opcodes-part6.db',
'good-opcodes-part7.db': 'https://www.bsk-consulting.de/yargen/good-opcodes-part7.db',
'good-opcodes-part8.db': 'https://www.bsk-consulting.de/yargen/good-opcodes-part8.db',
'good-opcodes-part9.db': 'https://www.bsk-consulting.de/yargen/good-opcodes-part9.db',
'good-strings-part1.db': 'https://www.bsk-consulting.de/yargen/good-strings-part1.db',
'good-strings-part2.db': 'https://www.bsk-consulting.de/yargen/good-strings-part2.db',
'good-strings-part3.db': 'https://www.bsk-consulting.de/yargen/good-strings-part3.db',
'good-strings-part4.db': 'https://www.bsk-consulting.de/yargen/good-strings-part4.db',
'good-strings-part5.db': 'https://www.bsk-consulting.de/yargen/good-strings-part5.db',
'good-strings-part6.db': 'https://www.bsk-consulting.de/yargen/good-strings-part6.db',
'good-strings-part7.db': 'https://www.bsk-consulting.de/yargen/good-strings-part7.db',
'good-strings-part8.db': 'https://www.bsk-consulting.de/yargen/good-strings-part8.db',
'good-strings-part9.db': 'https://www.bsk-consulting.de/yargen/good-strings-part9.db',
'good-exports-part1.db': 'https://www.bsk-consulting.de/yargen/good-exports-part1.db',
'good-exports-part2.db': 'https://www.bsk-consulting.de/yargen/good-exports-part2.db',
'good-exports-part3.db': 'https://www.bsk-consulting.de/yargen/good-exports-part3.db',
'good-exports-part4.db': 'https://www.bsk-consulting.de/yargen/good-exports-part4.db',
'good-exports-part5.db': 'https://www.bsk-consulting.de/yargen/good-exports-part5.db',
'good-exports-part6.db': 'https://www.bsk-consulting.de/yargen/good-exports-part6.db',
'good-exports-part7.db': 'https://www.bsk-consulting.de/yargen/good-exports-part7.db',
'good-exports-part8.db': 'https://www.bsk-consulting.de/yargen/good-exports-part8.db',
'good-exports-part9.db': 'https://www.bsk-consulting.de/yargen/good-exports-part9.db',
'good-imphashes-part1.db': 'https://www.bsk-consulting.de/yargen/good-imphashes-part1.db',
'good-imphashes-part2.db': 'https://www.bsk-consulting.de/yargen/good-imphashes-part2.db',
'good-imphashes-part3.db': 'https://www.bsk-consulting.de/yargen/good-imphashes-part3.db',
'good-imphashes-part4.db': 'https://www.bsk-consulting.de/yargen/good-imphashes-part4.db',
'good-imphashes-part5.db': 'https://www.bsk-consulting.de/yargen/good-imphashes-part5.db',
'good-imphashes-part6.db': 'https://www.bsk-consulting.de/yargen/good-imphashes-part6.db',
'good-imphashes-part7.db': 'https://www.bsk-consulting.de/yargen/good-imphashes-part7.db',
'good-imphashes-part8.db': 'https://www.bsk-consulting.de/yargen/good-imphashes-part8.db',
'good-imphashes-part9.db': 'https://www.bsk-consulting.de/yargen/good-imphashes-part9.db',
}
PE_STRINGS_FILE = "./3rdparty/strings.xml"
KNOWN_IMPHASHES = {'a04dd9f5ee88d7774203e0a0cfa1b941': 'PsExec',
'2b8c9d9ab6fefc247adaf927e83dcea6': 'RAR SFX variant'}
def get_abs_path(filename):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
def get_files(folder, notRecursive):
# Not Recursive
if notRecursive:
for filename in os.listdir(folder):
filePath = os.path.join(folder, filename)
if os.path.isdir(filePath):
continue
yield filePath
# Recursive
else:
for root, dirs, files in os.walk(folder, topdown = False):
for name in files:
filePath = os.path.join(root, name)
yield filePath
def parse_sample_dir(dir, notRecursive=False, generateInfo=False, onlyRelevantExtensions=False):
# Prepare dictionary
string_stats = {}
opcode_stats = {}
file_info = {}
known_sha1sums = []
for filePath in get_files(dir, notRecursive):
try:
print("[+] Processing %s ..." % filePath)
# Get Extension
extension = os.path.splitext(filePath)[1].lower()
if not extension in RELEVANT_EXTENSIONS and onlyRelevantExtensions:
if args.debug:
print("[-] EXTENSION %s - Skipping file %s" % (extension, filePath))
continue
# Info file check
if os.path.basename(filePath) == os.path.basename(args.b) or \
os.path.basename(filePath) == os.path.basename(args.r):
continue
# Size Check
size = 0
try:
size = os.stat(filePath).st_size
if size > (args.fs * 1024 * 1024):
if args.debug:
print("[-] File is to big - Skipping file %s (use -fs to adjust this behaviour)" % (filePath))
continue
except Exception as e:
pass
# Check and read file
try:
with open(filePath, 'rb') as f:
fileData = f.read()
except Exception as e:
print("[-] Cannot read file - skipping %s" % filePath)
# Extract strings from file
strings = extract_strings(fileData)
# Extract opcodes from file
opcodes = []
if use_opcodes:
print("[-] Extracting OpCodes: %s" % filePath)
opcodes = extract_opcodes(fileData)
# Add sha256 value
if generateInfo:
sha256sum = sha256(fileData).hexdigest()
file_info[filePath] = {}
file_info[filePath]["hash"] = sha256sum
file_info[filePath]["imphash"], file_info[filePath]["exports"] = get_pe_info(fileData)
# Skip if hash already known - avoid duplicate files
if sha256sum in known_sha1sums:
# if args.debug:
print("[-] Skipping strings/opcodes from %s due to MD5 duplicate detection" % filePath)
continue
else:
known_sha1sums.append(sha256sum)
# Magic evaluation
if not args.nomagic:
file_info[filePath]["magic"] = binascii.hexlify(fileData[:2]).decode('ascii')
else:
file_info[filePath]["magic"] = ""
# File Size
file_info[filePath]["size"] = os.stat(filePath).st_size
# Add stats for basename (needed for inverse rule generation)
fileName = os.path.basename(filePath)
folderName = os.path.basename(os.path.dirname(filePath))
if fileName not in file_info:
file_info[fileName] = {}
file_info[fileName]["count"] = 0
file_info[fileName]["hashes"] = []
file_info[fileName]["folder_names"] = []
file_info[fileName]["count"] += 1
file_info[fileName]["hashes"].append(sha256sum)
if folderName not in file_info[fileName]["folder_names"]:
file_info[fileName]["folder_names"].append(folderName)
# Add strings to statistics
for string in strings:
# String is not already known
if string not in string_stats:
string_stats[string] = {}
string_stats[string]["count"] = 0
string_stats[string]["files"] = []
string_stats[string]["files_basename"] = {}
# String count
string_stats[string]["count"] += 1
# Add file information
if fileName not in string_stats[string]["files_basename"]:
string_stats[string]["files_basename"][fileName] = 0
string_stats[string]["files_basename"][fileName] += 1
if filePath not in string_stats[string]["files"]:
string_stats[string]["files"].append(filePath)
# Add opcodes to statistics
for opcode in opcodes:
# Opcode is not already known
if opcode not in opcode_stats:
opcode_stats[opcode] = {}
opcode_stats[opcode]["count"] = 0
opcode_stats[opcode]["files"] = []
opcode_stats[opcode]["files_basename"] = {}
# Opcode count
opcode_stats[opcode]["count"] += 1
# Add file information
if fileName not in opcode_stats[opcode]["files_basename"]:
opcode_stats[opcode]["files_basename"][fileName] = 0
opcode_stats[opcode]["files_basename"][fileName] += 1
if filePath not in opcode_stats[opcode]["files"]:
opcode_stats[opcode]["files"].append(filePath)
if args.debug:
print("[+] Processed " + filePath + " Size: " + str(size) + " Strings: " + str(len(string_stats)) + \
" OpCodes: " + str(len(opcode_stats)) + " ... ")
except Exception as e:
traceback.print_exc()
print("[E] ERROR reading file: %s" % filePath)
return string_stats, opcode_stats, file_info
def parse_good_dir(dir, notRecursive=False, onlyRelevantExtensions=True):
# Prepare dictionary
all_strings = Counter()
all_opcodes = Counter()
all_imphashes = Counter()
all_exports = Counter()
for filePath in get_files(dir, notRecursive):
# Get Extension
extension = os.path.splitext(filePath)[1].lower()
if extension not in RELEVANT_EXTENSIONS and onlyRelevantExtensions:
if args.debug:
print("[-] EXTENSION %s - Skipping file %s" % (extension, filePath))
continue
# Size Check
size = 0
try:
size = os.stat(filePath).st_size
if size > (args.fs * 1024 * 1024):
continue
except Exception as e:
pass
# Check and read file
try:
with open(filePath, 'rb') as f:
fileData = f.read()
except Exception as e:
print("[-] Cannot read file - skipping %s" % filePath)
# Extract strings from file
strings = extract_strings(fileData)
# Append to all strings
all_strings.update(strings)
# Extract Opcodes from file
opcodes = []
if use_opcodes:
print("[-] Extracting OpCodes: %s" % filePath)
opcodes = extract_opcodes(fileData)
# Append to all opcodes
all_opcodes.update(opcodes)
# Imphash and Exports
(imphash, exports) = get_pe_info(fileData)
if imphash != "":
all_imphashes.update([imphash])
all_exports.update(exports)
if args.debug:
print("[+] Processed %s - %d strings %d opcodes %d exports and imphash %s" % (filePath, len(strings),
len(opcodes), len(exports),
imphash))
# return it as a set (unique strings)
return all_strings, all_opcodes, all_imphashes, all_exports
def extract_strings(fileData) -> list[str]:
# String list
cleaned_strings = []
# Read file data
try:
# Read strings
strings_full = re.findall(b"[\x1f-\x7e]{6,}", fileData)
strings_limited = re.findall(b"[\x1f-\x7e]{6,%d}" % args.s, fileData)
strings_hex = extract_hex_strings(fileData)
strings = list(set(strings_full) | set(strings_limited) | set(strings_hex))
wide_strings = [ws for ws in re.findall(b"(?:[\x1f-\x7e][\x00]){6,}", fileData)]
# Post-process
# WIDE
for ws in wide_strings:
# Decode UTF16 and prepend a marker (facilitates handling)
wide_string = ("UTF16LE:%s" % ws.decode('utf-16')).encode('utf-8')
if wide_string not in strings:
strings.append(wide_string)
for string in strings:
# Escape strings
if len(string) > 0:
string = string.replace(b'\\', b'\\\\')
string = string.replace(b'"', b'\\"')
try:
if isinstance(string, str):
cleaned_strings.append(string)
else:
cleaned_strings.append(string.decode('utf-8'))
except AttributeError as e:
print(string)
traceback.print_exc()
except Exception as e:
if args.debug:
print(string)
traceback.print_exc()
pass
return cleaned_strings
def extract_opcodes(fileData) -> list[str]:
# Opcode list
opcodes = []
try:
# Read file data
binary = lief.parse(fileData)
ep = binary.entrypoint
# Locate .text section
text = None
if isinstance(binary, lief.PE.Binary):
for sec in binary.sections:
if sec.virtual_address + binary.imagebase <= ep < sec.virtual_address + binary.imagebase + sec.virtual_size:
if args.debug:
print(f'EP is located at {sec.name} section')
text = sec.content.tobytes()
break
elif isinstance(binary, lief.ELF.Binary):
for sec in binary.sections:
if sec.virtual_address <= ep < sec.virtual_address + sec.size:
if args.debug:
print(f'EP is located at {sec.name} section')
text = sec.content.tobytes()
break
if text is not None:
# Split text into subs
text_parts = re.split(b"[\x00]{3,}", text)
# Now truncate and encode opcodes
for text_part in text_parts:
if text_part == '' or len(text_part) < 8:
continue
opcodes.append(binascii.hexlify(text_part[:16]).decode(encoding='ascii'))
except Exception as e:
if args.debug:
traceback.print_exc()
pass
return opcodes
def get_pe_info(fileData: bytes) -> tuple[str, list[str]]:
"""
Get different PE attributes and hashes by lief
:param fileData:
:return:
"""
imphash = ""
exports = []
# Check for MZ header (speed improvement)
if fileData[:2] != b"MZ":
return imphash, exports
try:
if args.debug:
print("Extracting PE information")
binary: lief.PE.Binary = lief.parse(fileData)
# Imphash
imphash = lief.PE.get_imphash(binary, lief.PE.IMPHASH_MODE.PEFILE)
# Exports (names)
for exp in binary.get_export().entries:
exp: lief.PE.ExportEntry
exports.append(str(exp.name))
except Exception as e:
if args.debug:
traceback.print_exc()
pass
return imphash, exports
def sample_string_evaluation(string_stats, opcode_stats, file_info):
# Generate Stats -----------------------------------------------------------
print("[+] Generating statistical data ...")
file_strings = {}
file_opcodes = {}
combinations = {}
inverse_stats = {}
max_combi_count = 0
super_rules = []
# OPCODE EVALUATION --------------------------------------------------------
for opcode in opcode_stats:
# If string occurs not too often in sample files
if opcode_stats[opcode]["count"] < 10:
# If string list in file dictionary not yet exists
for filePath in opcode_stats[opcode]["files"]:
if filePath in file_opcodes:
# Append string
file_opcodes[filePath].append(opcode)
else:
# Create list and then add the first string to the file
file_opcodes[filePath] = []
file_opcodes[filePath].append(opcode)
# STRING EVALUATION -------------------------------------------------------
# Iterate through strings found in malware files
for string in string_stats:
# If string occurs not too often in (goodware) sample files
if string_stats[string]["count"] < 10:
# If string list in file dictionary not yet exists
for filePath in string_stats[string]["files"]:
if filePath in file_strings:
# Append string
file_strings[filePath].append(string)
else:
# Create list and then add the first string to the file
file_strings[filePath] = []
file_strings[filePath].append(string)
# INVERSE RULE GENERATION -------------------------------------
if args.inverse:
for fileName in string_stats[string]["files_basename"]:
string_occurrance_count = string_stats[string]["files_basename"][fileName]
total_count_basename = file_info[fileName]["count"]
# print "string_occurance_count %s - total_count_basename %s" % ( string_occurance_count,
# total_count_basename )
if string_occurrance_count == total_count_basename:
if fileName not in inverse_stats:
inverse_stats[fileName] = []
if args.trace:
print("Appending %s to %s" % (string, fileName))
inverse_stats[fileName].append(string)
# SUPER RULE GENERATION -----------------------------------------------
if not nosuper and not args.inverse:
# SUPER RULES GENERATOR - preliminary work
# If a string occurs more than once in different files
# print sample_string_stats[string]["count"]
if string_stats[string]["count"] > 1:
if args.debug:
print("OVERLAP Count: %s\nString: \"%s\"%s" % (string_stats[string]["count"], string,
"\nFILE: ".join(string_stats[string]["files"])))
# Create a combination string from the file set that matches to that string
combi = ":".join(sorted(string_stats[string]["files"]))
# print "STRING: " + string
if args.debug:
print("COMBI: " + combi)
# If combination not yet known
if combi not in combinations:
combinations[combi] = {}
combinations[combi]["count"] = 1
combinations[combi]["strings"] = []
combinations[combi]["strings"].append(string)
combinations[combi]["files"] = string_stats[string]["files"]
else:
combinations[combi]["count"] += 1
combinations[combi]["strings"].append(string)
# Set the maximum combination count
if combinations[combi]["count"] > max_combi_count:
max_combi_count = combinations[combi]["count"]
# print "Max Combi Count set to: %s" % max_combi_count
print("[+] Generating Super Rules ... (a lot of magic)")
for combi_count in range(max_combi_count, 1, -1):
for combi in combinations:
if combi_count == combinations[combi]["count"]:
# print "Count %s - Combi %s" % ( str(combinations[combi]["count"]), combi )
# Filter the string set
# print "BEFORE"
# print len(combinations[combi]["strings"])
# print combinations[combi]["strings"]
string_set = combinations[combi]["strings"]
combinations[combi]["strings"] = []
combinations[combi]["strings"] = filter_string_set(string_set)
# print combinations[combi]["strings"]
# print "AFTER"
# print len(combinations[combi]["strings"])
# Combi String count after filtering
# print "String count after filtering: %s" % str(len(combinations[combi]["strings"]))
# If the string set of the combination has a required size
if len(combinations[combi]["strings"]) >= int(args.w):
# Remove the files in the combi rule from the simple set
if args.nosimple:
for file in combinations[combi]["files"]:
if file in file_strings:
del file_strings[file]
# Add it as a super rule
print("[-] Adding Super Rule with %s strings." % str(len(combinations[combi]["strings"])))
# if args.debug:
# print "Rule Combi: %s" % combi
super_rules.append(combinations[combi])
# Return all data
return (file_strings, file_opcodes, combinations, super_rules, inverse_stats)
def filter_opcode_set(opcode_set: list[str]) -> list[str]:
# Preferred Opcodes
pref_opcodes = [' 34 ', 'ff ff ff ']
# Useful set
useful_set = []
pref_set = []
for opcode in opcode_set:
opcode: str
# Exclude all opcodes found in goodware
if opcode in good_opcodes_db:
if args.debug:
print("skipping %s" % opcode)
continue
# Format the opcode
formatted_opcode = get_opcode_string(opcode)
# Preferred opcodes
set_in_pref = False
for pref in pref_opcodes:
if pref in formatted_opcode:
pref_set.append(formatted_opcode)
set_in_pref = True
if set_in_pref:
continue
# Else add to useful set
useful_set.append(get_opcode_string(opcode))
# Preferred opcodes first
useful_set = pref_set + useful_set
# Only return the number of opcodes defined with the "-n" parameter
return useful_set[:int(args.n)]
def filter_string_set(string_set):
# This is the only set we have - even if it's a weak one
useful_set = []
# Local string scores
localStringScores = {}
# Local UTF strings
utfstrings = []
for string in string_set:
# Filter meaningful words based on the flag
if args.meaningful_words_only:
# Tokenize the string and check if it contains any meaningful word
tokens = word_tokenize(string)
contains_meaningful_word = any(
word.lower() in nltk_words and len(word) >= 4 for word in tokens
)
# If no meaningful word is found, skip this string
if not contains_meaningful_word:
continue
# Goodware string marker
goodstring = False
goodcount = 0
# Goodware Strings
if string in good_strings_db:
goodstring = True
goodcount = good_strings_db[string]
# print "%s - %s" % ( goodstring, good_strings[string] )
if args.excludegood:
continue
# UTF
original_string = string
if string[:8] == "UTF16LE:":
# print "removed UTF16LE from %s" % string
string = string[8:]
utfstrings.append(string)
# Good string evaluation (after the UTF modification)
if goodstring:
# Reduce the score by the number of occurence in goodware files
localStringScores[string] = (goodcount * -1) + 5
else:
localStringScores[string] = 0
# PEStudio String Blacklist Evaluation
if pestudio_available:
(pescore, type) = get_pestudio_score(string)
# print("PE Match: %s" % string)
# Reset score of goodware files to 5 if blacklisted in PEStudio
if type != "":
pestudioMarker[string] = type
# Modify the PEStudio blacklisted strings with their goodware stats count
if goodstring:
pescore = pescore - (goodcount / 1000.0)
# print "%s - %s - %s" % (string, pescore, goodcount)
localStringScores[string] = pescore
if not goodstring:
# Length Score
#length = len(string)
#if length > int(args.y) and length < int(args.s):
# localStringScores[string] += round(len(string) / 8, 2)
#if length >= int(args.s):
# localStringScores[string] += 1
# Reduction
if ".." in string:
localStringScores[string] -= 5
if " " in string:
localStringScores[string] -= 5
# Packer Strings
if re.search(r'(WinRAR\\SFX)', string):
localStringScores[string] -= 4
# US ASCII char
if "\x1f" in string:
localStringScores[string] -= 4
# Chains of 00s
if string.count('0000000000') > 2:
localStringScores[string] -= 5
# Repeated characters
if re.search(r'(?!.* ([A-Fa-f0-9])\1{8,})', string):
localStringScores[string] -= 5
# Certain strings add-ons ----------------------------------------------
# Extensions - Drive
if re.search(r'[A-Za-z]:\\', string, re.IGNORECASE):
localStringScores[string] += 2
# Relevant file extensions
if re.search(r'(\.exe|\.pdb|\.scr|\.log|\.cfg|\.txt|\.dat|\.msi|\.com|\.bat|\.dll|\.pdb|\.vbs|'
r'\.tmp|\.sys|\.ps1|\.vbp|\.hta|\.lnk)', string, re.IGNORECASE):
localStringScores[string] += 4
# System keywords
if re.search(r'(cmd.exe|system32|users|Documents and|SystemRoot|Grant|hello|password|process|log)',
string, re.IGNORECASE):
localStringScores[string] += 5
# Protocol Keywords
if re.search(r'(ftp|irc|smtp|command|GET|POST|Agent|tor2web|HEAD)', string, re.IGNORECASE):
localStringScores[string] += 5
# Connection keywords
if re.search(r'(error|http|closed|fail|version|proxy)', string, re.IGNORECASE):
localStringScores[string] += 3
# Browser User Agents
if re.search(r'(Mozilla|MSIE|Windows NT|Macintosh|Gecko|Opera|User\-Agent)', string, re.IGNORECASE):
localStringScores[string] += 5
# Temp and Recycler
if re.search(r'(TEMP|Temporary|Appdata|Recycler)', string, re.IGNORECASE):
localStringScores[string] += 4
# Malicious keywords - hacktools
if re.search(r'(scan|sniff|poison|intercept|fake|spoof|sweep|dump|flood|inject|forward|scan|vulnerable|'
r'credentials|creds|coded|p0c|Content|host)', string, re.IGNORECASE):
localStringScores[string] += 5
# Network keywords
if re.search(r'(address|port|listen|remote|local|process|service|mutex|pipe|frame|key|lookup|connection)',
string, re.IGNORECASE):
localStringScores[string] += 3
# Drive
if re.search(r'([C-Zc-z]:\\)', string, re.IGNORECASE):
localStringScores[string] += 4
# IP
if re.search(
r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b',
string, re.IGNORECASE): # IP Address
localStringScores[string] += 5
# Copyright Owner
if re.search(r'(coded | c0d3d |cr3w\b|Coded by |codedby)', string, re.IGNORECASE):
localStringScores[string] += 7
# Extension generic
if re.search(r'\.[a-zA-Z]{3}\b', string):
localStringScores[string] += 3
# All upper case
if re.search(r'^[A-Z]{6,}$', string):
localStringScores[string] += 2.5
# All lower case
if re.search(r'^[a-z]{6,}$', string):
localStringScores[string] += 2
# All lower with space
if re.search(r'^[a-z\s]{6,}$', string):
localStringScores[string] += 2
# All characters
if re.search(r'^[A-Z][a-z]{5,}$', string):
localStringScores[string] += 2
# URL
if re.search(r'(%[a-z][:\-,;]|\\\\%s|\\\\[A-Z0-9a-z%]+\\[A-Z0-9a-z%]+)', string):
localStringScores[string] += 2.5
# certificates
if re.search(r'(thawte|trustcenter|signing|class|crl|CA|certificate|assembly)', string, re.IGNORECASE):
localStringScores[string] -= 4
# Parameters
if re.search(r'( \-[a-z]{,2}[\s]?[0-9]?| /[a-z]+[\s]?[\w]*)', string, re.IGNORECASE):
localStringScores[string] += 4
# Directory
if re.search(r'([a-zA-Z]:|^|%)\\[A-Za-z]{4,30}\\', string):
localStringScores[string] += 4
# Executable - not in directory
if re.search(r'^[^\\]+\.(exe|com|scr|bat|sys)$', string, re.IGNORECASE):
localStringScores[string] += 4
# Date placeholders
if re.search(r'(yyyy|hh:mm|dd/mm|mm/dd|%s:%s:)', string, re.IGNORECASE):
localStringScores[string] += 3
# Placeholders
if re.search(r'[^A-Za-z](%s|%d|%i|%02d|%04d|%2d|%3s)[^A-Za-z]', string, re.IGNORECASE):
localStringScores[string] += 3
# String parts from file system elements
if re.search(r'(cmd|com|pipe|tmp|temp|recycle|bin|secret|private|AppData|driver|config)', string,
re.IGNORECASE):
localStringScores[string] += 3
# Programming
if re.search(r'(execute|run|system|shell|root|cimv2|login|exec|stdin|read|process|netuse|script|share)',
string, re.IGNORECASE):
localStringScores[string] += 3
# Credentials
if re.search(r'(user|pass|login|logon|token|cookie|creds|hash|ticket|NTLM|LMHASH|kerberos|spnego|session|'
r'identif|account|login|auth|privilege)', string, re.IGNORECASE):
localStringScores[string] += 3
# Malware
if re.search(r'(\.[a-z]/[^/]+\.txt|)', string, re.IGNORECASE):
localStringScores[string] += 3
# Variables
if re.search(r'%[A-Z_]+%', string, re.IGNORECASE):
localStringScores[string] += 4
# RATs / Malware
if re.search(r'(spy|logger|dark|cryptor|RAT\b|eye|comet|evil|xtreme|poison|meterpreter|metasploit|/veil|Blood)',
string, re.IGNORECASE):
localStringScores[string] += 5
# Missed user profiles
if re.search(r'[\\](users|profiles|username|benutzer|Documents and Settings|Utilisateurs|Utenti|'
r'Usuários)[\\]', string, re.IGNORECASE):
localStringScores[string] += 3
# Strings: Words ending with numbers
if re.search(r'^[A-Z][a-z]+[0-9]+$', string, re.IGNORECASE):
localStringScores[string] += 1
# Spying
if re.search(r'(implant)', string, re.IGNORECASE):
localStringScores[string] += 1
# Program Path - not Programs or Windows
if re.search(r'^[Cc]:\\\\[^PW]', string):
localStringScores[string] += 3
# Special strings
if re.search(r'(\\\\\.\\|kernel|.dll|usage|\\DosDevices\\)', string, re.IGNORECASE):
localStringScores[string] += 5
# Parameters
if re.search(r'( \-[a-z] | /[a-z] | \-[a-z]:[a-zA-Z]| \/[a-z]:[a-zA-Z])', string):
localStringScores[string] += 4
# File
if re.search(r'^[a-zA-Z0-9]{3,40}\.[a-zA-Z]{3}', string, re.IGNORECASE):
localStringScores[string] += 3
# Comment Line / Output Log
if re.search(r'^([\*\#]+ |\[[\*\-\+]\] |[\-=]> |\[[A-Za-z]\] )', string):
localStringScores[string] += 4
# Output typo / special expression
if re.search(r'(!\.$|!!!$| :\)$| ;\)$|fucked|[\w]\.\.\.\.$)', string):
localStringScores[string] += 4
# Base64
if re.search(r'^(?:[A-Za-z0-9+/]{4}){30,}(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$', string) and \
re.search(r'[A-Za-z]', string) and re.search(r'[0-9]', string):
localStringScores[string] += 7
# Base64 Executables
if re.search(r'(TVqQAAMAAAAEAAAA//8AALgAAAA|TVpQAAIAAAAEAA8A//8AALgAAAA|TVqAAAEAAAAEABAAAAAAAAAAAAA|'
r'TVoAAAAAAAAAAAAAAAAAAAAAAAA|TVpTAQEAAAAEAAAA//8AALgAAAA)', string):
localStringScores[string] += 5
# Malicious intent
if re.search(r'(loader|cmdline|ntlmhash|lmhash|infect|encrypt|exec|elevat|dump|target|victim|override|'
r'traverse|mutex|pawnde|exploited|shellcode|injected|spoofed|dllinjec|exeinj|reflective|'
r'payload|inject|back conn)',
string, re.IGNORECASE):
localStringScores[string] += 5
# Privileges
if re.search(r'(administrator|highest|system|debug|dbg|admin|adm|root) privilege', string, re.IGNORECASE):
localStringScores[string] += 4
# System file/process names
if re.search(r'(LSASS|SAM|lsass.exe|cmd.exe|LSASRV.DLL)', string):
localStringScores[string] += 4
# System file/process names
if re.search(r'(\.exe|\.dll|\.sys)$', string, re.IGNORECASE):
localStringScores[string] += 4
# Indicators that string is valid
if re.search(r'(^\\\\)', string, re.IGNORECASE):
localStringScores[string] += 1
# Compiler output directories
if re.search(r'(\\Release\\|\\Debug\\|\\bin|\\sbin)', string, re.IGNORECASE):
localStringScores[string] += 2
# Special - Malware related strings
if re.search(r'(Management Support Team1|/c rundll32|DTOPTOOLZ Co.|net start|Exec|taskkill)', string):
localStringScores[string] += 4
# Powershell
if re.search(r'(bypass|windowstyle | hidden |-command|IEX |Invoke-Expression|Net.Webclient|Invoke[A-Z]|'
r'Net.WebClient|-w hidden |-encoded'
r'-encodedcommand| -nop |MemoryLoadLibrary|FromBase64String|Download|EncodedCommand)', string, re.IGNORECASE):
localStringScores[string] += 4
# WMI
if re.search(r'( /c WMIC)', string, re.IGNORECASE):
localStringScores[string] += 3
# Windows Commands
if re.search(r'( net user | net group |ping |whoami |bitsadmin |rundll32.exe javascript:|'
r'schtasks.exe /create|/c start )',
string, re.IGNORECASE):
localStringScores[string] += 3
# JavaScript
if re.search(r'(new ActiveXObject\("WScript.Shell"\).Run|.Run\("cmd.exe|.Run\("%comspec%\)|'
r'.Run\("c:\\Windows|.RegisterXLL\()', string, re.IGNORECASE):
localStringScores[string] += 3
# Signing Certificates
if re.search(r'( Inc | Co.| Ltd.,| LLC| Limited)', string):
localStringScores[string] += 2
# Privilege escalation
if re.search(r'(sysprep|cryptbase|secur32)', string, re.IGNORECASE):
localStringScores[string] += 2
# Webshells
if re.search(r'(isset\($post\[|isset\($get\[|eval\(Request)', string, re.IGNORECASE):
localStringScores[string] += 2
# Suspicious words 1
if re.search(r'(impersonate|drop|upload|download|execute|shell|\bcmd\b|decode|rot13|decrypt)', string,
re.IGNORECASE):
localStringScores[string] += 2
# Suspicious words 1
if re.search(r'([+] |[-] |[*] |injecting|exploit|dumped|dumping|scanning|scanned|elevation|'
r'elevated|payload|vulnerable|payload|reverse connect|bind shell|reverse shell| dump | '
r'back connect |privesc|privilege escalat|debug privilege| inject |interactive shell|'
r'shell commands| spawning |] target |] Transmi|] Connect|] connect|] Dump|] command |'
r'] token|] Token |] Firing | hashes | etc/passwd| SAM | NTML|unsupported target|'
r'race condition|Token system |LoaderConfig| add user |ile upload |ile download |'
r'Attaching to |ser has been successfully added|target system |LSA Secrets|DefaultPassword|'
r'Password: |loading dll|.Execute\(|Shellcode|Loader|inject x86|inject x64|bypass|katz|'
r'sploit|ms[0-9][0-9][^0-9]|\bCVE[^a-zA-Z]|privilege::|lsadump|door)',
string, re.IGNORECASE):
localStringScores[string] += 4
# Mutex / Named Pipes
if re.search(r'(Mutex|NamedPipe|\\Global\\|\\pipe\\)', string, re.IGNORECASE):
localStringScores[string] += 3
# Usage
if re.search(r'(isset\($post\[|isset\($get\[)', string, re.IGNORECASE):
localStringScores[string] += 2
# Hash
if re.search(r'\b([a-f0-9]{32}|[a-f0-9]{40}|[a-f0-9]{64})\b', string, re.IGNORECASE):
localStringScores[string] += 2
# Persistence
if re.search(r'(sc.exe |schtasks|at \\\\|at [0-9]{2}:[0-9]{2})', string, re.IGNORECASE):
localStringScores[string] += 3
# Unix/Linux
if re.search(r'(;chmod |; chmod |sh -c|/dev/tcp/|/bin/telnet|selinux| shell| cp /bin/sh )', string,
re.IGNORECASE):
localStringScores[string] += 3
# Attack
if re.search(
r'(attacker|brute force|bruteforce|connecting back|EXHAUSTIVE|exhaustion| spawn| evil| elevated)',
string, re.IGNORECASE):
localStringScores[string] += 3
# Strings with less value
if re.search(r'(abcdefghijklmnopqsst|ABCDEFGHIJKLMNOPQRSTUVWXYZ|0123456789:;)', string, re.IGNORECASE):
localStringScores[string] -= 5
# VB Backdoors
if re.search(
r'(kill|wscript|plugins|svr32|Select |)',
string, re.IGNORECASE):
localStringScores[string] += 3
# Suspicious strings - combo / special characters
if re.search(
r'([a-z]{4,}[!\?]|\[[!+\-]\] |[a-zA-Z]{4,}...)',
string, re.IGNORECASE):
localStringScores[string] += 3
if re.search(
r'(-->|!!!| <<< | >>> )',
string, re.IGNORECASE):
localStringScores[string] += 5
# Swear words
if re.search(
r'\b(fuck|damn|shit|penis)\b',
string, re.IGNORECASE):
localStringScores[string] += 5
# Scripting Strings
if re.search(
r'(%APPDATA%|%USERPROFILE%|Public|Roaming|& del|& rm| && |script)',
string, re.IGNORECASE):
localStringScores[string] += 3
# UACME Bypass
if re.search(
r'(Elevation|pwnd|pawn|elevate to)',
string, re.IGNORECASE):
localStringScores[string] += 3
# ENCODING DETECTIONS --------------------------------------------------
try:
if len(string) > 8:
# Try different ways - fuzz string
# Base64
if args.trace:
print("Starting Base64 string analysis ...")
for m_string in (string, string[1:], string[:-1], string[1:] + "=", string + "=", string + "=="):
if is_base_64(m_string):
try:
decoded_string = base64.b64decode(m_string, validate=False)
except binascii.Error as e:
continue
if is_ascii_string(decoded_string, padding_allowed=True):
# print "match"
localStringScores[string] += 10
base64strings[string] = decoded_string
# Hex Encoded string
if args.trace:
print("Starting Hex encoded string analysis ...")
for m_string in ([string, re.sub('[^a-zA-Z0-9]', '', string)]):
#print m_string
if is_hex_encoded(m_string):
#print("^ is HEX")
decoded_string = bytes.fromhex(m_string)
#print removeNonAsciiDrop(decoded_string)
if is_ascii_string(decoded_string, padding_allowed=True):
# not too many 00s
if '00' in m_string:
if len(m_string) / float(m_string.count('0')) <= 1.2:
continue
#print("^ is ASCII / WIDE")
localStringScores[string] += 8
hexEncStrings[string] = decoded_string
except Exception as e:
if args.debug:
traceback.print_exc()
pass
# Reversed String -----------------------------------------------------
if string[::-1] in good_strings_db:
if not args.excludegood:
localStringScores[string] += 10
reversedStrings[string] = string[::-1]
# Certain string reduce -----------------------------------------------
if re.search(r'(rundll32\.exe$|kernel\.dll$)', string, re.IGNORECASE):
localStringScores[string] -= 4
# Set the global string score
stringScores[original_string] = localStringScores[string]
if args.debug:
if string in utfstrings:
is_utf = True
else:
is_utf = False
# print "SCORE: %s\tUTF: %s\tSTRING: %s" % ( localStringScores[string], is_utf, string )
sorted_set = sorted(localStringScores.items(), key=operator.itemgetter(1), reverse=True)
# Only the top X strings
c = 0
result_set = []
for string in sorted_set:
# Skip the one with a score lower than -z X