-
Notifications
You must be signed in to change notification settings - Fork 1
/
hotkey_utils.py
1731 lines (1481 loc) · 74.2 KB
/
hotkey_utils.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
# hotkey_utils.py - bNull
#
# Some useful shortcuts for binding to hotkeys. Current output/hotkeys:
#
# [+] Bound make_dwords to Ctrl-Alt-D
# [+] Bound make_cstrings to Ctrl-Alt-A
# [+] Bound make_offset to Ctrl-Alt-O
# &
# &.update_file(__file__, __version_hash__, __version_info__)
from binascii import unhexlify
import ida_idaapi
from idautils import Heads, Chunks
import idaapi
import idc
import inspect
import time
import os
import ida_auto
from itertools import islice
from idc import *
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets
delayed_exec_timer = QtCore.QTimer()
import ida_kernwin
if not idc:
# from classmaker import sanitizedName, make_vfunc_struct_sig
from commenter import Commenter
# from di import *
# from helpers import unpatch
from is_flags import HasUserName, IsCode_
from membrick import FindInSegments
from obfu_helpers import MakeSigned, PatchNops
from sfcommon import GetFuncStart
from slowtrace_helpers import GetNumChunks
from start import *
from string_between import string_between, string_between
from exectools import make_refresh
refresh_hotkey_utils = make_refresh(os.path.abspath(__file__))
refresh = make_refresh(os.path.abspath(__file__))
if not 'searches' in globals():
searches = dict()
class MyHotkey(object):
"""Docstring for MyHotkey. """
def __init__(self, shortcut, func, ctx=None, active=False):
"""TODO: to be defined1.
:shortcut: TODO
:func: TODO
"""
self.shortcut = shortcut
self.func = func
self.ctx = None
self.active = False
def funcname(self):
return string_between('function ', ' at ', str(self.func))
class MyHotkeys(object):
"""Collection of MyHotkey instances"""
def __init__(self, items=None):
"""@todo: to be defined """
self.hotkeys = []
for hotkey in A(items):
self.append(hotkey)
def __len__(self):
return self.hotkeys.__len__()
def __getitem__(self, key):
return self.hotkeys.__getitem__(key)
def __setitem__(self, key, value):
self.hotkeys.__setitem__(key, value)
def __delitem__(self, key):
self.hotkeys.__delitem__(key)
def __iter__(self):
return self.hotkeys.__iter__()
def __reversed__(self):
return self.hotkeys.__reversed__()
def __contains__(self, item):
return self.hotkeys.__containers__(item)
def _remove(self, hotkey):
func_name = hotkey.funcname()
ctx = hotkey.ctx
shortcut = hotkey.shortcut
# print("[helpers::load_hotkeys] shortcut:{}, 'func_name':{}, ctx:{}".format(hotkey.shortcut, 'func_name', not not ctx))
if ctx:
if ida_kernwin.del_hotkey(ctx):
# print("[+] Removed previous binding: %s to %s" % (func_name, shortcut))
pass
else:
print("[-] Couldn't remove previous binding: %s to %s" % (func_name, shortcut))
pass
hotkey.ctx = None
hotkey.active = False
def _add(self, hotkey):
func_name = hotkey.funcname()
shortcut = hotkey.shortcut
func = hotkey.func
# print("[helpers::load_hotkeys] shortcut:{}, 'func_name':{}, ctx:{}".format(hotkey.shortcut, 'func_name', not not ctx))
self._remove(hotkey)
new_ctx = ida_kernwin.add_hotkey(shortcut, func)
if new_ctx:
# print("[+] Bound %s to %s" % (func_name, shortcut))
hotkey.ctx = new_ctx
hotkey.active = True
else:
print("[-] Error: Unable to bind %s to %s" % ('func_name', shortcut))
def find(self, match_object):
found = None
for hotkey in self.hotkeys:
for key, value in match_object.items():
if getattr(hotkey, key, {}) == value:
found = hotkey
else:
found = None
break
if found:
break
return found
def append(self, hotkey):
existing = self.find(_.pick(hotkey, 'shortcut'))
if existing:
self.remove(existing)
self._add(hotkey)
self.hotkeys.append(hotkey)
def clear(self):
for hotkey in self.hotkeys[:]:
# print("removing hotkey '{}'".format(hotkey.shortcut))
self._remove(hotkey)
self.hotkeys.remove(hotkey)
def copy(self):
return (type(self))(self.hotkeys.copy())
def count(self):
return self.hotkeys.count()
def extend(self, iterable):
for item in iterable:
self.append(item)
def index(self, value, start=0, stop=9223372036854775807):
self.hotkeys.index(value, start, stop)
def remove(self, value):
self._remove(value)
self.hotkeys.remove(value)
# def reverse(self):
# self.hotkeys.reverse()
#
# def sort(self):
# self.hotkeys.sort()
#
# def insert(self, index, object):
# self.hotkeys.insert(index, object)
#
# def pop(self, index=-1):
# return self.hotkeys.pop(index)
def mark(ea, comment):
c = Commenter(ea, 'func')
if not c.exists(comment):
c.add(comment)
def remove(ea, comment):
c = Commenter(ea, 'func')
return c.remove(comment)
def comment_sig(ea, pattern, _type='SHORTEST'):
version = idc.get_input_file_path().split('\\')[2]
mark(ea, "[PATTERN;%s:%s;VERSION:%s] %s" % (_type, idc.get_name(ea), version, pattern))
mark(ea, "[ADDRESS;NORMALISED:0x%x;VERSION:%s]" % (ea, version))
def selection_is_valid(selection, ea):
"""If the cursor is not at the beginning or the end of our selection, assume that
something bad has gone wrong and bail out instead of turning a lot of important
things into dwords.
"""
if not (ea == selection[1] or ea == selection[2] - 1):
print("%012x: Selection[1]" % selection[1])
print("%012x: Selection[2]" % selection[2])
print("%012x: ScreenEA " % ea)
return False
else:
return True
def get_selected_bytes():
"""Highlight a range and turn it into dwords
NOTE: read_selection appears to be a fickle bitch. You absolutely have to
select more than one line at a time in order for it to work as expected.
"""
selected = idaapi.read_selection()
curr_ea = idc.get_screen_ea()
print("[+] Processing range: %x - %x" % (selected[1], selected[2]))
# refer to selection_is_valid comments regarding the need for this check
if (selection_is_valid(selected, curr_ea)):
return selected
else:
return None
# It may be useful to know how many arguments the target function will take.
# import inspect
# inspect.getargspec(fn)
# Python>inspect.getargspec(slowtrace2)
# ArgSpec(args=['ea', 'max_depth'], varargs=None, keywords=None, defaults=(None, 4))
class Selection(object):
"""Perform a single command on a selection of addresses"""
def __init__(self, fn, step=None):
"""Take the function to excute as the constructor's argument
:fn: a user-defined or built-in function or method, or a class object
"""
self._fn = fn
self._selected = get_selected_bytes()
if step is None:
self._step = NextNotTail
else:
self._step = step
def increment(self, inc):
"""increments value by number or function
:inc: pre-increment value
:returns: TODO
"""
if callable(self._step):
return self._step(inc)
return inc + self._step
def apply(self, *_args):
"""Apply arguments (if any) to function specified in constructor
:args: varargs
:returns: list of results
"""
results = []
ea = self._selected[1]
while ea < self._selected[2]: # maybe '<='
args = [ea]
args += (list(_args))
print("Calling fn with args %s" % (", ".join(map(lambda x: str(x), args))))
results.append(self._fn(*args))
ea = self.increment(ea)
return results
def make_offset():
"""Resolve an offset to a pointer
For some reason, it seems as though IDA will not auto-define a pointer DWORD. Ex:
.rodata:08E30000 dd 8271234h
In the case that 0x8271234 is actually a function, resolving the offset will
result in:
.rodata:08E30000 dd offset _ZN29ClassAD1Ev ; ClassA::~ClassA()
"""
idc.OpOffset(idc.get_screen_ea(), 0)
def div3(n):
return (n + 1) // 3
def round3(n):
return 3 * div3(n)
def get_bytes_():
byteList = list();
for ea in range(idc.SelStart(), idc.SelEnd()):
byteList.append(idc.get_wide_byte(ea))
return " ".join(map(lambda x: "%02x" % x, byteList))
def bytes_as_hex(bytes):
return " ".join(map(lambda x: "%02x" % x, bytes))
def bytes_as_hex_no_spaces(bytes):
return "".join(map(lambda x: "%02x" % x, bytes))
def get_bytes_chunked_from_comb(addresses):
byteList = list()
for ea, count in addresses:
bytes = [idc.get_wide_byte(ea + i) for i in range(count)]
byteList.append(bytes)
return [bytes_as_hex(x) for x in byteList]
def get_bytes_chunked(start=0, end=0, maxlen=65535):
byteList = list()
ea = start if start else idc.SelStart()
end = end if end else idc.SelEnd()
inslen = 1
count = 0
while ea < end and inslen and count < maxlen:
inslen = IdaGetInsnLen(ea)
count += inslen
bytes = [idc.get_wide_byte(ea + i) for i in range(inslen)]
byteList.append(bytes)
ea += inslen
return [bytes_as_hex(x) for x in byteList]
def get_data_ref(frm, var, _globals=None):
_globals = A(_globals)
from JsonStoredList import JsonStoredDict
with JsonStoredDict('datarefs.json') as __data_ref_cache:
fullvar = idaapi.get_name(GetFuncStart(frm)) + "." + var
if fullvar in __data_ref_cache:
return __data_ref_cache[fullvar]
ea = idc.get_name_ea_simple(var)
inslen = IdaGetInsnLen(frm)
for offset in range(inslen - 4, 1, -1):
if MakeSigned(idc.get_wide_dword(frm + offset), 32) + frm + inslen == ea:
insOffset = frm - GetFuncStart(frm)
# print(" %% Found reference at offset %i (%i) of instruction offset %i of %s" % (offset, inslen - offset, insOffset, idc.get_func_name(frm)))
# pattern = sig_maker_ex(GetFuncStart(frm), GetFuncEnd(frm), offset = insOffset + offset, rip = inslen - offset, MyGetType(ea), name=var)
pattern = "mem(LocByName('{}')).chain().add({}).rip({}).type('{}').name('{}')".format(
idc.get_name(GetFuncStart(frm)), insOffset + offset, inslen - offset, MyGetType(ea), var)
# idc.apply_type(EA(), byteify(unbyteify(idc.get_tinfo(EA()))))
if isinstance(pattern, str) and len(pattern) > 0:
__data_ref_cache[fullvar] = pattern
_globals.append(pattern)
return pattern
else:
print(" %% couldn't get unique pattern for function")
def get_instructions_chunked(start=0, end=0, addresses=None, maxlen=65535, _globals=None):
_globals = A(_globals)
byteList = list()
if isinstance(addresses, list):
for ea, count in addresses:
inslen = IdaGetInsnLen(ea)
if inslen:
count += inslen
disasm = idc.GetDisasm(ea).split(';')[0]
var = string_between('cs:', '', disasm)
if var and not ~var.find(' '):
addr = idc.get_name_ea_simple(var)
if addr < idc.BADADDR and HasUserName(addr):
loc = get_data_ref(ea, var, _globals)
print(" %% global: 0x{:x} {} {}: {}".format(addr, MyGetType(addr), var, loc))
Commenter(addr).add('[DATA-PATTERN: {}]'.format(loc))
byteList.append(disasm)
else:
byteList.append('invalid')
break
return byteList
ea = start if start else idc.SelStart()
end = end if end else idc.SelEnd()
inslen = 1
count = 0
while ea < end and inslen and count < maxlen:
if IsCode_(ea):
inslen = IdaGetInsnLen(ea)
if inslen:
count += inslen
disasm = idc.GetDisasm(ea).split(';')[0]
var = string_between('cs:', '', disasm)
if var and not ~var.find(' '):
addr = get_name_ea_simple(var)
if addr < BADADDR and HasUserName(addr):
loc = get_data_ref(ea, var, _globals)
print(" %% global: 0x{:x} {} {}: {}".format(addr, MyGetType(addr), var, loc))
Commenter(addr).add('[DATA-PATTERN: {}]'.format(loc))
byteList.append(disasm)
ea += inslen
else:
byteList.append('invalid')
break
return byteList
# 48 83 EC 28 sub rsp, 28h
# 33 C0 xor eax, eax
# 38 05 F5 65 C9 01 cmp cs:_bIsOnline, al
# 74 0A jz short loc_7FF742F24438
# 83 F9 1F cmp ecx, 1Fh
# 77 05 ja short loc_7FF742F24438
# E8 6C 02 59 00 call playerIndexAsNetGamePlayer
# 0F 85 A8 00 00 00 jnz xxx
# (80 A1 C1 01 00 00 BF)
# 80 a1 c1 ?? ?? ?? ?? and byte ptr [rcx+1C1h], 0BFh; self->byte_01c1 &= 0xBFu; // b 1011 1111
# 8a c2 mov al, dl ; result = b1 << 6; // b 0100 1111
# 24 01 and al, 1 ; self->byte_01c1 |= result;
# c0 e0 06 shl al, 6
# 08 81 c1 01 00 00 or [rcx+1C1h], al
#
# 80 a1 ?? 01 00 00 ?? 8a c2 24 01 c0 e0 ?? 08 81 ?? 01 00 00
# 80 a1 ?? ?? 00 00 ?? 8a c2 24 01 c0 e0 ?? 08 81 ?? ?? 00 00
#
# 80 a1 c1 ?? ?? ?? ?? and byte ptr [rcx+1C1h], 0BFh; self->byte_01c1 &= 0xBFu; // b 1011 1111
# 8a c2 mov al, dl ; result = b1 << 6; // b 0100 1111
# 24 01 and al, 1 ; self->byte_01c1 |= result;
# c0 e0 06 shl al, 6
# 08 81 c1 01 00 00 or [rcx+1C1h], al
# .text2:0000000144CC1145 028 0F BA B7 88 01 00 00 08 btr dword ptr [rdi+188h], 8
# .text2:0000000144CC114D 028 83 E3 01 and ebx, 1
# .text2:0000000144CC1150 028 C1 E3 08 shl ebx, 8
# .text2:0000000144CC1153 028 09 9F 88 01 00 00 or [rdi+188h], ebx
# 0F BA B7 ?? ?? ?? 00 ?? btr dword ptr [rdi+188h], 8
# 83 E3 01 and ebx, 1
# C1 E3 ?? shl ebx, 8
# 09 9F ?? ?? ?? 00 or [rdi+188h], ebx
#
#
#
# 0F BA B7 ?? ?? ?? 00 ?? 83 ?? 01 C1 ?? ?? 09 9F ?? ?? ?? 00
def make_sig_from_comb(_chunks, addresses, ripRelAsQuad=False, replValues=None):
def addReplValue(_replValue):
if isinstance(replValues, list):
replValues.append(_replValue)
_pe = idautils.peutils_t()
_base = _pe.imagebase
procSet = set([o_far, o_near, o_mem, o_phrase])
newchunks = []
chunks = list()
chunks.extend(_chunks.lower())
chunks.reverse()
for ea, octets in addresses:
chunk = chunks.pop()
mnem = IdaGetMnem(ea)
op0 = idc.get_operand_type(ea, 0)
op1 = idc.get_operand_type(ea, 1)
opSet = set([op0, op1])
# ['o_mem', 2, 'Direct Memory Reference (DATA)', 'addr'],
# ['o_phrase', 3, 'Memory Ref [Base Reg + Index Reg]', 'phrase'],
# ['o_far', 6, 'Immediate Far Address (CODE)', 'addr'],
# ['o_near', 7, 'Immediate Near Address (CODE)', 'addr'],
# dprint("[debug] ea, chunks, opSet.isdisjoint(procSet)")
if debug: print("[debug] ea:{:x}, chunks:{}, opSet.isdisjoint(procSet):{}".format(ea, chunks, opSet.isdisjoint(procSet)))
changed = 0
if not opSet.isdisjoint(procSet):
opNum = -1
for i in range(2):
if idc.get_operand_type(ea, i) in procSet:
opNum = i
if opNum > -1:
_opValue = GetOperandValue(ea, opNum)
_insnEnd = ea + GetInsnLen(ea)
_tmp1 = str("{:08x}".format((_opValue - _insnEnd) & 0xffffffff))
_tmp2 = [''.join(y) for y in [x for x in chunk_tuple(_tmp1, 2)]]
_tmp2.reverse()
_ripRelHex = ' '.join(_tmp2)
_insnHex = ' '.join(["{:02x}".format(idc.get_wide_byte(ea + a)) for a in range(GetInsnLen(ea))])
_offsetChars = _insnHex.find(_ripRelHex)
# dprint("[debug] _ripRelHex, _insnHex, _offsetChars")
if debug: print("[debug] _ripRelHex:{}, _insnHex:{}, _offsetChars:{}".format(_ripRelHex, _insnHex, _offsetChars))
if ~_offsetChars:
_offsetBytes = div3(_offsetChars)
_replValue = "{:08x}".format(_opValue - _base)
if ripRelAsQuad:
_insn = idautils.DecodeInstruction(ea)
if _insn.itype in (idaapi.NN_jmp, idaapi.NN_jmpfi, idaapi.NN_jmpni, idaapi.NN_jmpshort) or \
_insn.itype in (idaapi.NN_ja, idaapi.NN_jae, idaapi.NN_jb, idaapi.NN_jbe, idaapi.NN_jc, idaapi.NN_jcxz,
idaapi.NN_jecxz, idaapi.NN_jrcxz, idaapi.NN_je, idaapi.NN_jg, idaapi.NN_jge, idaapi.NN_jl, idaapi.NN_jle,
idaapi.NN_jna, idaapi.NN_jnae, idaapi.NN_jnb, idaapi.NN_jnbe, idaapi.NN_jnc, idaapi.NN_jne, idaapi.NN_jng,
idaapi.NN_jnge, idaapi.NN_jnl, idaapi.NN_jnle, idaapi.NN_jno, idaapi.NN_jnp, idaapi.NN_jns, idaapi.NN_jnz,
idaapi.NN_jo, idaapi.NN_jp, idaapi.NN_jpe, idaapi.NN_jpo, idaapi.NN_js, idaapi.NN_jz) or \
_insn.itype in (idaapi.NN_call, idaapi.NN_callfi, idaapi.NN_callni):
if IsFuncHead(_opValue) and HasUserName(_opValue) and not ~idc.get_func_name(_opValue).find('___') and not ~idc.get_func_name(_opValue).find('::_0x'):
_replValue = "@{}".format(TagRemoveSubstring(idc.get_func_name(_opValue)))
elif (IsSameChunk(ea, _opValue)):
_replValue = "+{:x}".format(_opValue - ea).replace("+-", "-")
elif (IsSameFunc(ea, _opValue)):
_replValue = "~{:08x}".format(_opValue - _base)
elif _insn.itype in (idaapi.NN_lea, idaapi.NN_mov):
if idc.get_name(_opValue).startswith('??_7'):
_replValue = idc.get_name(_opValue, GN_DEMANGLED).replace('const ', '').replace('`', '').replace("'", '')
addReplValue(_replValue)
elif idc.get_name(_opValue).startswith('a'):
# st = idc.get_strlit_contents(_opValue, 256, idc.STRTYPE_C)
st = mb(_opValue).str()
if st and re.match(asBytes(r"""[-_a-zA-Z0-9./,'"]+$"""), st):
_replValue = "'{}'".format(asString(st).replace("'", "\\'").replace('"', '\\"'))
addReplValue(_replValue)
elif HasUserName(idc.get_item_head(_opValue)):
_replValue = "[{}]".format(TagRemoveSubstring(idc.get_name(idc.get_item_head(_opValue))))
addReplValue(_replValue)
chunk = "{}{}{}".format(_insnHex[0:_offsetChars], _replValue, _insnHex[_offsetChars+11:])
changed = 1
else:
chunk = "{}?? ?? ?? ??{}".format(_insnHex[0:_offsetChars], _insnHex[_offsetChars+11:])
changed = 1
# mov rax, [rcx+0E8h] ; o_reg, o_displ
if changed or (set([o_reg, o_displ]) <= opset):
pass
elif mnem == 'test': # octets == 7 and chunk[0:5] == '48 f7':
print("Testing letting test go without wildcards: {}".format(idc.GetDisasm(ea)))
pass
elif octets == 7 and chunk[0:5] == 'c7 43':
pass
elif octets == 6 and chunk[0:2] == '41':
pass
# 48 81 ec 80 00 00 00 sub rsp, 80h
elif octets == 7 and chunk[0:5] == '48 81':
pass
elif octets == 7 and chunk[0:5] == '80 a1':
pass
elif octets == 7 and chunk[0:5] == '81 a1':
pass
elif octets == 7 and chunk[0:5] == '83 a1':
pass
elif (mnem == 'cmp' or mnem == 'mov') and idc.get_operand_type(ea, 0) == o_reg and idc.get_operand_type(ea,
1) == o_imm:
print("Testing letting cmp/mov o_reg, o_imm go without wildcards: {}".format(idc.GetDisasm(ea)))
pass
elif octets == 7 and (mnem == 'cmp' or mnem == 'mov') and idc.get_operand_type(ea, 1) == o_imm:
# chunk = '80 3D 64 C2 D1 01 00'
# ch = chunk.split(' ')
# l = len(ch)
# new = (ch[0:l-1-4] + ['??'] * 4 + [ch[l-1]])
# chunk = " ".join(new)
# # chunk = re.sub(r'(.*) ((?:[0-9A-F]{2} ){4})([0-9A-F]{2})$', r'\1 ?? ?? ?? ?? \3', chunk)
chunk = chunk[0:5] + ' ??' * 4 + chunk[17:]
# '80 3D ?? ?? ?? ?? 00'
elif octets == 5:
if chunk[0] == 'e' and chunk[1] in ['8', '9']:
chunk = chunk[0:2] + ' ??' * 4
elif octets == 6:
# 38 05 F5 65 C9 01 cmp cs:_bIsOnline, al
# 8B 15 AE BF 17 01 mov edx, cs:dword_141BA9DB8
# 8B 1D 9C D0 AD 00 mov ebx, cs:seconds_60
if (chunk[0] == '3' and chunk[1] in ['8', '9']) or (chunk[0:2] == '8b'):
chunk = chunk[0:5] + ' ??' * 4
# 0F 85 0B 01 00 00 jnz loc_1401BF0BF
if chunk[0:4] == '0f 8':
# leave jumps that are less that 0xff bytes forward
if chunk[9:] != '00 00 00':
chunk = chunk[0:5] + ' ??' * 4
elif mnem == 'mov':
chunk = chunk[0:5] + ' ??' * 4
elif idc.get_operand_type(ea, 0) == o_mem and idc.get_operand_type(ea, 1) != o_imm:
chunk = chunk[0:5] + ' ??' * 4
# F6 81 C0 DF 03 00 04 test byte ptr [rcx+3DFC0h], 4
elif octets == 7 and chunk[0:2] == 'f6':
pass
elif octets == 8:
# 48 83 25 28 6E 5F 01 00 and cs:null_1427EB5E0, 0
if chunk[0:5] == '48 83':
# chunk[9:21] = ' ??' * 4
chunk = chunk[0:8] + ' ??' * 4 + chunk[20:23]
elif octets == 10:
chunk = chunk[0:5] + ' ??' * 8
elif octets > 6:
chunk = chunk[0:len(chunk) - (4 * 3)] + ' ??' * 4
newchunks.append(chunk)
globals()['lastSig'] = newchunks
return newchunks
# def sig_subs(ea=None, sig='', offset=0, filter=None):
# sent = set()
# if ea is None:
# ea = idc.get_screen_ea()
# ea = GetFuncStart(ea)
# results = []
# for (startea, endea) in Chunks(ea):
# for head in Heads(startea, endea):
# d = de(head)
# if d and isinstance(d, list):
# d = d[0]
# if d.mnemonic in ('JMP', 'CALL') and d.usedRegistersMask == 0:
# sub = d.operands[0].value
# if HasUserName(sub):
# name = idc.get_name(sub)
# if filter and not filter(sub, name):
# continue
# if name.startswith('?'):
# continue
# if sub not in sent:
# sent.add(sub)
# if sig:
# print(sig_protectscan(sig, head - ea + 1 + offset, 4, sig_type_fn(sub), idc.get_name(sub), func=1))
# results.append( \
# { 'ea': sub,
# 'name': TagRemoveSubstring(idc.get_name(sub)),
# 'path': [('offset', head - ea + 1 + offset), ('is_mnem', IdaGetMnem(head)), ('rip', 4), ('name', TagRemoveSubstring(idc.get_name(sub))), ('type', MyGetType(sub))],
# 'sub' : True,
# 'type': MyGetType(sub) })
# return results
def sig_globals(ea=None, sig='', sig_offset=0, fullFuncTypes=False):
sent = set()
if ea is None:
ea = idc.get_screen_ea()
results = []
ea = GetFuncStart(ea)
# ProtectScan("48 83 fb 1f").add(-204)
m = re.match(r"""Protect\w+\("([^"]+)"\)\.add\((-?\d+)\)""", sig)
if m:
sig_offset = int(m.group(2))
sig = m.group(1)
for (startea, endea) in Chunks(ea):
for instruction_start in Heads(startea, endea):
instruction_offset = instruction_start - ea
d = idii(instruction_start)
cs_arg = string_between('cs:', '', d) or string_between('g_', '', d, inclusive=1)
s = ida_lines.generate_disasm_line(instruction_start, 1)
# print(s)
# ' \x01 \x05lea\x02\x05 \x01 ) \x01 !rcx\x02!\x02) \x01 \t,\x02\t \x01 * \x01 \x06 \x01 (0000000141EE6738qword_141EE6738\x02\x06\x02*'
# ' \x01 \x05mov\x02\x05 \x01 ) \x01 !cs\x02! \x01 \t:\x02\t \x01 \x06 \x01 (0000000141EE6758dword_141EE6758\x02\x06\x02) \x01 \t,\x02\t \x01 * \x01 !ecx\x02!\x02*'
# \x01\x06 - generated name
# \x01\x07 - user defined name
# \x01* _ (prefaced) - offset
# \x01*\x01%\x01(0000000141501AECSYSTEM__WAIT\x02%\x02*'
m = re.search(r'((?:\x01.)*)\x01(?:\x07|%)\x01\(([0-9A-F]{16})(\w+)\x02(?:\x07|%)', s)
if m:
# pp(m.groups())
m_prefix, m_loc, m_name = m.groups()
found = 0
global_name = m_name
global_address = idc.get_name_ea_simple(global_name)
if global_address not in sent:
if global_address == BADADDR:
global_name = get_name_by_any(eax(m_loc.lstrip('0')))
global_address = idc.get_name_ea_simple(global_name)
if global_address == BADADDR:
print("'{}' == BADADDR".format(global_name, global_address))
instruction_length = IdaGetInsnLen(instruction_start)
for offset in range(instruction_length - 4, 0, -1):
a = MakeSigned(idc.get_wide_dword(instruction_start + offset),
32) + instruction_start + instruction_length
if a == global_address:
global_offset = global_address - ea
# print(" %% Found reference at offset(%i).rip(%i) of instruction offset(%i) of %s" % (offset, instruction_length - offset, instruction_offset, idc.get_func_name(ea)))
_offset = sig_offset + instruction_offset + offset
_rip = instruction_length - offset
_type = str(MyGetType(global_address))
if isinstance(_type, str):
if fullFuncTypes:
_type = _type.replace("__fastcall", "(*)").replace("__stdcall", "(*)").replace("None", "void*").replace("(*)", "(*) func")
else:
_type = _type.replace("__fastcall", "(*)").replace("__stdcall", "(*)").replace("None", "void*")
# dprint("[sig_globals] _type")
if debug: print("[sig_globals] _type:{} fullFuncTypes:{}".format(_type, fullFuncTypes))
sent.add(global_address)
if debug: print(
sig_protectscan(sig, _offset, _rip,
_type, idc.get_name(global_address), func=IsFuncHead(global_address), fullFuncTypes=fullFuncTypes))
found += 1
results.append( \
{ 'ea': global_address,
'name': global_name,
'path': [('offset', _offset),
('is_mnem', IdaGetMnem(instruction_start)),
('rip', _rip),
('name', global_name),
('type', MyGetType(global_address))],
'sub' : IsFuncHead(global_address),
'type': _type })
# pattern = sig_maker_ex(GetFuncStart(global_address), GetFuncEnd(global_address), offset = global_offset + offset, rip = instruction_length - offset, quick = 1) #, type = MyGetType(global_address))
if not found:
print(" %% Couldn't find solution for {} self {}".format(global_name, hex(global_address)))
return results
def make_sig(chunks, start, ripRelAsQuad=False, replValues=None):
def addReplValue(_replValue):
if isinstance(replValues, list):
replValues.append(_replValue)
_pe = idautils.peutils_t()
_base = _pe.imagebase
newchunks = []
procSet = set([o_far, o_near, o_mem, o_phrase])
for chunk in chunks:
chunk = chunk.lower()
octets = div3(len(chunk))
mnem = IdaGetMnem(start)
op0 = idc.get_operand_type(start, 0)
op1 = idc.get_operand_type(start, 1)
opSet = set([op0, op1])
# ['o_mem', 2, 'Direct Memory Reference (DATA)', 'addr'],
# ['o_phrase', 3, 'Memory Ref [Base Reg + Index Reg]', 'phrase'],
# ['o_far', 6, 'Immediate Far Address (CODE)', 'addr'],
# ['o_near', 7, 'Immediate Near Address (CODE)', 'addr'],
# dprint("[debug] start, chunks, opSet.isdisjoint(procSet)")
if debug: print("[debug] start:{:x}, chunks:{}, opSet.isdisjoint(procSet):{}".format(start, chunks, opSet.isdisjoint(procSet)))
changed = 0
if not opSet.isdisjoint(procSet):
opNum = -1
for i in range(2):
if idc.get_operand_type(start, i) in procSet:
opNum = i
if opNum > -1:
_opValue = GetOperandValue(start, opNum)
_insnEnd = start + GetInsnLen(start)
_tmp1 = str("{:08x}".format((_opValue - _insnEnd) & 0xffffffff))
_tmp2 = [''.join(y) for y in [x for x in chunk_tuple(_tmp1, 2)]]
_tmp2.reverse()
_ripRelHex = ' '.join(_tmp2)
_insnHex = ' '.join(["{:02x}".format(idc.get_wide_byte(start + a)) for a in range(GetInsnLen(start))])
_offsetChars = _insnHex.find(_ripRelHex)
if debug: print("[debug] _ripRelHex:{}, _insnHex:{}, _offsetChars:{}".format(_ripRelHex, _insnHex, _offsetChars))
if ~_offsetChars:
_offsetBytes = div3(_offsetChars)
_replValue = "{:08x}".format(_opValue - _base)
if ripRelAsQuad:
_insn = idautils.DecodeInstruction(start)
if _insn.itype in (idaapi.NN_jmp, idaapi.NN_jmpfi, idaapi.NN_jmpni, idaapi.NN_jmpshort) or \
_insn.itype in (idaapi.NN_ja, idaapi.NN_jae, idaapi.NN_jb, idaapi.NN_jbe, idaapi.NN_jc, idaapi.NN_jcxz,
idaapi.NN_jecxz, idaapi.NN_jrcxz, idaapi.NN_je, idaapi.NN_jg, idaapi.NN_jge, idaapi.NN_jl, idaapi.NN_jle,
idaapi.NN_jna, idaapi.NN_jnae, idaapi.NN_jnb, idaapi.NN_jnbe, idaapi.NN_jnc, idaapi.NN_jne, idaapi.NN_jng,
idaapi.NN_jnge, idaapi.NN_jnl, idaapi.NN_jnle, idaapi.NN_jno, idaapi.NN_jnp, idaapi.NN_jns, idaapi.NN_jnz,
idaapi.NN_jo, idaapi.NN_jp, idaapi.NN_jpe, idaapi.NN_jpo, idaapi.NN_js, idaapi.NN_jz) or \
_insn.itype in (idaapi.NN_call, idaapi.NN_callfi, idaapi.NN_callni):
if IsFuncHead(_opValue) and HasUserName(_opValue) and not ~idc.get_func_name(_opValue).find('___') and not ~idc.get_func_name(_opValue).find('::_0x'):
_replValue = "[{}]".format(TagRemoveSubstring(idc.get_func_name(_opValue)))
elif (IsSameChunk(start, _opValue)):
_replValue = "+{:x}".format(_opValue - start).replace("+-", "-")
elif (IsSameFunc(start, _opValue)):
_replValue = "~{:08x}".format(_opValue - _base)
elif _insn.itype in (idaapi.NN_lea, idaapi.NN_mov):
if idc.get_name(_opValue).startswith('??_7'):
_replValue = idc.get_name(_opValue, GN_DEMANGLED).replace('const ', '').replace('`', '').replace("'", '')
addReplValue(_replValue)
elif idc.get_name(_opValue).startswith('a'):
# st = idc.get_strlit_contents(_opValue, 256, idc.STRTYPE_C)
st = mb(_opValue).str()
if st and re.match(asBytes(r"""[-_a-zA-Z0-9./,'"]+$"""), st):
_replValue = "'{}'".format(asString(st).replace("'", "\\'").replace('"', '\\"'))
addReplValue(_replValue)
chunk = "{}{}{}".format(_insnHex[0:_offsetChars], _replValue, _insnHex[_offsetChars+11:])
changed = 1
else:
chunk = "{}?? ?? ?? ??{}".format(_insnHex[0:_offsetChars], _insnHex[_offsetChars+11:])
changed = 1
# mov rax, [rcx+0E8h] ; o_reg, o_displ
if changed or (set([o_reg, o_displ]) <= opSet):
pass
elif mnem == 'test':
pass
elif octets == 7 and chunk[0:5] == '48 f7':
pass
elif octets == 7 and chunk[0:5] == 'c7 43':
pass
elif octets == 6 and chunk[0:2] == '41':
pass
# 48 81 EC 80 00 00 00 sub rsp, 80h
elif octets == 7 and chunk[0:5] == '48 81':
pass
elif octets == 7 and chunk[0:5] == '80 A1':
pass
elif octets == 7 and chunk[0:5] == '81 A1':
pass
elif octets == 7 and chunk[0:5] == '83 A1':
pass
elif (mnem == 'cmp' or mnem == 'mov') and idc.get_operand_type(start, 0) == o_reg and idc.get_operand_type(
start, 1) == o_imm:
if debug: print("Testing letting cmp/mov o_reg, o_imm go without wildcards: {}".format(idc.GetDisasm(start)))
pass
elif octets == 7 and (mnem == 'cmp' or mnem == 'mov') and idc.get_operand_type(start, 1) == o_imm:
# chunk = '80 3D 64 C2 D1 01 00'
# ch = chunk.split(' ')
# l = len(ch)
# new = (ch[0:l-1-4] + ['??'] * 4 + [ch[l-1]])
# chunk = " ".join(new)
# # chunk = re.sub(r'(.*) ((?:[0-9A-F]{2} ){4})([0-9A-F]{2})$', r'\1 ?? ?? ?? ?? \3', chunk)
chunk = chunk[0:5] + ' ??' * 4 + chunk[17:]
# '80 3D ?? ?? ?? ?? 00'
elif octets == 5:
if chunk[0] == 'e' and chunk[1] in ['8', '9']:
chunk = chunk[0:2] + ' ??' * 4
elif octets == 6:
# 38 05 F5 65 C9 01 cmp cs:_bIsOnline, al
# 8B 15 AE BF 17 01 mov edx, cs:dword_141BA9DB8
# 8B 1D 9C D0 AD 00 mov ebx, cs:seconds_60
if (chunk[0] == '3' and chunk[1] in ['8', '9']) or (chunk[0:2] == '8b'):
chunk = chunk[0:5] + ' ??' * 4
# 0F 85 0B 01 00 00 jnz loc_1401BF0BF
if chunk[0:4] == '0f 8':
# leave jumps that are less that 0xff bytes forward
if chunk[9:] != '00 00 00':
chunk = chunk[0:5] + ' ??' * 4
elif mnem == 'mov':
chunk = chunk[0:5] + ' ??' * 4
elif idc.get_operand_type(start, 0) == o_mem and idc.get_operand_type(start, 1) != o_imm:
chunk = chunk[0:5] + ' ??' * 4
# F6 81 C0 DF 03 00 04 test byte ptr [rcx+3DFC0h], 4
elif octets == 7 and chunk[0:2] == 'f6':
pass
elif octets == 8:
# 48 83 25 28 6E 5F 01 00 and cs:null_1427EB5E0, 0
if chunk[0:5] == '48 83':
# chunk[9:21] = ' ??' * 4
chunk = chunk[0:8] + ' ??' * 4 + chunk[20:23]
elif octets == 10:
chunk = chunk[0:5] + ' ??' * 8
elif octets > 6:
chunk = chunk[0:len(chunk) - (4 * 3)] + ' ??' * 4
newchunks.append(chunk)
start += octets
globals()['lastSig'] = newchunks
return newchunks
def sig_maker_chunked(ea=None):
print("\n".join(make_sig(get_bytes_chunked(), ea or idc.SelStart())))
def sig_protectscan(pattern, add=0, rip=-1, type_="void*", name=None, rtg=True, func=False, fullFuncTypes=False):
if add:
while pattern[0:3] == "?? " and len(pattern):
pattern = pattern[3:]
add -= 1
if 0:
# seems slow
while hotkey_find_pattern(pattern[3:]) == 1 and len(pattern):
pattern = pattern[3:]
add -= 1
name_append = ''
if 0:
if name:
name_append = '.name("{}")'.format(name)
if add > 99 or add < 99:
add_string = hex(add).replace('0x-', '-0x')
else:
add_string = add
result = "ProtectScan(\"%s\").add(%i)" % (pattern, add)
if rip > -1 or type_ != "void*":
result = "ProtectScan(\"%s\").add(%s).rip(%i).type(%s)%s" % (pattern, add_string, rip, type_, name_append)
if rtg:
if func:
result = "static auto %s = ProtectScan(\"%s\").add(%s).rip(%i).as<%s>();" % (
name, pattern, add_string, rip, type_)
else:
result = "static auto& %s = ProtectScan(\"%s\").add(%s).rip(%i).as<%s&>();" % (
name, pattern, add_string, rip, type_)
result = result.replace('.add(0)', '')
result = result.replace('.rip(-1)', '')
result = result.replace('.as<None>("None")', '')
# dprint("[sig_protectscan] result")
print("[sig_protectscan] result:{}".format(result))
return result
def sig_maker_data(ea=None, wrt=None):
patterns = []
start = time.time()
try:
if type(ea) is str:
ea = idc.get_name_ea_simple(ea)
elif ea is None:
ea = EA()
f = idc.get_full_flags(ea)
if idc.is_data(f) or idc.is_code(f):
if idc.is_data(f):
print(" %% isData")
else:
print(" %% isCode")
if not ida_bytes.hasRef(f):
print(" %% no references to data type")
return None
print(" %% ida_bytes.hasRef")
found = 0
lastFunc = BADADDR
for ref in [x for x in idautils.XrefsTo(ea, flags=0) if
get_segm_name(x.frm) == '.text' and IsFunc_(x.frm) and not IsChunked(x.frm)]:
if (time.time() - start) > 60:
break
if wrt and found == 0:
ref.frm = wrt
found = 1
if found > 5:
break
print(" %% examining xref 0x%x - %s" % (ref.frm, GetFunctionName(ref.frm)))
# {'to': 5415931184L, 'type': 1L, 'user': 0L, 'frm': 5391113029L, 'iscode': 0L}
if ref.iscode == 0 or ref.iscode == 1:
frm = ref.frm
f = idc.get_full_flags(frm)
if IsFunc_(frm) and GetNumChunks(frm) == 1: # and HasUserName(GetFuncStart(frm)):
if frm != lastFunc:
lastFunc = frm
else:
print(" %% same as lastFunc")
continue
print(" %% isfunc and is not chunked: 0x{:x}".format(frm), GetFunctionName(frm))
inslen = IdaGetInsnLen(frm)
for offset in range(inslen - 4, 0, -1):
if MakeSigned(idc.get_wide_dword(frm + offset), 32) + frm + inslen == ea:
insOffset = frm - GetFuncStart(frm)
print(" %% Found reference at offset %i (%i) of instruction offset %i of %s" % (
offset, inslen - offset, insOffset, idc.get_func_name(frm)))
pattern = sig_maker_ex(GetFuncStart(frm), GetFuncEnd(frm), offset=insOffset + offset,
rip=inslen - offset, quick=1) # , type = MyGetType(ea))
if isinstance(pattern, str) and len(pattern) > 0 and len(pattern) < 128:
patterns.append(pattern)
print("%x: %s" % (ea, pattern))
found += 1
break
else:
print(" %% couldn't get unique pattern for function")
deCode
else:
print("MakeSigned: 0x{:x}, ea: 0x{:x}".format(
MakeSigned(idc.get_wide_dword(frm + offset), 32) + frm + inslen, ea))
else:
if not IsFunc_(frm):
print(" %% incompatible function (not function)")
# elif not HasUserName(GetFuncStart(frm)):
# print(" %% incompatible function (not named)")
elif GetNumChunks(frm) != 1:
print(" %% incompatible function (%i chunks)" % GetNumChunks(frm))
else:
print(" %% incompatible function (unknown reason)")
else:
print(ref.__dict__)
except KeyboardInterrupt:
print("W: interrupt received, stopping")
raise Exception('Keyboard');
return patterns
def chunk_list(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
def chunk_tuple(it, size):
"""Yield successive n-sized tuples from lst."""
it = iter(it)
return iter(lambda: tuple(islice(it, size)), ())