-
Notifications
You must be signed in to change notification settings - Fork 10
/
x86_RE_lib.py
executable file
·1971 lines (1834 loc) · 62.1 KB
/
x86_RE_lib.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
import vcg_Graph, vcg_GraphLink, vcg_GraphNode, string, copy, sets
from idaapi import *
import idc
"""
This file consists of a collection of utility functions that were written during various
reverse engineering projects to facilitate the process
"""
#
# A list of mnemonics that do not overwrite the first operand:
#
neutral_mnem = [ "cmp", "test", "push" ]
assign_mnem = [ "mov", "movzx", "movsx" ]
x86_registers = [ "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp"]
#
# Utility function
#
def idaline_to_string( idaline ):
"""
Takes an IDA Pro disassembly line and removes all the formatting info
from it to make it a "regular" string.
"""
i = 0
new = ""
while i < len(idaline):
if idaline[i] == '\x01' or idaline[i] == '\x02':
i = i + 1
else:
new += idaline[i]
i = i + 1
return new
#
# A function to get the name of the basic bloc a particular ea is in
#
def get_basic_block_begin( ea ):
return get_basic_block_begin_from_ea( ea )
def get_basic_block_begin_from_ea( ea ):
"""" Get basic block upper bound
While the current instruction is not referenced from anywhere and the preceding instruction is not
referencing anywhere else, step backwards. Return the first address at which the above conditions
are no longer true.
"""
oldea = 0
while get_first_fcref_to( ea ) == BADADDR and get_first_fcref_from( get_first_cref_to( ea ) ) == BADADDR and ea != BADADDR:
oldea = ea
ea = get_first_cref_to( ea )
if ea == BADADDR:
return oldea
return ea
def get_basic_block_end( ea ):
return get_basic_block_end_from_ea( ea )
#
# A function to get the name of the basic bloc a particular ea is in
#
def get_basic_block_end_from_ea( ea ):
""" Get basic block lower bound
The same as get_basic_block_begin_from_ea(), just forwards.
"""
lastea = ea
while get_first_fcref_from( ea ) == BADADDR and ea != BADADDR and \
get_first_fcref_to( get_first_cref_from(ea) ) == BADADDR:
lastea = ea
ea = get_first_cref_from( ea )
if ea == BADADDR:
return lastea
return ea
#
#
#
VCG_COLOR_WHITE = 0
VCG_COLOR_BLUE = 1
VCG_COLOR_RED = 2
VCG_COLOR_GREEN = 3
VCG_COLOR_YELLOW = 4
VCG_COLOR_MAGENTA = 5
VCG_COLOR_CYAN = 6
VCG_COLOR_DARKGREY = 7
VCG_COLOR_DARKBLUE = 8
VCG_COLOR_DARKRED = 9
VCG_COLOR_DARKGREEN = 10
VCG_COLOR_DARKYELLOW = 11
VCG_COLOR_DARKMAGENTA = 12
VCG_COLOR_DARKCYAN = 13
VCG_COLOR_GOLD = 14
VCG_COLOR_LIGHTGREY = 15
VCG_COLOR_LIGHTBLUE = 16
VCG_COLOR_LIGHTRED = 17
VCG_COLOR_LIGHTGREEN = 18
VCG_COLOR_LIGHTYELLOW = 19
VCG_COLOR_LIGHTMAGENTA = 20
VCG_COLOR_LIGHTCYAN = 21
VCG_COLOR_LILAC = 22
VCG_COLOR_TURQUOISE = 23
VCG_COLOR_AQUAMARINE = 24
VCG_COLOR_KHAKI = 25
VCG_COLOR_PURPLE = 26
VCG_COLOR_YELLOWGREEN = 27
VCG_COLOR_PINK = 28
VCG_COLOR_ORANGE = 29
VCG_COLOR_ORCHID = 30
VCG_COLOR_BLACK = 31
colormap = [
VCG_COLOR_WHITE, # IGNORE ! Just there to make array addressing nicer !
VCG_COLOR_BLACK, # Default
VCG_COLOR_RED, # Regular comment
VCG_COLOR_LIGHTBLUE, # Repeatable comment (comment defined somewhere else)
VCG_COLOR_LIGHTBLUE, # Automatic comment
VCG_COLOR_DARKBLUE, # Instruction
VCG_COLOR_DARKGREEN, # Dummy Data Name
VCG_COLOR_DARKGREEN, # Regular Data Name
VCG_COLOR_MAGENTA, # Demangled Name
VCG_COLOR_BLUE, # Punctuation
VCG_COLOR_DARKCYAN, # Char constant in instruction
VCG_COLOR_DARKCYAN, # String constant in instruction
VCG_COLOR_DARKCYAN, # Numeric constant in instruction
VCG_COLOR_RED, # Void operand
VCG_COLOR_DARKGREY, # Code reference
VCG_COLOR_DARKGREY, # Data reference
VCG_COLOR_RED, # Code reference to tail byte
VCG_COLOR_RED, # Data reference to tail byte
VCG_COLOR_RED, # Error or problem
VCG_COLOR_DARKGREY, # Line prefix
VCG_COLOR_DARKGREY, # Binary line prefix bytes
VCG_COLOR_DARKGREY, # Extra line
VCG_COLOR_PINK, # Alternative operand
VCG_COLOR_PINK, # Hidden name
VCG_COLOR_MAGENTA, # Library function name
VCG_COLOR_GREEN, # Local variable name
VCG_COLOR_DARKGREY, # Dummy code name
VCG_COLOR_DARKBLUE, # Assembler directive
VCG_COLOR_DARKGREY, # Macro
VCG_COLOR_DARKCYAN, # String constant in data directive
VCG_COLOR_DARKCYAN, # Char constant in data directive
VCG_COLOR_DARKCYAN, # Numeric constant in data directive
VCG_COLOR_DARKBLUE, # Keywords
VCG_COLOR_LIGHTBLUE, # Register name
VCG_COLOR_MAGENTA, # Imported name
VCG_COLOR_DARKGREY, # Segment name
VCG_COLOR_DARKGREY, # Dummy unknown name
VCG_COLOR_DARKGREY, # Regular code name
VCG_COLOR_DARKGREY, # Regular unknown name
VCG_COLOR_DARKGREY, # Collapsed line
VCG_COLOR_LIGHTGREY # hidden address marks
]
def basic_block_to_pretty_vcg( blk ):
print "y1"
allblk = "\x0C22%lx:\r\n\x0Cb" % blk[0][0]
print "y2"
for line in blk:
print line
colorstack = []
idaline = generate_disasm_line( line[0] )
newline = ""
ignorenext = 0
for i in range( len(idaline)-1):
if ignorenext:
ignorenext = ignorenext - 1
continue
if idaline[i] == COLOR_ON and ord(idaline[i+1]) < len( colormap ) and ord(idaline[i+1]) < 28:
colorstack.append( idaline[i+1] )
newline = newline + "\x0C%.02d" % colormap[ ord(idaline[i+1]) ]
ignorenext = 1
elif idaline[i] == COLOR_OFF:
if len( colorstack ) == 0:
newline = newline + "\x0C%.02d" % VCG_COLOR_BLACK
else:
newline = newline + "\x0C%.02d" % colormap[ ord( colorstack.pop())]
ignorenext = 1
elif idaline[i] == '\x01':
ignorenext = 1
continue
else:
if idaline[i] != '"' and idaline[i] != '\\':
newline = newline + idaline[i]
elif idaline[i] == '"':
newline = newline + "\x0C%.03d" % ord(idaline[i])
elif idaline[i] == '\\':
newline = newline + "\\\\"
newline = newline + "\x0C%.02d\r\n" % VCG_COLOR_BLACK
allblk = allblk + newline
return allblk
#
# Retrieves a list of xrefs from a particular location
#
def get_drefs_to( ea ):
"""
Retrieves a list of locations that are referring ea (data only)
"""
ret = []
xrf = get_first_dref_to( ea )
if xrf != BADADDR:
ret.append( xrf )
xrf = get_next_dref_to( ea, xrf )
while xrf != BADADDR:
ret.append( xrf )
xrf = get_next_dref_to( ea, xrf )
return ret
def get_drefs_from( ea ):
"""
Retrieves a list of locations that are referred to from ea (data only)
"""
ret = []
xrf = get_first_dref_from( ea )
if xrf != BADADDR:
ret.append( xrf )
xrf = get_next_dref_from( ea, xrf )
while xrf != BADADDR:
ret.append( xrf )
xrf = get_next_dref_from( ea, xrf )
return ret
def get_short_crefs_from( ea ):
"""
Retrieves a list of locations that
"""
ret = []
xrf = get_first_cref_from( ea )
xrf2 = get_first_fcref_from( ea )
if xrf != BADADDR and xrf != xrf2:
ret.append( xrf )
xrf = get_next_cref_from( ea, xrf )
while xrf != BADADDR and xrf != xrf2:
ret.append( xrf )
xrf = get_next_cref_from( ea, xrf )
return ret
def get_noncall_crefs_to( ea ):
"""
Retrieve a list of locations that branch to ea
"""
ret = []
xrf = get_first_cref_to( ea )
if xrf != BADADDR:
if ua_mnem( xrf ) != "call":
ret.append( xrf )
else:
if ea not in get_far_crefs_from( xrf ):
ret.append( xrf )
xrf = get_next_cref_to( ea, xrf )
while xrf != BADADDR:
if ua_mnem( xrf ) != "call":
ret.append( xrf )
xrf = get_next_cref_to( ea, xrf )
return ret
def get_short_crefs_to( ea ):
"""
Retrieve a list of locations that refer to ea using a non-call
"""
ret = []
xrf = get_first_cref_to( ea )
xrf2 = get_first_fcref_to( ea )
if xrf != BADADDR and xrf != xrf2:
ret.append( xrf )
xrf = get_next_cref_to( ea, xrf )
while xrf != BADADDR and xrf != xrf2:
ret.append( xrf )
xrf = get_next_cref_to( ea, xrf )
return ret
def get_crefs_from( ea ):
"""
Retrieve a list of locations that ea branches to
"""
ret = []
xrf = get_first_cref_from( ea )
if xrf != BADADDR:
ret.append( xrf )
xrf = get_next_cref_from( ea, xrf )
while xrf != BADADDR:
ret.append( xrf )
xrf = get_next_cref_from( ea, xrf )
return ret
def get_crefs_to( ea ):
"""
Retrieve a list of locations that branch to ea
"""
ret = []
xrf = get_first_cref_to( ea )
if xrf != BADADDR:
ret.append( xrf )
xrf = get_next_cref_to( ea, xrf )
while xrf != BADADDR:
ret.append( xrf )
xrf = get_next_cref_to( ea, xrf )
return ret
def get_far_crefs_from( ea ):
"""
Retrieve list of locations that ea branches to
"""
ret = []
xrf = get_first_fcref_from( ea )
if xrf != BADADDR:
ret.append( xrf )
xrf = get_next_fcref_from( ea, xrf )
while xrf != BADADDR:
ret.append( xrf )
xrf = get_next_fcref_from( ea, xrf )
return ret
def get_far_crefs_to( ea ):
ret = []
xrf = get_first_fcref_to( ea )
if xrf != BADADDR:
ret.append( xrf )
xrf = get_next_fcref_to( ea, xrf )
while xrf != BADADDR:
ret.append( xrf )
xrf = get_next_fcref_to( ea, xrf )
return ret
#
# Retrieves a line of disassembled code
#
def get_disasm_line( ea ):
""" Returns a list [ int address, string mnem, string op1, string op2, string op3 ]
"""
op1 = ua_outop2( ea, 0, 0 )
op2 = ua_outop2( ea, 1, 0 )
op3 = ua_outop2( ea, 2, 0 )
if op1 == None:
op1 = ""
else:
op1 = idaline_to_string( op1 )
if op2 == None:
op2 = ""
else:
op2 = idaline_to_string( op2 )
if op3 == None:
op3 = ""
else:
op3 = idaline_to_string( op3 )
ret = [ ea, ua_mnem( ea ), op1, op2, op3 ]
return ret
#
# Retrieves a string from the IDB
#
def get_string( ea ):
str = ""
while get_byte( ea ) != 0:
str = str + "%c" % get_byte( ea )
ea = ea+1
return str
#
# Returns a string for a disasm line
#
def disasm_line_to_string( baseblock ):
str = "%lx: %s " % (baseblock[0], baseblock[1])
if baseblock[2] != "":
str = str + baseblock[2]
if baseblock[3] != "":
str = str + ", %s" % baseblock[3]
if baseblock[4] != "":
str = str + ", %s" % baseblock[4]
return str
#
# Returns all the instructions in a basic block
#
def get_basic_block( ea ):
"""
A basic block will be a list of lists that contain all the instructions
in this particular basic block.
[
[ firstaddress, mnem, op1, op2, op3 ]
...
[ lastaddress, mnem, op1, op2, op3 ]
]
"""
begin = get_basic_block_begin_from_ea( ea )
realbegin = begin
end = get_basic_block_end_from_ea( ea )
ret = []
while begin <= end and begin >= realbegin:
ret.append( get_disasm_line( begin ) )
if get_first_cref_from( begin ) <= begin:
break
begin = get_first_cref_from( begin )
return ret
def get_basic_block_from( ea ):
x = get_basic_block( ea )
blk = []
for line in x:
if line[0] >= ea:
blk.append( line )
return blk
"""begin = ea
end = get_basic_block_end_from_ea( ea )
ret = []
#print "%lx: (end)" % end
while begin <= end and begin != BADADDR:
ret.append( get_disasm_line( begin ) )
begin = get_first_cref_from( begin )
if get_first_fcref_to( begin ) != BADADDR:
break
if begin == get_first_fcref_from( begin ):
break
return ret"""
def get_basic_block_to( ea ):
x = get_basic_block( ea )
blk = []
for line in x:
if line[0] <= ea:
blk.append( line )
return blk
"""
end = ea
begin = get_basic_block_begin_from_ea( ea )
ret = []
while begin <= end and begin != BADADDR:
ret.append( get_disasm_line( begin ) )
begin = get_first_cref_from( begin )
if get_first_fcref_to( begin ) != BADADDR:
break
if begin == get_first_fcref_from( begin ):
break
return ret"""
def might_be_immediate( str ):
if str == "":
return 0
if str == None:
return 0
try:
if str[-1] == 'h':
string.atol( str[:-1], 16 )
else:
string.atol( str, 10 )
return 1
except ValueError:
return 0
def print_basic_block( baseblock ):
#print baseblock
for line in baseblock:
print disasm_line_to_string( line )
def basic_block_to_string( baseblock ):
r = ""
for line in baseblock:
r = r + disasm_line_to_string(line) + "\n"
return r
def slice_basic_block_for_reg( baseblock, reg ):
retblk = []
for line in baseblock:
if reg == "eax" and line[1] == "call":
retblk.append( line )
elif line[2].find( reg ) != -1 or line[3].find( reg ) != -1 or \
line[4].find( reg ) != -1:
retblk.append( line )
return retblk
class slice_node:
def __init__( self, startea, endea, reg ):
self.startea = startea
self.endea = endea
self.reg = reg
#print "find_end!"
if( startea == 0 ):
self.find_begin()
if( endea == 0 ):
self.find_end()
def to_name( self ):
return "%lx-%lx-%s" % ( self.startea, self.endea, self.reg )
def find_end( self ):
bb = get_basic_block_from( self.startea )
self.endea = bb[-1][0]
bb2 = slice_basic_block_for_reg( bb, self.reg )
bb3 = []
for line in bb2:
bb3.append( line )
if self.reg == "eax" and line[1] == "call":
self.endea = line[0]
break
if line[1] not in neutral_mnem and (line[2] == self.reg or line[3] == self.reg):
self.endea = line[0]
break
self.lines = bb3
return self.endea
def find_begin( self ):
bb = get_basic_block_to( self.endea )
self.startea = bb[0][0]
bb2 = slice_basic_block_for_reg( bb, self.reg )
bb3 = []
for i in range( len(bb2)-1, -1, -1):
line = bb2[i]
bb3.insert( 0, line )
if self.reg == "eax" and line[1] == "call":
self.startea = line[0]
break
if line[1] not in neutral_mnem and (line[2] == self.reg or line[3] == self.reg):
self.startea = line[0]
break
self.lines = bb3
return self.startea
def get_target_reg_bwd( self ):
""" if len( self.lines ) > 0:
if self.reg == "eax" and self.lines[0][1] == "call":
# call is overwriting eax
return ["END",0]
if self.lines[0][1] == "xor" and self.lines[0][2] == self.reg and self.lines[0][3] == self.reg:
return ["END",0]
if self.lines[0][1] == "or" and self.lines[0][3] == "0FFFFFFFFh":
return ["END", 0]
if self.lines[0][1] == "or" and self.lines[0][3] == "-1":
return ["END", 0]
if self.lines[0][1] == "and" and self.lines[0][2] == self.reg and self.lines[0][3] == "0":
return ["END",0]
if self.lines[0][2] == self.reg and self.lines[0][1] not in neutral_mnem:
if self.lines[0][3] in x86_registers and self.lines[0][1] == "mov":
return [self.lines[0][3], 0 ]
if self.lines[0][3] in x86_registers and self.lines[0][1] != "mov":
return [ self.lines[0][3], 1]
if might_be_immediate( self.lines[0][3]) and self.lines[0][1] != "mov":
return [ self.lines[0][2], 0]
else:
return ["END",0]
return ["",0]
"""
if len( self.lines ) > 0:
if self.reg == "eax" and self.lines[0][1] == "call":
# call is overwriting eax
return ["END",0]
if self.lines[0][1] == "xor" and self.lines[0][2] == self.reg and self.lines[0][3] == self.reg:
return ["END",0]
if self.lines[0][1] == "or" and self.lines[0][3] == "0FFFFFFFFh":
return ["END", 0]
if self.lines[0][1] == "or" and self.lines[0][3] == "-1":
return ["END", 0]
if self.lines[0][1] == "and" and self.lines[0][2] == self.reg and self.lines[0][3] == "0":
return ["END",0]
if self.lines[0][2] == self.reg and self.lines[0][1] not in neutral_mnem:
if self.lines[0][3] in x86_registers and self.lines[0][1] == "mov":
return [self.lines[0][3], 0 ]
if self.lines[0][3] in x86_registers and self.lines[0][1] != "mov":
return [ self.lines[0][3], 1]
if might_be_immediate( self.lines[0][3]) and self.lines[0][1] != "mov":
return [ self.lines[0][2], 0]
else:
return ["END",0]
return ["",0]
def get_target_reg( self ):
""" Returns either "END", "", or the new register to track at the end of this block
This code returns eiter "END" if the register is fatally overwritten, "" if the register is dereferenced
or the new register in other cases
"""
if len( self.lines ) > 0:
if self.reg == "eax" and self.lines[-1][1] == "call":
# We have a call that overwrites EAX
return "END"
if self.lines[-1][2] == self.reg and self.lines[-1][1] not in neutral_mnem:
# We have a non-neutral instruction that writes to the register we're tracking
return "END"
elif self.lines[-1][2].find( self.reg ) != -1:
# We have memory access to the location this register is pointing to or an operation on itself
return ""
else:
# If the target is a register, return this register
if self.lines[-1][2] in x86_registers:
return self.lines[-1][2]
else:
return ""
else:
return ""
def get_lines( self ):
return self.lines
def self_to_string( self ):
str = "StartEA: %lx\nEndEA: %lx\nReg: %s\n" % (self.startea, self.endea\
,self.reg)
for line in self.lines:
str = str + disasm_line_to_string( line ) + "\n"
return str
def print_self( self ):
print self.self_to_string()
def add_data_to_slice_graph( graph, bib ):
for name in bib.keys():
node = graph.Get_Node( name )
node.set_attribute( "label", '"'+bib[name].self_to_string()+'"')
return
def slice_graph_bwd( endea, reg ):
"""
Creates a slice graph for this register from an EA (no recursion)
"""
graph = vcg_Graph.vcgGraph({"title":'"Slice for %s"' % reg, \
"manhattan_edges":"no", "layoutalgorithm":"maxdepth"})
#
# Retrieve the name of the current basic block
#
worklist = []
data_bib = {}
startnode = slice_node( 0, endea, reg ) # start at the end of the slice node
rootnode = graph.Add_Node( startnode.to_name() )
data_bib[ startnode.to_name() ] = startnode
worklist.insert( 0, rootnode )
while len( worklist ) > 0:
currnode = worklist.pop()
currslice = data_bib[ currnode.get_name() ]
[tgt_reg, split] = currslice.get_target_reg_bwd()
print tgt_reg
print split
if tgt_reg == "END":
# Do not process this node any further
pass
elif tgt_reg == "" or (( len( currslice.get_lines()) > 0) and \
currslice.startea != currslice.get_lines()[0][0]):
# Do process this node further, nothing really going on
print "ZEZ"
xrefs = get_crefs_to( currslice.startea )
for ref in xrefs:
newslice = slice_node( 0,ref, currslice.reg )
if graph.Get_Node( newslice.to_name() ) == 0:
newnode = graph.Add_Node( newslice.to_name() )
worklist.insert( 0, newnode )
data_bib[ newslice.to_name() ] = newslice
graph.Add_Link( newslice.to_name(), currnode.get_name() )
else:
xrefs = get_crefs_to( currslice.startea )
for ref in xrefs:
newslice = slice_node( 0,ref, tgt_reg )
if graph.Get_Node( newslice.to_name() ) == 0:
newnode = graph.Add_Node( newslice.to_name() )
worklist.insert( 0, newnode )
data_bib[ newslice.to_name() ] = newslice
graph.Add_Link( newslice.to_name(), currnode.get_name())
xrefs = get_crefs_to( currslice.startea )
if split:
for ref in xrefs:
newslice = slice_node( 0,ref, currslice.reg )
if graph.Get_Node( newslice.to_name() ) == 0:
newnode = graph.Add_Node( newslice.to_name() )
worklist.insert( 0, newnode )
data_bib[ newslice.to_name() ] = newslice
graph.Add_Link( newslice.to_name(), currnode.get_name())
return [ graph, data_bib ]
def slice_graph_fwd( startea, reg ):
"""
Creates a slice graph for this register from an EA (no recursion)
"""
graph = vcg_Graph.vcgGraph({"title":'"Slice for %s"' % reg, \
"manhattan_edges":"no", "layoutalgorithm":"maxdepth"})
#
# Retrieve the name of the current basic block
#
worklist = []
data_bib = {}
startnode = slice_node( startea, 0, reg )
rootnode = graph.Add_Node( startnode.to_name() )
data_bib[ startnode.to_name() ] = startnode
worklist.insert( 0, rootnode )
while len( worklist ) > 0:
currnode = worklist.pop()
currslice = data_bib[ currnode.get_name() ]
tgt_reg = currslice.get_target_reg()
if tgt_reg == "END":
# Do not process this node any further
pass
elif tgt_reg == "" or (( len( currslice.get_lines()) > 0) and \
currslice.endea != currslice.get_lines()[-1][0]):
# Nothing much happening here, just proceed to parent bocks
if ua_mnem( currslice.endea ) == "call":
xrefs = get_short_crefs_from( currslice.endea )
else:
xrefs = get_crefs_from( currslice.endea )
for ref in xrefs:
newslice = slice_node( ref, 0, currslice.reg )
if graph.Get_Node( newslice.to_name() ) == 0:
newnode = graph.Add_Node( newslice.to_name() )
worklist.insert( 0, newnode )
data_bib[ newslice.to_name() ] = newslice
graph.Add_Link( currnode.get_name(), newslice.to_name())
else:
# Register was modified, use new register
xrefs = get_crefs_from( currslice.endea )
for ref in xrefs:
newslice = slice_node( ref, 0, tgt_reg )
if graph.Get_Node( newslice.to_name() ) == 0:
newnode = graph.Add_Node( newslice.to_name() )
worklist.insert( 0, newnode )
data_bib[ newslice.to_name() ] = newslice
graph.Add_Link( currnode.get_name(), newslice.to_name())
xrefs = get_crefs_from( currslice.endea )
for ref in xrefs:
newslice = slice_node( ref, 0, currslice.reg )
if graph.Get_Node( newslice.to_name() ) == 0:
newnode = graph.Add_Node( newslice.to_name() )
worklist.insert( 0, newnode )
data_bib[ newslice.to_name() ] = newslice
graph.Add_Link( currnode.get_name(), newslice.to_name())
return [ graph, data_bib ]
def write_slice_graph( intuple, fname ):
newgraph = copy.deepcopy( intuple[0] )
add_data_to_slice_graph( newgraph, intuple[1] )
newgraph.write_VCG_File( fname )
def get_resolvable_calls( ea_func ):
[graph, bib] = slice_graph_fwd( ea_func, "ecx" )
# search for a node containing "[ecx]" in it's line
vtable_loads = []
calls = []
for name in bib.keys():
lines = bib[name].get_lines()
for line in lines:
if line[3] == "["+ bib[name].reg +"]":
vtable_loads.append( [line[0], line[2]] )
for load in vtable_loads:
[graph, bib] = slice_graph_fwd( load[0] + get_item_size( load[0]) \
, load[1] )
for name in bib.keys():
lines = bib[name].get_lines()
for line in lines:
if line[1] == "call":
calls.append( [line[0], line[2]] )
#for x in calls:
# print "%lx:" % x[0]
return calls
def get_subfuncs_with_same_thisptr( ea_func ):
[graph, bib] = slice_graph_fwd( ea_func, "ecx" )
funcs = []
#
# Now get all slice blocks which have "ecx" on them and look for subfunction
# calls in them
#
for slicename in bib.keys():
slice = bib[ slicename ]
if slice.reg == "ecx":
begin = slice.startea
while begin <= slice.endea:
if ua_mnem( begin ) == "call":
tgt = get_first_fcref_from( begin )
if tgt != BADADDR:
funcs.append( tgt )
begin = begin + get_item_size( begin )
return funcs
def get_subfuncs_with_same_thisptr_rec( ea_func ):
funcdict = {}
worklist = []
worklist.append( ea_func )
funcdict[ ea_func ] = 1
while len( worklist ) > 0:
ea = worklist.pop()
funcs = get_subfuncs_with_same_thisptr( ea )
for func in funcs:
if not funcdict.has_key( func ):
funcdict[ func ] = 1
worklist.append( func )
funcs = []
for x in funcdict.keys():
funcs.append( x )
return funcs
def resolve_indirect_calls_in_vtable_recursive( vtable_begin, vtable_end ):
targetdict = {}
current = vtable_begin
changed = 1
newlist = []
while changed:
changed = 0
current = vtable_begin
while current <= vtable_end:
tgts = get_subfuncs_with_same_thisptr_rec( get_first_dref_from( current ))
for tgt in tgts:
if targetdict.has_key( tgt ):
pass
else:
targetdict[ tgt ] = tgt
changed = 1
newlist.append( tgt )
current = current + 4
# iterated over vtable once, now resolve one step
if changed == 1:
while len( newlist ) > 0:
f = newlist.pop()
#print "%lx" % f
calls = get_resolvable_calls( f )
for call in calls:
#print "%lx: %s" % ( call[0], call[1])
resolve_call( call, vtable_begin )
#
# Excuse the erratic indentation
#
def resolve_call( call, vtable_begin ):
if call[1].find( "dword" ) != -1:
newcall = "0x" + call[1][ call[1].find('[')+5:-2]
if newcall == "0x":
newcall = "0"
offset = string.atol( newcall, 16 )
target = get_first_dref_from( vtable_begin + offset )
if target == BADADDR:
print "%lx: BADADDR as target from vtable at %lx, offset %lx\n" \
% (call[0], vtable_begin, offset)
else:
xrefs = get_far_crefs_from( call[0] )
if target not in xrefs:
if get_cmt( call[0], 0 ) != None:
newcmt = get_cmt( call[0], 0 ) + "target: 0x%lx\n" % target
else:
newcmt = "target: 0x%lx\n" % target
set_cmt( call[0], newcmt, 0 )
add_cref( call[0], target, fl_CN )
print "%lx: --> %lx" % ( call[0], target )
def resolve_indirect_calls_in_vtable( vtable_begin, vtable_end):
current = vtable_begin
while current <= vtable_end:
#print "%lx: getting graph..." % get_first_dref_from( current )
calls = get_resolvable_calls( get_first_dref_from( current ) )
for call in calls:
#
# strip stuff from call
#
resolve_call( call, vtable_begin )
current = current + 4
def find_vtables_aggressive( firstaddr = 0, lastaddr = 0x7FFFFFFF ):
"""
Returns list of begin/end tuples for vtables found in the executable
A table is considered a vtable if:
it consists of at least 1 pointers to functions
it's offset is written to a register in the form [reg]
"""
valid_reg_strings = [ "[eax", "[ebx", "[ecx", "[edx", "[esi", "[edi",\
"[ebp" ]
if firstaddr == 0:
startaddr = nextaddr( firstaddr)
else:
startaddr = firstaddr
vtables = []
while startaddr != BADADDR:
#
# Check if the offset is written
#
xrefs = get_drefs_to( startaddr )
is_written_to_beginning = 0
for xref in xrefs:
line = get_disasm_line( xref )
if len( line ) >= 3:
for reg in valid_reg_strings:
if line[2].find( reg ) != -1:
is_written_to_beginning = 1
#
# Check if
#
i = 0
if is_written_to_beginning == 1:
while get_first_dref_from( startaddr + (4 * (i+1))) != BADADDR:
ea = get_first_dref_from( startaddr + (4*i))
func = get_func( ea )
try:
if func.startEA != ea:
break
except( AttributeError ):
break;
i = i + 1
if len( get_drefs_to( startaddr + ( 4 * (i)))) != 0:
break;
if i > 0:
vtables.append( [ startaddr, startaddr + (4*i) ] )
if i > 0:
startaddr = startaddr + i*4
elif get_item_size( startaddr ) != 0:
startaddr = startaddr + get_item_size( startaddr )
else:
startaddr = startaddr + 1
if nextaddr( startaddr ) == BADADDR:
break
if startaddr >= lastaddr:
break
return vtables
def find_vtables( firstaddr = 0, lastaddr = 0x7FFFFFFF ):
"""
Returns list of begin/end tuples for vtables found in the executable
A table is considered a vtable if:
it consists of at least 2 pointers to functions
it's offset is written to a register in the form [reg]
"""
valid_reg_strings = [ "[eax]", "[ebx]", "[ecx]", "[edx]", "[esi]", "[edi]",\
"[ebp]" ]
if firstaddr == 0:
startaddr = nextaddr( firstaddr)
else:
startaddr = firstaddr
vtables = []
while startaddr != BADADDR:
#
# Check if the offset is written
#
xrefs = get_drefs_to( startaddr )
is_written_to_beginning = 0
for xref in xrefs:
line = get_disasm_line( xref )
if len( line ) >= 3:
for reg in valid_reg_strings:
if line[2].find( reg ) != -1:
is_written_to_beginning = 1
#
# Check if
#
i = 0
if is_written_to_beginning == 1:
while get_first_dref_from( startaddr + (4 * (i+1))) != BADADDR:
ea = get_first_dref_from( startaddr + (4*i))
func = get_func( ea )
try:
if func.startEA != ea:
break
except( AttributeError ):
break;
i = i + 1
if i > 2:
vtables.append( [ startaddr, startaddr + (4*i) ] )
if i > 0:
startaddr = startaddr + i*4
elif get_item_size( startaddr ) != 0:
startaddr = startaddr + get_item_size( startaddr )
else:
startaddr = startaddr + 1
if nextaddr( startaddr ) == BADADDR:
break
if startaddr >= lastaddr:
break
return vtables
def create_class_from_constructor( constr_addr, strucname ):
liste = get_addr_ofs_list_from_func( constr_addr, 'ecx' )
addr_ofs_list_to_IDC( liste, strucname, "c:\\makestruc.idc" )
def create_struct_from_ea( ea, reg, strucname):
[graph, bib] = slice_graph_fwd( ea, reg )
addr_ofs_list = []
for key in bib.keys():
slice = bib[ key ]
for line in slice.get_lines():
# check if the register is in Op1
if line[2].find( slice.reg ) != -1:
op_parts = line[2].split()
op = op_parts[-1]
if op[-1] == ']':
opoffset = op[4:-1]
if opoffset == "":
offset = 0
else:
# print "%s" % opoffset
if opoffset[-1] == 'h':
try:
offset = string.atol( opoffset[1:-1], 16 )
except ValueError:
op2 = opoffset[1:-1].split('+')[-1]
try:
offset = string.atol( op2, 16 )
except ValueError:
print op2
offset = 0
else: