-
Notifications
You must be signed in to change notification settings - Fork 92
/
funcap.py
1973 lines (1607 loc) · 72.2 KB
/
funcap.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
'''
Created on Nov 21, 2012
Python 3 and IDA 7 port on Sep 9, 2022
@author: [email protected]
@contributors: Bartol0 @ github
@version: 0.91
FunCap. A script to capture function calls during a debug session in IDA.
It is created to help quickly importing some runtime data into static IDA database to boost static analysis.
Was meant to be multi-modular but seems IDA does not like scripts broken in several files/modules.
So we got one fat script file atm.
'''
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
## BUGS:
# - need to cancel "Analyze Area" if it takes too long - code analysis problem in IDA ?
#
## TODO LIST:
# - better call and ret association: build a call tree for each thread instead of current stack pointer-based hashing (this turns out not reliable).
# - function call capture using tracing (thinking here about PIN as only this one is fast enough).
# We will probably have to calculate the destination jump address instead of using single stepping - it will be much more stable
# - instead of simple arg frame size calculation (get_num_args_stack()) + argument primitive type guessing (string, int),
# we need to read in function prototypes guessed by IDA (or even HexRays decompiler plugin...) and match arguments to them
# maybe it could be possible by getting some info from underlying debugger symbols via WinDbg/GDB, IDA pro static arg list analysis
# - some database interface for collected data + UI plugin in IDA - so that right click on a function call in IDA will show
# the table with links to different captures for that particular call. This would be really cool.
# - amd64 stack-based arguments are not always well captured
# IDA imports
from __future__ import absolute_import
from __future__ import print_function
#import sys
import pickle
from idaapi import *
from idautils import *
from ida_kernwin import *
from ida_entry import *
from idc import *
from ida_bytes import *
from ida_funcs import *
from ida_dbg import *
import ida_idd
from six.moves import range
# utility functions
def format_name(ea):
name = get_func_name(ea)
if name == "" or name == None:
name = "0x%x" % ea
return name
def format_offset(ea):
offset = get_func_off_str(ea)
if offset == "" or offset == None:
offset = "0x%x" % ea
return offset
def get_arch():
'''
Get the target architecture.
Supported archs: x86 32-bit, x86 64-bit, ARM 32-bit
'''
(arch, bits) = (None, None)
for x in dbg_get_registers():
name = x[0]
if name == 'RAX':
arch = 'amd64'
bits = 64
break
elif name == 'EAX':
arch = 'x86'
bits = 32
break
elif name == 'R0':
arch = 'arm'
bits = 32
break
return (arch, bits)
class FunCapHook(DBG_Hooks):
'''
Main class to implementing DBG_Hooks
'''
## CONSTANTS
# minimum length requirement to be ascii
STRING_EXPLORATION_MIN_LENGTH = 4
# length of discovered strings outputted to file and console
STRING_LENGTH = 164
# length of the same strings inserted in IDA code
STRING_LENGTH_IN_COMMENTS = 82
# length of single-line hexdumps in hexdump mode outputted to file and console
HEXMODE_LENGTH = 164
# length of the same hexdumps inserted in IDA code
HEXMODE_LENGTH_IN_COMMENTS = 82
# visited functions will be tagged as follows
FUNC_COLOR = 0xF7CBEA
#FUNC_COLOR = 0xF7A0A0
# visited items (except call instructions) will be tagged as follows
ITEM_COLOR = 0x70E01B
# calls will be tagged as follows
CALL_COLOR = 0x99CCCC
#CALL_COLOR = 0xB1A0F7
# maximum comment lines inserted after/before call instructions
CMT_MAX = 5
def __init__(self, **kwargs):
'''
@param outfile: log file where the output dump will be written (default: %USERPROFILE%\funcap.txt)
@param delete_breakpoints: delete a breakpoint after first pass ? (default: yes)
@param hexdump: include hexdump instead of ascii in outfile and IDA comments ? (default: no)
@param comments: add IDA comments ? (default: yes)
@param resume: resume program after hitting a breakpoint ? (default: yes)
@param depth: current stack depth capture for non-function hits (default: 0)
@param colors: mark the passage with colors ? (default: yes)
@param output_console: print everything to the console ? (default: yes)
@param overwrite_existing: overwrite existing capture comment in IDA when the same function is called ? (default: no)
@param recursive: when breaking on a call - are we recursively hooking all call instructions in the new function ? (default: no)
@param code_discovery: enable discovery of a dynamically created code - for obfuscators and stuff like that (default: no)
@param code_discovery_nojmp: don't hook jumps in code_discovery mode (default: no)
@param code_discovery_stop: stop if new code section is discovered (default: no)
@param no_dll: disable API calls capturing (default: no)
@param strings_file: file containing strings dump on captured function arguments (default: %USERPROFILE%\funcap_strings.txt)
@param multiple_dereferences: dereference each pointer resursively ? (default: 3 levels, 0 - off)
'''
self.outfile = kwargs.get('outfile', os.path.expanduser('~') + "/funcap.txt")
self.delete_breakpoints = kwargs.get('delete_breakpoints', True)
self.hexdump = kwargs.get('hexdump', False)
self.comments = kwargs.get('comments', True)
self.resume = kwargs.get('resume', True)
self.depth = kwargs.get('depth', 0)
self.colors = kwargs.get('colors', True)
self.output_console = kwargs.get('output_console', True)
self.overwrite_existing = kwargs.get('overwrite_existing', False)
self.recursive = kwargs.get('recursive', False)
self.code_discovery = kwargs.get('code_discovery', False) # for obfuscators
self.code_discovery_nojmp = kwargs.get('code_discovery_nojmp', False)
self.code_discovery_stop = kwargs.get('code_discovery_stop', False)
self.no_dll = kwargs.get('no_dll', False)
self.strings_file = kwargs.get('strings', os.path.expanduser('~') + "/funcap_strings.txt")
self.multiple_dereferences = kwargs.get('multiple_dereferences', 3)
self.visited = [] # functions visited already
self.saved_contexts = {} # saved stack contexts - to re-dereference arguments when the function exits
self.function_calls = {} # recorded function calls - used for several purposes
self.stop_points = [] # brekpoints where FunCap will pause the process to let user start the analysis
self.calls_graph = {} # graph nodes prepared for call graphs
self.hooked = [] # functions that were already hooked
self.stub_steps = 0
self.stub_name = None
self.current_caller = None # for single step - before-call context
self.delayed_caller = None # needed in case where single step lands on breakpoint (brekpoint fires first - which is bad...)
DBG_Hooks.__init__(self)
self.out = None
self.strings_out = None
###
# This a is public interface
# Switches are to be set manually - too lazy to implement setters and getters
# I started to implement GUI as well but it did not work as expected so it won't be implemented...
###
def on(self):
'''
Turn the script on
'''
if self.outfile:
self.out = open(self.outfile, 'w')
if self.strings_file:
self.strings_out = open(self.strings_file, 'w')
self.hook()
print("FunCap is ON")
def off(self):
'''
Turn the script off
'''
if self.out != None:
self.out.close()
if self.strings_out != None:
self.strings_out.close()
self.unhook()
print("FunCap is OFF")
def addFuncStart(self):
'''
Add breakpoints on all function starts
'''
for f in list(Functions()):
add_bpt(f)
def addFuncRet(self):
'''
Add breakpoints on all return from subroutine instructions
'''
for seg_ea in Segments():
# For each of the defined elements
for head in Heads(seg_ea, get_segm_end(seg_ea)):
# If it's an instruction
if is_code(get_full_flags(head)):
if self.is_ret(head):
add_bpt(head)
def addCallee(self):
'''
Add breakpoints on both function starts and return instructions
'''
self.addFuncStart()
self.addFuncRet()
def hookFunc(self, jump = False, func = ""):
'''
Add breakpoints on call instructions within a function
@param jump: if True, jump instructions will also be hooked in addition to calls - used in code discovery mode
@param func: this should be a function name. If null, the function that UI cursor points to will be processed
'''
if func:
ea = get_name_ea_simple(func)
else:
ea = get_screen_ea()
func = get_func_name(ea)
self.output("hooking function: %s()" % func)
chunks = Chunks(ea)
for (start_ea, end_ea) in chunks:
if jump:
self.add_call_and_jump_bp(start_ea, end_ea)
else:
self.add_call_bp(start_ea, end_ea)
self.hooked.append(func)
def hookSeg(self, seg = "", jump = False):
'''
Add breakpoints on call instructions within a given segment
@param jump: if True, jump instructions will also be hooked in addition to calls - used in code discovery mode
@param seg: this should be a segment name. If null, the segment that UI cursor points to will be processed
'''
if seg:
ea = None
for s in Segments():
if seg == get_segm_name(s):
ea = s
break
if ea == None:
self.output("WARNING: cannot hook segment %s" % seg)
return
else:
ea = get_screen_ea()
seg = get_segm_name(ea)
self.output("hooking segment: %s" % seg)
start_ea = get_segm_start(ea)
end_ea = get_segm_end(ea)
if jump:
self.add_call_and_jump_bp(start_ea, end_ea)
else:
self.add_call_bp(start_ea, end_ea)
def addCJ(self, func = ""):
'''
Hook all call and jump instructions
@param func: name of the function to hook
'''
self.hookFunc(jump = True, func = func)
def delAll(self):
'''
Delete all breakpoints
'''
for bp in range(get_bpt_qty(), 0, -1):
del_bpt(get_bpt_ea(bp))
def graph(self, exact_offsets = False):
'''
Draw the graph
@param exact_offsets: if enabled each function call with offset(e.g. function+0x12) will be treated as graph node
if disabled, only function name will be presented as node (more regular graph but less precise information)
'''
CallGraph("FunCap: function calls", self.calls_graph, exact_offsets).Show()
def saveGraph(self, path = os.path.expanduser('~') + "/funcap.graph"):
pickle.dump(d.calls_graph, open(path, "w"))
def loadGraph(self, path = os.path.expanduser('~') + "/funcap.graph"):
d.calls_graph = pickle.load(open(path, "r"))
def addStop(self, ea):
'''
Add a stop point - the script will pause the process when this is reached
@param ea: address of the new stop point to add
'''
self.stop_points.append(ea)
add_bpt(ea)
###
# END of public interface
###
def add_call_bp(self, start_ea, end_ea):
'''
Add breakpoints on every subrountine call instruction within the given scope (start_ea, end_ea)
@param start_ea:
@param end_ea:
'''
for head in Heads(start_ea, end_ea):
# If it's an instruction
if is_code(get_full_flags(head)):
if self.is_call(head):
add_bpt(head)
def add_call_and_jump_bp(self, start_ea, end_ea):
'''
Add breakpoints on every subrountine call instruction and jump instruction within the given scope (start_ea, end_ea)
@param start_ea:
@param end_ea:
'''
for head in Heads(start_ea, end_ea):
# If it's an instruction
if is_code(get_full_flags(head)):
if (self.is_call(head) or self.is_jump(head)):
add_bpt(head)
def get_num_args_stack(self, addr):
'''
Get the size of arguments frame
@param addr: address belonging to a function
'''
argFrameSize = get_struc_size(get_func_attr(addr, FUNCATTR_FRAME)) - get_frame_size(addr) + get_func_attr(addr, FUNCATTR_ARGSIZE)
return argFrameSize / (self.bits/8)
def get_caller(self):
return self.prev_ins(self.return_address())
def format_caller(self, ret):
return format_offset(ret) + " (0x%x)" % ret
def getRegValueFromCtx(self, name, context):
'''
Extract the value of a single register from the saved context
@param name: name of the register to extract
@param context: saved execution context
'''
for reg in context:
if reg['name'] == name:
return reg['value']
def add_comments(self, ea, lines, every = False):
'''
Insert lines (posterior and anterior lines which are referred to as "comments" in this code) into IDA assembly listing
@param ea: address where to insert the comments
@param lines: array of strings to be inserted as multiple lines using ExtLinA()
@param every: if set to True, the maximum number of lines per address (self.CMT_MAX) will not be respected
'''
idx = 0
for line in lines:
# workaround with Eval() - ExtLinA() doesn't work well in idapython
line_sanitized = line.replace('"', '\\"')
ret = eval_idc('ExtLinA(%d, %d, "%s");' % (ea, idx, line_sanitized))
if ret:
self.output("idc.eval_idc() returned an error: %s" % ret)
idx += 1
if every == False and idx > self.CMT_MAX: break
def format_normal(self, regs):
'''
Returns two lists of formatted values and derefs of registers, one for console/file dump, and another for IDA comments (tha latter is less complete)
Used for everything besides calling and returning from function.
@param regs: dictionary returned by get_context()
'''
full_ctx = []
cmt_ctx = []
if self.bits == 32:
format_string = "%3s: 0x%08x"
format_string_append = " -> 0x%08x"
getword = read_dbg_dword
else:
format_string = "%3s: 0x%016x"
format_string_append = " -> 0x%016x"
getword = read_dbg_qword
memval = None
next_memval = None
prev_memval = None
valchain_full = ""
valchain_cmt = ""
for reg in regs:
valchain_full = format_string % (reg['name'], reg['value'])
valchain_cmt = format_string % (reg['name'], reg['value'])
prev_memval = reg['value']
if prev_memval != None:
memval=getword(reg['value'])
if memval != None:
next_memval = getword(memval)
else:
next_memval = None
else:
memval = None
next_memval = None
if (self.multiple_dereferences):
maxdepth = self.multiple_dereferences
while (next_memval): #memval is a proper pointer
if (maxdepth == 0):
break
maxdepth-=1
if (prev_memval == memval):#points at itself
break
valchain_full += format_string_append % memval
valchain_cmt += format_string_append % memval
prev_memval = memval
memval = next_memval
next_memval = getword(memval)
function_name=get_func_off_str(prev_memval)#no more dereferencing. is this a function ?
if (function_name):
valchain_full += " (%s)" % function_name
valchain_cmt += " (%s)" % function_name
else: #no, dump data
if (self.hexdump):
valchain_full_left = (self.HEXMODE_LENGTH - len(valchain_full) - 1) / 4
valchain_cmt_left = (self.HEXMODE_LENGTH_IN_COMMENTS - len(valchain_cmt) - 1) / 4
format_string_dump = " (%s)"
else:
valchain_full_left = self.STRING_LENGTH - len(valchain_full)
valchain_cmt_left = self.STRING_LENGTH_IN_COMMENTS - len(valchain_cmt)
format_string_dump = " (\"%s\")"
if (valchain_full_left <4): valchain_full_left = 4 #allways dump at least 4 bytes
if (valchain_cmt_left <4): valchain_cmt_left = 4 #allways dump at least 4 bytes
valchain_full += format_string_dump % self.smart_format(self.dereference(prev_memval,2 * valchain_full_left), valchain_full_left)
valchain_cmt += format_string_dump % self.smart_format_cmt(self.dereference(prev_memval,2 * valchain_cmt_left),valchain_cmt_left)
full_ctx.append(valchain_full)
cmt_ctx.append(valchain_cmt)
return (full_ctx, cmt_ctx)
def format_call(self, regs):
'''
Returns two lists of formatted values and derefs of registers, one for console/file dump, and another for IDA comments
Used when calling a function.
@param regs: dictionary returned by get_context()
'''
full_ctx = []
cmt_ctx = []
if self.bits == 32:
format_string_full = "%3s: 0x%08x"
format_string_cmt = " %3s: 0x%08x"
format_string_append = " -> 0x%08x"
getword = read_dbg_dword
else:
format_string_full = "%3s: 0x%016x"
format_string_cmt = " %3s: 0x%016x"
format_string_append = " -> 0x%016x"
getword = read_dbg_qword
memval = None
next_memval = None
prev_memval = None
valchain_full = ""
valchain_cmt = ""
for reg in regs:
valchain_full = format_string_full % (reg['name'], reg['value'])
valchain_cmt = format_string_cmt % (reg['name'], reg['value'])
prev_memval = reg['value']
if prev_memval != None:
memval = getword(reg['value'])
if memval != None:
next_memval = getword(memval)
else:
next_memval = None
else:
memval = None
next_memval = None
if (self.multiple_dereferences):
maxdepth = self.multiple_dereferences
while (next_memval): #memval is a proper pointer
if (maxdepth == 0):
break
maxdepth-=1
if (prev_memval == memval):#points at itself
break
valchain_full += format_string_append % memval
valchain_cmt += format_string_append % memval
prev_memval = memval
memval = next_memval
next_memval = getword(memval)
function_name=get_func_off_str(prev_memval)#no more dereferencing. is this a function ?
if (function_name):
valchain_full += " (%s)" % function_name
valchain_cmt += " (%s)" % function_name
else: #no, dump data
if (self.hexdump):
valchain_full_left = (self.HEXMODE_LENGTH - len(valchain_full) - 1) / 4
valchain_cmt_left = (self.HEXMODE_LENGTH_IN_COMMENTS - len(valchain_cmt) - 1) / 4
format_string_dump = " (%s)"
else:
valchain_full_left = self.STRING_LENGTH - len(valchain_full)
valchain_cmt_left = self.STRING_LENGTH_IN_COMMENTS - len(valchain_cmt)
format_string_dump = " (\"%s\")"
if (valchain_full_left <4): valchain_full_left = 4 #allways dump at least 4 bytes
if (valchain_cmt_left <4): valchain_cmt_left = 4 #allways dump at least 4 bytes
valchain_full += format_string_dump % self.smart_format(self.dereference(prev_memval,2 * valchain_full_left), valchain_full_left)
valchain_cmt += format_string_dump % self.smart_format_cmt(self.dereference(prev_memval,2 * valchain_cmt_left),valchain_cmt_left)
full_ctx.append(valchain_full)
if any(regex.match(reg['name']) for regex in self.CMT_CALL_CTX):
cmt_ctx.append(valchain_cmt)
return (full_ctx, cmt_ctx)
def format_return(self, regs, saved_regs):
'''
Returns two lists of formatted values and derefs of registers, one for console/file dump, and another for IDA comments
Used when returning from function.
@param regs: dictionary returned by get_context()
@param saved_regs: dictionary in the format returned by get_context()
'''
full_ctx = []
cmt_ctx = []
if self.bits == 32:
format_string_append = " -> 0x%08x"
format_string_full = "%3s: 0x%08x"
format_string_cmt = " %3s: 0x%08x"
format_string_full_s = "s_%3s: 0x%08x"
format_string_cmt_s = " s_%3s: 0x%08x"
getword = read_dbg_dword
else:
format_string_full = "%3s: 0x%016x"
format_string_cmt = " %3s: 0x%016x"
format_string_full_s = "s_%3s: 0x%016x"
format_string_cmt_s = " s_%3s: 0x%016x"
format_string_append = " -> 0x%016x"
getword = read_dbg_qword
memval = None
next_memval = None
prev_memval = None
valchain_full = ""
valchain_cmt = ""
for reg in regs:
valchain_full = format_string_full % (reg['name'], reg['value'])
valchain_cmt = format_string_cmt % (reg['name'], reg['value'])
prev_memval = reg['value']
if prev_memval != None:
memval = getword(reg['value'])
if memval != None:
next_memval = getword(memval)
else:
next_memval = None
else:
memval = None
next_memval = None
if (self.multiple_dereferences):
maxdepth = self.multiple_dereferences
while (next_memval): #memval is a proper pointer
if (maxdepth == 0):
break
maxdepth-=1
if (prev_memval == memval):#points at itself
break
valchain_full += format_string_append % memval
valchain_cmt += format_string_append % memval
prev_memval = memval
memval = next_memval
next_memval = getword(memval)
function_name=get_func_off_str(prev_memval)#no more dereferencing. is this a function ?
if (function_name):
valchain_full += " (%s)" % function_name
valchain_cmt += " (%s)" % function_name
else: #no, dump data
if (self.hexdump):
valchain_full_left = (self.HEXMODE_LENGTH - len(valchain_full) - 1) / 4
valchain_cmt_left = (self.HEXMODE_LENGTH_IN_COMMENTS - len(valchain_cmt) - 1) / 4
format_string_dump = " (%s)"
else:
valchain_full_left = self.STRING_LENGTH - len(valchain_full)
valchain_cmt_left = self.STRING_LENGTH_IN_COMMENTS - len(valchain_cmt)
format_string_dump = " (\"%s\")"
if (valchain_full_left <4): valchain_full_left = 4 #allways dump at least 4 bytes
if (valchain_cmt_left <4): valchain_cmt_left = 4 #allways dump at least 4 bytes
valchain_full += format_string_dump % self.smart_format(self.dereference(prev_memval,2 * valchain_full_left), valchain_full_left)
valchain_cmt += format_string_dump % self.smart_format_cmt(self.dereference(prev_memval,2 * valchain_cmt_left),valchain_cmt_left)
full_ctx.append(valchain_full)
if any(regex.match(reg['name']) for regex in self.CMT_RET_CTX):
cmt_ctx.append(valchain_cmt)
if saved_regs:
for reg in saved_regs:
if any(regex.match(reg['name']) for regex in self.CMT_RET_SAVED_CTX):
valchain_full = format_string_full_s % (reg['name'], reg['value'])
valchain_cmt = format_string_cmt_s % (reg['name'], reg['value'])
prev_memval = reg['value']
if prev_memval != None:
memval = getword(reg['value'])
if memval != None:
next_memval = getword(memval)
else:
next_memval = None
else:
memval = None
next_memval = None
if (self.multiple_dereferences):
maxdepth = self.multiple_dereferences
while (next_memval): #memval is a proper pointer
if (maxdepth == 0):
break
if (prev_memval == memval):#points at itself
break
maxdepth-=1
valchain_full += format_string_append % memval
valchain_cmt += format_string_append % memval
prev_memval = memval
memval = next_memval
next_memval = getword(memval)
function_name=get_func_off_str(prev_memval)#no more dereferencing. is this a function ?
if (function_name):
valchain_full += " (%s)" % function_name
valchain_cmt += " (%s)" % function_name
else: #no, dump data
if (self.hexdump):
valchain_full_left = (self.HEXMODE_LENGTH - len(valchain_full) - 1) / 4
valchain_cmt_left = (self.HEXMODE_LENGTH_IN_COMMENTS - len(valchain_cmt) - 1) / 4
format_string_dump = " (%s)"
else:
valchain_full_left = self.STRING_LENGTH - len(valchain_full)
valchain_cmt_left = self.STRING_LENGTH_IN_COMMENTS - len(valchain_cmt)
format_string_dump = " (\"%s\")"
if (valchain_full_left <4): valchain_full_left = 4 #allways dump at least 4 bytes
if (valchain_cmt_left <4): valchain_cmt_left = 4 #allways dump at least 4 bytes
valchain_full += format_string_dump % self.smart_format(self.dereference(prev_memval,2 * valchain_full_left), valchain_full_left)
valchain_cmt += format_string_dump % self.smart_format_cmt(self.dereference(prev_memval,2 * valchain_cmt_left),valchain_cmt_left)
full_ctx.append(valchain_full)
cmt_ctx.append(valchain_cmt)
return (full_ctx, cmt_ctx)
def output(self, line):
'''
Standard "print" function used across the whole script
@param line: line to print
'''
if self.outfile:
self.out.write(line + "\n")
if self.output_console:
print(line)
if self.outfile:
self.out.flush()
def output_lines(self, lines):
'''
This prints a list, line by line
@param lines: lines to print
'''
for line in lines:
if self.outfile:
self.out.write(line + "\n")
if self.output_console:
print(line)
if self.outfile:
self.out.flush()
# the following few functions are adopted from PaiMei by Pedram Amini
# they are here to format and present data in a nice way
def get_ascii_string (self, data):
'''
Retrieve the ASCII string, if any, from data. Ensure that the string is valid by checking against the minimum
length requirement defined in self.STRING_EXPLORATION_MIN_LENGTH.
@type data: Raw
@param data: Data to explore for printable ascii string
@rtype: String
@return: False on failure, ascii string on discovered string.
'''
discovered = ""
for char in data:
# if we've hit a non printable char, break
if char < 32 or char > 126:
break
discovered += chr(char)
if len(discovered) < self.STRING_EXPLORATION_MIN_LENGTH:
return False
return discovered
def get_printable_string (self, data, print_dots=True):
'''
description
@type data: Raw
@param data: Data to explore for printable ascii string
@type print_dots: Bool
@param print_dots: (Optional, def:True) Controls suppression of dot in place of non-printable
@rtype: String
@return: False on failure, discovered printable chars in string otherwise.
'''
discovered = ""
for char in data:
if char >= 32 and char <= 126:
discovered += chr(char)
elif print_dots:
discovered += "."
return discovered
def get_unicode_string (self, data):
'''
description
@type data: Raw
@param data: Data to explore for printable unicode string
@rtype: String
@return: False on failure, ascii-converted unicode string on discovered string.
'''
### we need better function to find real unicode stuff, not ascii in unicode only
discovered = ""
every_other = True
for char in data:
if every_other:
# if we've hit a non printable char, break
if char < 32 or char > 126:
break
discovered += chr(char)
every_other = not every_other
if len(discovered) < self.STRING_EXPLORATION_MIN_LENGTH:
return False
return discovered
def hex_dump(self, data):
'''
Utility function that converts data into one-line hex dump format.
@type data: Raw Bytes
@param data: Raw bytes to view in hex dump
@rtype: String
@return: Hex dump of data.
'''
dump = ""
for byte in data:
dump += "%02x " % ord(byte)
for byte in data:
if byte >= 32 and byte <= 126:
dump += chr(byte)
else:
dump += "."
return dump
def dereference(self, address, size):
return ida_idd.dbg_read_memory(address, size)
def smart_format(self, raw_data, maxlen, print_dots=True):
'''
"Intelligently" discover data behind an address. The address is dereferenced and explored in search of an ASCII
or Unicode string. In the absense of a string the printable characters are returned with non-printables
represented as dots (.). The location of the discovered data is returned as well as either "heap", "stack" or
the name of the module it lies in (global data).
@param raw_data: Binary data to format
@type print_dots: Bool
@param print_dots: (Optional, def:True) Controls suppression of dot in place of non-printable
@rtype: String
@return: String of data discovered behind dereference.
'''
if not raw_data:
return 'N/A'
try_unicode = raw_data[:maxlen * 2]
try_ascii = raw_data[:maxlen]
data = raw_data[:maxlen]
to_strings_file = None
data_string = self.get_ascii_string(try_ascii)
to_strings_file = data_string
if not data_string:
data_string = self.get_unicode_string(try_unicode)
to_strings_file = data_string
if not data_string and self.hexdump:
data_string = self.hex_dump(data)
if not data_string:
data_string = self.get_printable_string(data, print_dots)
# shouldn't have been here but the idea of string dumping came out to me later on
# TODO: re-implement. We could also take much longer strings
if self.strings_file:
# that seems not to work very well
#self.strings_out.write(self.get_printable_string(raw_data, False) + "\n")
if not to_strings_file:
to_strings_file = self.get_printable_string(raw_data, False)
self.strings_out.write(to_strings_file + "\n")
self.strings_out.flush()
return data_string
def smart_format_cmt(self, raw_data, maxlen, print_dots=True):
'''
Same as smart_format() but for IDA comments
'''
if not raw_data:
return 'N/A'
try_unicode = raw_data[:maxlen * 2]
try_ascii = raw_data[:maxlen]
data = raw_data[:maxlen]
data_string = self.get_ascii_string(try_ascii)
if not data_string:
data_string = self.get_unicode_string(try_unicode)
if not data_string and self.hexdump:
data_string = self.hex_dump(data)
if not data_string:
data_string = self.get_printable_string(data, print_dots)
return repr(data_string).strip("'")
def next_ins(self, ea):
'''
Return next instruction to ea
'''
end = get_inf_structure().get_maxEA()
return next_head(ea, end)
def prev_ins(self, ea):
'''
Return previous instruction to ea
'''
start = get_inf_structure().get_minEA()
return idc.prev_head(ea, start)
# handlers called from within debug hooks
def handle_function_end(self, ea):
'''
Called when breakpoint hit on ret instruction
'''
function_name = get_func_name(ea)
caller = self.format_caller(self.get_caller())
if function_name:
header = "At function end: %s (0x%x) " % (function_name,ea) + "to " + caller
raw_context = self.get_context(ea=ea)
else:
header = "At function end - unknown function (0x%x) " % ea + "to " + caller
raw_context = self.get_context(ea=ea, depth=0)
if self.colors:
set_color(ea, CIC_ITEM, self.ITEM_COLOR)
(context_full, context_comments) = self.format_normal(raw_context)
if self.delete_breakpoints:
del_bpt(ea)
if self.comments and (self.overwrite_existing or ea not in self.visited):
self.add_comments(ea, context_comments, every = True)
self.visited.append(ea)
self.output_lines([ header ] + context_full + [ "" ])
def handle_return(self, ea):
'''
Called when breakpoint hit on next-to-call instruction
'''
# need to get context from within a called function
function_call = self.function_calls[ea]
ret_shift = function_call['ret_shift']
raw_context = self.get_context()
#raw_context = self.get_context(stack_offset = 0 - ret_shift, depth=function_call['num_args'] - ret_shift) # no stack here ?
sp = self.get_sp()
sp = sp - ret_shift
if sp in self.saved_contexts:
saved_context = self.saved_contexts[sp]['ctx']
func_name = self.saved_contexts[sp]['func_name']
del self.saved_contexts[sp]
else:
func_name = function_call['func_name']
self.output("WARNING: saved context not found for stack pointer 0x%x, assuming function %s" % (sp, function_call['func_name']))
saved_context = None