forked from Cisco-Talos/CASC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclamav_sig_creator.py
2431 lines (1990 loc) · 97.1 KB
/
clamav_sig_creator.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
#-------------------------------------------------------------------------------
#
# Copyright (C) 2015 Cisco Talos Security Intelligence and Research Group
#
# IDA Pro Plug-in: ClamAV Signature Creator (CASC)
# Author: Angel M. Villegas
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# Last revision: May 2017
# This IDA Pro plug-in will aid in creating ClamAV ndb and ldb signatures
# from data within the IDB the user selects.
#
# Installation
# ------------
# Drag and drop into IDA Pro's plugin folder for IDA Pro 6.6 and higher.
# To gain all the features of this plug-in, using IDA Pro 6.7 or higher.
# Older versions of IDA Pro may require other Python packages (i.e. PySide,
# Qt, etc.)
#
#-------------------------------------------------------------------------------
import idaapi
import idc
import idautils
from idaapi import PluginForm, action_handler_t, UI_Hooks, plugin_t, BADADDR, \
insn_t, execute_ui_requests, IDA_SDK_VERSION, BWN_DISASMS, \
BWN_STRINGS, BWN_IMPORTS, AST_ENABLE_ALWAYS
# Python Modules
import collections
import bisect
import pickle
import math
import types
import re
import csv
from urllib import quote_plus
from pprint import pprint
try:
# For IDA 6.8 and older using PySide
from PySide import QtGui, QtGui as QtWidgets, QtCore
from PySide.QtCore import Qt
except ImportError:
# For IDA 6.9 and newer using PyQt5
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import Qt
# Global Variables
#-------------------------------------------------------------------------------
b_asm_sig_handler_loaded = True
clamav_sig_creator_plugin = None
add_sig_handler_in_menu = False
valid_address_ranges = []
CLAMAV_ICON = None
# IDA Wrapper to ensure thread safety for function calls
#-------------------------------------------------------------------------------
class IDAWrapper(object):
'''
Class to wrap functions that are not thread safe
'''
def __getattribute__(self, name):
default = '[1st] default'
val = getattr(idaapi, name, default)
if val == default:
val = getattr(idc, name, default)
if val == default:
val = getattr(idautils, name, default)
if val == default:
msg = 'Unable to find {}'.format(name)
print msg
return
if hasattr(val, '__call__'):
def call(*args, **kwargs):
holder = [None] # need a holder, because 'global' sucks
def trampoline():
holder[0] = val(*args, **kwargs)
return 1
idaapi.execute_sync(trampoline, idaapi.MFF_FAST)
return holder[0]
return call
else:
return val
IDAW = IDAWrapper()
# Misc Helper Functions
#-------------------------------------------------------------------------------
def get_file_type():
# ClamAV Types: {1 : 'PE', 6 : 'ELF', 9 : 'Mach-O', 0 : 'Any'}
file_type = IDAW.get_file_type_name()
if None == file_type:
return 0
file_type = file_type.lower()
if 'mach-o' in file_type:
return 9
elif 'elf' in file_type:
return 6
elif ('pe' in file_type) or ('.net' in file_type):
return 1
return 0;
def get_type_name(file_type):
lookup = {1 : 'PE', 6 : 'ELF', 9 : 'Mach-O', 0 : 'Any'}
if file_type not in lookup:
return 'UNKNOWN'
return lookup[file_type]
def convert_to_ascii(data):
if data is None:
return data
if len(data) != 1:
return data
data = data[0].replace(' ', '')
converted = ''
not_complete = True
while not_complete:
if re.match('^([a-fA-F\d]{2})', data):
converted += data[:2].decode('hex')
data = data[2:]
elif data.startswith('{'):
match = re.match('^\{(?:(\d+)|(\d+)\-|\-(\d+)|(\d+)\-(\d))\}', data)
matches = match.groups()
if matches[0] is not None:
length = '=={}'.format(matches[0])
elif matches[1] is not None:
length = '>={}'.format(matches[1])
elif matches[2] is not None:
length = '<={}'.format(matches[2])
elif None not in matches [3:]:
length = '>={}&&<={}'.format(matches[3], matches[4])
end = data.index('}') + 1
converted += '{{WILDCARD_ANY_STRING(LENGTH{})}}'.format(length)
data = data[end:]
elif re.match('^\[(\d+)\-(\d+)\]', data):
matches = re.match('^\[(\d+)\-(\d+)\]').groups()
end = data.index(']') + 1
converted += '{{WILDCARD_ANY_STRING(LENGTH>={0[0]}&&<={0[1]})}}'.format(matches)
data = data[end:]
elif data.startswith('*'):
converted += '{WILDCARD_ANY_STRING}'
data = data[1:]
elif data.startswith('??'):
converted += '{WILDCARD_IGNORE}'
data = data[2:]
elif re.match('^(?:([a-fA-F\d])\?|\?([a-fA-F\d]))', data):
matches = re.match('^(?:([a-fA-F\d])\?|\?([a-fA-F\d]))').groups()
temp = '{{WILDCARD_NIBBLE_{}:{}}}'
if matches[0] is not None:
temp = temp.format('HIGH', hex(matches[0]))
else:
temp = temp.format('LOW', hex(matches[1]))
converted += temp
data = data[2:]
elif data.startswith('('):
end = data.index(')') + 1
alternates = convert_to_ascii([data[1:end-1]])
converted += '{{STRING_ALTERNATIVE:{}}}'.format(alternates)
data = data[end:]
else:
if data[0] not in ['|']:
print '[CASC] Error: idk how to handle {}'.format(data[0])
converted += data[0]
data = data[1:]
if len(data) == 0:
not_complete = False
return converted
def is_32bit():
info = IDAW.get_inf_structure()
if info.is_64bit():
return False
elif info.is_32bit():
return True
return False
def is_64bit():
info = IDAW.get_inf_structure()
return info.is_64bit()
def get_clamav_icon(return_hex=False, return_pixmap=False):
clamav_icon = ( '89504E470D0A1A0A0000000D494844520000001A0000001A08060000'
'00A94A4CCE000000097048597300000B1300000B1301009A9C180000'
'001974455874536F6674776172650041646F626520496D6167655265'
'61647971C9653C000004A54944415478DABC965F4CDB5514C7BFF7D7'
'5FFFD0C2DA04D8803A680B5306E34F7046972CA1D944F73081FD8926'
'EADC740F2688CB78501F8C913D9810E616E28359E603F3498D89AB31'
'B06571A6304748468031D9A285B4FC29B004C8DA425B28FDFD3CF757'
'685A2819F3CF9ADCFE7EBF7BEF399F7BCE3DE7DCCB6459C653F971D0'
'B0B9C4C29FFF754BD42BACF2DAFE273BE27A45FE770B912C3C535A5F'
'3239EC583FF34A5189A59289F56AC04E9FA675C34E6A8E52D7D0E07A'
'B9FBA4AF13CBB925ABDF8C9BF58ED97AB591A51D4807AB269822D45C'
'586C7A9E896D36269CDCC2CABBFC909BF7B9EE39572195D390BA2FCA'
'C1810EEF58751C5466DED970089A8BEF32DD0CF5557EA78D56EE652A'
'471153199FC44F3EC8E74C2189BB6BB0450EE60E60A5E99E77E2EB38'
'C86C369BC835D3ED6C9B2E1B42E8B22A9C661544BC226AB70CE9892E'
'E3EE4A042724ED7210B2E66DD9CFBBAD5EAFD71307F11FC11C855055'
'5F6219B17D6014913AD596412C1C2581D87B831C587421DA4710FBDA'
'B8901821A3889A3EC32216B8041792B69863526C3E97FB9CE4096230'
'0BE2A5C42971D03E8D1EF9E4AE5E3982F3E0C6D390C0B606A2797C3E'
'97EB21F92A951AAF6BF4875282D218CEAE39AA50A4A857B127CB189A'
'5FAED628AFB3B204DADDFA942011CCCE27EC22AB4EA8F5FF283B8F8A'
'3A940B6A05448A8D676CCF26EFD1416BA185D66FDC4F5156AF4E43E4'
'5F94828FB4E9784F6D4034F6990CA27DB448F4BF5325225310683B93'
'83A02FBC883F97C31B94FE160C20204593FAB2988062D2C3171B5DEF'
'3A89DA0AB5250AF54562388B0A70EDCD23E83368D13A3783D3D363F8'
'39F06803BCE9E18432F6905CF54B55296E57ED818FEBA08586A82D27'
'CC576A1D413C4B040892FFE649E8F8F916ECDABD1BBD3535386DB7A3'
'26DD888F337392407B75067C9A95872F66A7D079B806AD17BE442810'
'C0B5DAE3F07BBD08127029C1338A45BFBB473D61C83E0A6A78E4288C'
'9999CAE05F2E17F2F3F3D13E3480FEDA57B19070760DE56463FF5717'
'F0616323FA87EE2A7D1ABD1E93C545A0BAA7E45448568A6E72D491A9'
'4E3EC87DEBF7FB110E8731363686BADA5A6C379BF1566B0BF21CDF23'
'92978BC94FCEE20DE70D1C3C7614B57575E8EEEE56744CCFCCC0B7B0'
'A0B86F814ADF8F6E572A10DAF88A1963982080DBE3C10C09728BE2B9'
'9695A928297DF940BCCF5250A0CC191F1FC7FCDC1C82BD77F088161C'
'906547CA3CBAED1EE51675F949D195F73FC0FCFC3C8A699F8C2613FE'
'181E56DAF59FAE223035859B97BFC1FD070F94C58497965051518100'
'EDCF0F0D679440A02AEE0BD0B191540B13EF0C2F5A6D954630A71182'
'91E778765929B697976147CE0E4CDDEA41FA9D7E18287C79CD98DDF3'
'1C6CAF1DC636B2F266470742BF3A2191377C1C24CB4D1DEE91B64D41'
'4ACDB3169ECA00DA33485D3A091AE899468D1F186AFA5E2B534A4AC8'
'B110E6A11CA427773D59F26DA77BE4D486EA9EEA16F492D566278043'
'0F66E4101D99A0A5A7B8EA6B96907B1182F0540EC90AECDC0DF74873'
'CA6364B3EBD60B169B49C7589B0E38A921D59A583D8C6FAAA4647E2C'
'4AC9AA2ECA996627EDF3A6E7D5E3EE7504B46818AB276BECE4361381'
'2CD4ED916325C6495639280F071F7B303EAD0BE4DF020C0026BB3556'
'2D86F1AC0000000049454E44AE426082')
if return_hex:
return clamav_icon
image = QtGui.QImage()
image.loadFromData(QtCore.QByteArray.fromHex(clamav_icon))
pixmap = QtGui.QPixmap()
pixmap.convertFromImage(image)
if return_pixmap:
return pixmap
return QtGui.QIcon(pixmap)
def verify_clamav_sig(sig):
sig_format = ( '^('
'([\da-fA-F\?]{2})|'
'(\{(?:\d+|\-\d+|\d+\-|(?:\d+)\-(?:\d+))\})|'
'(\*)|'
'((?:!|)\((?:[\da-fA-F\?]{2})+(?:\|(?:[\da-fA-F\?]{2})+)+\))|'
'(\((?:B|L|W)\))|'
'(\[\d+\-\d+\])'
')+$')
pattern = sig_format[2:-3]
if None == re.match(sig_format, sig):
return 'Invalid signature, check ClamAV signature documentation'
matches = [filter(None, x)[0] for x in re.findall(pattern, sig)]
for i in xrange(len(matches)):
if matches[i].startswith('{'):
# Ensure that there are two bytes before and after
if (i-2 < 0) and (i+2 >= len(matches)):
return ('Invalid signature, two hex bytes are not before and '
'after {*} expression')
# Check bytes before for valid hex strings
before_check = 0
for j in list({max(i-2, 0), max(i-1, 0)}):
if re.match('[\da-fA-F]{2}', matches[j]):
before_check += 1
# Check bytes after for valid hex strings
after_check = 0
for j in [i+1, i+2]:
if j >= len(matches):
continue
if re.match('[\da-fA-F]{2}', matches[j]):
after_check += 1
if 2 not in [before_check, after_check]:
return ('Invalid signatrue, hex byte at {0} ({1}) is not '
'preceeded or followed by two fixed byte '
'values'.format(i, matches[i]))
# Look {n-m} extension
values = re.match('\{(\d+)\-(\d+)\}', matches[i])
if None != values:
if values.group(2) <= values.group(1):
return 'Invalid signature, m is less than or equal to n'
return None
def get_block(ea):
'''
Given a virtual address, this function will return a block object or None
'''
ea_func = IDAW.get_func(ea)
# Ensure ea is in a function
if ea_func:
fc = IDAW.FlowChart(ea_func)
for block in fc:
# Check address selected is in the block's range
if (block.startEA <= ea) and (ea < block.endEA):
return block
return None
def get_existing_segment_ranges():
return map(lambda x: [x.startEA, x.endEA], map(IDAW.getseg, IDAW.Segments()))
def is_in_sample_segments(ea):
global valid_address_ranges
for segment_range in valid_address_ranges:
if segment_range[0] <= ea < segment_range[1]:
return True
return False
def get_architecture():
info = IDAW.get_inf_structure()
proc = info.procName.lower()
if 'metapc' == proc:
proc = 'intel'
bits = 16
if info.is_64bit():
bits = 64
elif info.is_32bit():
bits = 32
return (proc, bits)
def get_parser():
proc, bits = get_architecture()
mapping = {'intel' : IntelParser}
if proc in mapping:
parser = mapping[proc]
if type(parser) != types.TypeType:
# For future use if mapping includes more of a breakdown
return CASCParser(bits)
return parser(bits)
return CASCParser(bits)
def get_gui():
proc, bits = get_architecture()
mapping = {'intel' : IntelMask}
if proc in mapping:
gui = mapping[proc]
if type(gui) != types.TypeType:
# For future use if mapping includes more of a breakdown
return CASCMask(bits)
return gui(bits)
return CASCMask(bits)
# Create ClamAV icon
CLAMAV_ICON = get_clamav_icon(True).decode('hex')
CLAMAV_ICON = IDAW.load_custom_icon(data=CLAMAV_ICON, format='png')
# Action Handler Classes - Supported for IDA Pro 6.7 and higher
#-------------------------------------------------------------------------------
try:
# Action Handlers, support added with IDA Pro 6.7
class CASCActionHandler(action_handler_t):
def __init__(self, fn):
action_handler_t.__init__(self)
self.fn = fn
def activate(self, ctx):
self.fn(ctx)
return 1
def update(self, ctx):
return AST_ENABLE_ALWAYS
class CASCHooks(UI_Hooks):
def __init__(self):
super(CASCHooks, self).__init__()
self.handlers_created = False
def finish_populating_tform_popup(self, form, popup):
global CLAMAV_ICON, clamav_sig_creator_plugin
if None == clamav_sig_creator_plugin:
return
if not self.handlers_created:
self.init_actions()
self.handlers_created = True
# Apply the right action to the popup menu
tform_type = IDAW.get_tform_type(form)
if BWN_DISASMS == tform_type:
IDAW.attach_action_to_popup(form, popup, 'clamav:add_sig')
elif BWN_STRINGS == tform_type:
IDAW.attach_action_to_popup(form, popup, 'clamav:add_string')
elif BWN_IMPORTS == tform_type:
IDAW.attach_action_to_popup(form, popup, 'clamav:add_import')
def init_actions(self):
global CLAMAV_ICON, clamav_sig_creator_plugin
add_sig_handler = CASCActionHandler(clamav_sig_creator_plugin.insert_asm_item)
add_sig_action_desc = IDAW.action_desc_t('clamav:add_sig',
'Add Assembly to ClamAV Sig Creator...',
add_sig_handler,
'Ctrl+`',
'From current selection or selected basic block',
CLAMAV_ICON)
IDAW.register_action(add_sig_action_desc)
strings_handler = CASCActionHandler(clamav_sig_creator_plugin.insert_string_item)
strings_action_desc = IDAW.action_desc_t('clamav:add_string',
'Add string to ClamAV Sig Creator',
strings_handler,
None,
'Add current string as sub signature',
CLAMAV_ICON)
IDAW.register_action(strings_action_desc)
import_handler = CASCActionHandler(clamav_sig_creator_plugin.insert_import_item)
import_action_desc = IDAW.action_desc_t('clamav:add_import',
'Add Import to ClamAV Sig Creator',
import_handler,
None,
'Add current import as sub signature',
CLAMAV_ICON)
IDAW.register_action(import_action_desc)
hooks = CASCHooks()
hooks.hook()
except NameError:
b_asm_sig_handler_loaded = False
#
# Masking GUI component
#-------------------------------------------------------------------------------
class CASCMask(object):
def __init__(self, bits):
self.bits = bits
self.gui = QtWidgets.QWidget()
def get_masking(self):
return []
def set_masking(self, masking):
pass
def register_signals(self, apply_mask_func, custom_ui_func):
pass
def disable(self):
pass
def enable(self):
pass
def set_custom(self, checked):
pass
def custom_checked(self):
pass
class IntelMask(CASCMask):
def __init__(self, bits):
super(IntelMask, self).__init__(bits)
self.maskings = [('ESP Offsets', 'sp_mask'),
('EBP Offsets', 'bp_mask'),
('Call Offsets', 'call_mask'),
('Jump Offsets', 'jmp_mask'),
('Global Offsets', 'global_mask'),
('Customize', 'custom_mask')]
self.registers = [ ('EAX', 'eax_mask'), ('EBX', 'ebx_mask'),
('ECX', 'ecx_mask'), ('EDX', 'edx_mask'),
('ESI', 'esi_mask'), ('EDI', 'edi_mask')]
if not is_32bit():
self.registers = []
self.gui = self._init_gui()
def _init_gui(self):
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(2)
mask_options = QtWidgets.QGroupBox()
sizePolicy.setHeightForWidth(mask_options.sizePolicy().hasHeightForWidth())
mask_options.setSizePolicy(sizePolicy)
mask_options.setObjectName('mask_options')
mask_options.setTitle('Mask Options')
vbox_mask = QtWidgets.QVBoxLayout(mask_options)
for text, name in self.maskings:
checkbox = QtWidgets.QCheckBox(text, mask_options)
checkbox.setObjectName(name)
vbox_mask.addWidget(checkbox)
vbox_mask.addStretch()
if self.registers:
# Original Opcodes GUI Area
reg_groupbox = QtWidgets.QGroupBox()
sizePolicy.setHeightForWidth(reg_groupbox.sizePolicy().hasHeightForWidth())
reg_groupbox.setSizePolicy(sizePolicy)
reg_groupbox.setObjectName('reg_groupbox')
reg_groupbox.setTitle('Mask Registers')
hbox_reg = QtWidgets.QHBoxLayout(reg_groupbox)
vbox_reg = QtWidgets.QVBoxLayout()
vbox_reg.setContentsMargins(1, 1, 1, 1)
hbox_reg.addLayout(vbox_reg)
vbox_mask.addWidget(reg_groupbox)
for text, name in self.registers:
if self.registers.index((text, name)) == (len(self.registers)/2):
vbox_reg = QtWidgets.QVBoxLayout()
vbox_reg.setContentsMargins(1, 1, 1, 1)
hbox_reg.addLayout(vbox_reg)
checkbox = QtWidgets.QCheckBox(text, mask_options)
checkbox.setObjectName(name)
vbox_reg.addWidget(checkbox)
return mask_options
def get_masking(self):
checked = [x for x in self.get_non_custom_masks() if x.isChecked()]
return [x.objectName().replace('_mask', '') for x in checked]
def set_masking(self, maskings):
checkboxes = [x[1] for x in self.maskings] + [x[1] for x in self.registers]
for x in [self.gui.findChild(QtWidgets.QCheckBox, x) for x in checkboxes]:
name = x.objectName().replace('_mask', '')
if name in maskings:
x.setChecked(True)
def register_signals(self, apply_mask_func, custom_ui_func):
checkboxes = [x[1] for x in self.maskings] + [x[1] for x in self.registers]
objs = [self.gui.findChild(QtWidgets.QCheckBox, x) for x in checkboxes]
for checkbox in objs:
name = checkbox.objectName()
if name.startswith('custom'):
checkbox.stateChanged.connect(custom_ui_func)
else:
checkbox.stateChanged.connect(apply_mask_func)
def disable(self):
[x.setEnabled(False) for x in self.get_non_custom_masks()]
def enable(self):
[x.setEnabled(True) for x in self.get_non_custom_masks()]
def get_non_custom_masks(self):
checkboxes = [x[1] for x in self.maskings if not x[1].startswith('custom')]
checkboxes += [x[1] for x in self.registers]
return [self.gui.findChild(QtWidgets.QCheckBox, x) for x in checkboxes]
def custom_checked(self):
return self.get_custom_checkbox().isChecked()
def set_custom(self, checked):
checkbox = self.get_custom_checkbox()
checkbox.blockSignals(True)
checkbox.setChecked(checked)
checkbox.blockSignals(False)
def get_custom_checkbox(self):
custom = [x[1] for x in self.maskings if x[1].startswith('custom')][0]
return self.gui.findChild(QtWidgets.QCheckBox, custom)
#
# Architecture parsers
#-------------------------------------------------------------------------------
class CASCParser(object):
def __init__(self, bits):
self.bits = bits
def get_gui_layout(self):
mask_options = QtWidgets.QGroupBox()
sizePolicy.setHeightForWidth(mask_options.sizePolicy().hasHeightForWidth())
mask_options.setSizePolicy(sizePolicy)
mask_options.setObjectName('mask_options')
mask_options.setTitle('Mask Options')
vbox_mask = QtWidgets.QVBoxLayout(mask_options)
raise mask_options
def set_masking(self):
pass
def register_gui_signals(self, gui_obj, apply_mask_func, custom_ui_func):
pass
def setEnable(self, gui_obj, is_enabled=False):
pass
def mask_instruction(self, ea, maskings):
instruction = IDAW.DecodeInstruction(ea)
if not instruction:
return ('db 0x{0:02}'.format(Byte(ea)), ' '.join(['{:02x}'.format(IDAW.Byte(ea))]))
size = IDAW.DecodeInstruction(ea).size
original = ' '.join(['{:02x}'.format(IDAW.Byte(ea + i)) for i in xrange(size)])
disassembly = IDAW.tag_remove(IDAW.generate_disasm_line(ea, 1))
if ';' in disassembly:
disassembly = disassembly[:disassembly.index(';')].rstrip()
return (disassembly, original)
class IntelParser(CASCParser):
prefixes = '^([\xf0\xf3\xf2\x2e\x36\x3e\x26\x64\x65\x66\x67]{1,4})'
prefixes_x64 = '^((?:[\xf0\xf3\xf2\x2e\x36\x3e\x26\x64\x65\x66\x67]|\x0f(?:\x38|\x3a){0,1}){1,4})'
prefix_required_modrm = [6, 8, 9, 0x0b, 0x0d] + range(0x14, 0x18) + \
[0x1f, 0x2c, 0x2d] + \
[0x40, 0x60, 0x61, 0x68, 0x6a] + \
range(0x6c, 0x70) + range(0x71, 0x77) + \
range(0x7c, 0x80) + \
[0xa3, 0xa4, 0xa5] + range(0xab, 0xb0) + \
[0xc2, 0xc3, 0xc8, 0xd4, 0xd5, 0xd7] + \
range(0xe0, 0xf0) + [0xf4] + range(0xf8, 0xfe)
noprefix_nomodrm = [1] + range(0x50, 0x62) + range(0x90, 0x9a) + \
range(0xb0, 0xc0)
two_opcodes = { 1 : range(0xc8, 0xd2) + [0xd5, 0xd6, 0xf8, 0xf9],
0xc6 : [0xf8], 0xc7 : [0xf8], 0xd4 : [0xa0], 0xd5 : [0xa0],
0xd8 : [0xc0, 0xc8, 0xd0, 0xd1, 0xd8, 0xd9, 0xe0, 0xe8,
0xf0, 0xf8],
0xd9 : [0xc0, 0xc8, 0xc9, 0xd0, 0xe0, 0xe1, 0xe4, 0xe5,
0xe8, 0xe9, 0xea, 0xec, 0xed, 0xee, 0xf0, 0xf1,
0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf9, 0xfa,
0xfb, 0xfc, 0xfd, 0xfe, 0xff],
0xda : [0xc0, 0xc8, 0xd0, 0xd8, 0xe9],
0xdb : [0xc0, 0xc8, 0xd0, 0xd8, 0xe2, 0xe3, 0xe8, 0xf0],
0xdc : [0xc0, 0xc8, 0xe0, 0xe8, 0xf0, 0xf8],
0xdd : [0xc0, 0xd0, 0xd8, 0xe0, 0xe1, 0xe8, 0xe9],
0xde : [0xc0, 0xc1, 0xc8, 0xc9, 0xd9, 0xe0, 0xe1, 0xe8,
0xe9, 0xf0, 0xf1, 0xf8, 0xf9],
0xdf : [0xe0, 0xe8, 0xf0],
0x0f : [0x34] + range(0x80,0x90) + [0xc8],
0xfa : [0xae]}
three_opcodes = {0x9b : ['\xd3\xe3', '\xdb\xe2', '\xdf\xe0']}
two_opcodes_modrm = {0x38 : range(0, 0x0c) + \
[0x10, 0x14, 0x15, 0x17, 0x1c, 0x1d, 0x1e] + \
range(0x20, 0x26) + [0x28, 0x29, 0x2a, 0x2b] + \
range(0x30, 0x42) + [0x82] + \
range(0xdb, 0xe0) + [0xf0, 0xf1],
0x3a : range(0x08, 0x10) + range(0x14, 0x18) + \
range(0x20, 0x23) + range(0x40, 0x45) + \
range(0x60, 0x64) + [0xdf],
0x9b : [0xd9, 0xdd],
0x0f : range(0, 4) + [0x06, 0x0d] + range(0x10, 0x19) + \
range(0x1f, 0x24) + [0x2a, 0x2b, 0x2d, 0x2e, 0x2f] + \
range(0x40, 0x50) + range(0x51, 0x6c) + \
range(0x70, 0x77) + [0x7f, 0xa3, 0xa4, 0xa5] + \
range(0xab, 0xb8) + range(0xba, 0xc8) + \
range(0xd2, 0xf0) + range(0x90, 0xa0) + \
range(0xf1, 0xf5) + range(0xf6, 0xff)}
no_modrm = [0x04, 0x05, 0x07, 0x0c, 0x0e, 0x1c, 0x1d, 0x1e, 0x24, 0x25,
0x27, 0x34, 0x35, 0x37, 0x3c, 0x3d, 0x3f] + range(0x40, 0x50) + \
[0x77, 0x78, 0x79, 0x7a, 0x7b, 0x82] + range(0x91, 0xa3) + \
[0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xc9, 0xca, 0xcb, 0xcc, 0xcd,
0xce, 0xcf, 0xf5]
reg_variants = {'eax' : re.compile('([^a-zA-Z_@]|^)(e{0,1}a(?:x|h|l))'),
'ebx' : re.compile('([^a-zA-Z_@]|^)(e{0,1}b(?:x|h|l))'),
'ecx' : re.compile('([^a-zA-Z_@]|^)(e{0,1}c(?:x|h|l))'),
'edx' : re.compile('([^a-zA-Z_@]|^)(e{0,1}d(?:x|h|l))'),
'esi' : re.compile('([^a-zA-Z_@]|^)(e{0,1}sil{0,1})'),
'edi' : re.compile('([^a-zA-Z_@]|^)(e{0,1}dil{0,1})')}
reg_exceptions = [(0x0f, 0xc8), 0x48, 0x40, 0xb0, 0xb8, 0x58, 0x50, 0x90]
bin2reg = { 0b000 : ['eax', 'ax', 'al', 'mmo', 'xmmo'],
0b001 : ['ecx', 'cx', 'cl', 'mm1', 'xmm1'],
0b010 : ['edx', 'dx', 'dl', 'mm2', 'xmm2'],
0b011 : ['ebx', 'bx', 'bl', 'mm3', 'xmm3'],
0b100 : ['ah', 'mm4', 'xmm4'],
0b101 : ['ch', 'mm5', 'xmm5'],
0b110 : ['esi', 'si', 'dh', 'mm6', 'xmm6'],
0b111 : ['edi', 'di', 'bh', 'mm7', 'xmm7']}
def __init__(self, bits):
super(IntelParser, self).__init__(bits)
def mask_instruction(self, ea, maskings):
instr = self.parse_instruction(ea)
m_disassembly = ''
default = (instr['disassembly'], ' '.join(instr['bytes']))
if ('prefix' not in instr) or ('opcode' not in instr):
return default
m_opcodes = [(instr['prefix'][0] + instr['opcode'][0]).encode('hex')]
# Call instructions
#--------------------
if ((instr['opcode'][1] == 'call') and ('call' in maskings)
and (len(instr['imm'][0] + instr['disp'][0]) > 0)):
# Mask off absolute/relative call offsets
masked_imm = '{{{}}}'.format(len(instr['imm'][0]))
if len(instr['imm'][0]) == 0:
masked_imm = '{{{}}}'.format(len(instr['disp'][0]))
if len(instr['modr/m']) > 1:
# Absolute call
m_opcodes += [instr['modr/m'][0].encode('hex'), masked_imm]
return ('call <Absolute Offset>', ' '.join(m_opcodes))
# Relative call
m_opcodes.append(masked_imm)
return ('call <Relative Offset>', ' '.join(m_opcodes))
# Jcc and JMP instructions
#---------------------------
if (instr['opcode'][1].startswith('j')) and ('jmp' in maskings):
# Mask off relative jump offsets
if len(m_opcodes[0]) > 1:
m_opcodes = [x.encode('hex') for x in m_opcodes[0].decode('hex')]
if len(instr['imm'][0]) == 1:
m_opcodes.append('??')
else:
m_opcodes.append('{{{}}}'.format(len(instr['imm'][0])))
return ('{: <8}<Jump Offset>'.format(instr['opcode'][1]), ' '.join(m_opcodes))
#-----------------------------------------------------------------
# Below multiple maskings can be applied to the same instruction
#-----------------------------------------------------------------
# Prepare structure for masking operands and details.
opcodes_order = ['prefix', 'opcode', 'modr/m', 'sib', 'disp', 'imm']
current_opcodes = [instr[x][0] for x in opcodes_order]
mnem = IDAW.GetMnem(ea)
operands = default[0][default[0].index(mnem)+len(mnem):].split(',')
operands = [x.lstrip() for x in operands]
prefix = ''
if len(instr['prefix']) > 1:
prefix = instr['prefix'][1]
current_disassembly = [prefix, instr['opcode'][1]] + operands
original_disassembly = current_disassembly
original_opcodes = current_opcodes
try:
# Global offset instructions
# A little complicated to do since it could just be a hard coded value
#-----------------------------------------------------------------------
if ('global' in maskings) and ((len(instr['imm']) + len(instr['disp'])) > 2):
# Assuming the value is a global offset if it exists within a
# segment
# Since VirtualAlloc uses 0x400000 and many PEs are based at that
# address we are going to exclude it
operand_masked = False
original_operand = -1
operand_index = 0
if (len(instr['imm']) > 1):
offset = int(instr['imm'][1][2:].replace('L', ''), 16)
if (IDAW.getseg(offset) is not None) and (offset != 0x400000):
imm = current_opcodes[5]
original_operand = imm
operand_index = 5
if len(imm) == 1:
current_opcodes[5] = '??'
else:
current_opcodes[5] = '{{{}}}'.format(len(imm))
for i in xrange(2, len(current_disassembly)):
if (('{:x}'.format(offset) in current_disassembly[i].lower())
or (IDAW.LocByName(current_disassembly[i]) == offset)):
operand_masked = True
current_disassembly[i] = '<Global Offset>'
if (len(instr['disp']) > 1):
offset = int(instr['disp'][1][2:].replace('L', ''), 16)
if (IDAW.getseg(offset) is not None) and (offset != 0x400000):
imm = current_opcodes[4]
original_operand = imm
operand_index = 4
if len(imm) == 1:
current_opcodes[4] = '??'
else:
current_opcodes[4] = '{{{}}}'.format(len(imm))
for i in xrange(2, len(current_disassembly)):
if (('{:x}'.format(offset) in current_disassembly[i].lower())
or (IDAW.LocByName(current_disassembly[i]) == offset)):
operand_masked = True
current_disassembly[i] = '<Global Offset>'
if (not operand_masked) and (original_operand != -1):
current_opcodes[operand_index] = original_operand
# SP and BP displacement masking
#-----------------------------------------------------------------------
if len(instr['disp']) > 0:
if len(instr['modr/m']) > 1:
# Check the displacement value is from an esp offset
modrm = instr['modr/m'][1]
if 0b01 <= modrm['mod'] <= 0b10:
mask_disp = ''
# EBP offset
if ('bp' in maskings) and (modrm['rm'] == 0b101):
mask_disp = 'bp'
# ESP offset
if (('sp' in maskings) and (modrm['rm'] == 0b100)
and (len(instr['sib']) > 1)):
sib = instr['sib'][1]
if sib['base'] == 0b100:
mask_disp = 'sp'
if mask_disp:
for i in xrange(2, len(current_disassembly)):
x = current_disassembly[i]
mask_re = '{}+[^\]]+'.format(mask_disp)
value = '{0}+<{1} Offset>'.format(mask_disp, mask_disp.upper())
current_disassembly[i] = self.mask_operand(x, mask_re, value)
disp = current_opcodes[4]
if len(disp) == 1:
current_opcodes[4] = '??'
else:
current_opcodes[4] = '{{{}}}'.format(len(disp))
# Register Masking
#-----------------------------------------------------------------------
regs = {'eax', 'ebx', 'ecx', 'edx', 'esi', 'edi'}.intersection(maskings)
masked_regs = []
for reg in regs:
for i in xrange(2, len(current_disassembly)):
operand = current_disassembly[i]
if self.reg_variants[reg].search(operand):
current_disassembly[i] = self.reg_variants[reg].sub('\\1<Reg Masked>', operand)
masked_reg = self.reg_variants[reg].search(operand).groups()[1]
opcode_masked = False
current_modrm = current_opcodes[2]
original_modrm = instr['modr/m'][0]
if len(original_modrm) == 1:
modrm = instr['modr/m'][1]
minreg = (modrm['mod'] << 6) | 0 | modrm['rm']
minrm = (modrm['mod'] << 6) | (modrm['reg'] << 3) | 0
if (operand == masked_reg) and (masked_reg in self.bin2reg[modrm['reg']]):
opcode_masked = True
if len(current_modrm) == 1:
values = [minreg + (x << 3) for x in range(8)]
current_opcodes[2] = ['{:02x}'.format(x) for x in values]
else:
current_opcodes[2] = list(set(['{:01x}?'.format(x) for x in range((modrm['mod'] << 2), (modrm['mod'] << 2) + 4)]))
elif (modrm['rm'] == 0b100) and (modrm['mod'] in range(0, 3)):
# The instruction requires the SIB bytes
if len(instr['sib'][0]) == 1:
sib = instr['sib'][1]
minindex = (sib['ss'] << 6) | 0 | sib['base']
minbase = (sib['ss'] << 6) | (sib['index'] << 3) | 0
current_sib = current_opcodes[3]
if (sib['index'] != 0b100) and (masked_reg in self.bin2reg[sib['index']]):
opcode_masked = True
if len(current_sib) == 1:
values = [minindex + (x << 3) for x in range(8)]
current_opcodes[3] = ['{:02x}'.format(x) for x in values]
else:
current_opcodes[3] = list(set(['{:01x}?'.format(x) for x in range((sib['ss'] << 2), (sib['ss'] << 2) + 4)]))
elif masked_reg in self.bin2reg[sib['base']]:
opcode_masked = True
if len(current_sib) == 1:
values = [minbase + x for x in range(8)]
current_opcodes[3] = ['{:02x}'.format(x) for x in values]
else:
current_opcodes[3] = list(sorted(set(['{}?'.format(x[0]) for x in current_opcodes[3]])))
elif (not (modrm['rm'] == 0b100 and modrm['mod'] == 0b11)
and (masked_reg in self.bin2reg[modrm['rm']])):
opcode_masked = True
if len(current_modrm) == 1:
values = [minrm + x for x in range(8)]
current_opcodes[2] = ['{:02x}'.format(x) for x in values]
else:
current_opcodes[2] = list(sorted(set(['{}?'.format(x[0]) for x in current_opcodes[2]])))
else:
binreg = [x for x in self.bin2reg if masked_reg in self.bin2reg[x]][0]
# Values are part of the operand
opcode = ord(instr['opcode'][0][-1]) - binreg
if ((opcode in self.reg_exceptions)
or ((len(instr['opcode'][0]) == 2)
and (opcode == self.reg_exceptions[0][1])
and (ord(instr['opcode'][0][0]) == self.reg_exceptions[0][0]))):
opcode_masked = True
values = range(opcode, opcode + 8)
if len(instr['opcode'][0]) == 2:
current_opcodes[1] = '{0:02x}({1})'.format(ord(instr['opcode'][0][0]),
'|'.join(['{:02x}'.format(x) for x in values]))
else:
current_opcodes[1] = ['{:02x}'.format(x) for x in values]
if not opcode_masked:
# Opcode couldn't be masked, revert masked disassembly
current_disassembly[i] = operand
except:
print '=' * 40
print ('[CASC] Unsupported masking on instruction. Please open an '
'issue in the git repo with the below information:')
ddebug = [x for x in original_disassembly if x]
ddebug = '{0: <8}{1}'.format(ddebug[0], ', '.join(ddebug[1:]))
print ' disassembly: {}'.format(ddebug)
print ' opcodes: {}'.format(' '.join([x.encode('hex') for x in original_opcodes if x]))
pprint(instr)
print '=' * 40
raise
# Register masking exceptions
# Instructions that leavage a base opcode value and increment it to
# get the right register
#-----------------------------------------------------------------------
# Customize
# Clean up opcodes and disassembly for display to user
current_disassembly = [x for x in current_disassembly if x]
current_disassembly = '{0: <8}{1}'.format(current_disassembly[0], ', '.join(current_disassembly[1:]))
opcodes = []
for x in [x for x in current_opcodes if x]:
if type(x) == list:
opcodes += ['({})'.format('|'.join(x))]
elif not re.search('(\?\?|\{.+\}|\[.+\])', x):
opcodes += [y.encode('hex') for y in x]
else:
opcodes.append(x)
return (current_disassembly, ' '.join(opcodes))
def parse_instruction(self, ea):
instruction = IDAW.DecodeInstruction(ea)