-
Notifications
You must be signed in to change notification settings - Fork 1
/
obfu_helpers.py
2085 lines (1923 loc) · 84.1 KB
/
obfu_helpers.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
from idc import *
import idaapi
import idautils
import struct
from binascii import unhexlify, hexlify
import os, sys, json
import ctypes
# from sfcommon import *
import itertools
from keypatch import Keypatch_Asm
kp = Keypatch_Asm(KS_ARCH_X86, KS_MODE_64)
from exectools import make_refresh
refresh_obfu_helpers = make_refresh(os.path.abspath(__file__))
refresh = make_refresh(os.path.abspath(__file__))
use_commenter = True
def GetSize(ea):
"""
Get instruction size
@param ea: linear address of instruction
@return: number of bytes, or None
"""
inslen = MyGetInstructionLength(ea)
if inslen == 0:
return None
return inslen
# def MakeCodeAndWait(ea, force = False, comment = ""):
# """
# MakeCodeAndWait(ea)
# Create an instruction at the specified address, and Wait() afterwards.
#
# @param ea: linear address
#
# @return: 0 - can not create an instruction (no such opcode, the instruction
# would overlap with existing items, etc) otherwise returns length of the
# instruction in bytes
# """
#
# if Byte(ea) == 0xcc:
# print("0x%x: %s can't make 0xCC into code" % (ea, comment))
# return 0
#
# insLen = MakeCode(ea)
# if insLen == 0:
# if force:
# print("0x%x: %s %s" % (ea, comment, GetDisasm(ea)))
# count = 0
# # This should work, as long as we are not started mid-stream
# while not insLen and count < 16: # and idc.next_head(ea) != NextNotTail(ea):
# count += 1
# MyMakeUnknown(ItemHead(ea), count, 0)
# Wait()
# insLen = MakeCodeAndWait(ea)
# # print("0x%x: MakeCodeAndWait: making %i unknown bytes (insLen now %i): %s" % (ea, count, insLen, GetDisasm(ea + count)))
# if count > 0:
# print("0x%x: MakeCodeAndWait: made %i unknown bytes (insLen now %i): %s" % (ea, count, insLen, GetDisasm(ea + count)))
# # print("0x%x: MakeCodeAndWait returning %i" % (ea, count))
# idaapi.Wait()
# return insLen
"""
TODO: Rewrite
1: JMP 5
5: JMP [rsp+8]
into
1: JMP [rsp+8]
"""
class ObfuFailure(Exception):
pass
## The Generic Ranger
def GenericRangerPretty(genericRange, sort = False):
ranges = GenericRanger(genericRange, sort = sort)
result = ""
for r in ranges:
result += "0x%012x..0x%012x\n" % (r.start, r.last);
return result
def DeleteFunctionNames():
for fnName in idautils.Functions():
if idaapi.has_user_name(idc.get_full_flags((fnName))):
idaapi.del_global_name(fnName)
def DeleteCodeAndData(start = idaapi.cvar.inf.min_ea, end = BADADDR):
"""
Delete all segments, instructions, comments, i.e. everything
except values of bytes.
"""
ea = start
# Brute-force nuke all info from all the heads
count = 0
while ea != BADADDR and ea <= end:
count += 1
if count > 16384:
count = 0
found = FindBinary(ea, SEARCH_DOWN | SEARCH_CASE, "48")
try:
if not idc.is_unknown(idc.get_full_flags(ea)):
MyMakeUnknown(ea, idc.next_head(ea) - ea, 1)
else:
ea = idc.next_head(ea)
continue
except:
pass
idaapi.del_local_name(ea)
idaapi.del_global_name(ea)
func = idaapi.get_func(ea)
if func:
# idaapi.del_func_cmt(func, False)
# idaapi.del_func_cmt(func, True)
idaapi.del_func(ea)
# idaapi.del_hidden_area(ea)
# seg = idaapi.getseg(ea)
# if seg:
# idaapi.del_segment_cmt(seg, False)
# idaapi.del_segment_cmt(seg, True)
# idaapi.del_segm(ea, idaapi.SEGDEL_KEEP | idaapi.SEGDEL_SILENT)
ea = idc.next_head(ea)
# ea = idaapi.next_head(ea, idaapi.cvar.inf.maxEA)
def DeleteData(start, end):
"""
Delete all segments, instructions, comments, i.e. everything
except values of bytes.
"""
ea = start
# Brute-force nuke all info from all the heads
while ea != BADADDR and ea <= end:
if idc.is_data(idc.get_full_flags(ea)):
MyMakeUnknown(ea, idc.next_head(ea) - ea, 1)
# idaapi.del_local_name(ea)
# idaapi.del_global_name(ea)
# func = idaapi.get_func(ea)
# if func:
# idaapi.del_func_cmt(func, False)
# idaapi.del_func_cmt(func, True)
# idaapi.del_func(ea)
# idaapi.del_hidden_area(ea)
# seg = idaapi.getseg(ea)
# if seg:
# idaapi.del_segment_cmt(seg, False)
# idaapi.del_segment_cmt(seg, True)
# idaapi.del_segm(ea, idaapi.SEGDEL_KEEP | idaapi.SEGDEL_SILENT)
ea = idc.next_head(ea)
# ea = idaapi.next_head(ea, idaapi.cvar.inf.maxEA)
def DeleteAllHiddenAreas(ea = idaapi.cvar.inf.min_ea):
"""
Delete all segments, instructions, comments, i.e. everything
except values of bytes.
"""
# ea = idaapi.cvar.inf.min_ea
hidden_area = idaapi.get_next_hidden_area(ea);
while hidden_area:
idaapi.del_hidden_area(hidden_area.start_ea)
hidden_area = idaapi.get_next_hidden_area(hidden_area.end_ea);
# Brute-force nuke all info from all the heads
# while ea != BADADDR and ea <= idaapi.cvar.inf.maxEA:
# if (ea & 0xfffff) == 0:
# print("0x%x: Clearing hidden areas..." % ea)
# idaapi.del_local_name(ea)
# idaapi.del_global_name(ea)
# func = idaapi.get_func(ea)
# if func:
# idaapi.del_func_cmt(func, False)
# idaapi.del_func_cmt(func, True)
# idaapi.del_func(ea)
# idaapi.del_hidden_area(ea)
# seg = idaapi.getseg(ea)
# if seg:
# idaapi.del_segment_cmt(seg, False)
# idaapi.del_segment_cmt(seg, True)
# idaapi.del_segm(ea, idaapi.SEGDEL_KEEP | idaapi.SEGDEL_SILENT)
# ea = idaapi.next_not_tail(ea)
def hideRepeatedBytes(ea):
# DelHiddenArea(start)
# HideArea(start, end+1, 'Bytes nulled after de-obfu', 'obfu-start', 'obfu-end', 0)
# SetHiddenArea(start, 0)
start = ea
end = ea
count = -1
while end < BADADDR and Byte(start) == Byte(end):
count += 1
end += 1
if count > 1:
count += 1 # Not sure why this is always short 1
print("0x%09x - 0x%09x (%id): 0x%x" % (start, end, count, Byte(start)))
MyMakeUnknown(start, count, DELIT_DELNAMES)
MakeArray(start, count)
HideArea(start, end, ('0x%x bytes nulled after de-obfu' % count), 'obfu-start-nulled', 'obfu-end-nulled', 0)
SetHiddenArea(start, 0)
return count
def listAsHex(l):
if isInt(l):
l = list(l)
try:
return " ".join(map(lambda x: ("%02x" % x) if isinstance(x, (integer_types, bytearray)) else x, _.flatten(list(l))))
except TypeError as e:
print("listasHex: TypeError: {}; l was {}".format(e, l))
raise e
def listAsHexIfPossible(l):
try:
listAsHex(l)
except TypeError as e:
return ", ".join([str(x) for x in _.flatten([l])])
def listAsHexWith0x(l):
return " ".join(map(lambda x: ("0x%02x" % x) if isinstance(x, (integer_types, bytearray)) else x, list(l)))
def readDword(array, offset):
return struct.unpack_from("<I", bytearray(array), offset)[0]
def writeDword(array, offset, word):
array[offset:offset+4] = bytearray(struct.pack("<I", word))
try:
import __builtin__ as builtins
integer_types = (int, long)
string_types = (str, unicode)
string_type = unicode
byte_type = str
long_type = long
except:
import builtins
integer_types = (int,)
string_types = (str, bytes)
byte_type = bytes
string_type = str
long_type = int
def IsCode(ea): return (idc.get_full_flags(ea) & idc.MS_CLS) == idc.FF_CODE
@perf_timed()
def PatchBytes(ea, patch=None, comment=None, code=False, put=False, ease=True):
"""
@param ea [optional]: address to patch (or ommit for screen_ea)
@param patch list|string|bytes: [0x66, 0x90] or "66 90" or b"\x66\x90" (py3)
@param comment [optional]: comment to place on first patched line
@returns int containing nbytes patched
Can be invoked as PatchBytes(ea, "66 90"), PatchBytes("66 90", ea),
or just PatchBytes("66 90").
"""
if 'record_patched_bytes' in globals():
globals()['record_patched_bytes'].append([ea, patch, comment])
if not IsValidEA(_.first(ea)) \
and isIterableOrStringish(ea) \
and not isIterableOrStringish(patch):
ea, patch = patch, ea
if ea is None:
ea = idc.get_screen_ea()
# was_code = idc.is_code(idc.get_full_flags(idc.get_item_head(ea)))
was_code = IsCode_(ea)
# was_code = code or idc.is_code(idc.get_full_flags(ea))
# was_head = code or idc.get_item_head(ea)
# was_func = ida_funcs.get_func(ea)
# if was_func:
# was_func = clone_items(was_func)
if isinstance(patch, str):
# unicode for py3, bytes for py2 - but "default" form for
# passing "06 01 05" type arguments, which is all that counts.
# -- pass a `bytearray` if you want faster service :)
def int_as_byte(i, byte_len=0):
# empty byte container without using
# py3 `bytes` type
b = bytearray()
while byte_len > 0:
b.append(i & 255)
i >>= 8
byte_len -= 1
for b8bit in b:
yield b8bit;
def hex_pattern_as_bytearray(str_list, u8_list=None):
u8_list = A(u8_list)
for item in str_list:
l = len(item)
if l % 2:
raise ValueError("hex must be specified in multiples of 2 characters")
u8_list.extend(int_as_byte(int(item, 16), l // 2))
return u8_list
def hex_pattern_as_list(s):
return -1 if '?' in s else int(s, 16)
if '?' not in patch:
# patch = hex_pattern_as_bytearray(patch.split(' '))
patch = bytearray().fromhex(patch)
else:
patch = [-1 if '?' in x else int(x, 16) for x in patch.split(' ')]
length = len(patch)
for addr in range(ea, ea + length):
idc.del_stkpnt(GetFuncStart(ea), addr)
idc.add_user_stkpnt(ea, 0)
# deal with fixups
fx = idaapi.get_next_fixup_ea(ea - 1)
while fx < ea + length:
idaapi.del_fixup(fx)
fx = idaapi.get_next_fixup_ea(fx)
# cstart, cend = idc.get_fchunk_attr(ea, idc.FUNCATTR_START), \
# idc.get_fchunk_attr(ea, idc.FUNCATTR_END)
# if cstart == BADADDR: cstart = ea
# if cend == BADADDR: cend = 0
# disable automatic tracing and such to prevent function trucation
# with InfAttr(idc.INF_AF, lambda v: v & 0xdfe60008):
# old_auto = ida_auto.enable_auto(False)
# for _ea in range(ea, ea+length):
# MyMakeUnknown(_ea, 1)
# code_heads = genAsList( NotHeads(ea, ea + length + 16, IsCode) )
# [0x140a79dfd, 0x140a79e05, 0x140a79e09, 0x140a79e0a]
if isinstance(patch, bytearray):
# fast patch
if put:
unpatch(ea, ea + len(patch))
idaapi.put_bytes(ea, byte_type(patch))
else:
idaapi.patch_bytes(ea, byte_type(patch))
else:
# slower patch to allow for unset values
if put:
[ida_bytes.revert_byte(ea+i) for i in range(length) if patch[i] != -1]
[idaapi.put_byte(ea+i, patch[i]) for i in range(length) if patch[i] != -1]
else:
[idaapi.patch_byte(ea+i, patch[i]) for i in range(length) if patch[i] != -1]
# if 'emu_helper' in globals() and hasattr(globals()['emu_helper'], 'writeEmuMem'):
# # print("[PatchBytes] also writing to writeEmuMem")
# [helper.writeEmuMem(ea+i, bytearray([patch[i]])) for i in range(length) if patch[i] != -1]
# if was_code:
# if debug: print("was_code")
# pos = ea + length
# while code_heads:
# if code_heads[0] < pos:
# code_heads = code_heads[1:]
# else:
# break
# if code_heads:
# next_code_head = code_heads[0]
# else:
# next_code_head = idc.next_head(pos)
# if next_code_head > pos:
# idaapi.patch_bytes(pos, byte_type(bytearray([0x90] * (next_code_head - pos))))
#
if ease and (code or was_code): EaseCode(ea, ea + length, noFlow=1, forceStart=1, noExcept=1)
if comment:
if use_commenter: Commenter(ea, 'line').add(comment)
Plan(ea, ea + length, name='PatchBytes:' + str(comment))
# EaseCode(ea, next_code_head)
# ida_auto.enable_auto(old_auto)
# this may seem superfluous, but it stops wierd things from happening
# if was_code:
# remain = len(patch)
# cpos = cstart
# length = idc.create_insn(cstart)
# while length > 0:
# remain -= length
# cpos += length
# if remain <= 0:
# break
# length = idc.create_insn(cpos)
# if was_code:
# idc.auto_wait()
# EaseCode(ea, end=ea+length, create=1)
# Plan(cstart, cend or (cstart + length))
# ensures the resultant patch stays in the chunk and as code
# if was_code:
# Plan(cstart, cend or (cstart + length))
# idc.auto_wait()
# if comment:
# # comment_formatted = "[PatchBytes:{:x}-{:x}] {}".format(ea, ea + length, str(comment))
# comment_formatted = "[PatchBytes] {}".format(str(comment))
# if 'Commenter' in globals():
# Commenter(was_head, 'line').add(comment_formatted)
# else:
# idaapi.set_cmt(was_head, comment_formatted, 0)
return ea, length
def MakeNop(length):
if 'NopList' not in MakeNop.__dict__:
MakeNop.NopList = [ list(bytearray(unhexlify(hex)))
for hex in [
'',
'90',
'6690',
'0f1f00',
'0f1f4000',
'0f1f440000',
'660f1f440000',
'0f1f8000000000',
'0f1f840000000000', # Intel recommends these 8 NOPs
# '660f1f840000000000', # AMD recommend three more:
# '66660f1f840000000000',
# '6666660f1f840000000000'
]
]
return MakeNop.NopList[length]
# PatchBytes(ea, MakeNop.NopList(length))
# return length
def MakeNops(contigCount):
## Nop contigCount bytes
result = []
while contigCount > 0:
nopCount = min(contigCount, 8)
result = result + MakeNop(nopCount)
contigCount = contigCount - nopCount
return result
def MakeTerms(length):
if '_list' not in dir(MakeTerms):
MakeTerms._list = [ list(bytearray(unhexlify(hex)))
for hex in [
'c3',
'f3c3',
'c20000',
# 'f3c20000',
]]
MakeTerms._len = len(MakeTerms._list)
result = []
remain = length
while remain > 0:
result.extend(MakeTerms._list[min(remain, MakeTerms._len) - 1])
remain = length - len(result)
return result
@perf_timed()
def PatchNops(ea, count=None, comment="PatchNops", put=False, nop=0x90, trailingRet=False, ease=True):
if count is None and ea < 100000:
ea, count = count, ea
if ea is None:
ea = ScreenEA()
while count > ea:
count = count - ea
for addr in range(ea, ea + count + 1):
idc.add_user_stkpnt(addr, 0)
if nop == 0x90:
if trailingRet:
PatchBytes(ea, MakeNops(count-1), code=1, put=put)
PatchBytes(ea + count - 1, 'c3', code=1, put=put)
if ease:
end = EaseCode(ea)
for addr in idautils.Heads(ea, end):
if use_commenter: Commenter(addr, 'line').add('{}'.format(comment))
else:
PatchBytes(ea, MakeNops(count), code=1, comment=comment, put=put, ease=ease)
else:
MyMakeUnknown(ea, count, DOUNK_DELNAMES)
if put:
unpatch(ea, count)
ida_bytes.put_bytes(ea, bytes([nop] * count))
else:
ida_bytes.patch_bytes(ea, bytes([nop] * count))
idc.SetType(ea, "_BYTE[{}]".format(count))
idc.set_cmt(ea, comment, 0)
return ea, count
# PatchBytes(ea, [nop] * count, code=1, comment=comment, put=put)
# comment_formatted = "[PatchNops] {}".format(ea, str(comment))
# idc.auto_wait()
# if 'Commenter' in globals():
# Commenter(EA(), 'line').add(comment_formatted)
# else:
# idaapi.set_cmt(was_head, comment_formatted, 0)
def remove_null_sub_jmps():
"""
Check for **jmp** to nullsub, and replaces with RETN
"""
for i in range(5000):
# print("Checking nullsub_%i" % i)
for fmt in ['nullsub_%i', 'j_nullsub_%i', 'j_j_nullsub_%i']:
loc = LocByName(fmt % i)
if loc < BADADDR:
refs = list(idautils.CodeRefsTo(loc, 1))
for ref in refs:
if IdaGetMnem(ref) == 'jmp' and Byte(ref) == 0xe9:
target = GetOperandValue(ref, 0)
if target != loc:
print("0x%x: wasn't jump to nullsub at %012x" % (ref, loc))
continue
result = [0xcc] * GetSize(ref)
result[0] = 0xc3 # retn
PatchBytes(ref, result)
print("0x%x: was jmp to nullsub at %012x" % (ref, loc))
MakeCodeAndWait(ref)
# MakeDword(ref + 1)
MakeComm(ref, "was call to nullsub at %012x" % (loc))
elif IdaGetMnem(ref) == 'call':
# NOP_5 = list(bytearray(b"\x0f\x1f\x44\x00\x00"))
# PatchBytes(ref, MakeNop(5));
MakeComm(ref, "0x%x: was call to nullsub at %012x" % (ref, loc))
# MakeCodeAndWait(ref)
MakeComm(ref, "is call to nullsub at %012x" % (loc))
print("0x%x: was CALL (?!) to nullsub at %012x" % (ref, loc))
else:
print("ref %x was a %s, left it alone" % (ref, IdaGetMnem(ref)))
def QueueClear(queue):
count = -1
ref = 0
while ref < BADADDR:
ref = idaapi.QueueGetType(queue, ref)
idaapi.QueueDel( queue, ref)
count += 1
print("Cleared %i items from queue %i" % (count, queue))
def QueueClearAll():
queues = [idaapi.Q_noBase, idaapi.Q_noName, idaapi.Q_noFop,
idaapi.Q_noComm, idaapi.Q_noRef, idaapi.Q_jumps, idaapi.Q_disasm,
idaapi.Q_head, idaapi.Q_noValid, idaapi.Q_lines, idaapi.Q_badstack,
idaapi.Q_att, idaapi.Q_final, idaapi.Q_rolled, idaapi.Q_collsn,
idaapi.Q_decimp, idaapi.Q_Qnum]
for q in queues:
QueueClear(q)
def check_misaligned_code(queue, ref, dry_run = 0):
"""
Checks for misaligned code, indicated by xrefs such as:
jmp short near ptr loc_7FF79AB58431+3
By searching for blah+n, or blah-n, ignoring [blah+/-n]
Or by using:
idaapi.QueueGetType(idaapi.Q_head, lowea)
And now trying:
idaapi.Q_disasm
"""
ref = idaapi.QueueGetType(queue, ref)
if Byte(ref) == 0xCC:
idaapi.QueueDel( idaapi.Q_disasm, ref)
return ref + 1
refFlags = idc.get_full_flags(ref)
head = ref if idc.is_head(refFlags) else ItemHead(ref)
flags = idc.get_full_flags(head)
if idc.is_code(flags):
print("0x%x: (%02x): %s" % (head, ref - head, GetDisasm(head)))
if (queue == idaapi.Q_disasm):
forceAsCode(ref, 8)
head = ref if idc.is_head(refFlags) else ItemHead(ref)
flags = idc.get_full_flags(head)
# Jump(ref)
if idc.is_code(flags):
# Jump(head)
if GetOpType(head, 1) == 0: # Check for single operand instruction
# (This will be okay for jumps and calls, but
# we'll hit more complex stuff like MOV/LEA)
if GetOpType(head, 0) == o_near:
target = GetOperandValue(head, 0)
# Jump(target)
if not dry_run:
forceAsCode(target, 8) # 5 is an E9 JMP, the most likely command,
# next most likely commands are 6 bytes
else:
print("0x%x" % ref)
print("Unknown OpType %i" % GetOpType(head, 0))
# GetDisasm(ea()).find('+')
# GetDisasm(ea()).find('-')
return head + MyGetInstructionLength(head)
elif 0:
if idc.is_data(idc.get_full_flags(ea - 1)):
codeLen = MakeCodeAndWait(ea - 1)
if not codeLen:
print("0x%x Couldn't convert block into code at (head: 0x%09x)" % (ea, head))
return None
elif idc.is_data(flags):
print("0x%x: Data Problem" % ref)
return ref + 1
elif idc.is_unknown(flags):
print("0x%x: Unknown Problem" % ref)
return ref + 1
else:
print("0x%x: REALLY Unknown Problem" % ref)
return ref + 1
def patch_everything():
count = 0x10000 - 2
try:
x = obfu.get_next_instruction()
while True:
result = x.next()
count = count + 1
if count > 0x50000:
count = 0
print("Scanning %012x" % result[0])
except StopIteration:
print("Finished patch_everything")
def MakeSigned(number, size = 32):
number = number & (1<<size) - 1
return number if number < 1<<size - 1 else - (1<<size) - (~number + 1)
def bitsize_unsigned(n):
for i in [8, 16, 32, 64, 128, 256, 512, 1024]:
if n < (1<<i) and n > (-1<<i):
return i
def bitsize_signed(n):
for i in [8, 16, 32, 64, 128, 256, 512, 1024]:
if n < (1<<(i-1)) and n > (-1<<(i-1)):
return i
def bitsize_signed_2(n):
i = bitsize_unsigned(n)
j = MakeSigned(n, 32)
return bitsize_signed(j)
def patch_manual_instruction_rsp(search, replace, original, ea):
if idc.is_code(idc.get_full_flags(ea)):
adjustment = MakeSigned(original[len(original) - 1], 8)
if adjustment > 0:
SetManualInsn(ea, ("RSP += %i" % adjustment))
else:
SetManualInsn(ea, ("RSP -= %i" % (0 - adjustment)))
return search
return None
# def patch_lea_rsp_stack_diff(search, replace, original, ea):
# if not forceAsCode(ea, len(search)):
# return None
# if not idc.is_code(idc.get_full_flags(idc.next_head((ea)))):
# return None
# if not idc.is_flow(idc.get_full_flags(idc.next_head((ea)))):
# return None
# adjustment = MakeSigned(original[len(original) - 1], 8)
# originalAdjustment = GetSpDiff(idc.next_head(ea))
# # if not originalAdjustment:
# # originalAdjustment = -1
# if originalAdjustment != None:
# if adjustment != originalAdjustment:
# SetSpDiff(idc.next_head(ea), adjustment)
# print("adjust stack delta from %i to %i @ 0x%09x" % (originalAdjustment, adjustment, ea))
# return None
def patch_force_as_code(search, replace, original, ea, comment):
MakeCodeAndWait(ea)
# slowtrace2(ea, "0x%x" % ea, 20)
return []
""" rsp/rbp jmp 2
000 mov rax, [rcx+10h] ; rax = pArg1
000 mov ecx, [rax] ; ecx = *(DWORD *)rax
000 lea rsp, [rsp-8] ; push rbp (pt1)
008 mov [rsp+0], rbp ; push rbp (pt 2)
008 lea rbp, sub_7FF7431C03A8 ; rbp = sub_7FF7431C03A8
008 xchg rbp, [rsp+0] ; pop rbp; *rsp = sub_7FF7431C03A8
008 lea rsp, [rsp+8] ; pop (pt2)
000 jmp qword ptr [rsp-8] ; jmp *(rsp - 8) (sub_7FF7431C03A8)
0: 48 8d 2d 77 77 77 77 lea rbp,[rip+0x77777777] # 7777777e <_main+0x7777777e>
7: 48 87 2c 24 xchg QWORD PTR [rsp],rbp
b: 48 8d 64 24 08 lea rsp,[rsp+0x8]
10: e9 88 24 95 fc jmp loc_7FF742F88D2E
10: ff 64 24 f8 jmp QWORD PTR [rsp-0x8]
0: 48 8d 2d 77 77 77 77 lea rbp,[rip+0x77777777] # 0x7777777e
7: 48 87 2c 24 xchg QWORD PTR [rsp],rbp
b: 48 8d 64 24 08 lea rsp,[rsp+0x8]
10: e9 77 77 77 77 jmp 0x7777778c
15: 90 nop
10: ff 64 24 f8 jmp QWORD PTR [rsp-0x8]
14: (bad code)
"""
def colorise_xor(cmd):
"""
http://malwaremuncher.blogspot.com.au/2012/10/enhancing-ida-pro-part-1-highlighting.html
"""
if cmd.itype in colorise_xor.xor_instructions:
# check if different operands
if cmd.Op1.type != cmd.Op2.type or cmd.Op1.reg != cmd.Op2.reg or cmd.Op1.value != cmd.Op2.value:
idaapi.set_item_color(cmd.ea, 0xffd2f8)
colorise_xor.xor_instructions = [idaapi.NN_xor, idaapi.NN_pxor, idaapi.NN_xorps, idaapi.NN_xorpd]
# Fixes labels with offsets, eg loc_7ff7+1
def fix_loc_offset(label=None, _new_ea=None):
"""
fix the target of a stupid jump like `jmp loc_123+1`
@param label: label (str) or linear address (int)
@param _new_ea: optional (and pointless) result of `label` + `offset`
"""
old_ea = eax(string_between('', '+', label))
new_ea = _new_ea or eax(label)
# if loc > ida_ida.cvar.inf.max_ea or loc < ida_ida.cvar.inf.min_ea:
# return
MyMakeUnknown(old_ea, GetInsnLen(new_ea) + new_ea - old_ea)
MakeCodeAndWait(new_ea, force = 1)
# else:
# print("0x%x: not code: " % (realLoc))
return (old_ea, new_ea, new_ea - old_ea)
# Jump(loc)
# Sleep(1000)
def FixTargetLabels(ea):
for target in [GetOperandValue(ea, 0), GetOperandValue(ea, 1)]:
disasm = GetDisasm(ea)
if SegName(target) == SegName(ea):
m = re.search(r'([a-z]+_([A-F0-9]+)\+[A-F0-9]+)', disasm)
if m:
listedTarget = int(m.group(2), 16)
badLabel = m.group(1)
if listedTarget >= ida_ida.cvar.inf.min_ea and listedTarget < ida_ida.cvar.inf.max_ea:
rv = fix_loc_offset(badLabel)
Wait()
# MyMakeUnkn(ea, 0)
disasm = GetDisasm(ea)
if re.search(r'[a-z]+_([A-Z0-9]+)\+', disasm):
print("0x%x: Failed to label offset: %s" % (ea, GetDisasm(ea)))
raise ObfuFailure("0x%x: Failed to label offset: %s" % (ea, GetDisasm(ea)))
# MakeCodeAndWait(ea)
# disasm = GetDisasm(ea)
print("0x%x: Fixed bad label: %s" % (ea, disasm))
# MyMakeUnknown(ItemHead(listedTarget), 1, DELIT_EXPAND | DELIT_NOTRUNC)
# MyMakeUnknown(listedTarget, 1 + target - listedTarget, DELIT_EXPAND | DELIT_NOTRUNC)
# MakeCodeAndWait(target)
if not idc.is_code(idc.get_full_flags(target)):
if not MakeCodeAndWait(target, force = 1):
print("0x%x: Jump target %012x not recognised as code" % (ea, target))
# push eax
# is equiv to
# sub esp, 4
# mov [esp], eax
# http://stackoverflow.com/a/14060554/912236
patch_logs = []
# Patch factory
def generate_log():
"""
"""
def patch(search, replace, original, ea, addressList, patternComment, addressListWithNops):
addressList = addressList[:len(search)]
patch_logs.append(ea)
print("0x%x: LOG_PATCH: ********** %s ***********" % (ea, patternComment))
return patch
def find_contig(startIndex, length, addressList):
nopCount = BADADDR
for index in xrange(startIndex, len(addressList) - length):
if (addressList[index + length - 1] - addressList[index] == length - 1):
nopCount = index - startIndex
break
if nopCount == BADADDR:
print("0x%x: %s contiguous bytes not found at nopCount" % (ea, length))
return None
# If initial padding with nops is needed
result = []
if nopCount:
if debug: print("0x%x: Making %i nops" % (addressList[startIndex], nopCount))
nopAddresses = [addressList[n] for n in range(startIndex, startIndex + nopCount)]
print("nopAddresses", hex(nopAddresses))
nopRanges = GenericRanger(nopAddresses, sort = 0, outsort = 0)
for r in nopRanges:
print("%i nops" % r.length)
result += MakeNops(r.length)
return result
def contig_ranges(addressList, startIndex = 0, length = None):
addressLen = len(addressList)
if not length or length > addressLen - startIndex:
length = addressLen - startIndex
if length < 2:
print("ContigCount: %i: %i" % (startIndex, 1))
return 1
endIndex = addressLen - 1
endRange = length
print("addressLen: %i" % addressLen)
print("length: %i" % length)
print("startIndex %i" % startIndex)
print("endIndex %i" % endIndex)
print("endRange %i" % endRange)
contigCount = BADADDR
for index in range(startIndex, endRange):
i = startIndex + index
print("")
print("index %i" % index)
print("i %i" % i)
diff = addressList[i] - addressList[startIndex]
print("diff %i" % diff)
if (diff == index):
contigCount = index + 1
print("contigCount %i" % contigCount)
else:
break
print("")
print("contigCount: %i: %i" % (startIndex, contigCount))
nextIndex = startIndex + contigCount
if nextIndex < endIndex:
print("nextIndex %i" % (startIndex + contigCount))
print("endIndex %i" % endIndex)
contig_ranges(addressList, startIndex + contigCount, length - contigCount)
if contigCount == BADADDR:
print("0x%x: %contigCount contiguous bytes not found at contigCount" % (ea, length))
return None
# If initial padding with nops is needed
result = []
if contigCount:
print("0x%x: Making %i nops" % (addressList[startIndex], contigCount))
nopAddresses = [addressList[n] for n in range(startIndex, startIndex + contigCount)]
print("nopAddresses2", str(nopAddresses))
nopRanges = GenericRanger(nopAddresses, sort=0, outsort=0)
for r in nopRanges:
print("%i nops" % r.length)
result += MakeNops(r.length)
return result
def kassemble(string, ea=None, apply=False, arch=None, mode=None, syntax=None):
""" assemble with keypath
"""
if type(ea) is str:
ea, string = string, ea
if ea is None:
ea = idc.get_screen_ea()
if ea == BADADDR:
ea = 0
result = kp.assemble(kp.ida_resolve(string, ea), ea, arch, mode, syntax)
if type(result) is tuple and result[1] > 0:
if apply:
PatchBytes(ea, result[0])
MakeCode(ea)
return result[0]
# failed
return None
def iassemble(string, ea=None, apply=False, arch=None, mode=None, syntax=None):
""" try to assemble with keypath, then ida, then nasm
"""
if type(ea) is str:
ea, string = string, ea
if ea is None:
ea = idc.get_screen_ea()
if ea == BADADDR:
ea = 0
result = qassemble(ea, string)
if result is list:
if apply:
PatchBytes(ea, result)
MakeCode(ea)
return result
string = ida_resolve(string)
result = kp.assemble(kp.ida_resolve(string, ea), ea, arch, mode, syntax)
if type(result) is tuple and result[1] > 0:
if apply:
PatchBytes(ea, result[0])
MakeCode(ea)
return result[0]
result = nassemble(string, ea, apply=apply)
if type(result) is tuple and result[1] > 0:
if apply:
PatchBytes(ea, result[0])
MakeCode(ea)
return result[0]
raise ObfuFailure("couldn't assemble %s" % ida_resolve(string))
def ida_resolve(assembly):
def rename_if_possible(match):
name = match.group(1)
# dprint("[rename_if_possible] match.group(0), match.group(1)")
if name and not re.match(r'^[_a-zA-Z]\w+$', name.rstrip(':')):
print("[rename_if_possible] name: '{}'".format(name))
if name.endswith(':'):
return "LABEL_" + re.sub(r'[^_a-zA-Z0-9]', '_', name)
else:
ea = idc.get_name_ea_simple(name)
if IsValidEA(ea):
return hex(ea)
# else:
# raise ValueError("Couldn't resolve label '{}'".format(name))
return name
def _resolve(assembly):
# assembly = re.sub(r'(?<=[^\w])([a-zA-Z@$%&().?:_\[\]][a-zA-Z0-9@$%&().?:_\[\]]+)(?=[ *+-\]]|$)', rename_if_possible, assembly)
# assembly = re.sub(r'(?<!\w)([a-zA-Z@$%&().?:_\[\]][a-zA-Z0-9@$%&().?:_\[\]]+)(?=[ *+-\]]|$)', rename_if_possible, assembly)
# assembly = re.sub(r'(?<!\w)([a-zA-Z@$%&().?:_][a-zA-Z0-9@$%&().?:_\[]+)(?=[ *+\r\-\]]|$)', rename_if_possible, assembly)
assembly = re.sub(r'(?<!\w)([a-zA-Z@$%&().?:_][a-zA-Z0-9@$%&().?:_\[]+)(?=[-+*\]\n])', rename_if_possible, assembly)
return assembly
return _resolve(assembly)
def nassemble(ea, string = None, apply=None, comment=None, quiet=False, put=False, ease=True):
""" assemble with nasm
:param ea: target address
:param string: assembly, seperated by ; or \\n
:param apply: patch result to target address
:throws RelocationAssemblerError if cannot assemble
:returns list(int) of assembled bytes
"""
if type(ea) in (str, list):
ea, string = string, ea
if ea == 1 or ea is True:
ea, apply = apply, ea
if ea is None:
ea = idc.get_screen_ea()
if ea == BADADDR:
ea = 0
if isinstance(string, list):
string = "\n".join(string)
string = "\n".join([x.strip() for x in string.split(';')])
if len(string.strip()) == 0:
return []
result = nasm64(ea, ida_resolve(string), quiet=quiet)
# if obfu_debug:
# print("[nassemble] {:#x} {} {}".format(ea, " ".join([x.hex() for x in A(result[1]['output'])]), "; ".join(diCode(bytes(result[1]['output']), noHex=1))))
if result[0]:
# r = bytes_as_hex(result[1])
r = result[1]['output']
# dprint("[debug] result[1]['output']")
if apply:
length = len(r)
# print("length: {}".format(length))
next = ea + length
if IsTail(next):
# print("idc.is_tail({:x})".format(next))
nextInsn = idc.next_head(next)
else:
# print("idc.is_not tail({:x})".format(next))
nextInsn = next
# print("nextInsn: {:x}".format(nextInsn))
# with InfAttr(idc.INF_AF, lambda v: v & 0xdfe60008):
# MyMakeUnknown(ea, length, DELIT_EXPAND | ida_bytes.DELIT_NOTRUNC)
# PatchBytes(ea, r + bytes(MakeNops(nextInsn - next)))
_was_code = IsCode_(ea)
if _was_code:
_code_len = MyGetInstructionLength(ea)
PatchBytes(ea, r, comment=comment, put=put, ease=False)
if _was_code and _code_len > length:
print("PatchNops({:x}, {})".format(next, _code_len - length))
PatchNops(next, _code_len - length, ease=True)
# idc.auto_wait()
# idc.plan_and_wait(ea, nextInsn)
# forceCode(ea, nextInsn) # , nextInsn) # , ea + nextInsn)
# idc.auto_wait()
# if ease:
# EaseCode(ea, end=ea + _code_len, noExcept=1, forceStart=1)
# forceCode(ea, end=ea + _code_len - 1)