forked from joxeankoret/diaphora
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diaphora_ida.py
2539 lines (2167 loc) · 83.9 KB
/
diaphora_ida.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
"""
Diaphora, a diffing plugin for IDA
Copyright (c) 2015-2019, Joxean Koret
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import os
import sys
import imp
import time
import json
import decimal
import difflib
import sqlite3
import traceback
import threading
from hashlib import md5
import diaphora
from pygments import highlight
from pygments.lexers import NasmLexer, CppLexer, DiffLexer
from pygments.formatters import HtmlFormatter
from others.tarjan_sort import strongly_connected_components, robust_topological_sort
from jkutils.factor import primesbelow as primes
from jkutils.graph_hashes import CKoretKaramitasHash
from idc import *
from idaapi import *
from idautils import *
from PyQt5 import QtCore, QtGui, QtWidgets
#-------------------------------------------------------------------------------
# Constants unexported in IDA Python
PRTYPE_SEMI = 0x0008
# Messages
MSG_RELAXED_RATIO_ENABLED = """AUTOHIDE DATABASE\n
Relaxed ratio calculations can be enabled. It will ignore many small
modifications to functions and will match more functions with higher ratios.
Enable this option if you're only interested in the new functionality. Disable
it for patch diffing if you're interested in small modifications (like buffer
sizes).
This is recommended for diffing big databases (more than 20,000 functions in the
database).
You can disable it by un-checking the 'Relaxed calculations of differences
ratios' option."""
MSG_FUNCTION_SUMMARIES_ONLY = """AUTOHIDE DATABASE\n
Do not export basic blocks or instructions will be enabled. It will not export
the information relative to basic blocks or instructions and 'Diff assembly in a
graph' will not be available.
This is automatically done for exporting huge databases with more than 100,000
functions. You can disable it by un-checking the 'Do not export basic blocks or
instructions' option."""
LITTLE_ORANGE = 0x026AFD
#-------------------------------------------------------------------------------
def log(message):
msg("[%s] %s\n" % (time.asctime(), message))
#-------------------------------------------------------------------------------
def log_refresh(msg, show=False, do_log=True):
if show:
show_wait_box(msg)
else:
replace_wait_box(msg)
if do_log:
log(msg)
#-------------------------------------------------------------------------------
# TODO: FIX hack
diaphora.log = log
diaphora.log_refresh = log_refresh
#-------------------------------------------------------------------------------
g_bindiff = None
def show_choosers():
global g_bindiff
if g_bindiff is not None:
g_bindiff.show_choosers(False)
#-------------------------------------------------------------------------------
def save_results():
global g_bindiff
if g_bindiff is not None:
filename = ask_file(1, "*.diaphora", "Select the file to store diffing results")
if filename is not None:
g_bindiff.save_results(filename)
#-------------------------------------------------------------------------------
def load_results():
tmp_diff = CIDABinDiff(":memory:")
filename = ask_file(0, "*.diaphora", "Select the file to load diffing results")
if filename is not None:
tmp_diff.load_results(filename)
#-------------------------------------------------------------------------------
def import_definitions():
tmp_diff = diaphora.CIDABinDiff(":memory:")
filename = ask_file(0, "*.sqlite", "Select the file to import structures, unions and enumerations from")
if filename is not None:
if ask_yn(1, "HIDECANCEL\nDo you really want to import all structures, unions and enumerations?") == 1:
tmp_diff.import_definitions_only(filename)
#-------------------------------------------------------------------------------
def diaphora_decode(ea):
ins = idaapi.insn_t()
decoded_size = idaapi.decode_insn(ins, ea)
return decoded_size, ins
#-------------------------------------------------------------------------------
class CHtmlViewer(PluginForm):
def OnCreate(self, form):
self.parent = self.FormToPyQtWidget(form)
self.PopulateForm()
self.browser = None
self.layout = None
return 1
def PopulateForm(self):
self.layout = QtWidgets.QVBoxLayout()
self.browser = QtWidgets.QTextBrowser()
self.browser.setLineWrapMode(QtWidgets.QTextEdit.FixedColumnWidth)
self.browser.setLineWrapColumnOrWidth(150)
self.browser.setHtml(self.text)
self.browser.setReadOnly(True)
self.browser.setFontWeight(12)
self.layout.addWidget(self.browser)
self.parent.setLayout(self.layout)
def Show(self, text, title):
self.text = text
return PluginForm.Show(self, title)
#-------------------------------------------------------------------------------
class CBasicChooser(Choose):
def __init__(self, title):
Choose.__init__(
self,
title,
[ ["Id", 10 | Choose.CHCOL_PLAIN] ,
["Name", 30 | Choose.CHCOL_PLAIN] ])
self.items = []
def OnGetSize(self):
return len(self.items)
def OnGetLine(self, n):
return self.items[n]
#-------------------------------------------------------------------------------
# Hex-Rays finally removed AddCommand(). Now, instead of a 1 line call, we need
# 2 classes...
class command_handler_t(ida_kernwin.action_handler_t):
def __init__(self, obj, cmd_id, num_args = 2):
self.obj = obj
self.cmd_id = cmd_id
self.num_args = num_args
ida_kernwin.action_handler_t.__init__(self)
def activate(self, ctx):
if self.num_args == 1:
return self.obj.OnCommand(self.cmd_id)
if len(self.obj.selected_items) == 0:
sel = 0
else:
sel = self.obj.selected_items[0]
return self.obj.OnCommand(sel, self.cmd_id)
def update(self, ctx):
return idaapi.AST_ENABLE_ALWAYS
#-------------------------------------------------------------------------------
# Support for the removed AddCommand() API
class CDiaphoraChooser(diaphora.CChooser, Choose):
def __init__(self, title, bindiff, show_commands = True):
diaphora.CChooser.__init__(self, title, bindiff, show_commands)
self.actions = []
def AddCommand(self, menu_name, shortcut=None):
if menu_name is not None:
action_name = "Diaphora:%s" % menu_name.replace(" ", "")
else:
action_name = None
self.actions.append([len(self.actions), action_name, menu_name, shortcut])
return len(self.actions)-1
def OnPopup(self, form, popup_handle):
for num, action_name, menu_name, shortcut in self.actions:
if menu_name is None:
ida_kernwin.attach_action_to_popup(form, popup_handle, None)
else:
handler = command_handler_t(self, num, 2)
desc = ida_kernwin.action_desc_t(action_name, menu_name, handler, shortcut)
ida_kernwin.attach_dynamic_action_to_popup(form, popup_handle, desc)
#-------------------------------------------------------------------------------
class CIDAChooser(CDiaphoraChooser):
def __init__(self, title, bindiff, show_commands=True):
CDiaphoraChooser .__init__(self, title, bindiff, show_commands)
if title.startswith("Unmatched in"):
Choose.__init__(self, title, [ ["Line", 8], ["Address", 8], ["Name", 20] ], Choose.CH_MULTI)
else:
Choose.__init__(self, title, [ ["Line", 8], ["Address", 8], ["Name", 20], ["Address 2", 8], ["Name 2", 20],
["Ratio", 5], ["BBlocks 1", 5], ["BBlocks 2", 5], ["Description", 30] ], Choose.CH_MULTI)
def OnSelectLine(self, n):
item = self.items[n[0]]
if self.primary:
try:
jump_ea = int(item[1], 16)
# Only jump for valid addresses
if is_mapped(jump_ea):
jumpto(jump_ea)
except:
print("OnSelectLine", sys.exc_info()[1])
else:
self.bindiff.show_asm(self.items[n[0]], self.primary)
def OnGetLine(self, n):
try:
return self.items[n]
except:
print("OnGetLine", sys.exc_info()[1])
def OnGetSize(self):
return len(self.items)
def OnDeleteLine(self, items):
for n in items:
if n >= 0:
name1 = self.items[n][2]
name2 = self.items[n][4]
del self.items[n]
if name1 in self.bindiff.matched1:
self.bindiff.matched1.remove(name1)
if name2 in self.bindiff.matched2:
self.bindiff.matched2.remove(name2)
return [Choose.ALL_CHANGED] + items
def show(self, force=False):
if self.show_commands:
self.items = sorted(self.items, key=lambda x: decimal.Decimal(x[5]), reverse=True)
t = self.Show()
if t < 0:
return False
if self.show_commands and (self.cmd_diff_asm is None or force):
# create aditional actions handlers
self.cmd_rediff = self.AddCommand("Diff again")
self.cmd_save_results = self.AddCommand("Save results")
self.cmd_add_manual_match = self.AddCommand("Add manual match")
self.AddCommand(None)
self.cmd_diff_asm = self.AddCommand("Diff assembly")
self.cmd_diff_c = self.AddCommand("Diff pseudo-code")
self.cmd_diff_graph = self.AddCommand("Diff assembly in a graph")
self.cmd_diff_c_patch = self.AddCommand("Show pseudo-code patch")
self.AddCommand(None)
self.cmd_import_selected = self.AddCommand("Import selected", "Ctrl+Alt+i")
self.cmd_import_selected_auto = self.AddCommand("Import selected sub_*")
self.cmd_import_all = self.AddCommand("Import *all* functions")
self.cmd_import_all_funcs = self.AddCommand("Import *all* data for sub_* functions")
self.AddCommand(None)
self.cmd_highlight_functions = self.AddCommand("Highlight matches")
self.cmd_unhighlight_functions = self.AddCommand("Unhighlight matches")
elif not self.show_commands and (self.cmd_show_asm is None or force):
self.cmd_show_asm = self.AddCommand("Show assembly")
self.cmd_show_pseudo = self.AddCommand("Show pseudo-code")
return True
def OnCommand(self, n, cmd_id):
# Aditional right-click-menu commands handles
if cmd_id == self.cmd_show_asm:
self.bindiff.show_asm(self.items[n], self.primary)
elif cmd_id == self.cmd_show_pseudo:
self.bindiff.show_pseudo(self.items[n], self.primary)
elif cmd_id == self.cmd_import_all:
if ask_yn(1, "HIDECANCEL\nDo you really want to import all matched functions, comments, prototypes and definitions?") == 1:
self.bindiff.import_all(self.items)
elif cmd_id == self.cmd_import_all_funcs:
if ask_yn(1, "HIDECANCEL\nDo you really want to import all IDA named matched functions, comments, prototypes and definitions?") == 1:
self.bindiff.import_all_auto(self.items)
elif cmd_id == self.cmd_import_selected or cmd_id == self.cmd_import_selected_auto:
if len(self.selected_items) <= 1:
self.bindiff.import_one(self.items[n])
else:
if ask_yn(1, "HIDECANCEL\nDo you really want to import all selected IDA named matched functions, comments, prototypes and definitions?") == 1:
self.bindiff.import_selected(self.items, self.selected_items, cmd_id == self.cmd_import_selected_auto)
elif cmd_id == self.cmd_diff_c:
self.bindiff.show_pseudo_diff(self.items[n])
elif cmd_id == self.cmd_diff_c_patch:
self.bindiff.show_pseudo_diff(self.items[n], html=False)
elif cmd_id == self.cmd_diff_asm:
self.bindiff.show_asm_diff(self.items[n])
elif cmd_id == self.cmd_highlight_functions:
if ask_yn(1, "HIDECANCEL\nDo you want to change the background color of each matched function?") == 1:
color = self.get_color()
for item in self.items:
ea = int(item[1], 16)
if not set_color(ea, CIC_FUNC, color):
print("Error setting color for %x" % ea)
self.Refresh()
elif cmd_id == self.cmd_unhighlight_functions:
for item in self.items:
ea = int(item[1], 16)
if not set_color(ea, CIC_FUNC, 0xFFFFFF):
print("Error setting color for %x" % ea)
self.Refresh()
elif cmd_id == self.cmd_diff_graph:
item = self.items[n]
ea1 = int(item[1], 16)
name1 = item[2]
ea2 = int(item[3], 16)
name2 = item[4]
log("Diff graph for 0x%x - 0x%x" % (ea1, ea2))
self.bindiff.graph_diff(ea1, name1, ea2, name2)
elif cmd_id == self.cmd_save_results:
filename = ask_file(1, "*.diaphora", "Select the file to store diffing results")
if filename is not None:
self.bindiff.save_results(filename)
elif cmd_id == self.cmd_add_manual_match:
self.add_manual_match()
elif cmd_id == self.cmd_rediff:
self.bindiff.db.execute("detach diff")
timeraction_t(self.bindiff.re_diff, None, 1000)
return True
def get_diff_functions(self):
cur = self.bindiff.db_cursor()
cur.execute("select cast(id as text), name from diff.functions order by id")
rows = list(cur.fetchall())
rows = list(map(list, rows))
cur.close()
return rows
def add_manual_match(self):
f = choose_func("Select a function from the current database...", 0)
if f is not None:
diff_chooser = CBasicChooser("Select a function from the external database...")
diff_funcs = self.get_diff_functions()
diff_chooser.items = diff_funcs
ret = diff_chooser.Show(modal=True)
if ret > -1:
name1 = get_func_name(f.start_ea)
name2 = diff_funcs[ret][1]
if name1 in self.bindiff.matched1 or name2 in self.bindiff.matched2:
line = "Either the local function %s or the foreign function %s are already matched.\n" + \
"Please remove the previously assigned match before adding a manual match."
warning(line % (repr(name1), repr(name2)))
else:
log("Adding manual match between %s and %s" % (name1, name2))
sql = """ select distinct f.address ea, f.name name1, df.address ea2, df.name name2,
'Manual Match' description,
f.pseudocode pseudo1, df.pseudocode pseudo2,
f.assembly asm1, df.assembly asm2,
f.pseudocode_primes pseudo_primes1, df.pseudocode_primes pseudo_primes2,
f.nodes bb1, df.nodes bb2,
cast(f.md_index as real) md1, cast(df.md_index as real) md2
from functions f,
diff.functions df
where f.name = %s
and df.name = %s""" % (repr(name1), repr(name2))
self.bindiff.add_matches_from_query_ratio(sql, self.bindiff.best_chooser, self.bindiff.partial_chooser)
for chooser in [self.bindiff.best_chooser, self.bindiff.partial_chooser, self.bindiff.unreliable_chooser]:
chooser.Refresh()
def OnSelectionChange(self, sel_list):
self.selected_items = sel_list
def seems_false_positive(self, item):
name1 = item[2]
name2 = item[4]
name1 = name1.rstrip("_0")
name2 = name2.rstrip("_0")
if not name1.startswith("sub_") and not name2.startswith("sub_"):
if name1 != name2:
if name2.find(name1) == -1 and not name1.find(name2) == -1:
return True
return False
def OnGetLineAttr(self, n):
if not self.title.startswith("Unmatched"):
item = self.items[n]
ratio = float(item[5])
if self.seems_false_positive(item):
return [LITTLE_ORANGE, 0]
else:
red = int(164 * (1 - ratio))
green = int(128 * ratio)
blue = int(255 * (1 - ratio))
color = int("0x%02x%02x%02x" % (blue, green, red), 16)
return [color, 0]
return [0xFFFFFF, 0]
#-------------------------------------------------------------------------------
class CBinDiffExporterSetup(Form):
def __init__(self):
s = r"""Diaphora
Please select the path to the SQLite database to save the current IDA database and the path of the SQLite database to diff against.
If no SQLite diff database is selected, it will just export the current IDA database to SQLite format. Leave the 2nd field empty if you are
exporting the first database.
SQLite databases: Export filter limits:
<#Select a file to export the current IDA database to SQLite format#Export IDA database to SQLite :{iFileSave}> <#Minimum address to find functions to export#From address:{iMinEA}>
<#Select the SQLite database to diff against #SQLite database to diff against:{iFileOpen}> <#Maximum address to find functions to export#To address :{iMaxEA}>
<Use the decompiler if available:{rUseDecompiler}>
<Do not export library and thunk functions:{rExcludeLibraryThunk}>
<#Enable if you want neither sub_* functions nor library functions to be exported#Export only non-IDA generated functions:{rNonIdaSubs}>
<#Export only function summaries, not all instructions. Showing differences in a graph between functions will not be available.#Do not export instructions and basic blocks:{rFuncSummariesOnly}>
<Use probably unreliable methods:{rUnreliable}>
<Recommended to disable with databases with more than 5.000 functions#Use slow heuristics:{rSlowHeuristics}>
<#Enable this option if you aren't interested in small changes#Relaxed calculations of differences ratios:{rRelaxRatio}>
<Use experimental heuristics:{rExperimental}>
<#Enable this option to ignore sub_* names for the 'Same name' heuristic.#Ignore automatically generated names:{rIgnoreSubNames}>
<#Enable this option to ignore all function names for the 'Same name' heuristic.#Ignore all function names:{rIgnoreAllNames}>
<#Enable this option to ignore thunk functions, nullsubs, etc....#Ignore small functions:{rIgnoreSmallFunctions}>{cGroup1}>
Project specific rules:
<#Select the project specific Python script rules#Python script:{iProjectSpecificRules}>
NOTE: Don't select IDA database files (.IDB, .I64) as only SQLite databases are considered.
"""
args = {'iFileSave': Form.FileInput(save=True, swidth=40),
'iFileOpen': Form.FileInput(open=True, swidth=40),
'iMinEA': Form.NumericInput(tp=Form.FT_HEX, swidth=22),
'iMaxEA': Form.NumericInput(tp=Form.FT_HEX, swidth=22),
'cGroup1' : Form.ChkGroupControl(("rUseDecompiler",
"rExcludeLibraryThunk",
"rUnreliable",
"rNonIdaSubs",
"rSlowHeuristics",
"rRelaxRatio",
"rExperimental",
"rFuncSummariesOnly",
"rIgnoreSubNames",
"rIgnoreAllNames",
"rIgnoreSmallFunctions")),
'iProjectSpecificRules' : Form.FileInput(open=True)}
Form.__init__(self, s, args)
def set_options(self, opts):
if opts.file_out is not None:
self.iFileSave.value = opts.file_out
if opts.file_in is not None:
self.iFileOpen.value = opts.file_in
if opts.project_script is not None:
self.iProjectSpecificRules.value = opts.project_script
self.rUseDecompiler.checked = opts.use_decompiler
self.rExcludeLibraryThunk.checked = opts.exclude_library_thunk
self.rUnreliable.checked = opts.unreliable
self.rSlowHeuristics.checked = opts.slow
self.rRelaxRatio.checked = opts.relax
self.rExperimental.checked = opts.experimental
self.iMinEA.value = opts.min_ea
self.iMaxEA.value = opts.max_ea
self.rNonIdaSubs.checked = opts.ida_subs == False
self.rIgnoreSubNames.checked = opts.ignore_sub_names
self.rIgnoreAllNames.checked = opts.ignore_all_names
self.rIgnoreSmallFunctions.checked = opts.ignore_small_functions
self.rFuncSummariesOnly.checked = opts.func_summaries_only
def get_options(self):
opts = dict(
file_out = self.iFileSave.value,
file_in = self.iFileOpen.value,
use_decompiler = self.rUseDecompiler.checked,
exclude_library_thunk = self.rExcludeLibraryThunk.checked,
unreliable = self.rUnreliable.checked,
slow = self.rSlowHeuristics.checked,
relax = self.rRelaxRatio.checked,
experimental = self.rExperimental.checked,
min_ea = self.iMinEA.value,
max_ea = self.iMaxEA.value,
ida_subs = self.rNonIdaSubs.checked == False,
ignore_sub_names = self.rIgnoreSubNames.checked,
ignore_all_names = self.rIgnoreAllNames.checked,
ignore_small_functions = self.rIgnoreSmallFunctions.checked,
func_summaries_only = self.rFuncSummariesOnly.checked,
project_script = self.iProjectSpecificRules.value
)
return BinDiffOptions(**opts)
#-------------------------------------------------------------------------------
class timeraction_t(object):
def __init__(self, func, args, interval):
self.func = func
self.args = args
self.interval = interval
self.obj = idaapi.register_timer(self.interval, self)
if self.obj is None:
raise RuntimeError("Failed to register timer")
def __call__(self):
if self.args is not None:
self.func(self.args)
else:
self.func()
return -1
#-------------------------------------------------------------------------------
class uitimercallback_t(object):
def __init__(self, g, interval):
self.interval = interval
self.obj = idaapi.register_timer(self.interval, self)
if self.obj is None:
raise RuntimeError("Failed to register timer")
self.g = g
def __call__(self):
f = find_widget(self.g._title)
activate_widget(f, 1)
process_ui_action("GraphZoomFit", 0)
return -1
#-------------------------------------------------------------------------------
class CDiffGraphViewer(GraphViewer):
def __init__(self, title, g, colours):
try:
GraphViewer.__init__(self, title, False)
self.graph = g[0]
self.relations = g[1]
self.nodes = {}
self.colours = colours
except:
warning("CDiffGraphViewer: OnInit!!! " + str(sys.exc_info()[1]))
def OnRefresh(self):
try:
self.Clear()
self.nodes = {}
for key in self.graph:
self.nodes[key] = self.AddNode([key, self.graph[key]])
for key in self.relations:
if not key in self.nodes:
self.nodes[key] = self.AddNode([key, [[0, 0, ""]]])
parent_node = self.nodes[key]
for child in self.relations[key]:
if not child in self.nodes:
self.nodes[child] = self.AddNode([child, [[0, 0, ""]]])
child_node = self.nodes[child]
self.AddEdge(parent_node, child_node)
return True
except:
print("GraphViewer Error:", sys.exc_info()[1])
return True
def OnGetText(self, node_id):
try:
ea, rows = self[node_id]
if ea in self.colours:
colour = self.colours[ea]
else:
colour = 0xFFFFFF
ret = []
for row in rows:
ret.append(row[2])
label = "\n".join(ret)
return (label, colour)
except:
print("GraphViewer.OnGetText:", sys.exc_info()[1])
return ("ERROR", 0x000000)
def Show(self):
return GraphViewer.Show(self)
#-------------------------------------------------------------------------------
class CIdaMenuHandlerShowChoosers(idaapi.action_handler_t):
def __init__(self):
idaapi.action_handler_t.__init__(self)
def activate(self, ctx):
show_choosers()
return 1
def update(self, ctx):
return idaapi.AST_ENABLE_ALWAYS
#-------------------------------------------------------------------------------
class CIdaMenuHandlerSaveResults(idaapi.action_handler_t):
def __init__(self):
idaapi.action_handler_t.__init__(self)
def activate(self, ctx):
save_results()
return 1
def update(self, ctx):
return idaapi.AST_ENABLE_ALWAYS
#-------------------------------------------------------------------------------
class CIdaMenuHandlerLoadResults(idaapi.action_handler_t):
def __init__(self):
idaapi.action_handler_t.__init__(self)
def activate(self, ctx):
load_results()
return 1
def update(self, ctx):
return idaapi.AST_ENABLE_ALWAYS
#-------------------------------------------------------------------------------
class CIDABinDiff(diaphora.CBinDiff):
def __init__(self, db_name):
diaphora.CBinDiff.__init__(self, db_name, chooser=CIDAChooser)
self.decompiler_available = True
self.names = dict(Names())
self.min_ea = get_inf_attr(INF_MIN_EA)
self.max_ea = get_inf_attr(INF_MAX_EA)
self.project_script = None
self.hooks = None
def load_hooks(self):
if self.project_script is None or self.project_script == "":
return True
try:
log("Loading project specific Python script %s" % self.project_script)
module = imp.load_source("diaphora_hooks", self.project_script)
except:
print("Error loading project specific Python script: %s" % str(sys.exc_info()[1]))
return False
if module is None:
# How can it be?
return False
keys = dir(module)
if 'HOOKS' not in keys:
log("Error: The project specific script doesn't export the HOOKS dictionary")
return False
hooks = module.HOOKS
if 'DiaphoraHooks' not in hooks:
log("Error: The project specific script exports the HOOK dictionary but it doesn't contain a 'DiaphoraHooks' entry.")
return False
hook_class = hooks["DiaphoraHooks"]
self.hooks = hook_class(self)
return True
def refresh(self):
idaapi.request_refresh(0xFFFFFFFF)
def show_choosers(self, force=False):
if len(self.best_chooser.items) > 0:
self.best_chooser.show(force)
if len(self.partial_chooser.items) > 0:
self.partial_chooser.show(force)
if self.unreliable_chooser is not None and len(self.unreliable_chooser.items) > 0:
self.unreliable_chooser.show(force)
if self.unmatched_primary is not None and len(self.unmatched_primary.items) > 0:
self.unmatched_primary.show(force)
if self.unmatched_second is not None and len(self.unmatched_second.items) > 0:
self.unmatched_second.show(force)
def diff(self, db):
res = diaphora.CBinDiff.diff(self, db)
if res:
# And, finally, show the list of best and partial matches and
# register the hotkey for re-opening results
self.show_choosers()
self.register_menu()
hide_wait_box()
return res
def get_last_crash_func(self):
sql = "select address from functions order by id desc limit 1"
cur = self.db_cursor()
cur.execute(sql)
row = cur.fetchone()
if not row:
return None
address = int(row[0])
cur.close()
return address
def recalculate_primes(self):
sql = "select primes_value from functions"
callgraph_primes = 1
callgraph_all_primes = {}
cur = self.db_cursor()
cur.execute(sql)
for row in cur.fetchall():
ret = row[0]
callgraph_primes *= decimal.Decimal(row[0])
try:
callgraph_all_primes[ret] += 1
except KeyError:
callgraph_all_primes[ret] = 1
cur.close()
return callgraph_primes, callgraph_all_primes
def do_export(self, crashed_before = False):
callgraph_primes = 1
callgraph_all_primes = {}
func_list = list(Functions(self.min_ea, self.max_ea))
total_funcs = len(func_list)
t = time.time()
if crashed_before:
start_func = self.get_last_crash_func()
if start_func is None:
warning("Diaphora cannot resume the previous crashed session, the export process will start from scratch.")
crashed_before = False
else:
callgraph_primes, callgraph_all_primes = self.recalculate_primes()
self.db.commit()
self.db.execute("PRAGMA synchronous = OFF")
self.db.execute("PRAGMA journal_mode = MEMORY")
self.db.execute("BEGIN transaction")
i = 0
for func in func_list:
if user_cancelled():
raise Exception("Canceled.")
i += 1
if (total_funcs >= 100) and i % (int(total_funcs/100)) == 0 or i == 1:
line = "Exported %d function(s) out of %d total.\nElapsed %d:%02d:%02d second(s), remaining time ~%d:%02d:%02d"
elapsed = time.time() - t
remaining = (elapsed / i) * (total_funcs - i)
m, s = divmod(remaining, 60)
h, m = divmod(m, 60)
m_elapsed, s_elapsed = divmod(elapsed, 60)
h_elapsed, m_elapsed = divmod(m_elapsed, 60)
replace_wait_box(line % (i, total_funcs, h_elapsed, m_elapsed, s_elapsed, h, m, s))
if crashed_before:
rva = func - self.get_base_address()
if rva != start_func:
continue
# When we get to the last function that was previously exported, switch
# off the 'crash' flag and continue with the next row.
crashed_before = False
continue
props = self.read_function(func)
if props == False:
continue
ret = props[11]
callgraph_primes *= decimal.Decimal(ret)
try:
callgraph_all_primes[ret] += 1
except KeyError:
callgraph_all_primes[ret] = 1
self.save_function(props)
# Try to fix bug #30 and, also, try to speed up operations as
# doing a commit every 10 functions, as before, is overkill.
if total_funcs > 5000 and i % (total_funcs/10) == 0:
self.db.commit()
self.db.execute("PRAGMA synchronous = OFF")
self.db.execute("PRAGMA journal_mode = MEMORY")
self.db.execute("BEGIN transaction")
md5sum = GetInputFileMD5()
self.save_callgraph(str(callgraph_primes), json.dumps(callgraph_all_primes), md5sum)
self.export_structures()
self.export_til()
replace_wait_box("Creating indexes...")
self.create_indexes()
def export(self):
if self.project_script is not None:
log("Loading project specific Python script...")
if not self.load_hooks():
return False
crashed_before = False
crash_file = "%s-crash" % self.db_name
if os.path.exists(crash_file):
log("Resuming a previously crashed session...")
crashed_before = True
log("Creating crash file %s..." % crash_file)
with open(crash_file, "wb") as f:
f.close()
try:
show_wait_box("Exporting database")
self.do_export(crashed_before)
finally:
hide_wait_box()
self.db.commit()
log("Removing crash file %s-crash..." % self.db_name)
os.remove("%s-crash" % self.db_name)
cur = self.db_cursor()
cur.execute("analyze")
cur.close()
self.db_close()
def import_til(self):
log("Importing type libraries...")
cur = self.db_cursor()
sql = "select name from diff.program_data where type = 'til'"
cur.execute(sql)
for row in cur.fetchall():
til = row["name"]
if type(til) is bytes:
til = til.decode("utf-8")
try:
add_default_til(til)
except:
log("Error loading til %s: %s" % (row["name"], str(sys.exc_info()[1])))
cur.close()
auto_wait()
def import_definitions(self):
cur = self.db_cursor()
sql = "select type, name, value from diff.program_data where type in ('structure', 'struct', 'enum')"
cur.execute(sql)
rows = diaphora.result_iter(cur)
new_rows = set()
for row in rows:
if row["name"] is None:
continue
the_name = row["name"].split(" ")[0]
if get_struc_id(the_name) == BADADDR:
type_name = "struct"
if row["type"] == "enum":
type_name = "enum"
elif row["type"] == "union":
type_name == "union"
new_rows.add(row)
line = "%s %s;" % (type_name, row["name"])
try:
ret = idc.parse_decls(line)
if ret != 0:
pass
except:
log("Error importing type: %s" % str(sys.exc_info()[1]))
for _ in range(10):
for row in new_rows:
if row["name"] is None:
continue
the_name = row["name"].split(" ")[0]
if get_struc_id(the_name) == BADADDR and get_struc_id(row["name"]) == BADADDR:
definition = self.get_valid_definition(row["value"])
ret = idc.parse_decls(definition) # Remove the "idc." to reproduce some strange behaviour
if ret != 0:
pass
cur.close()
auto_wait()
def reinit(self, main_db, diff_db, create_choosers=True):
log("Main database '%s'." % main_db)
log("Diff database '%s'." % diff_db)
self.__init__(main_db)
self.attach_database(diff_db)
if create_choosers:
self.create_choosers()
def import_definitions_only(self, filename):
self.reinit(":memory:", filename)
self.import_til()
self.import_definitions()
def show_asm_diff(self, item):
cur = self.db_cursor()
sql = """select *
from (
select prototype, assembly, name, 1
from functions
where address = ?
and assembly is not null
union select prototype, assembly, name, 2
from diff.functions
where address = ?
and assembly is not null)
order by 4 asc"""
ea1 = str(int(item[1], 16))
ea2 = str(int(item[3], 16))
cur.execute(sql, (ea1, ea2))
rows = cur.fetchall()
if len(rows) != 2:
warning("Sorry, there is no assembly available for either the first or the second database.")
else:
row1 = rows[0]
row2 = rows[1]
html_diff = CHtmlDiff()
asm1 = self.prettify_asm(row1["assembly"])
asm2 = self.prettify_asm(row2["assembly"])
buf1 = "%s proc near\n%s\n%s endp" % (row1["name"], asm1, row1["name"])
buf2 = "%s proc near\n%s\n%s endp" % (row2["name"], asm2, row2["name"])
fmt = HtmlFormatter()
fmt.noclasses = True
fmt.linenos = False
fmt.nobackground = True
src = html_diff.make_file(buf1.split("\n"), buf2.split("\n"), fmt, NasmLexer())
title = "Diff assembler %s - %s" % (row1["name"], row2["name"])
cdiffer = CHtmlViewer()
cdiffer.Show(src, title)
cur.close()
def import_one(self, item):
ret = ask_yn(1, "AUTOHIDE DATABASE\nDo you want to import all the type libraries, structs and enumerations?")
if ret == 1:
# Import all the type libraries from the diff database
self.import_til()
# Import all the struct and enum definitions
self.import_definitions()
elif ret == -1:
return
# Import just the selected item
ea1 = str(int(item[1], 16))
ea2 = str(int(item[3], 16))
self.do_import_one(ea1, ea2, True)
new_func = self.read_function(str(ea1))
self.delete_function(ea1)
self.save_function(new_func)
self.db.commit()
self.update_choosers()
def show_asm(self, item, primary):
cur = self.db_cursor()
if primary:
db = "main"
else:
db = "diff"
ea = str(int(item[1], 16))
sql = "select prototype, assembly, name from %s.functions where address = ?"
sql = sql % db
cur.execute(sql, (ea, ))
row = cur.fetchone()
if row is None: