This repository has been archived by the owner on Oct 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 128
/
Analysis.py
1086 lines (959 loc) · 34.7 KB
/
Analysis.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
# Copyright (c) 2011-2015 Rusty Wagner
#
# 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, see <http://www.gnu.org/licenses/>.
import threading
import time
import struct
import X86
import PPC
import Arm
from ElfFile import *
from PEFile import *
from MachOFile import *
ExeFormats = [ElfFile, PEFile, MachOFile]
class InstructionText:
def __init__(self):
self.lines = []
self.tokens = []
class X86Instruction:
def __init__(self, opcode, addr, disasm, addr_size):
self.opcode = opcode
self.addr = addr
self.disasm = disasm
self.addr_size = addr_size
self.plt = None
self.text = InstructionText()
if ((disasm.operation == "jmpn") or self.isCall() or self.isConditionalBranch()) and (disasm.operands[0].operand == "imm"):
self.target = disasm.operands[0].immediate
else:
self.target = None
def isConditionalBranch(self):
return self.disasm.operation in ["jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns",
"jpe", "jpo", "jl", "jge", "jle", "jg", "jcxz", "jecxz", "jrcxz", "loop"]
def isLocalJump(self):
if self.disasm.operation == "jmpn":
return True
if self.isConditionalBranch():
return True
return False
def isCall(self):
if self.disasm.operation == "calln":
return True
if self.disasm.operation == "callf":
return True
return False
def isBlockEnding(self):
if self.disasm.operation in ["jmpn", "jmpf", "retn", "retf"]:
return True
if self.isConditionalBranch():
return True
if self.disasm.operation == "hlt":
return True
return False
def isValid(self):
return self.disasm.operation != None
def length(self):
return self.disasm.length
def format_text(self, block, options):
old_lines = []
old_tokens = []
self.text.lines = []
self.text.tokens = []
line = []
tokens = []
x = 0
instr = self.disasm
if "address" in options:
string = "%.8x " % self.addr
line += [[string, QColor(0, 0, 128)]]
x += len(string)
if instr.operation == None:
line += [["??", Qt.black]]
self.text.lines += [line]
self.text.tokens += [tokens]
return (old_lines != self.text.lines) or (old_tokens != self.text.tokens)
result = ""
operation = ""
if instr.flags & X86.FLAG_LOCK:
operation += "lock "
if instr.flags & X86.FLAG_ANY_REP:
operation += "rep"
if instr.flags & X86.FLAG_REPNE:
operation += "ne"
elif instr.flags & X86.FLAG_REPE:
operation += "e"
operation += " "
operation += instr.operation
if len(operation) < 7:
operation += " " * (7 - len(operation))
result += operation + " "
for j in range(0, len(instr.operands)):
if j != 0:
result += ", "
if instr.operands[j].operand == "imm":
value = instr.operands[j].immediate & ((1 << (instr.operands[j].size * 8)) - 1)
numfmt = "0x%%.%dx" % (instr.operands[j].size * 2)
string = numfmt % value
if (instr.operands[j].size == self.addr_size) and (block.analysis.functions.has_key(value)):
# Pointer to existing function
func = block.analysis.functions[value]
string = func.name
if func.plt:
color = QColor(192, 0, 192)
else:
color = QColor(0, 0, 192)
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
line += [[string, color]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
elif (instr.operands[j].size == self.addr_size) and (value >= block.exe.start()) and (value < block.exe.end()) and (not self.isLocalJump()):
# Pointer within module
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
if value in block.exe.symbols_by_addr:
string = block.exe.symbols_by_addr[value]
line += [[string, QColor(0, 0, 192)]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
else:
result += string
elif instr.operands[j].operand == "mem":
plus = False
result += X86.get_size_string(instr.operands[j].size)
if (instr.segment != None) or (instr.operands[j].segment == "es"):
result += instr.operands[j].segment + ":"
result += '['
if instr.operands[j].components[0] != None:
tokens += [[x + len(result), len(instr.operands[j].components[0]), "reg", instr.operands[j].components[0]]]
result += instr.operands[j].components[0]
plus = True
if instr.operands[j].components[1] != None:
if plus:
tokens += [[x + len(result) + 1, len(instr.operands[j].components[1]), "reg", instr.operands[j].components[1]]]
else:
tokens += [[x + len(result), len(instr.operands[j].components[1]), "reg", instr.operands[j].components[1]]]
result += X86.get_operand_string(instr.operands[j].components[1],
instr.operands[j].scale, plus)
plus = True
if (instr.operands[j].immediate != 0) or ((instr.operands[j].components[0] == None) and (instr.operands[j].components[1] == None)):
if plus and (instr.operands[j].immediate >= -0x80) and (instr.operands[j].immediate < 0):
result += '-'
result += "0x%.2x" % (-instr.operands[j].immediate)
elif plus and (instr.operands[j].immediate > 0) and (instr.operands[j].immediate <= 0x7f):
result += '+'
result += "0x%.2x" % instr.operands[j].immediate
elif plus and (instr.operands[j].immediate >= -0x8000) and (instr.operands[j].immediate < 0):
result += '-'
result += "0x%.8x" % (-instr.operands[j].immediate)
elif instr.flags & X86.FLAG_64BIT_ADDRESS:
if plus:
result += '+'
value = instr.operands[j].immediate
string = "0x%.16x" % instr.operands[j].immediate
if hasattr(block.exe, "plt") and block.exe.plt.has_key(value):
# Pointer to PLT entry
self.plt = block.exe.plt[value]
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
string = self.plt + "@PLT"
line += [[string, QColor(0, 0, 192)]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
elif (value >= block.exe.start()) and (value < block.exe.end()):
# Pointer within module
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
if value in block.exe.symbols_by_addr:
string = block.exe.symbols_by_addr[value]
line += [[string, QColor(0, 0, 192)]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
else:
result += string
else:
if plus:
result += '+'
value = instr.operands[j].immediate & 0xffffffff
string = "0x%.8x" % value
if (self.addr_size == 4) and hasattr(block.exe, "plt") and block.exe.plt.has_key(value):
# Pointer to PLT entry
self.plt = block.exe.plt[value]
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
string = block.exe.decorate_plt_name(self.plt)
line += [[string, QColor(0, 0, 192)]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
elif (self.addr_size == 4) and (value >= block.exe.start()) and (value < block.exe.end()):
# Pointer within module
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
if value in block.exe.symbols_by_addr:
string = block.exe.symbols_by_addr[value]
line += [[string, QColor(0, 0, 192)]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
else:
result += string
result += ']'
else:
tokens += [[x + len(result), len(instr.operands[j].operand), "reg", instr.operands[j].operand]]
result += instr.operands[j].operand
if len(result) > 0:
line += [[result, Qt.black]]
self.text.lines += [line]
self.text.tokens += [tokens]
return (old_lines != self.text.lines) or (old_tokens != self.text.tokens)
def get_prefix_count(self):
for count in range(0, len(self.opcode)):
if self.opcode[count] in ["\x26", "\x2e", "\x36", "\x3e", "\x64", "\x65", "\x66", "\x67", "\xf0", "\xf2", "\xf3"]:
continue
if (self.addr_size == 8) and (self.opcode[count] >= '\x40') and (self.opcode[count] <= "\x4f"):
continue
return count
return len(self.opcode)
def patch_to_nop(self, exe):
exe.write(self.addr, "\x90" * len(self.opcode))
def is_patch_branch_allowed(self):
return self.isConditionalBranch()
def patch_to_always_branch(self, exe):
prefix_count = self.get_prefix_count()
if self.opcode[prefix_count] == "\x0f":
# Two byte branch
exe.write(self.addr, ("\x90" * (prefix_count + 1)) + "\xb9" + self.opcode[prefix_count+2:])
else:
# One byte branch
exe.write(self.addr, ("\x90" * prefix_count) + "\xeb" + self.opcode[prefix_count+1:])
def patch_to_invert_branch(self, exe):
prefix_count = self.get_prefix_count()
if self.opcode[prefix_count] == "\x0f":
# Two byte branch
exe.write(self.addr, self.opcode[0:prefix_count+1] + chr(ord(self.opcode[prefix_count+1]) ^ 1) +
self.opcode[prefix_count+2:])
else:
# One byte branch
exe.write(self.addr, self.opcode[0:prefix_count] + chr(ord(self.opcode[prefix_count]) ^ 1) +
self.opcode[prefix_count+1:])
def is_patch_to_zero_return_allowed(self):
return self.isCall()
def patch_to_zero_return(self, exe):
exe.write(self.addr, "\x31\xc0" + ("\x90" * (len(self.opcode) - 2)))
def is_patch_to_fixed_return_value_allowed(self):
return self.isCall() and (len(self.opcode) >= 5)
def patch_to_fixed_return_value(self, exe, value):
if len(self.opcode) < 5:
return
exe.write(self.addr, "\xb8" + struct.pack("<I", value & 0xffffffff) + ("\x90" * (len(self.opcode) - 5)))
class PPCInstruction:
def __init__(self, opcode, addr, disasm):
self.opcode = opcode
self.addr = addr
self.disasm = disasm
self.plt = None
self.text = InstructionText()
self.target = None
if self.disasm.operation and self.disasm.operation.startswith('b') and (len(self.disasm.operands) > 0):
if type(disasm.operands[-1]) != str:
self.target = disasm.operands[-1]
def isConditionalBranch(self):
return self.disasm.operation in PPC.ConditionalBranches
def isLocalJump(self):
if self.disasm.operation in ["b", "ba"]:
return True
if self.isConditionalBranch():
return True
return False
def isCall(self):
return self.disasm.operation in PPC.CallInstructions
def isBlockEnding(self):
if self.disasm.operation in (PPC.BranchInstructions + ["trap"]):
return True
if self.isLocalJump():
return True
return False
def isValid(self):
return self.disasm.operation != None
def length(self):
return 4
def format_text(self, block, options):
old_lines = []
old_tokens = []
self.text.lines = []
self.text.tokens = []
line = []
tokens = []
x = 0
instr = self.disasm
if "address" in options:
string = "%.8x " % self.addr
line += [[string, QColor(0, 0, 128)]]
x += len(string)
if instr.operation == None:
line += [["??", Qt.black]]
self.text.lines += [line]
self.text.tokens += [tokens]
return (old_lines != self.text.lines) or (old_tokens != self.text.tokens)
result = ""
operation = instr.operation
if len(operation) < 7:
operation += " " * (7 - len(operation))
result += operation + " "
for j in range(0, len(instr.operands)):
if j != 0:
result += ", "
if type(instr.operands[j]) != str:
value = instr.operands[j]
if instr.operands[j] < 0:
string = "-0x%x" % -instr.operands[j]
else:
string = "0x%x" % instr.operands[j]
if block.analysis.functions.has_key(value):
# Pointer to existing function
func = block.analysis.functions[value]
string = func.name
if func.plt:
color = QColor(192, 0, 192)
else:
color = QColor(0, 0, 192)
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
line += [[string, color]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
elif (value >= block.exe.start()) and (value < block.exe.end()) and (not self.isLocalJump()):
# Pointer within module
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
if value in block.exe.symbols_by_addr:
string = block.exe.symbols_by_addr[value]
line += [[string, QColor(0, 0, 192)]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
else:
result += string
else:
tokens += [[x + len(result), len(instr.operands[j]), "reg", instr.operands[j]]]
result += instr.operands[j]
if len(result) > 0:
line += [[result, Qt.black]]
self.text.lines += [line]
self.text.tokens += [tokens]
return (old_lines != self.text.lines) or (old_tokens != self.text.tokens)
def patch_to_nop(self, exe):
exe.write(self.addr, "\x60\x00\x00\x00")
def is_patch_branch_allowed(self):
return self.isConditionalBranch()
def patch_to_always_branch(self, exe):
pass
def patch_to_invert_branch(self, exe):
pass
def is_patch_to_zero_return_allowed(self):
return self.isCall()
def patch_to_zero_return(self, exe):
pass
def is_patch_to_fixed_return_value_allowed(self):
return self.isCall()
def patch_to_fixed_return_value(self, exe, value):
pass
class ArmInstruction:
def __init__(self, opcode, addr, disasm):
self.opcode = opcode
self.addr = addr
self.disasm = disasm
self.plt = None
self.text = InstructionText()
self.target = None
if self.disasm.operation and ((self.disasm.operation == "b") or (self.disasm.operation == "bx") or (self.disasm.operation == "bl") or (self.disasm.operation == "blx")) and (type(self.disasm.operands[0]) != str):
self.target = disasm.operands[0]
elif self.disasm.operation and ((self.disasm.operation[0:2] == "b.") or (self.disasm.operation[0:3] == "bx.") or (self.disasm.operation[0:3] == "bl.") or (self.disasm.operation[0:4] == "blx.")) and (type(self.disasm.operands[0]) != str):
self.target = disasm.operands[0]
def isConditionalBranch(self):
if self.disasm.operation and ((self.disasm.operation[0:2] == "b.") or (self.disasm.operation[0:3] == "bx.")) and (self.target is not None):
return True
return False
def isLocalJump(self):
if self.disasm.operation and ((self.disasm.operation == "b") or (self.disasm.operation == "bx")) and (self.target is not None):
return True
return self.isConditionalBranch()
def isCall(self):
return self.disasm.operation and ((self.disasm.operation == "bl") or (self.disasm.operation == "blx") or (self.disasm.operation[0:3] == "bl.") or (self.disasm.operation[0:4] == "blx."))
def isBlockEnding(self):
if self.isLocalJump():
return True
if self.disasm.operation and ((self.disasm.operation == "b") or (self.disasm.operation == "bx")):
return True
if self.disasm.operation and (self.disasm.operation[0:3] == "ldm") and ("pc" in self.disasm.operands[1:]):
return True
if self.disasm.operation and (self.disasm.operation == "ldr") and (self.disasm.operands[0] == "pc"):
return True
if self.disasm.operation and (self.disasm.operation == "pop") and ("pc" in self.disasm.operands):
return True
return False
def isValid(self):
return self.disasm.operation != None
def length(self):
return self.disasm.length
def format_text(self, block, options):
old_lines = []
old_tokens = []
self.text.lines = []
self.text.tokens = []
line = []
tokens = []
x = 0
instr = self.disasm
if "address" in options:
string = "%.8x " % self.addr
line += [[string, QColor(0, 0, 128)]]
x += len(string)
if instr.operation == None:
line += [["??", Qt.black]]
self.text.lines += [line]
self.text.tokens += [tokens]
return (old_lines != self.text.lines) or (old_tokens != self.text.tokens)
result = ""
operation = instr.operation.replace(".", "")
if len(operation) < 7:
operation += " " * (7 - len(operation))
result += operation + " "
for j in range(0, len(instr.operands)):
if j != 0:
result += ", "
if type(instr.operands[j]) == list:
if instr.operands[j][0][0] == "-":
tokens += [[x + len(result) + 1, len(instr.operands[j][0]) - 1, "reg", instr.operands[j][0][1:]]]
elif instr.operands[j][0][-1] == "!":
tokens += [[x + len(result), len(instr.operands[j][0]) - 1, "reg", instr.operands[j][0][:-1]]]
else:
tokens += [[x + len(result), len(instr.operands[j][0]), "reg", instr.operands[j][0]]]
result += instr.operands[j][0] + " "
if len(instr.operands[j]) == 2:
result += instr.operands[j][1]
elif type(instr.operands[j][2]) == str:
result += instr.operands[j][1] + " "
if instr.operands[j][2][0] == "-":
tokens += [[x + len(result) + 1, len(instr.operands[j][2]) - 1, "reg", instr.operands[j][2][1:]]]
elif instr.operands[j][0][-1] == "!":
tokens += [[x + len(result), len(instr.operands[j][2]) - 1, "reg", instr.operands[j][2][:-1]]]
else:
tokens += [[x + len(result), len(instr.operands[j][2]), "reg", instr.operands[j][2]]]
result += instr.operands[j][2]
else:
result += " %s %d" % (instr.operands[j][1], instr.operands[j][2])
elif instr.operands[j].__class__ == Arm.MemoryOperand:
result += "["
for k in range(0, len(instr.operands[j].components)):
if k != 0:
result += ", "
if type(instr.operands[j].components[k]) == str:
if instr.operands[j].components[k][0] == "-":
tokens += [[x + len(result) + 1, len(instr.operands[j].components[k]) - 1, "reg", instr.operands[j].components[k][1:]]]
elif instr.operands[j].components[k][-1] == "!":
tokens += [[x + len(result), len(instr.operands[j].components[k]) - 1, "reg", instr.operands[j].components[k][:-1]]]
else:
tokens += [[x + len(result), len(instr.operands[j].components[k]), "reg", instr.operands[j].components[k]]]
result += instr.operands[j].components[k]
elif type(instr.operands[j].components[k]) == list:
if instr.operands[j].components[k][0][0] == "-":
tokens += [[x + len(result) + 1, len(instr.operands[j].components[k][0]) - 1, "reg", instr.operands[j].components[k][0][1:]]]
elif instr.operands[j].components[k][0][-1] == "!":
tokens += [[x + len(result), len(instr.operands[j].components[k][0]) - 1, "reg", instr.operands[j].components[k][0][:-1]]]
else:
tokens += [[x + len(result), len(instr.operands[j].components[k][0]), "reg", instr.operands[j].components[k][0]]]
result += instr.operands[j].components[k][0] + " "
if len(instr.operands[j].components[k]) == 2:
result += instr.operands[j].components[k][1]
elif type(instr.operands[j].components[k][2]) == str:
result += instr.operands[j].components[k][1] + " "
if instr.operands[j].components[k][2][0] == "-":
tokens += [[x + len(result) + 1, len(instr.operands[j].components[k][2]) - 1, "reg", instr.operands[j].components[k][2][1:]]]
elif instr.operands[j][2][-1] == "!":
tokens += [[x + len(result), len(instr.operands[j].components[k][2]) - 1, "reg", instr.operands[j].components[k][2][:-1]]]
else:
tokens += [[x + len(result), len(instr.operands[j].components[k][2]), "reg", instr.operands[j].components[k][2]]]
result += instr.operands[j].components[k][2]
else:
result += "%s %d" % (instr.operands[j].components[k][1], instr.operands[j].components[k][2])
else:
value = instr.operands[j].components[k]
if instr.operands[j].components[k] < 0:
string = "-0x%x" % -instr.operands[j].components[k]
else:
string = "0x%x" % instr.operands[j].components[k]
if block.analysis.functions.has_key(value):
# Pointer to existing function
func = block.analysis.functions[value]
string = func.name
if func.plt:
color = QColor(192, 0, 192)
else:
color = QColor(0, 0, 192)
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
line += [[string, color]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
elif (value >= block.exe.start()) and (value < block.exe.end()) and (not self.isLocalJump()):
# Pointer within module
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
if value in block.exe.symbols_by_addr:
string = block.exe.symbols_by_addr[value]
line += [[string, QColor(0, 0, 192)]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
else:
result += string
result += "]"
if instr.operands[j].writeback:
result += "!"
elif type(instr.operands[j]) != str:
value = instr.operands[j]
if instr.operands[j] < 0:
string = "-0x%x" % -instr.operands[j]
else:
string = "0x%x" % instr.operands[j]
if block.analysis.functions.has_key(value):
# Pointer to existing function
func = block.analysis.functions[value]
string = func.name
if func.plt:
color = QColor(192, 0, 192)
else:
color = QColor(0, 0, 192)
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
line += [[string, color]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
elif (value >= block.exe.start()) and (value < block.exe.end()) and (not self.isLocalJump()):
# Pointer within module
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
if value in block.exe.symbols_by_addr:
string = block.exe.symbols_by_addr[value]
line += [[string, QColor(0, 0, 192)]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
else:
result += string
else:
if instr.operands[j][0] == "-":
tokens += [[x + len(result) + 1, len(instr.operands[j]) - 1, "reg", instr.operands[j][1:]]]
elif instr.operands[j][-1] == "!":
tokens += [[x + len(result), len(instr.operands[j]) - 1, "reg", instr.operands[j][:-1]]]
else:
tokens += [[x + len(result), len(instr.operands[j]), "reg", instr.operands[j]]]
result += instr.operands[j]
if (instr.operation == "ldr") and (instr.operands[1].__class__ == Arm.MemoryOperand) and (len(instr.operands[1].components) == 1) and (type(instr.operands[1].components[0]) != str) and (type(instr.operands[1].components[0]) != list):
addr = instr.operands[1].components[0]
if (addr >= block.exe.start()) and ((addr + 4) <= block.exe.end()):
result += " ; ="
value = block.exe.read_uint32(addr)
string = "0x%x" % value
if block.analysis.functions.has_key(value):
# Pointer to existing function
func = block.analysis.functions[value]
string = func.name
if func.plt:
color = QColor(192, 0, 192)
else:
color = QColor(0, 0, 192)
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
line += [[string, color]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
elif (value >= block.exe.start()) and (value < block.exe.end()) and (not self.isLocalJump()):
# Pointer within module
if len(result) > 0:
line += [[result, Qt.black]]
x += len(result)
result = ""
if value in block.exe.symbols_by_addr:
string = block.exe.symbols_by_addr[value]
line += [[string, QColor(0, 0, 192)]]
tokens += [[x, len(string), "ptr", value, string]]
x += len(string)
else:
result += string
if len(result) > 0:
line += [[result, Qt.black]]
self.text.lines += [line]
self.text.tokens += [tokens]
return (old_lines != self.text.lines) or (old_tokens != self.text.tokens)
def patch_to_nop(self, exe):
if self.addr & 1:
if self.disasm.length == 4:
exe.write(self.addr & (~1), "\x00\x46\x00\x46")
else:
exe.write(self.addr & (~1), "\x00\x46")
else:
exe.write(self.addr, "\x00\x00\xa0\xe1")
def is_patch_branch_allowed(self):
return self.isConditionalBranch()
def patch_to_always_branch(self, exe):
if self.addr & 1:
opcode = exe.read_uint16(self.addr & (~1))
imm8 = opcode & 0xff
if imm8 & 0x80:
imm11 = imm8 | 0x700
else:
imm11 = imm8
opcode = 0xe000 | imm11
exe.write_uint16(self.addr & (~1), opcode)
else:
exe.write_uint32(self.addr, (exe.read_uint32(self.addr) & 0x0fffffff) | 0xe0000000)
def patch_to_invert_branch(self, exe):
if self.addr & 1:
exe.write_uint16(self.addr & (~1), self.read_uint16(self.addr & (~1)) ^ (1 << 8))
else:
exe.write_uint32(self.addr, exe.read_uint32(self.addr) ^ (1 << 28))
def is_patch_to_zero_return_allowed(self):
return self.isCall()
def patch_to_zero_return(self, exe):
if self.addr & 1:
if self.disasm.length == 4:
exe.write(self.addr & (~1), "\x00\x20\x00\x46")
else:
exe.write(self.addr & (~1), "\x00\x20")
else:
cc = exe.read_uint32(self.addr) & 0xf0000000
if cc == 0xf0000000:
cc = 0xe0000000
exe.write_uint32(self.addr, cc | 0x03a00000)
def is_patch_to_fixed_return_value_allowed(self):
return self.isCall()
def patch_to_fixed_return_value(self, exe, value):
if self.addr & 1:
exe.write_uint16(self.addr & (~1), 0x2000 | (value & 0xff))
if self.disasm.length == 4:
exe.write((self.addr + 2) & (~1), "\x00\x46")
else:
cc = exe.read_uint32(self.addr) & 0xf0000000
if cc == 0xf0000000:
cc = 0xe0000000
exe.write_uint32(self.addr, cc | 0x03000000 | ((value << 4) & 0xf0000) | (value & 0xfff))
class BasicBlock:
def __init__(self, analysis, exe, entry):
self.analysis = analysis
self.exe = exe
self.entry = entry
self.exits = []
self.prev = []
self.true_path = None
self.false_path = None
self.instrs = []
self.header_text = InstructionText()
def populate(self, known_instrs):
addr = self.entry
while True:
known_instrs[addr] = self
if self.exe.architecture() == "x86":
opcode = self.exe.read(addr, 15)
result = X86.disassemble32(opcode, addr)
opcode = opcode[0:result.length]
instr = X86Instruction(opcode, addr, result, 4)
arch = X86
elif self.exe.architecture() == "x86_64":
opcode = self.exe.read(addr, 15)
result = X86.disassemble64(opcode, addr)
opcode = opcode[0:result.length]
instr = X86Instruction(opcode, addr, result, 8)
arch = X86
elif self.exe.architecture() == "ppc":
opcode = self.exe.read(addr, 4)
if len(opcode) == 4:
result = PPC.disassemble(struct.unpack(">I", opcode)[0], addr)
instr = PPCInstruction(opcode, addr, result)
else:
instr = PPCInstruction("", addr, PPC.Instruction())
arch = PPC
elif self.exe.architecture() == "arm":
opcode = self.exe.read(addr & (~1), 4)
if len(opcode) == 4:
result = Arm.disassemble(struct.unpack("<I", opcode)[0], addr)
instr = ArmInstruction(opcode, addr, result)
else:
instr = ArmInstruction("", addr, Arm.Instruction())
arch = Arm
else:
break
self.instrs += [instr]
instr.format_text(self, self.analysis.options)
if not instr.isValid():
break
if instr.isBlockEnding():
if instr.isConditionalBranch():
self.true_path = instr.target
self.false_path = addr + instr.length()
self.exits += [self.true_path, self.false_path]
elif instr.target != None:
self.exits += [instr.target]
break
addr += instr.length()
if addr in known_instrs:
self.exits += [addr]
break
def update(self):
changed = False
for instr in self.instrs:
if instr.format_text(self, self.analysis.options):
changed = True
return changed
class Function:
def __init__(self, analysis, exe, entry, name = None):
self.analysis = analysis
self.exe = exe
self.entry = entry
if name:
self.name = name
else:
self.name = "sub_%.8x" % entry
self.blocks = {}
self.plt = False
self.ready = False
self.update_id = None
def findBasicBlocks(self):
# Reset block information in case we are reanalyzing an updated function
self.blocks = {}
self.plt = False
self.ready = False
self.update_id = self.analysis.get_next_update_id()
# Create initial basic block and add it to the queue
block = BasicBlock(self.analysis, self.exe, self.entry)
block.header_text.lines += [[[self.name + ":", QColor(192, 0, 0)]]]
block.header_text.tokens += [[[0, len(self.name), "ptr", self.entry, self.name]]]
queue = [block]
known_instrs = {}
# Process until all blocks are found
while len(queue) > 0:
block = queue.pop()
# Find instructions for this block
block.populate(known_instrs)
self.blocks[block.entry] = block
# Follow block exits
for edge in block.exits:
already_found = edge in self.blocks
for i in queue:
if i.entry == edge:
already_found = True
if not already_found:
if edge in known_instrs:
# Address is within another basic block, split the block so that
# the new edge can point to a basic block as well
block = known_instrs[edge]
for i in range(0, len(block.instrs)):
if block.instrs[i].addr == edge:
break
new_block = BasicBlock(self.analysis, self.exe, edge)
new_block.exits = block.exits
new_block.true_path = block.true_path
new_block.false_path = block.false_path
new_block.instrs = block.instrs[i:]
for instr in new_block.instrs:
known_instrs[instr.addr] = new_block
self.blocks[edge] = new_block
block.exits = [edge]
block.true_path = None
block.false_path = None
block.instrs = block.instrs[0:i]
else:
# New basic block
block = BasicBlock(self.analysis, self.exe, edge)
self.blocks[edge] = block
known_instrs[edge] = block
queue += [block]
# Set previous block list for each block
for block in self.blocks.values():
block.prev = []
for block in self.blocks.values():
for exit in block.exits:
self.blocks[exit].prev.append(block)
if (len(self.blocks) == 1) and (len(block.instrs) == 1) and (block.instrs[0].plt != None):
# Function is a trampoline to a PLT entry
self.rename(block.instrs[0].plt)
self.plt = True
self.exe.create_symbol(self.entry, self.name)
def findCalls(self):
calls = []
for block in self.blocks.values():
for instr in block.instrs:
if instr.isCall() and (instr.target != None):
if (instr.target >= self.exe.start()) and (instr.target < self.exe.end()):
calls += [instr.target]
return calls
def update(self):
changed = False
for block in self.blocks.values():
if block.update():
changed = True
if changed:
self.update_id = self.analysis.get_next_update_id()
def rename(self, name):
self.name = name
self.blocks[self.entry].header_text.lines[0] = [[name + ":", QColor(192, 0, 0)]]
self.blocks[self.entry].header_text.tokens[0] = [[0, len(self.name), "ptr", self.entry, self.name]]
class Analysis:
def __init__(self, exe):
self.exe = exe
self.start = None
self.functions = {}
self.run = True
self.lock = threading.Lock()
self.queue = []
self.status = ""
self.update_id = 0
self.update_request = False
self.options = set()
self.exe.add_callback(self)
def get_next_update_id(self):
self.update_id += 1
return self.update_id
def analyze(self):
self.lock.acquire()
if hasattr(self.exe, "entry"):
self.status = "Disassembling function at 0x%.8x..." % self.exe.entry()
self.start = Function(self, self.exe, self.exe.entry(), '_start')
self.functions[self.exe.entry()] = self.start
self.start.findBasicBlocks()
self.queue += self.start.findCalls()
self.start.ready = True
self.lock.release()
while self.run:
while (len(self.queue) > 0) and self.run:
self.lock.acquire()
entry = self.queue.pop()
self.status = "Disassembling function at 0x%.8x..." % entry
if entry not in self.functions:
if entry in self.exe.symbols_by_addr:
func = Function(self, self.exe, entry, self.exe.symbols_by_addr[entry])
else:
func = Function(self, self.exe, entry)
self.functions[entry] = func
else:
func = self.functions[entry]
func.findBasicBlocks()
calls = func.findCalls()
for call in calls:
already_found = self.functions.has_key(call)
for i in self.queue:
if i == call:
already_found = True
if not already_found:
self.queue += [call]
func.ready = True
self.lock.release()
# Give GUI thread a chance to do stuff
time.sleep(0.001)
# Update disassembly so that function names are correct