-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbinsequencer.py
executable file
·1871 lines (1346 loc) · 74 KB
/
binsequencer.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
import sys, argparse, time, os, re, binascii
try:
import yara
except:
print("\n [!] Please install the Python 'yara' module")
sys.exit(1)
try:
import pefile
except:
print("\n [!] Please install the Python 'pefile' module")
sys.exit(1)
try:
from capstone import *
except:
print("\n [!] Please install the Python 'capstone' module")
sys.exit(1)
__author__ = "Jeff White [karttoon] @noottrak"
__email__ = "[email protected]"
__version__ = "1.1.0"
__date__ = "13MAY2020"
#
# The data structure used throughout this program is below:
#
# data {
# hash {
# "op_blob": {
# "section0": "jmp|ret|nop"
# "section1": "mov|add|sub"
# "op_offset": {
# "section0": ["0x10001000: jmp | e9 ?? ?? ??", "0x10001001: ret | c3"]
# "section1": ["0x10003000: mov | bf ?? ??", "0x10003001: add | 83"]
# "op_chain": {
# "section0": ["jmp", "ret"]
# "section1": ["mov", "add"]
# "section_name": {
# "section0": ".text"
# "section1": ".code"
# "gold": hash
# "matches": {
# op_blob: {
# "count" : int_match_count
# "hashes" : ["hash", "hash"]
# "sets" {
# "longest" : {
# "section0": 154
# "section1": 25
# "yara" {
# "rule1" : {
# "start" : "0x10001700"
# "end" : "0x10001afe"
# "hashes" : ["hash", "hash"]
# "bytes" : "e9010203bf010203c383"
# "result" : "e9 ?? ?? ?? bf ?? ?? c3 83"
# "msg" : "Status messages"
# "blacklist" : [op_blob, op_blob]
# "keeplist" : [op_blob, op_blob]
# "strings" : ["string1", "string2"]
#
################
# User Prompts #
################
def user_prompt(usr_msg):
user_response = (input(usr_msg)).upper()
if user_response == "Y":
return "Y"
else:
return "N"
def print_asst(msg, args):
if not args.quiet:
print(msg)
return
#################
# Process Files #
#################
def process_pe(hash, data, args):
pe = pefile.PE(hash)
count = 0
data[hash] = {"op_blob": {}, "op_offset": {}, "op_chain": {}, "section_name": {}} # Initialize each hash dictionary
print_asst("\t[-]" + hash, args)
for section in pe.sections:
if section.IMAGE_SCN_CNT_CODE == True or section.IMAGE_SCN_MEM_EXECUTE == True: # Only work on code sections
section_start = 0
zero_check = binascii.hexlify(pe.sections[count].get_data()[0:2]).decode("ascii")
# This loop will move the start forward until it no longer begins with null bytes
# Idea is to try and get to valid bytes in the code section for disassembly without using EP
while zero_check == "0000":
if args.verbose == True:
print_asst("debug zc %s" % zero_check, args)
section_start += 4
zero_check = binascii.hexlify(pe.sections[count].get_data()[section_start:section_start + 2]).decode("ascii")
if args.verbose == True:
print_asst("debug section start %s" % section_start, args)
op_blob = "" # Initialize opcode blob
instruction_count = 0 # Count for maximum number of ops
section_value = "section%d" % len(data[hash]["op_blob"])
data[hash]["op_blob"][section_value] = ""
data[hash]["op_offset"][section_value] = []
data[hash]["op_chain"][section_value] = []
code_section = pe.sections[count].get_data()[section_start:section.SizeOfRawData]
virt_addr = pe.sections[count].VirtualAddress
for op in md.disasm(code_section, int(hex(virt_addr), 16) + 0x10000000 + int(hex(section_start), 16)):
op_blob += "%s|" % op.mnemonic
data[hash]["op_offset"][section_value].append("0x%x:\t%s |%s" % (op.address, op.mnemonic, "".join('{:02x}'.format(x) for x in op.bytes)))
data[hash]["op_chain"][section_value].append("%s" % op.mnemonic)
if args.verbose == True:
if hasattr(op, "bytes"):
print_asst("debug %x | %-15s | %-15s | %2d | %-10s | %-15s | %-12s | %s" % (op.address, op.prefix, op.opcode, len(op.operands), op.mnemonic, op.op_str, "".join('{:02x}'.format(x) for x in op.bytes), "1"), args)
instruction_count += 1
data[hash]["op_blob"][section_value] = op_blob
data[hash]["section_name"][section_value] = section.Name.decode("ascii")
print_asst("\t\t%s - %d instructions extracted" % (section.Name.decode("ascii"), instruction_count), args)
count += 1 # Count for each section processed
# Remove files with no instructions identified
count = 0
for entry in data[hash]["op_chain"]:
if data[hash]["op_chain"][entry] == []:
count += 1
if count == len(data[hash]["op_chain"]):
print_asst("\t\t\t[!] Removed due to no extracted instructions", args)
del data[hash]
return data
def process_nonpe(hash, data, args):
file_data = open(hash, "rb").read().strip() # Remove newline - usually an issue with copy/paste shellcode
data[hash] = {"op_blob": {}, "op_offset": {}, "op_chain": {}, "section_name": {}} # Initialize each hash dictionary
print_asst("\t[-]" + hash, args)
op_blob = "" # Initialize opcode blob
instruction_count = 0 # Count for maximum number of ops
data[hash]["op_blob"]["section0"] = ""
data[hash]["op_offset"]["section0"] = []
data[hash]["op_chain"]["section0"] = []
code_section = file_data
virt_addr = 0x0
for op in md.disasm(code_section, int(hex(virt_addr), 16) + 0x10000000 + int(hex(0), 16)):
# if hasattr(op, "_detail"):
if hasattr(op, "bytes"):
op_blob += "%s|" % op.mnemonic
data[hash]["op_offset"]["section0"].append("0x%x:\t%s |%s" % (op.address, op.mnemonic, "".join('{:02x}'.format(x) for x in op.bytes)))
data[hash]["op_chain"]["section0"].append("%s" % op.mnemonic)
if args.verbose == True:
if hasattr(op, "bytes"):
print_asst("debug %x | %-15s | %-15s | %2d | %-10s | %-15s | %-12s | %s" % (op.address, op.prefix, op.opcode, len(op.operands), op.mnemonic, op.op_str, "".join('{:02x}'.format(x) for x in op.bytes), "1"), args)
instruction_count += 1
data[hash]["op_blob"]["section0"] = op_blob
data[hash]["section_name"]["section0"] = "nonpefile"
print_asst("\t\t%s - %d instructions extracted" % ("nonpefile", instruction_count), args)
return data
def process_files(hash, data, args):
data[hash] = {} # Initialize hash dictionary
if not args.nonpe:
try:
pefile.PE(hash)
data = process_pe(hash, data, args)
except:
del data[hash]
else:
data = process_nonpe(hash, data, args)
return data
######################
# Identify Gold Hash #
######################
def find_gold(hashes, data, args):
instruction_count = 0
if len(hashes) == 0:
print_asst("[!] No files loaded. Please use (-n) flag for non-PE files\n", args)
sys.exit(1)
for hash in hashes:
if len(hashes) == 1:
gold_hash = hash
section_count = 0
try:
for section_name in data[hash]["section_name"]:
section_count += len(data[hash]["op_chain"][section_name])
except:
print_asst("[!] Unable to find section data. Please use (-n) flag for non-PE files\n", args)
sys.exit(1)
# If 100% commonality, gold hash will be the hash with lowest amount of opcodes
if args.commonality == 1.0:
if instruction_count == 0:
instruction_count = section_count
gold_hash = hash
if section_count < instruction_count:
instruction_count = section_count
gold_hash = hash
if args.verbose == True:
print_asst("debug hash %s sec_count %d instruction_count %d gold %s" % (hash, section_count, instruction_count, gold_hash), args)
# If not a 100% commonality, gold hash will be the hash with the highest amount of opcodes
else:
if section_count > instruction_count:
instruction_count = section_count
gold_hash = hash
# If gold specified via argument, use it
if args.gold:
for hash in hashes:
if args.gold.replace("'","") in hash:
data["gold"] = hash
else:
data["gold"] = gold_hash
print_asst("\n[+] Golden hash (%d instructions) - %s" % (instruction_count, data["gold"]), args)
return data
########################
# Identify Longest Set #
########################
def longest_match(hashes, data, args):
section_total = len(data[data["gold"]]["section_name"])
section_count = 0
while section_count < section_total:
# Stop processing subsequent sections if match count is met
if len(data["keeplist"]) >= args.matches:
break
section_value = "section" + str(section_count)
initial_size = len(data[data["gold"]]["op_chain"][section_value])
print_asst("\n[+] Zeroing in longest mnemonic instruction set in %s\n" % data[data["gold"]]["section_name"][section_value], args)
# YARA has a limit on the number of hex tokens (10K) so we artificially limit our size
# Minimum 1 byte per instruction, usually 2-5 bytes for operands, but we'll have additional logic to cut hex off if it goes further
if initial_size > 4000:
blob_size = 4000
else:
blob_size = initial_size
if initial_size == 0:
print_asst("\t[-] No instructions in this section", args)
max_size = blob_size
delta_value = int(blob_size / 2)
closing_flag = 0
while blob_size > 0:
start = time.time()
data = find_match(hashes, data, blob_size, section_value, args)
end = time.time()
# Validate number of instructions in blob are longer than minimum - 25 has been fairly reliable for a default
# Figure prologue / epilogue will be around 6 instructions alone
if blob_size < args.length and section_count != (section_total - 1):
break
# If we have no matches, all sections have been checked, exit
if len(data["matches"]) == 0 and blob_size < args.length and section_count == (section_total - 1) and len(data["keeplist"]) == 0:
print_asst("\n\t[!] Unable to match set above the minimum count\n\tConsider adjusting lower with -l flag or adjusting sample set with -c\n", args)
sys.exit(1)
# If the size is maxed out and matched, immediately go into review
if len(data["matches"]) >= 1 and blob_size == max_size:
print_asst("\t[-] Moving %d instruction sets to review with a length of %d" % (len(data["matches"]), blob_size), args)
data = check_match(data, args, "longest", section_value)
# If match has been blacklisted, remove it
for match in data["blacklist"]:
data["matches"].pop(match, None)
# If we've hit our match cap, move on
if len(data["keeplist"]) >= args.matches or len(data["matches"]) > 0:
data["matches"] = {}
break
# If all matches removed, continue the hunt
if len(data["matches"]) == 0 or len(data["keeplist"]) < args.matches:
closing_flag = 0
blob_size = int(blob_size / 2)
delta_value = int(blob_size / 2)
data["matches"] = {}
print_asst("", args) # Spacing
else:
break # Go to next section
print_asst("\t[-] Matches - %-5d Block Size - %-5d Time - %0.2f seconds" % (len(data["matches"]), blob_size, end-start), args)
if args.verbose == True:
print_asst("debug - ins size %d, # of matches %d, closing_flag %d, delta %d" % (blob_size, len(data["matches"]), closing_flag, delta_value), args)
# Shrinks blob size by half and begins dividing delta
if len(data["matches"]) == 0 and delta_value != 0:
blob_size = blob_size - delta_value
delta_value = int(delta_value / 2)
# Grows blob size by adding half of the delta to existing size
if len(data["matches"]) >= 1 and delta_value != 0:
blob_size = blob_size + delta_value
delta_value = int(delta_value / 2)
data["matches"] = {}
# If previous run had a match and set the closing flag, this will trigger once there are no more matches
# Subtract one from the existing size to find longest
if len(data["matches"]) == 0 and delta_value == 0 and closing_flag == 1:
blob_size = blob_size - 1
data = find_match(hashes, data, blob_size, section_value, args)
# Validate we still haven't fallen below our minimum length
if blob_size >= args.length:
print_asst("\n\t[-] Moving %d instruction sets to review with a length of %d" % (len(data["matches"]), blob_size), args)
data = check_match(data, args, "longest", section_value)
else:
print_asst("\t[!] Unable to meet the minimum match count, continuing with remaining sets", args)
break
# If we've hit our match cap, move on
if len(data["keeplist"]) >= args.matches:
data["matches"] = {}
break
# If match has been blacklisted, remove it
for match in data["blacklist"]:
data["matches"].pop(match, None)
# If all matches removed, continue the hunt
if len(data["matches"]) == 0:
closing_flag = 0
blob_size = int(blob_size / 2)
delta_value = int(blob_size / 2)
data["matches"] = {}
print_asst("", args) # Spacing
else:
break # Go to next section
# Continue increasing by one until we no longer have matches
if len(data["matches"]) >= 1 and delta_value == 0:
blob_size += 1
closing_flag = 1
data["matches"] = {}
# If we've run out of our delta with no matches, we'll be above our target, so we need to reduce by one until we match
if len(data["matches"]) == 0 and delta_value == 0 and closing_flag == 0:
blob_size -= 1
data["matches"] = {}
section_count += 1
# Validate we have matches, otherwise exit program
if len(data["keeplist"]) >= 1:
print_asst("\n[+] Keeping %d mnemonic set using %d %% commonality out of %d hashes\n" % (len(data["keeplist"]), args.commonality * 100, len(hashes)), args)
else:
print_asst("\t[!] Unable to match set above the minimum count\n\tConsider adjusting lower with -l flag or adjusting sample set with -c\n", args)
sys.exit(1)
for section in data["sets"]["longest"]:
print_asst("\t[-] Length - %-5d Section - %s" % (data["sets"]["longest"][section], data[data["gold"]]["section_name"][section]), args)
if args.verbose == True:
print_asst("debug sets %s" % data["sets"], args)
return data
#########################
# Find Instruction Sets #
#########################
def find_match(hashes, data, opset_size, section_value, args):
slider_start = 0
slider_end = int(opset_size + slider_start)
slider_length = int(opset_size)
while slider_length == opset_size: # breaks once we go outside of possible range
if args.verbose == True:
print_asst("debug - slider start %d, end %d, len %d, size %d" % (slider_start, slider_end, slider_length, opset_size), args)
instruction_blob = "|".join(data[data["gold"]]["op_chain"][section_value][slider_start:slider_end]) # instruction size - 1 if you count pipes
disregard_value = 0
first_run = 0
hash_count = 0
match_count = 0
for hash in hashes:
if len(hashes) == 1:
hash_count = 1
data, disregard_value, first_run, hash_count, match_count, opset_size = find_data(data,
args,
hash,
instruction_blob,
disregard_value,
first_run,
hash_count,
match_count,
opset_size)
else:
if hash != data["gold"]: # Don't run it against gold, since it will match everything
hash_count += 1
data, disregard_value, first_run, hash_count, match_count, opset_size = find_data(data,
args,
hash,
instruction_blob,
disregard_value,
first_run,
hash_count,
match_count,
opset_size)
# Exponentially increases speed, breaks iteration loop once match count dips below minimum criteria
if (float(match_count) / float(hash_count)) < args.commonality:
break
# Remove blob from matches if we drop below the minimum criteria
if instruction_blob in data["matches"].keys() and (float(data["matches"][instruction_blob]["count"])/float(len(hashes))) < args.commonality:
data["matches"].pop(instruction_blob, None)
if args.verbose == True:
print_asst("debug break instruction size in keys %d" % opset_size, args)
# Advances window by one and will cause loop to break towards end of window, when length drops below the size
slider_start += 1
slider_end = opset_size + slider_start
slider_length = len(data[data["gold"]]["op_chain"][section_value][slider_start:slider_end])
return data
def find_data(data, args, hash, instruction_blob, disregard_value, first_run, hash_count, match_count, opset_size):
for section in data[hash]["section_name"]: # Check for blob in all code executable sections
# See if the instruction blob exists within other hashes blobs
line_check = data[hash]["op_blob"][section].find(instruction_blob)
# Line check will be -1 if it doesn't find a match
if line_check >= 0 and first_run == 0:
# Validate the instruction blob is not found within a blacklisted instruction set
for match in data["blacklist"]:
if instruction_blob in match:
disregard_value = 1
# First match across the samples
if disregard_value == 0:
data["matches"][instruction_blob] = {"count": 2, "hashes": [hash, data["gold"]]}
first_run = 1
match_count += 1
if args.verbose == True:
print_asst("debug break instruction size found first %d" % opset_size, args)
# Subsequent matches
elif line_check >= 0 and first_run == 1:
data["matches"][instruction_blob]["hashes"].append(hash)
data["matches"][instruction_blob]["count"] += 1
match_count += 1
return data, disregard_value, first_run, hash_count, match_count, opset_size
#################
# Check Matches #
#################
def check_pe(data, match, args, match_section, set_match):
display_flag = 0
keep_flag = 0
count = 0
pe = pefile.PE(data["gold"])
for pe_section in pe.sections:
if len(data["matches"]) > 0 and match not in data["blacklist"]:
if pe_section.Name.decode("ascii") == data[data["gold"]]["section_name"][match_section]:
# For multiple sections, make sure we don't keep prompting
if args.default:
user_answer = "N"
else:
if display_flag == 0:
user_answer = user_prompt("\n [*] Do you want to display matched instruction set? [Y/N] ")
if user_answer == "N":
display_flag = 1
if user_answer == "Y" or display_flag == 0:
print_asst("\n\t%s" % match, args)
display_flag = 1
user_answer = user_prompt("\n [*] Do you want to disassemble the underlying bytes? [Y/N] ")
if user_answer == "Y":
byte_list = []
string_start = data[data["gold"]]["op_blob"][match_section].find(match) # Find offset of match in blob
if string_start == 0:
pre_match = 0
else:
pre_match = (data[data["gold"]]["op_blob"][match_section][0:string_start].count("|"))
match_start = (data[data["gold"]]["op_offset"][match_section][pre_match]).split(":")[0]
match_end = (data[data["gold"]]["op_offset"][match_section][pre_match + len(set_match) - 1]).split(":")[0]
scrape_flag = 0
print_asst("", args) # Spacing
code_section = pe.sections[count].get_data()[:pe_section.SizeOfRawData]
virt_addr = pe.sections[count].VirtualAddress
for op in md.disasm(code_section, int(hex(virt_addr), 16) + 0x10000000):
# Due to a Capstone bug, sometimes object won't have '_detail' which causes an infinite recursive loop and crash
#if hasattr(op, "_detail"):
if hasattr(op, "bytes"):
# Start of match
if op.address == int(match_start, 16) or scrape_flag == 1:
scrape_flag = 1
byte_array = "".join('{:02x}'.format(x) for x in op.bytes)
byte_list.append(byte_array)
print_asst("\t0x%x:\t%-10s %-40s | %s" % (op.address, op.mnemonic, op.op_str, byte_array.upper()), args)
if op.address == int(match_end, 16):
break
# Print raw bytes in the event it doesn't disassemble
else:
if scrape_flag == 1:
byte_array = "".join('{:02x}'.format(x) for x in op.bytes)
byte_list.append(byte_array)
print_asst("\tDATA:\t%s" % (byte_array.upper()), args)
user_answer = user_prompt("\n [*] Do you want to display the raw byte blob? [Y/N] ")
if user_answer == "Y":
print_asst("\n\t%s" % ("".join(byte_list)).upper(), args)
# For multiple sections, make sure we don't keep prompting
if keep_flag == 0:
keep_flag = 1
if args.default:
user_answer = "Y"
else:
user_answer = user_prompt("\n [*] Do you want to keep this set? [Y/N] ")
if user_answer == "N" or match in data["blacklist"]:
data["blacklist"].append(match)
# Matched result
else:
data["sets"]["longest"][match_section] = len(set_match)
data["keeplist"][match] = data["matches"][match]
data["blacklist"].append(match)
# If accepted number of rules equals minimum, go ahead and stop
if len(data["keeplist"]) >= args.matches:
for match in data["matches"]:
data["blacklist"].append(match)
return data
if pe_section.IMAGE_SCN_CNT_CODE == True or pe_section.IMAGE_SCN_MEM_EXECUTE == True:
count += 1
return data
def check_nonpe(data, match, args, match_section, set_match):
display_flag = 0
keep_flag = 0
if len(data["matches"]) > 0 and match not in data["blacklist"]:
# For multiple sections, make sure we don't keep prompting
if args.default:
user_answer = "N"
else:
if display_flag == 0:
user_answer = user_prompt("\n [*] Do you want to display matched instruction set? [Y/N] ")
if user_answer == "N":
display_flag = 1
if user_answer == "Y" or display_flag == 0:
print_asst("\n\t%s" % match, args)
display_flag = 1
user_answer = user_prompt("\n [*] Do you want to display the raw byte blob? [Y/N] ")
if user_answer == "Y":
byte_list = []
string_start = data[data["gold"]]["op_blob"][match_section].find(match) # Find offset of match in blob
if string_start == 0:
pre_match = 0
else:
pre_match = (data[data["gold"]]["op_blob"][match_section][0:string_start].count("|"))
match_start = int((data[data["gold"]]["op_offset"][match_section][pre_match]).split(":")[0], 16) - 0x10000000
match_end = int((data[data["gold"]]["op_offset"][match_section][pre_match + len(set_match) - 1]).split(":")[0], 16) - 0x10000000
scrape_flag = 0
print_asst("", args) # Spacing
code_section = open(data["gold"], "rb").read()[match_start:match_end + 1] # Remove newline typical in shellcode copy/paste files
virt_addr = 0x0
for op in md.disasm(code_section, int(hex(virt_addr), 16) + 0x10000000):
# Due to a Capstone bug, sometimes object won't have '_detail' which causes an infinite recursive loop and crash
#if hasattr(op, "_detail"):
if hasattr(op, "bytes"):
# Start of match
if op.address == (match_start + 0x10000000) or scrape_flag == 1:
scrape_flag = 1
byte_array = "".join('{:02x}'.format(x) for x in op.bytes)
byte_list.append(byte_array)
print_asst(
"\t0x%x:\t%-10s %-40s | %s" % (op.address, op.mnemonic, op.op_str, byte_array.upper()),
args)
if op.address == (match_end + 0x10000000):
break
# Print raw bytes in the event it doesn't disassemble
else:
if scrape_flag == 1:
byte_array = "".join('{:02x}'.format(x) for x in op.bytes)
byte_list.append(byte_array)
print_asst("\tDATA:\t%s" % (byte_array.upper()), args)
print_asst("\n\t%s" % ("".join(byte_list)).upper(), args)
# For multiple sections, make sure we don't keep prompting
if keep_flag == 0:
keep_flag = 1
if args.default:
user_answer = "Y"
else:
user_answer = user_prompt("\n [*] Do you want to keep this set? [Y/N] ")
if user_answer == "N" or match in data["blacklist"]:
data["blacklist"].append(match)
# Matched result
else:
data["sets"]["longest"][match_section] = len(set_match)
data["keeplist"][match] = data["matches"][match]
data["blacklist"].append(match)
# If accepted number of rules equals minimum, go ahead and stop
if len(data["keeplist"]) >= args.matches:
for match in data["matches"]:
data["blacklist"].append(match)
return data
return data
def check_match(data, args, function, match_section):
for match in data["matches"]:
set_match = match.split("|")
# Blacklist any sets with lower than 3 types
# Double NULL bytes (00 00) will disassemble to "add byte ptr [eax], al"
# Some matches append or preprend one instruction to a NULL byte run
if len(list(set(set_match))) <= 3:
data["blacklist"].append(match)
print_asst("\t[!] Blacklisted a potentially bad match", args)
if args.verbose == True:
print_asst("debug # of matches %d - %d long - %d match" % (len(data["matches"]), match.count("|") + 1, len(set_match)), args)
# Routine to review match
if function == "longest":
if args.nonpe:
data = check_nonpe(data, match, args, match_section, set_match)
else:
pefile.PE(data["gold"])
data = check_pe(data, match, args, match_section, set_match)
# Black list remaining matches (these were not kept)
for match in data["matches"]:
if match in data["blacklist"]:
data["blacklist"].append(match)
return data
###################################
# Print Match Offsets By Function #
###################################
def print_offset(data, args):
for type in data["sets"]:
print_asst("\n[+] Printing offsets of type: %s" % type, args)
for section in data["sets"][type]:
print_asst("\n\t[-] Gold matches", args)
find_offset(data, args, "gold")
print_asst("\n\t[-] Remaining matches", args)
find_offset(data, args, "others")
return
######################
# Find Match Offsets #
######################
def find_offset(data, args, run_type):
match_count = 0
for match in data["keeplist"]:
set_match = match.split("|")
hash_list = []
# Handle the gold hash first
if run_type == "gold":
hash_list = [data["gold"]]
print_asst("\n\t----------v SET rule%d v----------\n\t%s\n\t----------^ SET rule%d ^-----------\n" % (match_count, match, match_count), args)
else:
for hash in data["keeplist"][match]["hashes"]:
if hash != data["gold"]:
hash_list.append(hash)
# Remaining matches
if run_type != "gold":
print_asst("\n\t----------v SET rule%d v----------" % (match_count), args)
for hash in hash_list:
for section in data[hash]["section_name"]:
try:
string_start = data[hash]["op_blob"][section].find(match) # Find offset of match in blob
if string_start == 0:
pre_match = 0
else:
pre_match = (data[hash]["op_blob"][section][0:string_start].count("|"))
match_start = (data[hash]["op_offset"][section][pre_match]).split(":")[0]
match_end = (data[hash]["op_offset"][section][pre_match + len(set_match) - 1]).split(":")[0]
if args.verbose == True:
print_asst("debug offset %d pre %d start %s end %s" % (string_start, pre_match, match_start, match_end), args)
print_asst("\t\t%-100s %s - %s in %s" % (hash, match_start, match_end, data[hash]["section_name"][section]), args)
# Record offset for gold hash to use later
if hash == data["gold"]:
data["yara"]["rule" + str(match_count)] = {"start":match_start, "end":match_end, "hashes":data["keeplist"][match]["hashes"]}
if args.verbose == True:
print_asst("debug match blob %s " % (" ".join(data[hash]["op_offset"][section][pre_match:pre_match + len(set_match)])), args)
except:
if args.verbose == True:
print_asst("debug - section empty", args)
continue
if run_type != "gold":
print_asst("\t----------^ SET rule%d ^-----------" % (match_count), args)
match_count += 1
return
################
# Find Strings #
################
def find_string(data, args):
data["strings"] = []
check_strings = []
file = open(data["gold"], "rb").read().strip()
# ASCII
for string in re.finditer(rb"[ -~]{%d,}" % 4, file):
if string.group(0) not in check_strings:
check_strings.append(string.group(0))
# UNICODE
for string in re.finditer(rb"(([ -~]\x00){%d,})" % 4, file):
if string not in check_strings:
check_strings.append(string.group(0))
# Check the strings to make sure they match across the samples
for string in check_strings:
for rule in data["yara"]:
match_count = string_count(string, data, rule)
if (float(match_count) / float(len(data["yara"][rule]["hashes"]))) >= args.commonality:
data["strings"].append(string)
return data
def string_count(string, data, rule):
match_count = 0
for hash in data["yara"][rule]["hashes"]:
if re.search(re.escape(string), open(hash, "rb").read()):
match_count += 1
return match_count
######################
# Generate YARA Rule #
######################
def yara_disa(data, args, hashes, code_section, virt_addr, rule):
yara_list = []
byte_list = []
scrape_flag = 0
hex_count = 0
for op in md.disasm(code_section, int(hex(virt_addr), 16) + 0x10000000):
# Due to a Capstone bug, sometimes object won't have '_detail' which causes an infinite recursive loop and crash
#if hasattr(op, "_detail"):
if hasattr(op, "bytes"):
# Start of match
if op.address == int(data["yara"][rule]["start"], 16) or scrape_flag == 1:
byte_array = "".join('{:02x}'.format(x) for x in op.bytes)
byte_length = int(len(byte_array) / 2)
byte_list.append(byte_array)
try:
keep_bytes = ((4 - (op.prefix).count(0)) + (4 - (op.opcode).count(0))) * 2
except:
keep_bytes = byte_length
# These are opcode variatons that we want to try and account for
# A lot of time there will be varying lengths due to operands as well
# Increase hex_count by a rough estimate of the operand lengths in bytes
list_call = ["e8", "ff"]
list_jmp = ["e9", "eb"]
list_zero = ["00"]
list_ret = ["c2", "c3"]
list_mov = ["88", "89", "8a", "8b", "8c", "8e", "a0", "a1", "a2", "a3", "a4", "a5", "c6", "c7"]
list_push = ["50", "51", "52", "53", "54", "55", "56", "57", "6a", "ff"]
list_pop = ["58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "07", "17", "1f", "8f"]
list_cmp = ["38", "39", "3a", "3b", "3c", "3d", "80", "81", "82", "83"]
list_test = ["84", "85", "A8", "A9", "F6", "F7"]
list_inc = ["40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "FE", "FF"]
# CALL variations
if op.mnemonic == "call":
match_count = yara_count(" ".join(yara_list) + byte_array[:2], data, rule)
if (float(match_count) / float(len(hashes))) >= args.commonality:
yara_string = "%s " % byte_array[:2] + ("?? " * (byte_length - 1)).strip()
else:
yara_string = "(E8|FF) [0-12] "
hex_count += 7
# JMP variations
elif op.mnemonic == "jmp":
match_count = yara_count(" ".join(yara_list) + byte_array[:2], data, rule)
if (float(match_count) / float(len(hashes))) >= args.commonality:
yara_string = "%s " % byte_array[:2] + ("?? " * (byte_length - 1)).strip()
else:
yara_string = "(E9|EB) [0-12] "
hex_count += 5
# All 00's
elif byte_array[:2] in list_zero and byte_array.count("0") == len(byte_array):
yara_string = ("00 " * byte_length).strip()
hex_count += byte_length
# RET variations
elif op.mnemonic == "ret":
match_count = yara_count(" ".join(yara_list) + byte_array[:2], data, rule)
if (float(match_count) / float(len(hashes))) >= args.commonality:
yara_string = "%s " % byte_array[:2] + ("?? " * (byte_length - 1)).strip()
else:
yara_string = "(C2|C3) [0-12] "
hex_count += 5
# MOV variations
elif op.mnemonic == "mov":
match_count = yara_count(" ".join(yara_list) + byte_array[:2], data, rule)
if (float(match_count) / float(len(hashes))) >= args.commonality:
yara_string = "%s " % byte_array[:2] + ("?? " * (byte_length - 1)).strip()
else:
yara_string = "(8?|A?|C?) [0-12] "
hex_count += 5
# PUSH variations