-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.py
2324 lines (1981 loc) · 78.1 KB
/
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
# &.update_file(__file__)
import idautils
import inspect
import collections
import json
import os
import idc
# import circularlist
from static_vars import *
from attrdict1 import SimpleAttrDict
# import pydot.src.pydot
from exectools import make_refresh
refresh_helpers = make_refresh(os.path.abspath(__file__))
"""
Some shortcut functions for CLI work in IDA via the Python REPL
See: help2()
"""
# import sfcommon
def helpers():
print("""
EA() short for idc.get_screen_ea (return current address)
pos() return/show position in hex with label name
down() move down one line
up() move up one line
next() trace backwards one instruction
prev() trace forwards one instruction
""")
def _A(o):
if o is None:
return []
if isinstance(o, list):
return o
if isflattenable(o) and len(list(o)) > 1:
return list(o)
if isflattenable(o):
return genAsList(o)
# list(o) will break up strings
return [o]
EA_circular = CircularList(64)
def EA():
ea = idc.get_screen_ea()
EA_circular.append(ea)
return ea
def EAhist():
for ea in EA_circular:
print("{:x} {}".format(ea, idc.get_name(ea)))
def F(ea = idc.get_screen_ea()):
return idc.get_full_flags(ea)
def pos(ea = idc.get_screen_ea()):
if type(ea) is tuple:
ea = eval(ea[0])
# print("type(ea): {0}, ea: {1}".format(type(ea), ea))
name = NameEx(ea, ea) # Will return '' if none
return ("0x%012x" % ea, name)
def traversalFactory(*args):
def traversalFn(ea = None):
if ea is None:
ea = idc.get_screen_ea()
targets = [x for x in [x(ea) for x in args] if x != idc.BADADDR]
for target in targets:
if not IsCode_(target):
forceCode(target)
idc.jumpto(target)
target = ea
nextAny = fn1(ea)
nextHead = fn2(ea)
if nextAny != nextHead:
# The means that the next instruction is data
print(("fn1: {0} fn2: {1}".format(nextAny, nextHead)))
else:
target = nextHead
Jump(target)
return pos(target)
return "%x" % target
return traversalFn
up = traversalFactory(idc.prev_not_tail, idc.prev_head)
down = traversalFactory(lambda x: GetTarget(x, flow=1, calls=0, conditionals=0), lambda x: x + idc.get_item_size(x), idc.next_not_tail, idc.next_head)
# Normal
# FF_CODE 0x00000600 0x00000600 Code
# FF_FLOW 0x00010000 0x00010000 Exec flow from up instruction
# FF_IMMD 0x40000000 0x40000000 Has Immediate value
# MS_VAL 0x000000ff 0x00000000 Stack variable
# o_displ phrase+addr Op1 0x30 [[rbp+30h]] Memory Reg [Base Reg + Index Reg + Displacement]
# o_reg reg Op2 0x1 [rcx] General Register (al,ax,es,ds...)
# First Instruction
# FF_CODE 0x00000600 0x00000600 Code
# FF_REF 0x00001000 0x00001000 has references
# FF_LABL 0x00008000 0x00008000 Has dummy name
# FF_IMMD 0x40000000 0x40000000 Has Immediate value
# FF_1STK 0x0f000000 0x0b000000 Stack variable
# MS_VAL 0x000000ff 0x0b000000 Stack variable
# o_reg reg Op1 0x5 [rbp] General Register (al,ax,es,ds...)
# o_displ phrase+addr Op2 0x20 [[rsp+20h]] Memory Reg [Base Reg + Index Reg + Displacement]
def hasAnyName(F): # becuase idc.hasName() in idc.py 6.8 is broken
return idc.hasName(F) or (F & idc.FF_LABL)
def makeFunctionFromInstruction(ea=None):
"""
makeFunctionFromInstruction
@param ea: linear address
"""
ea = eax(ea)
inslen = idaapi.decode_insn(ea)
if not inslen:
print("makeFunctionFromInstruction: couldn't decode instruction at {:x}".format(ea))
return False
return idc.add_func(ea, ea + inslen)
def myassert(condition, message):
if not condition:
print("%s" % (message))
def PrevGap(ea=None):
ea = eax(ea)
gap = ea - prev_func(ea) # + InsnLen(idc.prev_head(ea))
if gap > 256:
return 256
return gap
def MakePrevHeadSuggestions(ea=None):
ea = eax(ea)
gap = PrevGap(ea)
if gap > 0:
for start in range(ea - gap, ea):
yield start, diida(start, ea, returnLength=1)
def PrevMakeHead(ea=None):
ea = eax(ea)
if not IsCode_(idc.prev_not_tail(ea)) and not IsCode_(idc.next_not_tail(ea)):
tmp = next_code(ea)
if IsCode_(idc.next_not_tail(tmp)):
ea = tmp
next_code_ea = next_code(ea)
unlikely = ['db'] + _unlikely_mnems()
suggestions = [x for x in MakePrevHeadSuggestions(ea)]
count = 0
for start, _suggestion in suggestions:
length, suggestion, *a = _suggestion
if a:
# dprint("[PrevMakeHead] _suggestion")
print("[PrevMakeHead] _suggestion: {}".format(_suggestion))
raise RuntimeError('suggestion')
# print("Suggestion {:#x}:\n{}".format(start, indent(4, suggestion)))
failed = False
end = start + length
if end != ea and end != next_code_ea:
if debug: print(" bad end: {:x} {}".format(end, suggestion))
continue
for mnem in unlikely:
if re.match(r'\b' + re.escape(mnem) + '\b', suggestion):
if debug: print(" rejected unlikely: {}".format(suggestion))
failed = True
break
if failed:
continue
if count == 0:
if debug: print(" Easing code {:x} - {:x}".format(start, ea))
new_start = start
while new_start < ea:
new_start = EaseCode(start, ea, forceStart=True)
if new_start == start:
if debug: print(" Got stuck at {:#x}".format(start))
return
start = new_start
if debug: print("huh... happy?")
return
count += 1
# dprint("[PrevMakeHead] count")
print("[PrevMakeHead] count: {}".format(count))
if count == 0:
print("trying this")
EaseCode(ida_bytes.prev_that(ea, 0, isRef), forceStart=1)
def smartTraversalFactory(fn1, direction = -1):
def next(ea = None, noJump = False):
if ea is None:
ea = idc.get_screen_ea()
target = fn1(ea)
idc.create_insn(ea)
idc.create_insn(target)
flags = F(ea)
if direction < 0: # backwards
if not idc.is_flow(flags) and not idc.isRef(flags) and PrevGap(ea) > 0:
PrevMakeHead(ea)
return ea
if not idc.is_flow(flags) or idc.isRef(flags): # we must^H^H^H^Hmight have jumped here
myassert(hasAnyName(flags), "No name flag")
myassert(idc.isRef(flags), "No ref flag")
# refs = list(idautils.CodeRefsTo(ea, flow = 0))
# assert len(refs) == 1, "More than 1 CodeRefTo: how to follow?"
# target = refs[0]
# codeRefs = set(idautils.CodeRefsTo(ea, 1))
# jmpRefs = set(idautils.CodeRefsTo(ea, 0))
# dataRefs = set(idautils.DataRefsTo(ea))
# flowRefs = codeRefs - jmpRefs
# xrefRefs = jmpRefs | dataRefs
refs = AllRefsTo(ea)
callCount = len(refs['callRefs'])
jumpCount = len(refs['jmpRefs'])
codeCount = callCount + jumpCount
dataCount = len(refs['dataRefs'])
flowCount = len(refs['flowRefs'])
xrefCount = len(refs['nonFlowRefs'])
targetList = _.filter(list(refs['jmpRefs']) + list(refs['dataRefs']), lambda x, *a: idc.get_item_size(x) > 2)
if not targetList:
targetList = _.filter(list(refs['jmpRefs']), lambda x, *a: idc.get_item_size(x) > 1)
myassert(len(targetList) > 0, "Not enough refs")
# if not targetList: return
# targetList = _.filter(targetList, lambda x, *a: not IsSameFunc(x, ea))
targetList2 = []
targetList2.extend(_.filter(targetList, lambda x, *a: isCall(x)))
targetList2.extend(_.filter(targetList, lambda x, *a: isJmp(x)))
targetList2.extend(_.filter(targetList, lambda x, *a: IsCode_(x)))
targetList2.extend([x for x in targetList if x not in targetList2])
targetList2 = _.flatten(targetList2)
# if not targetList2:
targetList2.extend(refs['callRefs'])
if debug:
# dprint("[next] targetList2")
print("[next] targetList2:{}".format(targetList2))
targetList2 = _.uniq(targetList2)
while targetList2:
target = targetList2.pop(0)
if targetList2:
# we still have alternatives
if is_same_func(ea, target): continue
if max([0] + [is_same_func(ea, _ea) for _ea in xrefs_to(target)]):
continue
# skip dead-end jumps
if IsFlow(target) or IsRef(target):
break
elif direction > 0: # forwards
loop = 0
while loop < 10:
loop += 1
fnName = GetFunctionName(ea)
fnStart = LocByName(fnName)
fnEnd = FindFuncEnd(ea)
instruction = IdaGetMnem(ea)
instructionStart = ItemHead(ea)
instructionSize = idaapi.get_item_size(instructionStart)
instructionEnd = instructionStart + instructionSize
nextInsn = ea + instructionSize
nextHead = next_head(ea)
nextAny = NextNotTail(ea)
hitFnEnd = nextAny == fnEnd
allRefs = set(idautils.CodeRefsFrom(EA(), 1))
jmpRefs = set(idautils.CodeRefsFrom(EA(), 0))
flowRefs = allRefs - jmpRefs
# Method 1
if len(flowRefs) == 1 and hitFnEnd:
# Expand Function
idc.set_func_end(ea, idc.next_not_tail(fnEnd))
Wait()
continue
# Method 2
if fnName and instructionEnd == fnEnd and idc.is_flow(F(nextHead)):
# Extend the function end to match flow
SetFunctionEnd(fnStart, NextNotTail(nextHead))
Wait()
continue
if len(jmpRefs) == 1 and len(flowRefs) == 0:
if instruction != 'jmp':
raise AdvanceFailure("flow inconsistency, instruction: '%s'" % instruction)
if len(jmpRefs) == 2:
if not re.match(r"^(call|ja|jae|jb|jbe|jc|jcxz|je|jecxz|jg|jge|jl|jle|jna|jnae|jnb|jnbe|jnc|jne|jng|jnge|jnl|jnle|jno|jnp|jns|jnz|jo|jp|jpe|jpo|jrcxz|js)$", instruction):
raise AdvanceFailure("unknown condition jump or call: %s" % instruction)
if len(allRefs) == 0 and nextHead != nextAny:
innerLoop = 0
while innerLoop < 10 and len(set(idautils.CodeRefsFrom(EA(), 1))) == 0 and nextHead != nextAny:
# The next bit of non-instruction surely must actually be
# an instruction
innerLoop += 1
nextHead = next_head(ea)
nextAny = NextNotTail(ea)
if nextHead == nextAny:
break
MyMakeUnknown(nextAny, NextNotTail(nextAny) - nextAny, 0)
Wait()
MakeCodeAndWait(nextAny)
continue
continue
####
mnem = IdaGetMnem(ea)
flow = 1
numRefs = -1
if mnem == 'call':
flow = 0
if mnem == 'jmp':
loop = 0
while loop < 10:
loop += 1
refs = list(idautils.CodeRefsFrom(ea, flow))
numRefs = len(refs)
if numRefs == 1:
break
inslen = idaapi.decode_insn(ea)
AnalyseArea(ea, ea + inslen)
if numRefs == 1 and refs[0] != target:
target = refs[0]
# Check if there was more than one way here
refs = list(idautils.CodeRefsTo(target, flow = 0)) # Or should we use flow=1 and include any name.group(0)
numRefs = len(refs)
line = ""
if numRefs > 1:
line += ("There were %i xrefs to this location. " % numRefs)
if idc.is_flow(F(target)):
line += "Instruction flow from previous instruction. "
if line:
print(line)
elif numRefs > 1:
raise AdvanceFailure("Multiple ways to go from here")
if not noJump:
Jump(target)
idc.set_color(target, CIC_ITEM, 0xffffffff & colorsys_rgb_to_dword(lighten(int_to_rgb(color_here(target)))))
return pos(target)
return target
return next
prev = smartTraversalFactory(idc.prev_head, -1)
nextFn = smartTraversalFactory(idc.next_head, 1)
def _next():
try:
nextFn()
except AdvanceFailure as e:
print("AdvanceFailure: %s" % e)
def alpha(byte):
if byte > 0x40 and byte < 0x5b:
return True
if byte > 0x60 and byte < 0x7b:
return True
return False
strings = set()
def autoStringBlocks(ea = idc.get_screen_ea()):
skipped = 0
counter = 0
while alpha(Byte(ea)) or skipped < 1000:
valid = alpha(Byte(ea)) and Byte(ea-1) == 0
if not valid:
skipped = skipped + 1
else:
skipped = 0
MakeStr(ea, BADADDR)
counter = counter + 1
strings.add(GetString(ea))
ea = ea + 0x10
print("Count: %i" % counter)
def autoMakeQwords(ea = idc.get_screen_ea, count = -1):
plausibleStart = idaapi.cvar.inf.min_ea
plausibleEnd = idaapi.cvar.inf.maxEA
if count > 0:
end = ea + 8 * count
else:
end = plausibleEnd
while ea < end:
if idc.is_unknown(F(ea)):
# print("0x%0x: unknown" % ea)
qword = Qword(ea)
# print("0x%0x: qword: 0x%0x" % (ea, qword))
if ea % 8 or ((qword < plausibleStart or qword > plausibleEnd) and qword != 0):
MakeQword(ea)
pass
else:
MakeQword(ea)
else:
print("0x%0x: not unknown, exiting" % ea)
Jump(ea)
return
ea += 8
def makeQwords(ea = idc.get_screen_ea(), count = 1):
end = ea + 8 * count
while ea < end:
if not idc.is_code(F(ea)):
# qword = Qword(ea)
MakeQword(ea)
ea += 8
Jump(ea)
def colorPopularFunctions():
k = Kolor()
for ea in idautils.Functions():
crefs = list(idautils.CodeRefsTo(ea, 0))
drefs = list(idautils.DataRefsTo(ea))
refCount = len(crefs) + len(drefs)
if (refCount > 1):
c = Commenter(ea, repeatable = 0)
c.comments = filter(lambda x: "TEST" not in x, c.comments)
c.commit()
c = Commenter(ea, repeatable = 1)
if len(crefs):
c.add("[TEST] %i code refs" % len(crefs))
if len(drefs):
c.add("[TEST] %i data refs" % len(drefs))
if (refCount > 10):
# idaapi.set_item_color(ea, k.get(refCount))
SetColor(ea, CIC_FUNC, k.get(refCount))
SetColor(ea, CIC_ITEM, DEFCOLOR)
for ref in (crefs + drefs):
SetColor(ref, CIC_ITEM, k.get(refCount))
else:
# idaapi.del_item_color(ea)
SetColor(ea, CIC_FUNC, DEFCOLOR)
SetColor(ea, CIC_ITEM, DEFCOLOR)
for ref in (crefs + drefs):
SetColor(ref, CIC_ITEM, DEFCOLOR)
def trace_back_to_label(ea = None, fn1 = idc.prev_not_tail):
if ea is None:
ea = idc.get_screen_ea()
try:
nextEA = ea
ea = 0
while nextEA != ea:
ea = nextEA
flags = F(ea)
if not idc.is_flow(flags): break # we must have jumped here
elif hasAnyName(flags): break # stop at label
elif idc.isRef(flags): break # stop at xref in
nextEA = fn1(ea)
print("nextEA", hex(nextEA))
except:
pass
return ea
def trace_forward(ea = idc.get_screen_ea(), fn1 = idc.next_not_tail):
start = ea
try:
nextEA = ea
ea = 0
while nextEA != ea:
ea = nextEA
flags = F(ea)
if start != ea and not idc.is_flow(flags): break # we must have jumped here
elif not idc.is_head(flags): break
elif hasAnyName(flags): break # stop at label
elif idc.isRef(flags): break # stop at xref in
elif idc.is_unknown(flags): break
else: nextEA = fn1(ea)
except:
pass
return ea
def CheckCode(ea = idc.get_screen_ea()):
mnem = IdaGetMnem(ea)
if mnem in ['in', 'out']:
start = trace_back_to_label(ea)
end = trace_forward(ea)
print("0x%x: %012x - %012x: bad block" % (ea, start, end))
MyMakeUnknown(start, end - start, 1)
return end
return 0
def MakeCodeRepeatedly(ea = idc.get_screen_ea()):
start = ea
result = MakeCodeAndWait(ea)
while result:
AnalyseArea(ea, ea + result)
codeInvalid = CheckCode(ea)
if codeInvalid:
ea = codeInvalid
while ea < BADADDR:
f = F(ea)
if hasAnyName(f): break
if idc.is_code(f): break
if idc.isRef(f): break
ea = NextAddr(ea)
else:
ea += result
f = F(ea)
if idc.is_code(f): break
result = MakeCodeAndWait(ea)
return ea - start
def findbase():
header = LocByName('__ImageBase')
if (idaapi.cvar.inf.min_ea & 0xffff == 0x1000):
header = idaapi.cvar.inf.min_ea &~ 0xffff
print("Assuming that header == 0x1000 bytes before start of file, at: 0x%x" % header)
return header
if (idaapi.cvar.inf.min_ea & 0xffff == 0x0000):
header = idaapi.cvar.inf.min_ea &~ 0xffff
print("Assuming that header is at the start of file, at: 0x%x" % header)
return header
if header < BADADDR:
print("Obtained header from __ImageBase")
header = header &~ 0xffff
return header
for ref in idautils.Functions():
gst = GetSegmentAttr(ref, SEGATTR_TYPE)
# SegName(ea) == ".text"
if gst == 2:
gfn = GetFunctionName(ref)
ss = idc.get_segm_attr(ref, SEGATTR_START)
header = ss - 0x1000
print("Found function %s, segment start: 0x%x, assuming exe starts at: 0x%x" % (gfn, ss, header))
return header
break
print("unable to find header, defaulting to start of file")
header = idaapi.cvar.inf.min_ea
print("Assuming that header is at the start of file, at: 0x%x" % header)
return header
def autobase(ea, base = 0):
"""
autobase(ea)
Calculate specifed linear address, adjusting for rebased addresses
in either direction.
@param ea: linear address in rebased, offset, or original form.
@eg: autobase(ida_ida.cvar.inf.min_ea), autobase(0x7FF69E6C9D70), autobase(0x20fed3)
@notes:requires __ImageBase to be a defined label pointing to the header
of the dump, eg: HEADER:0000000140000000 __ImageBase dw 5A4Dh
(This should be automatically done by IDA, but sometimes isn't).
@see-also: asoffset, normalise
"""
imageBase = findbase()
if imageBase == BADADDR:
imageBase = findbase()
originalImageBase = Qword(imageBase + 0x1a0) # sometimes 1a8?
if originalImageBase == BADADDR:
originalImageBase = imageBase
# we have no originalImageBase, flip it around
baseDifference = imageBase - idc.MinEA()
else:
baseDifference = imageBase - originalImageBase
if base:
return ea - base + imageBase
# This probably won't work so well if you happen to have other segments loaded
imageLen = idaapi.cvar.inf.maxEA - idaapi.cvar.inf.min_ea
# for xxxx.exe+0x12345 offsets
if ea < imageLen:
return ea + imageBase
# if ea >= idaapi.cvar.inf.min_ea && ea < idaapi.cvar.inf.maxEA:
# return ea + baseDifference
# Address is inside our image, so translate it outside
if ea >= imageBase and ea < imageBase + imageLen:
return ea - baseDifference
# Address is in the range of our original image, translate to our actual image
if ea >= originalImageBase and ea < originalImageBase + imageLen:
return ea + baseDifference
def is_sequence(arg):
""" https://stackoverflow.com/questions/1835018/how-to-check-if-an-object-is-a-list-or-tuple-but-not-string/1835259#1835259
"""
return (not hasattr(arg, "strip") and
hasattr(arg, "__getitem__") or
hasattr(arg, "__iter__"))
# def overlap(r1, r2):
# start = 0
# end = 1
# """Does the range r1 overlap the range r2?"""
# return r1[end] > r2[start] and r2[end] > r1[start]
#
# def overlap2(ranges1, ranges2):
# len1 = len(A(ranges1))
# len2 = len(A(ranges2))
# i1 = 0
# i2 = 0
# loop = 0
# try:
# while i1 < len1 and i2 < len2:
# while loop or not overlap(ranges1[i1], ranges2[i2]):
# loop = 0
# if ranges1[i1+1][0] < ranges2[i2+1][0]:
# i1 += 1
# else:
# i2 += 1
# s1 = set(range(ranges1[i1][0], ranges1[i1][1]))
# s2 = set(range(ranges2[i2][0], ranges2[i2][1]))
# s = list(s1 & s2)
# yield (s[0], s[-1]+1, ranges1[i1], ranges2[i2])
#
# loop = 1
# except IndexError:
# return
#
# def overlap3(ranges1, ranges2):
# return [x for x in overlap2(ranges1, ranges2)]
def __unpatch_worker(ea):
ida_bytes.revert_byte(ea)
return 0
def unpatch(start, end = None):
if end is None:
if is_sequence(start):
try:
end = start[1]
if end is not None:
return unpatch(start[0], end)
except TypeError:
return 0
except ValueError:
return 0
end = InsnLen(start) + start
if end < start and end < ida_ida.cvar.inf.min_ea:
end = start + end
count = 0
if IsValidEA((start, end)):
while start < end:
# if start in obfu.combed: obfu.combed.clear()
# if idc.get_cmt(start, 0):
idc.set_cmt(start, '', 0)
if ida_bytes.revert_byte(start):
count += 1
start += 1
return count
print("InvalidEAs: ({}, {})".format(start, end))
# ida_bytes.visit_patched_bytes(start, end, lambda ea, fpos, org_val, patch_val:
# # print("ida_bytes.visit_patched_bytes: {}, {}, {}, {}".format(ea, fpos, org_val, patch_val))
# __unpatch_worker(ea))
def UnpatchFunc(funcea=None):
"""
UnpatchFunc
@param funcea: any address in the function
"""
funcea = eax(funcea)
func = ida_funcs.get_func(funcea)
if not func:
return 0
else:
funcea = func.start_ea
def work(funcea):
for ea1, ea2 in idautils.Chunks(funcea):
n = UnpatchUntilChunk(ea1)
if n: print("Unpatched {} bytes".format(n))
idc.auto_wait()
EaseCode(ea1, unpatch=1, noExcept=1)
n = unpatch(ea1, ea2)
if n: print("Unpatched {} bytes".format(n))
n = UnpatchUntilChunk(ea1)
if n: print("Unpatched {} bytes".format(n))
EaseCode(ea1, unpatch=1, noExcept=1)
idc.auto_wait()
EaseCode(ea1, unpatch=1, noExcept=1)
idc.auto_wait()
EaseCode(ea1, unpatch=1, noExcept=1)
work(funcea)
ZeroFunction(funcea)
RemoveAllChunks(funcea)
try:
slowtrace2(funcea, modify=0)
except AdvanceFailure:
pass
work(funcea)
# slowtrace2(funcea, modify=0)
ZeroFunction(funcea)
RemoveAllChunks(funcea)
try:
slowtrace2(funcea, modify=0)
except AdvanceFailure:
pass
for ea1, ea2 in idautils.Chunks(funcea):
EaseCode(ea1, noExcept=1)
work(funcea)
# slowtrace2(funcea, modify=0)
ZeroFunction(funcea)
RemoveAllChunks(funcea)
try:
slowtrace2(funcea, modify=0)
except AdvanceFailure:
pass
func = ida_funcs.func_t()
func.start_ea = funcea
r = ida_funcs.find_func_bounds(func, ida_funcs.FIND_FUNC_DEFINE | ida_funcs.FIND_FUNC_IGNOREFN)
if r == ida_funcs.FIND_FUNC_OK:
print("FIND_FUNC_OK")
SetFuncStart(funcea, func.start_ea)
SetFuncEnd(funcea, func.end_ea)
EaseCode(funcea)
@static_vars(good = 0)
def color_patched_byte(ea, fpos, org_val, patch_val):
good = good + 1
p.update(good)
idc.set_color(ea, idc.CIC_ITEM, 0x280128)
def color_patches():
p = ProgressBar(count)
idaapi.visit_patched_bytes(0, idaapi.BADADDR, color_patched_byte)
def get_cmt_patch_ranges(ea=None):
"""
get_cmt_patch_ranges
@param ea: linear address
"""
if isinstance(ea, list):
return [get_cmt_patch_ranges(x) for x in ea]
ea = eax(ea)
s = [x.split('–') for x in re.findall(r'14[0-9a-f]{7}(?:–14[0-9a-f]{7})?', idc.get_cmt(ea, 0))]
h = _.map(s, lambda v, *a: _.map(v, lambda v, *a: parseHex(v)))
gr = GenericRanges([], cmp=overlaps)
for cs, *a in h:
ce = _.first(a, default=cs)
gr.add((cs, ce + 1))
return gr
patchedBytes=[]
def FindPatchedBy(pattern='Patched by: ', return_addrs=False, return_all=False):
patchedBytes=[]
def get_patch_byte(ea, fpos, org_val, patch_val):
patchedBytes.append([ea, org_val])
with BatchMode(True):
idaapi.visit_patched_bytes(0, idaapi.BADADDR, get_patch_byte)
pbs = list()
p = ProgressBar((ida_ida.cvar.inf.min_ea, ida_ida.cvar.inf.max_ea))
for ea, x in patchedBytes:
p.update(ea)
cmt = idc.get_cmt(ea, False)
if isinstance(cmt, str):
c = Commenter(ea, "line").matches(pattern)
if c:
if return_all:
pbs.append((ea, c))
if return_addrs:
pbs.append(ea)
else:
pb = [string_between(pattern, '', x) for x in c]
for x in pb:
if x not in pbs:
print(x)
pbs.append(x)
return pbs
def FindCommentedPatches():
patchedBytes=[]
def get_patch_byte(ea, fpos, org_val, patch_val):
patchedBytes.append([ea, org_val])
idaapi.visit_patched_bytes(0, idaapi.BADADDR, get_patch_byte)
idc.auto_wait()
pbs = set()
unk = set()
bad_pbs = set()
bad_unk = set()
for ea, x in patchedBytes:
if IsTail(ea):
pbs.add(idc.get_item_head(ea))
continue
if IsHead(ea):
pbs.add(ea)
continue
for ea in pbs:
if idc.get_cmt(ea, False):
bad_pbs.add(ea)
return bad_pbs
def FindPatchedAnonymousNop():
patchedBytes=[]
def get_patch_byte(ea, fpos, org_val, patch_val):
patchedBytes.append([ea, org_val])
idaapi.visit_patched_bytes(0, idaapi.BADADDR, get_patch_byte)
idc.auto_wait()
pbs = set()
unk = set()
bad_pbs = set()
bad_unk = set()
for ea, x in patchedBytes:
if IsTail(ea):
pbs.add(idc.get_item_head(ea))
continue
if IsHead(ea):
pbs.add(ea)
continue
else: # if IsUnknown(ea) or IsData(ea):
unk.add(ea)
for ea in pbs:
if isNop(ea) and not idc.get_cmt(ea, False):
bad_pbs.add(ea)
return bad_pbs, unk
def unpatch_all():
patchedBytes=[]
def get_patch_byte(ea, fpos, org_val, patch_val):
patchedBytes.append([ea, patch_val])
idaapi.visit_patched_bytes(0, idaapi.BADADDR, get_patch_byte)
count = 0
for x, y in patchedBytes:
# if idc.get_segm_name(x) == '.text2':
# break
if IsValidEA(x):
count += 1
ida_bytes.revert_byte(x)
# idaapi.patch_byte(x, y)
# return patchedBytes
def get_patches(minea=0, maxea=idc.BADADDR):
ns = Namespace()
ns.patchedBytes = defaultdict(bytearray)
ns.lastEa = None
ns.firstEa = None
def get_patch_byte(ea, fpos, org_val, patch_val):
if ns.lastEa is None or ea - ns.lastEa > 1:
ns.firstEa = ea
ns.lastEa = ea
ns.patchedBytes[ns.firstEa].append(patch_val)
idaapi.visit_patched_bytes(minea, maxea, get_patch_byte)
return ns.patchedBytes
# return pickle.dumps( ns.patchedBytes ).hex()
def get_patches_hex(minea=0, maxea=idc.BADADDR):
p = get_patches(minea, maxea)
h = dict()
for k in p.keys():
h[k] = bytes_as_hex(p[k])
return h
def get_patches_idarest():
return pickle.dumps(get_patches()).hex()
def save_patches(fn):
with open(smart_path(fn), 'wb') as handle:
pickle.dump(a, handle)
def load_patches(fn):
with open(smart_path(fn), 'rb') as handle:
b = pickle.load(handle)
def unpatch_all_count():
patchedBytes=[]
def get_patch_byte(ea, fpos, org_val, patch_val):
patchedBytes.append([ea, patch_val])
idaapi.visit_patched_bytes(0, idaapi.BADADDR, get_patch_byte)
idc.auto_wait()
patchedBytes.sort()
count = 0
for x, y in patchedBytes:
# if idc.get_segm_name(x) == '.text2':
# break
if IsValidEA(x):
count += 1
# ida_bytes.revert_byte(x)
# idaapi.patch_byte(x, y)
return count
def unpatch_all2():
patchedBytes=[]
def get_patch_byte(ea, fpos, org_val, patch_val):
patchedBytes.append([ea, patch_val])
idaapi.visit_patched_bytes(0, idaapi.BADADDR, get_patch_byte)
idc.auto_wait()
patchedBytes.sort()
count = 0
for r in GenericRanger(patchedBytes, sort=0):
unpatch(r.start, r.trend)
def GetFuncPatches(funcea=None):
"""
GetFuncPatches
@param funcea: any address in the function
"""
patchedBytes=[]
def get_patch_byte(ea, fpos, org_val, patch_val):
patchedBytes.append([ea, org_val])
if isinstance(funcea, list):
return [GetFuncPatches(x) for x in funcea]
funcea = eax(funcea)
func = ida_funcs.get_func(funcea)
if not func:
return 0
else:
funcea = func.start_ea
for start, end in idautils.Chunks(funcea):
idaapi.visit_patched_bytes(start, end, get_patch_byte)
return patchedBytes
@static_vars(patched=[])
def UnpatchPredicate(predicate):