-
-
Notifications
You must be signed in to change notification settings - Fork 373
/
diaphora_ida.py
4076 lines (3493 loc) · 123 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-2024, 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 time
import json
import decimal
import difflib
import sqlite3
import datetime
import traceback
from hashlib import md5
# pylint: disable=wildcard-import
# pylint: disable=unused-wildcard-import
from idc import *
from idaapi import *
from idautils import *
# pylint: enable=unused-wildcard-import
# pylint: enable=wildcard-import
import idaapi
idaapi.require("diaphora")
try:
import ida_hexrays as hr
HAS_HEXRAYS = True
except ImportError:
HAS_HEXRAYS = False
sys.path.append(os.path.join(os.path.dirname(__file__), "codecut"))
from codecut import lfa
from pygments import highlight
from pygments.lexers import NasmLexer, CppLexer, DiffLexer
from pygments.formatters import HtmlFormatter
import diaphora_config as config
from others.tarjan_sort import strongly_connected_components, robust_topological_sort
from jkutils.factor import primesbelow
from jkutils.graph_hashes import CKoretKaramitasHash
try:
from jkutils.IDAMagicStrings import get_source_strings
HAS_GET_SOURCE_STRINGS = True
except ImportError:
print(f"Error loading IDAMagicStrings.py: {str(sys.exc_info()[1])}")
HAS_GET_SOURCE_STRINGS = False
# pylint: disable-next=wrong-import-order
from PyQt5 import QtWidgets
#-------------------------------------------------------------------------------
# Chooser items indices. They do differ from the CChooser.item items that are
# handled in diaphora.py.
import diaphora
CHOOSER_ITEM_MAIN_EA = diaphora.ITEM_MAIN_EA + 1
CHOOSER_ITEM_MAIN_NAME = diaphora.ITEM_MAIN_NAME + 1
CHOOSER_ITEM_DIFF_EA = diaphora.ITEM_DIFF_EA + 1
CHOOSER_ITEM_DIFF_NAME = diaphora.ITEM_DIFF_NAME + 1
CHOOSER_ITEM_RATIO = diaphora.ITEM_RATIO
# 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).
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
#-------------------------------------------------------------------------------
# Python linter specific things to disable (temporarily, I guess...)
#
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
# pylint: disable=protected-access
#-------------------------------------------------------------------------------
def log(message):
"""
Print a message
"""
print(f"[Diaphora: {time.asctime()}] {message}")
#-------------------------------------------------------------------------------
def log_refresh(message, show=False, do_log=True):
"""
Print a message and refresh the UI.
"""
if show:
show_wait_box(message)
else:
replace_wait_box(message)
if user_cancelled():
raise Exception("Cancelled")
if do_log:
log(message)
#-------------------------------------------------------------------------------
def debug_refresh(message):
"""
Print a debugging message if debugging is enabled.
"""
if os.getenv("DIAPHORA_DEBUG"):
log(message)
#-------------------------------------------------------------------------------
diaphora.log = log
diaphora.log_refresh = log_refresh
#-------------------------------------------------------------------------------
# pylint: disable=global-variable-not-assigned
g_bindiff = None
def show_choosers():
"""
Show the non empty choosers.
"""
if g_bindiff is not None:
g_bindiff.show_choosers(False)
#-------------------------------------------------------------------------------
def save_results():
"""
Show the dialogue to save the diffing results.
"""
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)
# pylint: enable=global-variable-not-assigned
#-------------------------------------------------------------------------------
def load_and_import_all_results(filename, main_db, diff_db):
"""
Load the diffing results and import all matches.
"""
tmp_diff = CIDABinDiff(":memory:")
if os.path.exists(filename) and os.path.exists(main_db) and os.path.exists(diff_db):
tmp_diff.load_and_import_all_results(filename, main_db, diff_db)
idaapi.qexit(0)
#-------------------------------------------------------------------------------
def load_results():
"""
Load previously saved diffing 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():
"""
Import *only* the definitions (struct, enums and unions).
"""
tmp_diff = CIDABinDiff(":memory:")
message = "Select the file to import structures, unions and enumerations from"
filename = ask_file(0, "*.sqlite", message)
if filename is not None:
message = "HIDECANCEL\nDo you really want to import all structures, unions and enumerations?"
if ask_yn(1, message) == 1:
tmp_diff.import_definitions_only(filename)
#-------------------------------------------------------------------------------
def diaphora_decode(ea):
"""
Wrapper for IDA's decode_insn
"""
ins = idaapi.insn_t()
decoded_size = idaapi.decode_insn(ins, ea)
return decoded_size, ins
#-------------------------------------------------------------------------------
def get_string_at(ea):
"""
Get the defined string at the given address.
"""
if ida_bytes.is_mapped(ea):
return get_strlit_contents(ea, -1, -1)
return None
#-------------------------------------------------------------------------------
# pylint: disable=redefined-outer-name
# pylint: disable=arguments-renamed
# pylint: disable=attribute-defined-outside-init
# pylint: disable=c-extension-no-member
class CHtmlViewer(PluginForm):
"""
Class used to graphically show the differences.
"""
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.layout.addWidget(self.browser)
self.parent.setLayout(self.layout)
def Show(self, text, title):
self.text = text
return PluginForm.Show(self, title)
# pylint: enable=c-extension-no-member
# pylint: enable=attribute-defined-outside-init
# pylint: enable=arguments-renamed
# pylint: enable=redefined-outer-name
#-------------------------------------------------------------------------------
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
# pylint: disable=super-init-not-called
# pylint: disable=arguments-differ
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:
tmp = menu_name.replace(" ", "")
action_name = f"Diaphora:{tmp}"
else:
action_name = None
self.actions.append([len(self.actions), action_name, menu_name, shortcut])
return len(self.actions) - 1
def OnPopup(self, widget, popup_handle):
for num, action_name, menu_name, shortcut in self.actions:
if menu_name is None:
ida_kernwin.attach_action_to_popup(widget, 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(widget, popup_handle, desc)
# pylint: enable=arguments-differ
# pylint: enable=super-init-not-called
#-------------------------------------------------------------------------------
class CIDAChooser(CDiaphoraChooser):
"""
Wrapper class for IDA choosers
"""
# pylint: disable=non-parent-init-called
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", 10], ["Name", 20]],
Choose.CH_MULTI,
)
else:
columns = [
["Line", 8],
["Address", 10],
["Name", 20],
["Address 2", 10],
["Name 2", 20],
["Ratio", 8],
["BBlocks 1", 5],
["BBlocks 2", 5],
["Description", 30],
]
Choose.__init__(self, title, columns, Choose.CH_MULTI)
# pylint: enable=non-parent-init-called
def OnSelectLine(self, sel):
item = self.items[sel[0]]
if self.primary:
jump_ea = int(item[CHOOSER_ITEM_MAIN_EA], 16)
# Only jump for valid addresses
if is_mapped(jump_ea):
jumpto(jump_ea)
else:
self.bindiff.show_asm(self.items[sel[0]], self.primary)
def OnGetLine(self, n):
return self.items[n]
def OnGetSize(self):
return len(self.items)
def OnDeleteLine(self, sel):
for n in sorted(sel, reverse=True):
if n >= 0:
def get_item(n, index):
try:
return self.items[n][index]
except IndexError:
return None
name1 = get_item(n, CHOOSER_ITEM_MAIN_NAME)
name2 = get_item(n, CHOOSER_ITEM_DIFF_NAME)
del self.items[n]
if name1 in self.bindiff.matched_primary:
del self.bindiff.matched_primary[name1]
if name2 in self.bindiff.matched_secondary:
del self.bindiff.matched_secondary[name2]
return [Choose.ALL_CHANGED] + sel
def show(self, force=False):
"""
Sort items, add menu items and show the chooser.
"""
if self.show_commands:
self.items = sorted(
self.items,
key=lambda x: decimal.Decimal(x[CHOOSER_ITEM_RATIO]),
reverse=True,
)
t = self.Show()
if t < 0:
return False
# pylint: disable=attribute-defined-outside-init
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_microcode = self.AddCommand("Diff microcode")
self.cmd_diff_c = self.AddCommand("Diff pseudo-code")
self.cmd_diff_graph = self.AddCommand("Diff assembly in a graph")
self.cmd_diff_graph_microcode = self.AddCommand("Diff microcode in a graph")
self.cmd_diff_external = self.AddCommand("Diff using an external tool")
self.cmd_diff_asm_patch = self.AddCommand("Show assembly patch")
self.cmd_diff_c_patch = self.AddCommand("Show pseudo-code patch")
self.cmd_view_callgraph_context = self.AddCommand(
"Show callers and callees graph"
)
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")
# pylint: enable=attribute-defined-outside-init
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:
text = "HIDECANCEL\n"
text += "Do you want to import all functions, comments, prototypes and definitions?"
if ask_yn(1, text) == 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_patch:
self.bindiff.show_asm_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_diff_microcode:
self.bindiff.show_microcode_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[CHOOSER_ITEM_MAIN_EA], 16)
if not set_color(ea, CIC_FUNC, color):
# pylint: disable-next=consider-using-f-string
print("Error setting color for %x" % ea)
self.Refresh()
elif cmd_id == self.cmd_unhighlight_functions:
for item in self.items:
ea = int(item[CHOOSER_ITEM_MAIN_EA], 16)
if not set_color(ea, CIC_FUNC, 0xFFFFFF):
# pylint: disable-next=consider-using-f-string
print("Error setting color for %x" % ea)
self.Refresh()
elif cmd_id == self.cmd_diff_graph:
item = self.items[n]
ea1 = int(item[CHOOSER_ITEM_MAIN_EA], 16)
name1 = item[CHOOSER_ITEM_MAIN_NAME]
ea2 = int(item[CHOOSER_ITEM_DIFF_EA], 16)
name2 = item[CHOOSER_ITEM_DIFF_NAME]
# pylint: disable-next=consider-using-f-string
log("Diff graph for 0x%x - 0x%x" % (ea1, ea2))
self.bindiff.graph_diff(ea1, name1, ea2, name2)
elif cmd_id == self.cmd_diff_graph_microcode:
item = self.items[n]
ea1 = int(item[CHOOSER_ITEM_MAIN_EA], 16)
name1 = item[CHOOSER_ITEM_MAIN_NAME]
ea2 = int(item[CHOOSER_ITEM_DIFF_EA], 16)
name2 = item[CHOOSER_ITEM_DIFF_NAME]
# pylint: disable-next=consider-using-f-string
log("Diff microcode graph for 0x%x - 0x%x" % (ea1, ea2))
self.bindiff.graph_diff_microcode(ea1, name1, ea2, name2)
elif cmd_id == self.cmd_view_callgraph_context:
item = self.items[n]
ea1 = int(item[CHOOSER_ITEM_MAIN_EA], 16)
name1 = item[CHOOSER_ITEM_MAIN_NAME]
ea2 = int(item[CHOOSER_ITEM_DIFF_EA], 16)
name2 = item[CHOOSER_ITEM_DIFF_NAME]
# pylint: disable-next=consider-using-f-string
log("Showing call graph context for 0x%x - 0x%x" % (ea1, ea2))
self.bindiff.show_callgraph_context(name1, 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)
elif cmd_id == self.cmd_diff_external:
self.bindiff.diff_external(self.items[n])
return True
def get_diff_functions(self):
"""
Return the functions rows for the diff database
"""
cur = self.bindiff.db_cursor()
try:
cur.execute("select cast(id as text), name, address from diff.functions order by id")
rows = list(cur.fetchall())
rows = list(map(list, rows))
finally:
cur.close()
return rows
def add_manual_match_internal(self, ea1, ea2):
"""
Internal function, add a manual match directly to the partial chooser.
"""
main_row = self.bindiff.get_function_row_by_ea(ea1)
if main_row is None:
warning("Can't find the local function!")
return
diff_row = self.bindiff.get_function_row_by_ea(ea2, "diff")
if diff_row is None:
warning("Can't find the foreign function!")
return
ratio = self.bindiff.compare_function_rows(main_row, diff_row)
ea1 = main_row["address"]
name1 = main_row["name"]
ea2 = diff_row["address"]
name2 = diff_row["name"]
desc = "Manual match"
nodes1 = main_row["nodes"]
nodes2 = diff_row["nodes"]
if name1 in self.bindiff.matched_primary or name2 in self.bindiff.matched_secondary:
line = (
"Either the local function or the foreign function is already matched!\n"
+ "Please remove the previously assigned match before adding a manual match."
)
warning(line)
return
self.bindiff.partial_chooser.add_item(
diaphora.CChooser.Item(ea1, name1, ea2, name2, desc, ratio, nodes1, nodes2)
)
self.bindiff.matched_primary[name1] = {"name": name2, "ratio": ratio}
self.bindiff.matched_secondary[name2] = {"name": name1, "ratio": ratio}
self.bindiff.partial_chooser.Refresh()
def add_manual_match(self):
"""
Menu item handler for adding a manual match.
"""
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:
ea1 = f.start_ea
ea2 = int(diff_funcs[ret][2])
# pylint: disable-next=consider-using-f-string
log("Adding manual match between 0x%08x and 0x%08x" % (ea1, ea2))
self.add_manual_match_internal(ea1, ea2)
def OnSelectionChange(self, sel):
self.selected_items = sel
def seems_false_positive(self, item):
"""
Check if it looks like a false positive because the names are different.
"""
name1 = item[CHOOSER_ITEM_MAIN_NAME]
name2 = item[CHOOSER_ITEM_DIFF_NAME]
name1 = name1.rstrip("_0")
name2 = name2.rstrip("_0")
name1 = name1.strip(".")
name2 = name2.strip(".")
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[CHOOSER_ITEM_RATIO])
if self.seems_false_positive(item):
return [LITTLE_ORANGE, 0]
else:
red = abs(int(164 * (1 - ratio)))
green = abs(int(128 * ratio))
blue = abs(int(255 * (1 - ratio)))
# pylint: disable-next=consider-using-f-string
color = int("0x%02x%02x%02x" % (blue, green, red), 16)
return [color, 0]
return [0xFFFFFF, 0]
#-------------------------------------------------------------------------------
# pylint: disable=no-member
class CBinDiffExporterSetup(Form):
"""
IDA class to build the export dialogue.
"""
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}>
Export options:
<Use the decompiler if available:{rUseDecompiler}>
<#Enable this option to disable exporting microcode#Export microcode instructions and basic blocks:{rExportMicrocode}>
<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}>
<#Enable this option to ignore thunk functions, nullsubs, etc....#Ignore small functions:{rIgnoreSmallFunctions}>{cGroupExport}>|
Diffing options:
<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 speed ups:{rExperimental}##Use tricks to speed ups some of the most common diffing tasks>
<#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 use the Machine Learning engine with an already trained model specified in diaphora_config.py!ML_TRAINED_MODEL.#Use an already trained model:{rUseTrainedModel}>{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, hlp="SQLite database (*.sqlite)"),
"iFileOpen": Form.FileInput(open=True, swidth=40, hlp="SQLite database (*.sqlite)"),
"iMinEA": Form.NumericInput(tp=Form.FT_HEX, swidth=22),
"iMaxEA": Form.NumericInput(tp=Form.FT_HEX, swidth=22),
"cGroupExport": Form.ChkGroupControl(
(
"rUseDecompiler",
"rExcludeLibraryThunk",
"rIgnoreSmallFunctions",
"rExportMicrocode",
"rNonIdaSubs",
"rFuncSummariesOnly",
)
),
"cGroup1": Form.ChkGroupControl(
(
"rUnreliable",
"rSlowHeuristics",
"rRelaxRatio",
"rExperimental",
"rIgnoreSubNames",
"rIgnoreAllNames",
"rUseTrainedModel"
)
),
"iProjectSpecificRules": Form.FileInput(
open=True, hlp="Python scripts (*.py)"
),
}
Form.__init__(self, s, args)
def set_options(self, opts):
"""
Set the configuration options from 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.rUseTrainedModel.checked = opts.use_trained_model
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 = not opts.ida_subs
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
self.rExportMicrocode.checked = opts.export_microcode
def get_options(self):
"""
Get a dictionary with the configuration options.
"""
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,
use_trained_model=self.rUseTrainedModel.checked,
relax=self.rRelaxRatio.checked,
experimental=self.rExperimental.checked,
min_ea=self.iMinEA.value,
max_ea=self.iMaxEA.value,
ida_subs=self.rNonIdaSubs.checked is 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,
export_microcode=self.rExportMicrocode.checked,
)
return BinDiffOptions(**opts)
# pylint: enable=no-member
#-------------------------------------------------------------------------------
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):
"""
Class used to show graphs.
"""
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 key not in self.nodes:
self.nodes[key] = self.AddNode([key, [[0, 0, ""]]])
parent_node = self.nodes[key]
for child in self.relations[key]:
if child not 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 CCallGraphViewer(GraphViewer):
def __init__(self, title, callers, callees, target):
GraphViewer.__init__(self, title, False)
self.target = target
self.callers = callers
self.callees = callees
self.root = None
self.nodes = {}
self.node_types = {
"target": config.CALLGRAPH_COLOR_TARGET,
"callee": config.CALLGRAPH_COLOR_CALLEE,
"caller": config.CALLGRAPH_COLOR_CALLER,
}
def OnRefresh(self):
self.Clear()
self.root = self.AddNode(self.target)
self.nodes[self.root] = [self.target, "target"]
for caller in self.callers:
name = caller["name1"]
node = self.AddNode(name)
self.AddEdge(node, self.root)
self.nodes[node] = [name, "caller"]
for callee in self.callees:
name = callee["name1"]
node = self.AddNode(name)
self.AddEdge(self.root, node)
self.nodes[node] = [name, "callee"]
return True
def OnGetText(self, node_id):
node = self.nodes[node_id]
name, node_type = node
colour = self.node_types[node_type]
return name, colour
def OnHint(self, node_id):
node = self.nodes[node_id]
_, node_type = node
return node_type
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