-
Notifications
You must be signed in to change notification settings - Fork 1
/
obfu_class.py
1542 lines (1323 loc) · 70 KB
/
obfu_class.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
COMB_NOP = 0x4
COMB_CALL = 0x8
COMB_RET = 0x10
COMB_UNC_BRANCH = 0x40
COMB_CND_BRANCH = 0x80
# _base = os.path.abspath(__file__.replace('_class.py', ''))
# check_for_updates = [
# make_auto_refresh(_base + '.py'),
# make_auto_refresh(_base + '_patches.py'),
# make_auto_refresh(_base + '_helpers.py'),
# make_auto_refresh(_base + '_generators.py'),
# ]
# check_for_update = lambda: (x() for x in check_for_updates)
def _to_string(o):
return str(o)
class BasicPattern(object):
def __init__(self):
self.used = 0
self.tried = 0
self.insn_matches = set()
pass
class PatternResult(object):
"""Docstring for PatternResult """
def __init__(self, pat, result):
"""@todo: to be defined
:pat: @todo
:result: @todo
"""
self.pat = pat
self.result = result
class PatternGroup(object):
def __init__(self, *items, **options):
self.container = items
self.options = options
def __len__(self):
return self.container.__len__()
def __getitem__(self, key):
return self.container.__getitem__(key)
def __setitem__(self, key, value):
self.container.__setitem__(key, value)
def __delitem__(self, key):
self.container.__delitem__(key)
def __iter__(self):
return self.container.__iter__()
def __reversed__(self):
return self.container.__reversed__()
def __contains__(self, item):
return self.container.__containers__(item)
def append(self, object):
self.container.append(object)
def clear(self):
self.container.clear()
def copy(self):
return (type(self))(self.container.copy())
def count(self):
return self.container.count()
def extend(self, iterable):
for item in iterable:
self.append(item)
def index(self, value, start=0, stop=9223372036854775807):
self.container.index(value, start, stop)
def insert(self):
self.container.insert()
def pop(self):
self.container.pop()
def remove(self):
self.container.remove()
def reverse(self):
self.container.reverse()
def sort(self):
self.container.sort()
def insert(self, index, object):
self.container.insert(index, object)
def pop(self, index=-1):
return self.container.pop(index)
def remove(self, value):
self.container.remove(value)
class Pattern(BasicPattern):
# @param notes Text description, and copy of output from dissasembly with offsets usually goes here.
# @param brief a short description of the patch
# @param search list of lines to match
# @param repl list of replacement lines; or
# @param replFunc function to perform replacements
# @param safe if True, doesn't require backtracking
# @param group predicate to speed lookups
def __init__(self, notes='', brief='', search=None, repl=None, replFunc=None, safe=False, group=None, **kwargs):
super(Pattern, self).__init__()
self.notes = notes
self.brief = brief
self.search = search
self.repl = A(repl)
self.replFunc = replFunc
self.safe = safe
self.group = group
self.priority = 4
self.options = SimpleAttrDict(kwargs)
for k, v in kwargs.items():
if k not in ('resume', 'reflow', 'then', 'priority', 'label'):
printi("set pattern.options.{} to {} in {}".format(k, v, brief))
def __repr__(self):
return '{}'.format(self.brief)
class BitwisePattern(BasicPattern):
def __init__(self, search, mask, replFunc, brief, safe, bitmask=None, **kwargs):
super(BitwisePattern, self).__init__()
self.brief = brief
self.search = search
self.mask = mask
self.replFunc = replFunc
self.safe = safe
self.bitmask = bitmask
self.options = SimpleAttrDict(kwargs)
for k, v in kwargs.items():
if k not in ('resume', 'reflow', 'then', 'priority', 'label'):
printi("set bitwisepattern.options.{} to {} in {}".format(k, v, brief))
def as_list(self):
return [self.search, self.mask, self.replFunc, self.brief, self.safe, self.options]
def __len__(self):
return 6
def __getitem__(self, key):
return self.as_list()[key]
# def __setitem__(self, key, value):
# pass
#
# def __delitem__(self, key):
# pass
def __iter__(self):
return self.as_list().__iter__()
# def __reversed__(self):
# pass
#
# def __contains__(self, item):
# pass
def bytepatch(b, address):
return list(b)
def make_bitwise_patch(bm):
def patch(search, _unused_replace, original, ea, addressList, patternComment, addressListWithNops, **kwargs):
a = [addressList[x] for x in range(len(search))]
c = [original[x] for x in range(len(search))] # [Byte(x) for x in a]
p = bm.pattern
# d = [idc.get_wide_byte(x) for x in a]
r = bm.sub(c)
# dprint("[make_bitwise_patch] c, r")
if obfu_debug: printi("[make_bitwise_patch] a:{}\c:{}\np:{}\nr:{}".format(listAsHex(a), binlist(c), p, listAsHex(r)))
return len(search), r
return patch
class Obfu(object):
# Copyright 2016 Orwellophile LLC. MIT License.
#
# Useful notes for future development maybe:
# https://reverseengineering.stackexchange.com/questions/14815/how-can-i-call-ida-pros-makecode-for-one-instruction-at-a-time
#
# https://reverseengineering.stackexchange.com/questions/13101/set-register-to-specific-value-for-use-in-autoanalysis-in-ida-pro-6-9/13105
FlowControlFlags = [
# Indicates the instruction is not a flow-control instruction.
"FC_NONE",
# Indicates the instruction is one of: CALL, CALL FAR.
"FC_CALL",
# Indicates the instruction is one of: RET, IRET, RETF.
"FC_RET",
# Indicates the instruction is one of: SYSCALL, SYSRET, SYSENTER, SYSEXIT.
"FC_SYS",
# Indicates the instruction is one of: JMP, JMP FAR.
"FC_UNC_BRANCH",
# Indicates the instruction is one of:
# JCXZ, JO, JNO, JB, JAE, JZ, JNZ, JBE, JA, JS, JNS, JP, JNP, JL, JGE, JLE, JG, LOOP, LOOPZ, LOOPNZ.
"FC_CND_BRANCH",
# Indiciates the instruction is one of: INT, INT1, INT 3, INTO, UD2.
"FC_INT",
# Indicates the instruction is one of: CMOVxx.
"FC_CMOV",
# Indicates the instruction is HLT.
"FC_NOP",
"FC_REF",
]
(
CALL, # 1
RET, # 2
SYS, # 3
UNC_BRANCH, # 4
CND_BRANCH, # 5
INT, # 6
CMOV, # 7
NOP, # 8
REF, # 9
) = [1 << x for x in range(0, 9)]
def _makeFlagFromDi(self, insn):
meta = insn.meta & 0xff
flag = 0
if meta > 7:
# we're re-purposing these
meta = 0
if meta == 4: # unc_jmp
if insn.operands[0].type != 'Immediate':
meta ^= 4
if insn.opcode == 581: # nop
meta = 8
if meta:
flag |= 1 << (meta - 1)
if IsRef(insn.address):
flag |= 1 << (9 - 1)
return flag
def __init__(self):
self.quiet = False
self._depth = 0
self.combed = []
self.default_comb_len = 128
self.stage2 = True
self.AnalyzeQueue = []
self.start = 0
self.end = BADADDR
self.eip = self.start
self.patterns = []
self.patterns_bitwise = []
self.patternSet = set()
self.searchSets = sets = [set() for __ in range(10)]
self.longestPattern = 0
self.groups = None
self.labels = dict()
self.triggers = {}
self.slow_patterns = []
self.slow_patterns_bitwise = []
self.slow_patternSet = set()
self.slow_searchSets = sets = [set() for __ in range(10)]
self.slow_longestPattern = 0
self.visited = set()
# self.searchSets = list()
def find(self, pat=None, first=False, **kwargs):
if isinstance(pat, Pattern):
pst = _to_string(pat.search)
if pst in self.patternSet:
# printi("type(self.patterns)", type(self.patterns))
method = _.find if first else _.filter
found = method(self.patterns, lambda v, k, l: _to_string(v.search) == pst)
elif isinstance(pat, dict):
found = _.where(self.patterns, pat, first)
elif kwargs:
found = _.where(self.patterns, dict(**kwargs), first)
else:
raise Exception("find can only accept a pattern or object with pattern-like conditions")
return found
def add(self, pat, **kwargs):
if not isinstance(pat, Pattern):
raise Exception("Obfu.add can only accept Patterns")
pst = _to_string(pat.search)
if pst in self.patternSet:
# printi("type(self.patterns)", type(self.patterns))
found = _.find(self.patterns, lambda v, k, l: _to_string(v.search) == pst)
if found:
printi("Obfu Duplicate Search Pattern:\n{}\n{}".format(pfh(pat), pfh(found)))
return
raise ObfuFailure("Duplicate search pattern")
setLen = len(self.searchSets)
searchLen = len(pat.search)
if searchLen > self.longestPattern:
self.longestPattern = searchLen
searchIndex = []
for i in range(searchLen):
searchIndex.append(i)
if i < setLen:
self.searchSets[i].add(pat.search[i])
pat.searchIndex = searchIndex
if searchLen < setLen:
self.searchSets = self.searchSets[0:searchLen]
# for i in xrange(searchLen, setLen):
# printi("self.searchSets[i] del: %s" % i)
# del self.searchSets[i]
# while len(repl) and repl[len(repl)-1] == 0xcc:
# printi("removed %02x from pattern %s" % (repl.pop(), brief))
# printi("%s: length: %d" % (_to_string(repl), len(repl)))
self.patterns.append(pat) # [search, repl, replFunc, searchIndex, brief, safe, notes])
self.patternSet.add(_to_string(pat.search))
# ' '.join([bin(x) for x in [x[0] for x in obfu.patterns][0]]).repl('0b', '')
label = getattr(pat.options, 'label', None)
# printi("label: {}".format(label))
if label:
if label not in self.labels:
if debug: printi("[add] label: {}".format(label))
self.labels[label] = []
self.labels[label].append(pat)
def __repr__(self):
return 'Obfu(%s patterns)' % len(self.patterns)
def __len__(self):
return len(self.patterns)
def reset(self):
"""resets scan eip to start location
:returns: None
"""
self.eip = self.start
def dump(self):
for x in self.patterns:
printi("dump:", x)
def range(self, start, end):
self.start = start
self.end = end
self.eip = start
def prep_groups(self):
if not self.groups:
self.groups = _.groupBy(self.patterns, lambda x, *a: x.group.firstn(6))
if obfu_debug: printi("[Obfu::prep_groups] {} pattern groups: {}".format(len(self.groups), [type(x) for x in self.groups]))
##
# @brief append obfu pattern to database
#
# @param notes Text description, and copy of output from dissasembly with offsets usually goes here.
# @param brief a short description of the patch
# @param search list of lines to match
# @param repl list of replacement lines; or
# @param replFunc function to perform replacements
# @param safe if True, doesn't require backtracking
# @param group predicate to speed lookups
#
# @return None
def append(self, notes='', brief='', search=None, repl=None, replFunc=None, safe=False, group=None, trigger=None, **kwargs):
# printi("append: \"{}\", <<{}>>, <<{}>>, {}".format(brief, search, repl, replFunc))
if repl is None:
repl = A(repl)
if trigger:
self.triggers[trigger] = replFunc
if isinstance(search, PatternGroup):
for item in search:
self.append(notes=notes, brief=brief, search=item, repl=repl, replFunc=replFunc, safe=safe, group=group, **kwargs)
return
if group is None:
if isString(search):
# group = search
raise RuntimeError("unexpected string for obfu search-term")
elif isinstance(search, BitwiseMask):
group = search
else:
with BitwiseMask() as bm:
bm.add_list(search)
group = bm
if isinstance(search, BitwiseMask):
if obfu_debug: printi("[Obfu::append] BitwiseMask: {}".format(str(brief)))
if replFunc:
self.append_bitwise(search=search.value, mask=search.mask, bitmask=search, replFunc=replFunc, brief=brief, safe=safe, group=group, **kwargs)
elif isinstance(repl, BitwiseMask):
self.append_bitwise(search=search.value, mask=search.mask, bitmask=search, replFunc=make_bitwise_patch(repl), brief=brief, safe=safe, group=group, **kwargs)
else:
printi("[Obfu::append] Don't understand replacement method for BitwiseMask {}, repl is {}, replFunc is {}".format(str(brief), type(repl), type(replFunc)))
return
self.add(
Pattern(
notes=notes,
brief=brief,
search=search,
repl=repl,
replFunc=replFunc,
safe=safe,
group=group,
**kwargs
), **kwargs
)
def append_bitwise(self, search, mask, bitmask, replFunc, brief, safe=False, group=None, **kwargs):
# printi("append: \"{}\", <<{}>>, <<{}>>, {}".format(brief, search, repl, replFunc))
if str(search) in self.patternSet:
found = _.find(self.patterns, lambda v, k, l: v.search == search)
if found:
printi(("Possible Obfu Duplicate Search Pattern (mask): {}\n{}".format(found.brief, search)))
raise ObfuFailure("Duplicate search pattern")
searchLen = len(search)
if searchLen > self.longestPattern:
self.longestPattern = searchLen
self.patterns_bitwise.append(BitwisePattern(search, mask, replFunc, brief, safe, bitmask=bitmask, **kwargs))
def process_replacement(self, search, repl, addressList, patternComment, addressListWithNops, addressListFull, pat=None, context=None, length=None, printed=False):
assemble = nassemble
if obfu_debug: printi("[process_replacement] repl:{}".format(listAsHex(repl)))
patternComment += " at {:#x}".format(_.first(addressList))
if isinstance(repl, list):
# printi("addressList")
# pp(addressList)
if isinstance(repl[0], str):
# length = length or sum(_.map(repl, lambda x, *a: len(assemble(x, addressList[0]))))
length = length or len(search)
repl = length, repl
else:
printed = True
printi("{:x} {} repl:Comment: {}"
.format(addressList[0],
type(repl[0]).__name__,
# listAsHex(search),
# listAsHex(repl),
patternComment)) # listAsHex(search),
# printi("{:x} {} repl:Search: {}\n Replace: {}\n Comment: {}"
# .format(addressList[0],
# type(repl[0]).__name__,
# listAsHex(search),
# listAsHex(repl),
# patternComment)) # listAsHex(search),
repl = (length or len(repl), repl)
# bitwise stuff
if isinstance(repl, tuple) and len(repl) == 2:
_search, _repl = repl
try:
if not isinstance(_search, int):
_search = list(_search)
except TypeError as e:
printi("obfu exception: {}: {} [_search:{}]".format(e.__class__.__name__, str(e), _search))
pass
# printi("[ignore] exception: {}: {} [_search:{}]".format(e.__class__.__name__, str(e), _search))
# raise
try:
_repl = list(_repl)
except TypeError as e:
printi("obfu exception: {}: {} [_repl:{}]".format(e.__class__.__name__, str(e), _repl))
raise
# dprint("[process_replacement] _search, _repl")
if obfu_debug: printi("[process_replacement] tuple: _search:{}, _repl:{}".format(listAsHexIfPossible(_search), listAsHexIfPossible(_repl)))
if not printed:
printi("{:x} bitwise: Comment: {}"
.format(addressList[0],
patternComment)) # listAsHex(search),
# printi("{:x} bitwise: Search: {}\n Replace: {}\n Comment: {}"
# .format(addressList[0],
# listAsHex(search),
# listAsHex(_repl),
# patternComment)) # listAsHex(search),
if -1 in _repl:
for i in range(len(search)):
# if _search[i] == -1 and _repl[i] == -1:
# _repl[i] = idc.get_wide_byte(addressList[i])
if _search[i] == -1:
_search[i] = idc.get_wide_byte(addressList[i])
if _repl[i] == -1:
_repl[i] = _search[i]
# TODO: we can expand this to include a bigger range, both by adding
# the 1 octet removed by using _search[:-1] and further by checking for
# nops ahead
# why was this here, it didn't work
# addressListWithNops = [x for x in it.takewhile(lambda x: x != _search[:-1], addressListWithNops)]
usedRanges = []
# we need to translate the position in addressList with the equiv. position in addressListWithNops
if isinstance(_search, int):
_end = _search
else:
_end = len(_search)
if _end > len(addressList):
raise IndexError("_end is greater than the length of address list")
# elif _end == len(addressList):
# printi("shortening _end by 1")
# _end -= 1
try:
_end_address = addressList[_end - 1]
except IndexError:
# dprint("[IndexError] _end, len(addressList)")
printi("[IndexError] _end:{}, len(addressList):{}, _search:{}".format(_end, len(addressList), _search))
printi("[hm] _end:{}, addressList:{}, addressListWithNops:{}".format(_end, addressList,
addressListWithNops))
raise IndexError("pfft")
_nop_end_index = addressListWithNops.index(_end_address)
_full_end_index = addressListWithNops.index(_end_address)
if _nop_end_index == -1:
raise RuntimeError("couldn't match addressListWithNops to addressList")
else:
_nop_end_index += 1
if _full_end_index == -1:
raise RuntimeError("couldn't match addressListWithfulls to addressList")
else:
_full_end_index += 1
# dprint("[hm] _end, _nop_end_index, addressList, addressListWithNops, addressListFull")
is_int3 = False
# XXX
patchedAddresses = set()
targetRanges = GenericRanger(addressListWithNops[0:_nop_end_index], sort=0, outsort=0)
oriTargetRanges = targetRanges.copy()
_targetRanges = str(targetRanges)
# targetRanges.reverse()
if isinstance(_repl, list) and isinstance(_repl[0], str) and _repl[-1] == 'int3' or \
isinstance(_repl, list) and isinstance(_repl[0], int) and _repl[-1] == 'cc':
is_int3 = True
# targetRanges = GenericRanger(addressListFull, sort=0, outsort=0)
# oriTargetRanges = targetRanges.copy()
# _targetRanges = str(targetRanges)
# if obfu_debug: printi("full targetRanges: {}".format(targetRanges))
# if obfu_debug: printi("full oriTargetRanges: {}".format(oriTargetRanges))
_repl.pop()
# if obfu_debug: printi("obfu_class: extending targetRanges... locating longest range...")
# sortedRanges = _.sortBy(targetRanges, lambda x, *a: len(x))
# for r in targetRanges:
# if r.start == sortedRanges[0].start:
# if obfu_debug: printi("r.last: {:x}".format(r.last))
# # disabled because it was causing overruns into the next chunk (when there were two jmps)
# # now attempting to curtail it by checking for end of flow
# # that only seems to work sometimes... (flow doesn't end at 143a659cb clc)
# # back to disabling!
# if False and (not isFlowEnd(r.last) or isJmp(r.last) and not isFlowEnd(r.last+1)):
# if obfu_debug: printi("flow doesn't end at {:x} {}".format(r.last, diida(r.last)))
# # if True and not isFlowEnd(r.last + 1) and isJmp(r.last + 1) and not isFlowEnd(idc.get_item_head(r.last)) isJmp(idc.get_item_head(r.last)):
# r.last += GetInsnLen(r.last + 1)
# if obfu_debug: printi("r.last (+new): {:x}".format(r.last))
# else:
# if obfu_debug: printi("flow ends at {:x} {}".format(r.last, diida(r.last)))
if obfu_debug: printi("targetRanges: {}".format(targetRanges))
if obfu_debug: printi("oriTargetRanges: {}".format(oriTargetRanges))
if is_int3:
for r in targetRanges:
PatchNops(r.start, r.length, 'prenup', nop=0xc3, ease=0)
# if obfu_debug: printi("targetRanges", targetRanges)
if isinstance(_repl, list):
if getattr(pat.options, 'exact', 0) and isinstance(_repl[0], int):
targetRanges = GenericRanger(addressList[0:_end], sort=0, outsort=0)
oriTargetRanges = targetRanges.copy()
_targetRanges = str(targetRanges)
for i in range(min(len(addressList), len(_repl))):
ida_bytes.patch_byte(addressList[i], _repl[i])
if i == 0:
Commenter(addressList[i], 'line').add('{} exact {}'.format(patternComment, _targetRanges))
# while _repl: # and targetRanges:
# r = targetRanges[0]
# # spread reversed asm to beginning and start of range where possible
# length = min(len(_repl), r.length)
# if obfu_debug: print("exact copy at {:#x}".format(r.start))
# PatchBytes(r.start, _repl[0:length], code=1, ease=1, comment="{} {}".format(patternComment, _targetRanges))
# patchedAddresses.update(list(range(r.start, r.start + length)))
# _repl = _repl[length:]
# if _repl and len(targetRanges) < 2:
# raise ObfuFailure("Not enough targetRanges for exact replacement")
# targetRanges = targetRanges[1:]
# [Plan(ra.start, ra.start + ra.length) for ra in oriTargetRanges]
# # [Plan(ra[0], EaseCode(ra[0], forceStart=1, noExcept=1)) for ra in oriTargetRanges]
return {'patchedAddresses': patchedAddresses}
if isinstance(_repl[0], int):
# dprint("[process_replacement] _repl")
if obfu_debug: printi("[process_replacement] _repl:{} ({})".format(_repl, type(_repl).__name__))
_repl = [(bytearray().fromhex(x[3])) for x in diInsnsIter(_repl)]
assemble = bytepatch
if isinstance(_repl[0], (str, bytearray)):
with PerfTimer('obfu.patch.str'):
# assemble for length
# reverse = is_int3 # and len(targetRanges) == 1
reverse = False
address = targetRanges[0].start
test_assembled = [assemble(x, address) for x in _repl]
# this isn't a particualr good check
if not isinstance(test_assembled, (bytearray, list)):
if obfu_debug: printi("couldn't assemble (for length) '%s': %s" % ("; ".join(_repl), test_assembled))
raise ObfuFailure("assemble: {}".format(asm))
else:
test_assembled.reverse()
if obfu_debug: printi("test_assembly length {} '{}': {}".format(
[len(x) for x in test_assembled],
"; ".join(_repl) if isinstance(_repl, str) else 'bytearray',
listAsHex(test_assembled))
)
# run the whole thing through a test
targetLengths = [x.length for x in targetRanges]
for raw, nxt in stutter_chunk(test_assembled, 2, 1):
length = len(raw)
if len(targetLengths) == 0:
printi("ran out of ranges to fill")
raise ObfuFailure("ran out of ranges to fill")
# get the [perhaps approximate] length of insn
found = _.find(targetLengths, lambda v, *a: v >= length)
if found is None:
raise ObfuFailure("ran out of room for {}".format(listAsHex(raw)))
idx = targetLengths.index(found)
targetLengths[idx] -= length
# r.length -= length;
if idx > 0:
targetLengths = targetLengths[idx:]
# printi("test assembled with remaining lengths: {}".format(targetLengths))
no_trailing_ret = False
pad_tail = 0
tail_padded = 0
if reverse:
_repl.reverse()
targetRanges.reverse()
if isinstance(_repl[0], str) and _repl[0].startswith(('ret', 'jmp')) or isinstance(_repl[0], bytes) and _repl[0].startswith((b'\xc3', b'\xe9', b'\xeb')):
no_trailing_ret = True
else:
pad_tail = 1
found = None
i = -1
for asm, next_asm in stutter_chunk(_repl, 2, 1):
i += 1
# dprint("[process_replacement] asm, next_asm")
if obfu_debug: print("[process_replacement] asm:{}, next_asm:{}".format(asm, next_asm))
last_for_range = False
if next_asm is None:
next_asm = ''
last_for_range = True
if len(targetRanges) == 0:
printi("ran out of ranges to fill")
raise ObfuFailure("ran out of ranges to fill")
# get the [perhaps approximate] length of insn
try:
if pad_tail:
tail_padded = pad_tail
pad_tail = 0
asm1 = "{}; ret".format(asm)
asm2 = "{}; {}; ret".format(asm, next_asm)
else:
asm1 = asm
asm2 = "{}; {}".format(asm, next_asm)
length = len(assemble(asm1, targetRanges[0].start))
length2 = len(assemble(asm2, targetRanges[0].start))
# dprint("[process_replacement] length, length2")
if obfu_debug: print("[process_replacement] length:{}, length2:{}".format(length, length2))
if not "shorted chunks":
if found is not None and asm == "int3":
addr = eax(found)
# SetFuncOrChunkEnd(addr, addr)
continue
found = _.find(targetRanges, lambda v, *a: v.length >= length)
if found is None:
raise ObfuFailure("ran out of room assembling {}".format(asm))
found2 = _.find(targetRanges, lambda v, *a: v.length >= length2)
if found2 is None:
last_for_range = True
idx2 = None
else:
idx2 = targetRanges.index(found2)
idx = targetRanges.index(found)
last_for_range = last_for_range or idx != idx2
if idx:
# not using previous ranges
[PatchNops(r.start, r.length, 'skipped') for r in targetRanges[0:idx]]
targetRanges = targetRanges[idx:]
r = targetRanges[0]
# spread reversed asm to beginning and start of range where possible
if reverse: # and not last_for_range:
target = r.trend - length
else:
target = r.start
assembled = assemble(asm1, target)
if not isinstance(assembled, list):
if obfu_debug: printi(("assemble failed '%s': %s" % (asm, assembled)))
raise ObfuFailure("assemble: {}".format(asm))
else:
if obfu_debug: printi(("assembled %x-%x %s %s" % (target, target + length, listAsHex(assembled), asm)))
PatchBytes(target, assembled, code=1, ease=1, comment="{} {}".format(patternComment, _targetRanges))
patchedAddresses.update(list(range(target, target + len(assembled))))
forceCode(target)
if not IsCode_(target):
if obfu_debug: printi("0x%x: Couldn't MakeCode" % target)
# we could also leave the generic ranges in place with
# modificiations to indication not to use, then erase over
# them later... but remember, the reason we are ejecting them
# is because we need to avoid out-of-order code
if reverse: # and not last_for_range:
r.trend -= length;
else:
r.start += length
# r.length -= length;
# if idx > 0:
# # we have skipped to the next range, marked the rest
# # of the previous range as used
# usedRanges.extend(targetRanges[0:idx])
# targetRanges = targetRanges[idx:]
# no need to do this
# # yes, this is safe and works. r is like an magic c++ iterator
# if r.length < 1:
# usedRanges = targetRanges[:1]
# targetRanges = targetRanges[1:]
# pp(hex(targetRanges))
except KeyboardInterrupt:
raise KeyboardInterrupt()
# except ValueError:
# printi(("couldn't find room for '%s' in %s" % (asm, _targetRanges)))
# raise ObfuFailure("assemble: {}".format(asm))
# if not is_int3:
# usedRanges.extend(targetRanges)
if obfu_debug:
printi("usedRanges: {}".format(pf(usedRanges)))
# for r in usedRanges:
# if r.length > 0:
# ## ZeroCode(start, length)
# if obfu_debug:
# printi("usedRangesNopping: {:x}, {:x}, {} {}".format(r.start, r.length, patternComment, _targetRanges))
# PatchNops(r.start, r.length, patternComment)
# for _addr in range(r.start, r.start + r.length):
# patchedAddresses.add(_addr)
patchedRanges = GenericRanger(patchedAddresses, sort=0, outsort=0)
# dprint("[process_replacement] patchedRanges")
# print("[process_replacement] patchedRanges:{}".format(patchedRanges))
# XXX: the `difference` probably isn't neccessary, as the two should be mutually exlusive
# YYY: it's necessary now, we're using the original target ranges!
if obfu_debug:
setglobal('oriTargetRanges', oriTargetRanges)
setglobal('patchedRanges', patchedRanges)
# finish rest of targetRanges
if not is_int3:
[PatchNops(r.start, r.length, 'unused-after') for r in targetRanges if r.length]
targetRanges.clear()
# if reverse:
# _usedRanges = str(usedRanges)
# for r in usedRanges:
# PatchNops(r.start, r.length, patternComment + " usedRanges *["+str(r)+"]* " + _usedRanges, ease=1)
# _targetRanges = str(targetRanges)
# for r in targetRanges:
# PatchNops(r.start, r.length, patternComment + " targetRanges *["+str(r)+"]* " + _targetRanges, ease=1)
# d = difference(oriTargetRanges, patchedRanges, ordered=1) # usedRanges
# dprint("[process_replacement] difference")
# print("[process_replacement] difference:{}".format(d))
if False:
# if d:
*all, last = d
# dprint("[process_replacement] all, last")
for r in all:
## ZeroCode(start, length)
if obfu_debug:
printi("remainingRangesNopping: {:#x}-{:#x}".format(r.start, r.trend))
PatchNops(r.start, r.length, patternComment + " " + _targetRanges, ease=1)
for _addr in range(r.start, r.start + r.length):
patchedAddresses.add(_addr)
if obfu_debug:
printi("lastRangeNopping: {:#x}-{:#x}".format(last.start, last.trend))
PatchNops(last.start, last.length, patternComment + _targetRanges + " (trailing)", ease=1) # , trailingRet=is_int3 and tail_padded)
for _addr in range(last.start, last.start + last.length):
patchedAddresses.add(_addr)
[Plan(ra.start, ra.start + ra.length) for ra in oriTargetRanges]
# [Plan(ra[0], EaseCode(ra[0], forceStart=1, noExcept=1)) for ra in oriTargetRanges]
return {'patchedAddresses': patchedAddresses}
else:
printi(("ProcessReplacement: Unexpected type (exected tuple): %s" % type(repl)))
pp(repl)
return False
# def replace_pattern_bitwise(self, search, mask, replFunc, patternComment, addressList, ea, addressListWithNops, safe):
def replace_pattern_bitwise(self, pat, ea, addressList, addressListWithNops, addressListFull, context=None):
# result = self.replace_pattern_bitwise(pattern[0], pattern[1], pattern[2], pattern[3], list(addressList), ea, list(addressListWithNops), pattern[4], pattern[5])
# result = self.replace_pattern_bitwise(pattern, ea, list(addressList), list(addressListWithNops))
# printi(json.dumps(searchIndex))
search, mask, replFunc, brief = pat.search, pat.mask, pat.replFunc, pat.brief
searchLen = len(search)
if len(addressList) < searchLen:
return False
tmp = BitwiseMask()
tmp.resize(searchLen)
for i in range(searchLen):
c = idc.get_wide_byte(addressList[i])
tmp._add_byte(i, c)
if c & mask[i] != search[i]:
return False
if pat.bitmask.eval:
# print("bitmask match eval: {}".format(pat.bitmask.eval))
if not pat.bitmask.match(tmp):
return False
if obfu_debug: printi("[replace_pattern_bitwise] matched {} [{}]".format(pat.bitmask.pattern if pat.bitmask else 'no_bitmask', type(pat).__name__))
if replFunc:
original = [idc.get_wide_byte(x) for x in addressList]
repl = replFunc(search, [], original, ea, addressList, brief,
addressListWithNops=addressListWithNops, addressListFull=addressListFull)
if repl:
if obfu_debug: printi("Replace bitwise with {}:".format(pfh(repl)))
# pp(repl)
# (9, [89])
r = self.process_replacement(search, repl, addressList, brief, addressListWithNops, addressListFull, pat=pat, context=context)
if r:
return {'addressList': addressList, 'pattern': pat, 'result': r}
return False
def replace_pattern_ex(self, search, repl, replFunc, searchIndex, patternComment, addressList, ea,
addressListWithNops, addressListFull, safe, pat=None, context=None):
# inslen = MyGetInstructionLength(ea)
# buf = GetManyBytes(ea, ItemSize(ea))
# printi(json.dumps(searchIndex))
if not isInt(ea):
raise ValueError("ea is {}".format(ea))
searchLen = len(search)
if len(addressList) < searchLen:
if obfu_debug: printi("addressList too short ({} < {})".format(len(addressList), searchLen))
return False
failed = 0
for i in searchIndex:
if search[i] == -1 or Byte(addressList[i]) == search[i]:
pass
else:
failed = 1
if obfu_debug:
printi("returning, no match at index {} (wanted: {:x} found: {:x} at {:x})".format(i, search[i], idc.get_wide_byte(addressList[i]), addressList[i]))
printi("search string: {}".format(listAsHex(search)))
printi("values : {}".format(listAsHex([idc.get_wide_byte(addressList[i]) for i in searchIndex])))
if i == 12:
printi("12", Byte(addressList[i]), search[i])
break
if failed:
return False
# del addressList[searchLen:]
if replFunc:
if not isInt(ea):
raise ValueError("ea is {}".format(ea))
original = [idc.get_wide_byte(x) for x in addressList]
repl = replFunc(search, repl, original, ea, addressList, patternComment,
addressListWithNops=addressListWithNops, addressListFull=addressListFull, pat=pat, context=context)
if not repl:
return False
# printi("Replace:")
# pp(repl)
# 141057f05 Search|Replace (A): 21|('0x15', ['<generator object recursive_map at 0x0000021AAAFC8F48>', '<generator object recursive_map at 0x0000021AAAFC8F48>'])
# jmp via push rbp, xchg, lea rsp, jmp rsp-8
if not self.quiet:
printi("{:x} replFunc:Comment: {}"
.format(ea,
patternComment)) # listAsHex(search),
# printi("{:x} replFunc:Search: {}\n Replace: {}\n Comment: {}"
# .format(ea,
# listAsHex(search),
# ahex(repl),
# patternComment)) # listAsHex(search),
r = self.process_replacement(search, repl, addressList, patternComment, addressListWithNops, addressListFull, length=len(search), pat=pat, context=context, printed=True)
if r:
return {'addressList': addressList, 'safe': safe, 'result': r}
elif repl:
# printi("{:x} Search|Replace (B): {}|{}\n {}".format(ea, listAsHex(search), ahex(repl), patternComment))
if not self.quiet:
printi("{:x} repl: Comment: {}"
.format(ea,
patternComment)) # listAsHex(search),
# printi("{:x} repl: Search: {}\n Replace: {}\n Comment: {}"
# .format(ea,
# listAsHex(search),
# ahex(repl),
# patternComment)) # listAsHex(search),
r = self.process_replacement(search, (search, repl), addressList, patternComment,
addressListWithNops, addressListFull, pat=pat, context=context, printed=True)
if r:
return {'addressList': addressList, 'pattern': pat, 'safe': safe, 'result': r}
elif not repl:
printi(("0x%x: No replacement for patch %s" % (ea, patchComment)))
return False
else:
printi("repl but could not process_replacement")
return False
# requiredLen = len(repl)
def AnalyzeArea(self, start, end):
self.AnalyzeQueue.append([start, end])
def comb(self, ea, length, recursion=0, nops=False, comment="", limit=None, debugComments=False):
if obfu_debug: printi(("0x%x: obfu::comb: length:%i" % (ea, length)))
# Make sure all the instructions disassembled, and break up the JMPs
fnFlags = idc.get_full_flags(ea)
fnEnd = FindFuncEnd(ea)
nextAny = NextNotTail(ea)
allRefs = set(idautils.CodeRefsFrom(ea, 1))
jmpRefs = set(idautils.CodeRefsFrom(ea, 0))
flowRefs = allRefs - jmpRefs
hitFnEnd = nextAny == fnEnd
if idc.is_tail(fnFlags):
if not MyMakeUnkn(ea, 0):
printi(("0x%x: MyMakeUnkn: failed" % ea))
# Wait()
MakeCodeAndWait(ea, force=1, comment=GetFunctionName(ea))
fnFlags = idc.get_full_flags(ea)
if idc.is_tail(fnFlags):
raise ObfuFailure("0x%x: attempted to start comb on tail byte: " % ea)
if fnEnd < BADADDR and len(flowRefs) == 1 and hitFnEnd:
# Expand Function
SetFunctionEnd(ea, NextNotTail(fnEnd))
# Wait()
ip = ea
count = 0
addressList = []
visited = set()
while count < length and ip != limit:
if idc.get_color(ip, CIC_ITEM) == 0xffffffff: