forked from joxeankoret/diaphora
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiaphora.py
2172 lines (1829 loc) · 73.6 KB
/
diaphora.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
#!/usr/bin/python
"""
Diaphora, a diffing plugin for IDA
Copyright (c) 2015-2020, 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 sys
import os
import re
import sys
import time
import json
import decimal
import sqlite3
import threading
from threading import Thread
from io import StringIO
from difflib import SequenceMatcher
from multiprocessing import cpu_count
from diaphora_heuristics import *
from jkutils.kfuzzy import CKoretFuzzyHashing
from jkutils.factor import (FACTORS_CACHE, difference, difference_ratio,
primesbelow as primes)
try:
import idaapi
is_ida = True
except ImportError:
is_ida = False
#-------------------------------------------------------------------------------
VERSION_VALUE = "2.0.4"
COPYRIGHT_VALUE="Copyright(c) 2015-2020 Joxean Koret"
COMMENT_VALUE="Diaphora diffing plugin for IDA version %s" % VERSION_VALUE
# Used to clean-up the pseudo-code and assembly dumps in order to get
# better comparison ratios
CMP_REPS = ["loc_", "j_nullsub_", "nullsub_", "j_sub_", "sub_",
"qword_", "dword_", "byte_", "word_", "off_", "def_", "unk_", "asc_",
"stru_", "dbl_", "locret_"]
CMP_REMS = ["dword ptr ", "byte ptr ", "word ptr ", "qword ptr ", "short ptr"]
#-------------------------------------------------------------------------------
def result_iter(cursor, arraysize=1000):
""" An iterator that uses fetchmany to keep memory usage down. """
while True:
results = cursor.fetchmany(arraysize)
if not results:
break
for result in results:
yield result
#-------------------------------------------------------------------------------
def quick_ratio(buf1, buf2):
try:
if buf1 is None or buf2 is None or buf1 == "" or buf1 == "":
return 0
s = SequenceMatcher(None, buf1.split("\n"), buf2.split("\n"))
return s.quick_ratio()
except:
print("quick_ratio:", str(sys.exc_info()[1]))
return 0
#-------------------------------------------------------------------------------
def real_quick_ratio(buf1, buf2):
try:
if buf1 is None or buf2 is None or buf1 == "" or buf1 == "":
return 0
s = SequenceMatcher(None, buf1.split("\n"), buf2.split("\n"))
return s.real_quick_ratio()
except:
print("real_quick_ratio:", str(sys.exc_info()[1]))
return 0
#-------------------------------------------------------------------------------
def ast_ratio(ast1, ast2):
if ast1 == ast2:
return 1.0
elif ast1 is None or ast2 is None:
return 0
return difference_ratio(decimal.Decimal(ast1), decimal.Decimal(ast2))
#-------------------------------------------------------------------------------
def log(msg):
if isinstance(threading.current_thread(), threading._MainThread):
print(("[%s] %s" % (time.asctime(), msg)))
#-------------------------------------------------------------------------------
def log_refresh(msg, show=False, do_log=True):
log(msg)
#-------------------------------------------------------------------------------
def debug_refresh(msg, show=False):
if os.getenv("DIAPHORA_DEBUG"):
log(msg)
#-------------------------------------------------------------------------------
class CChooser():
class Item:
def __init__(self, ea, name, ea2 = None, name2 = None, desc="100% equal", ratio = 0, bb1 = 0, bb2 = 0):
self.ea = ea
self.vfname = name
self.ea2 = ea2
self.vfname2 = name2
self.description = desc
self.ratio = ratio
self.bb1 = int(bb1)
self.bb2 = int(bb2)
self.cmd_import_selected = None
self.cmd_import_all = None
self.cmd_import_all_funcs = None
def __str__(self):
return '%08x' % int(self.ea)
def __init__(self, title, bindiff, show_commands=True):
if title == "Unmatched in primary":
self.primary = False
else:
self.primary = True
self.title = title
self.n = 0
self.items = []
self.icon = 41
self.bindiff = bindiff
self.show_commands = show_commands
self.cmd_diff_asm = None
self.cmd_diff_graph = None
self.cmd_diff_c = None
self.cmd_import_selected = None
self.cmd_import_all = None
self.cmd_import_all_funcs = None
self.cmd_show_asm = None
self.cmd_show_pseudo = None
self.cmd_highlight_functions = None
self.cmd_unhighlight_functions = None
self.selected_items = []
def add_item(self, item):
if self.title.startswith("Unmatched in"):
self.items.append(["%05lu" % self.n, "%08x" % int(item.ea), item.vfname])
else:
self.items.append(["%05lu" % self.n, "%08x" % int(item.ea), item.vfname,
"%08x" % int(item.ea2), item.vfname2, "%.3f" % item.ratio,
"%d" % item.bb1, "%d" % item.bb2, item.description])
self.n += 1
def get_color(self):
if self.title.startswith("Best"):
return 0xffff99
elif self.title.startswith("Partial"):
return 0x99ff99
elif self.title.startswith("Unreliable"):
return 0x9999ff
#-------------------------------------------------------------------------------
MAX_PROCESSED_ROWS = 1000000
TIMEOUT_LIMIT = 60 * 3
#-------------------------------------------------------------------------------
class bytes_encoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, bytes):
return obj.decode("utf-8")
return json.JSONEncoder.default(self, obj)
#-------------------------------------------------------------------------------
class CBinDiff:
def __init__(self, db_name, chooser=CChooser):
self.names = dict()
self.primes = primes(2048*2048)
self.db_name = db_name
self.dbs_dict = {}
self.db = None # Used exclusively by the exporter!
self.open_db()
self.matched1 = set()
self.matched2 = set()
self.matches_cache = {}
self.total_functions1 = None
self.total_functions2 = None
self.equal_callgraph = False
self.kfh = CKoretFuzzyHashing()
# With this block size we're sure it will only apply to functions
# somehow big
self.kfh.bsize = 32
self.pseudo = {}
self.pseudo_hash = {}
self.pseudo_comments = {}
self.unreliable = self.get_value_for("unreliable", False)
self.relaxed_ratio = self.get_value_for("relaxed_ratio", False)
self.experimental = self.get_value_for("experimental", False)
self.slow_heuristics = self.get_value_for("slow_heuristics", False)
self.unreliable = False
self.relaxed_ratio = False
self.experimental = False
self.slow_heuristics = False
self.use_decompiler_always = True
self.exclude_library_thunk = True
self.project_script = None
self.hooks = None
# Create the choosers
self.chooser = chooser
# Create the choosers
self.create_choosers()
self.last_diff_db = None
self.re_cache = {}
####################################################################
# LIMITS
#
# Do not run heuristics for more than X seconds (by default, 3 minutes).
self.timeout = self.get_value_for("TIMEOUT_LIMIT", TIMEOUT_LIMIT)
# It's typical in SQL queries to get a cartesian product of the
# results in the functions tables. Do not process more than this
# value per each 20k functions.
self.max_processed_rows = self.get_value_for("MAX_PROCESSED_ROWS", MAX_PROCESSED_ROWS)
# Limits to filter the functions to export
self.min_ea = 0
self.max_ea = 0
# Export only non IDA automatically generated function names? I.e.,
# excluding these starting with sub_*
self.ida_subs = True
# Export only function summaries instead of also exporting both the
# basic blocks and all instructions used by functions?
self.function_summaries_only = False
# Ignore IDA's automatically generated sub_* names for heuristics
# like the 'Same name'?
self.ignore_sub_names = True
# Ignore any and all function names for the 'Same name' heuristic?
self.ignore_all_names = self.get_value_for("ignore_all_names", True)
# Ignore small functions?
self.ignore_small_functions = self.get_value_for("ignore_small_functions", False)
# Number of CPU threads/cores to use?
cpus = cpu_count() - 1
if cpus < 1:
cpus = 1
self.cpu_count = self.get_value_for("CPU_COUNT", cpus)
####################################################################
def __del__(self):
if self.db is not None:
try:
if self.last_diff_db is not None:
tid = threading.current_thread().ident
if tid in self.dbs_dict:
db = self.dbs_dict[tid]
with db.cursor() as cur:
cur.execute('detach "%s"' % self.last_diff_db)
except:
pass
self.db_close()
def get_value_for(self, value_name, default):
# Try to search for a DIAPHORA_<value_name> environment variable
value = os.getenv("DIAPHORA_%s" % value_name.upper())
if value is not None:
if type(value) != type(default):
value = type(default)(value)
return value
return default
def open_db(self):
db = sqlite3.connect(self.db_name, check_same_thread=True)
db.text_factory = str
db.row_factory = sqlite3.Row
tid = threading.current_thread().ident
self.dbs_dict[tid] = db
if isinstance(threading.current_thread(), threading._MainThread):
self.db = db
self.create_schema()
db.execute("analyze")
def get_db(self):
tid = threading.current_thread().ident
if not tid in self.dbs_dict:
self.open_db()
if self.last_diff_db is not None:
self.attach_database(self.last_diff_db)
return self.dbs_dict[tid]
def db_cursor(self):
db = self.get_db()
return db.cursor()
def db_close(self):
tid = threading.current_thread().ident
if tid in self.dbs_dict:
self.dbs_dict[tid].close()
del self.dbs_dict[tid]
if isinstance(threading.current_thread(), threading._MainThread):
self.db.close()
def create_schema(self):
cur = self.db_cursor()
cur.execute("PRAGMA foreign_keys = ON")
sql = """ create table if not exists functions (
id integer primary key,
name varchar(255),
address text unique,
nodes integer,
edges integer,
indegree integer,
outdegree integer,
size integer,
instructions integer,
mnemonics text,
names text,
prototype text,
cyclomatic_complexity integer,
primes_value text,
comment text,
mangled_function text,
bytes_hash text,
pseudocode text,
pseudocode_lines integer,
pseudocode_hash1 text,
pseudocode_primes text,
function_flags integer,
assembly text,
prototype2 text,
pseudocode_hash2 text,
pseudocode_hash3 text,
strongly_connected integer,
loops integer,
rva text unique,
tarjan_topological_sort text,
strongly_connected_spp text,
clean_assembly text,
clean_pseudo text,
mnemonics_spp text,
switches text,
function_hash text,
bytes_sum integer,
md_index text,
constants text,
constants_count integer,
segment_rva text,
assembly_addrs text,
kgh_hash text,
userdata text) """
cur.execute(sql)
sql = """ create table if not exists program (
id integer primary key,
callgraph_primes text,
callgraph_all_primes text,
processor text,
md5sum text
) """
cur.execute(sql)
sql = """ create table if not exists program_data (
id integer primary key,
name varchar(255),
type varchar(255),
value text
)"""
cur.execute(sql)
sql = """ create table if not exists version (value text) """
cur.execute(sql)
sql = """ create table if not exists instructions (
id integer primary key,
address text unique,
disasm text,
mnemonic text,
comment1 text,
comment2 text,
name text,
type text,
pseudocomment text,
pseudoitp integer) """
cur.execute(sql)
sql = """ create table if not exists basic_blocks (
id integer primary key,
num integer,
address text unique)"""
cur.execute(sql)
sql = """ create table if not exists bb_relations (
id integer primary key,
parent_id integer not null references basic_blocks(id) ON DELETE CASCADE,
child_id integer not null references basic_blocks(id) ON DELETE CASCADE)"""
cur.execute(sql)
sql = """ create table if not exists bb_instructions (
id integer primary key,
basic_block_id integer references basic_blocks(id) on delete cascade,
instruction_id integer references instructions(id) on delete cascade)"""
cur.execute(sql)
sql = """ create table if not exists function_bblocks (
id integer primary key,
function_id integer not null references functions(id) on delete cascade,
basic_block_id integer not null references basic_blocks(id) on delete cascade)"""
cur.execute(sql)
sql = """create table if not exists callgraph (
id integer primary key,
func_id integer not null references functions(id) on delete cascade,
address text not null,
type text not null)"""
cur.execute(sql)
sql = """create table if not exists constants (
id integer primary key,
func_id integer not null references functions(id) on delete cascade,
constant text not null)"""
cur.execute(sql)
cur.execute("select 1 from version")
row = cur.fetchone()
if not row:
cur.execute("insert into main.version values ('%s')" % VERSION_VALUE)
cur.close()
def create_indexes(self):
cur = self.db_cursor()
sql = "create index if not exists idx_assembly on functions(assembly)"
cur.execute(sql)
sql = "create index if not exists idx_bytes_hash on functions(bytes_hash)"
cur.execute(sql)
sql = "create index if not exists idx_pseudocode on functions(pseudocode)"
cur.execute(sql)
sql = "create index if not exists idx_name on functions(name)"
cur.execute(sql)
sql = "create index if not exists idx_mangled_name on functions(mangled_function)"
cur.execute(sql)
sql = "create index if not exists idx_names on functions(names)"
cur.execute(sql)
sql = "create index if not exists idx_asm_pseudo on functions(assembly, pseudocode)"
cur.execute(sql)
sql = "create index if not exists idx_nodes_edges_instructions on functions(nodes, edges, instructions)"
cur.execute(sql)
sql = "create index if not exists idx_composite1 on functions(nodes, edges, mnemonics, names, cyclomatic_complexity, prototype2, indegree, outdegree)"
cur.execute(sql)
sql = "create index if not exists idx_composite2 on functions(instructions, mnemonics, names)"
cur.execute(sql)
sql = "create index if not exists idx_composite3 on functions(nodes, edges, cyclomatic_complexity)"
cur.execute(sql)
sql = "create index if not exists idx_composite4 on functions(pseudocode_lines, pseudocode)"
cur.execute(sql)
sql = "create index if not exists idx_composite5 on functions(pseudocode_lines, pseudocode_primes)"
cur.execute(sql)
sql = "create index if not exists idx_composite6 on functions(names, mnemonics)"
cur.execute(sql)
sql = "create index if not exists idx_pseudocode_hash1 on functions(pseudocode_hash1)"
cur.execute(sql)
sql = "create index if not exists idx_pseudocode_hash2 on functions(pseudocode_hash2)"
cur.execute(sql)
sql = "create index if not exists idx_pseudocode_hash3 on functions(pseudocode_hash3)"
cur.execute(sql)
sql = "create index if not exists idx_pseudocode_hash on functions(pseudocode_hash1, pseudocode_hash2, pseudocode_hash3)"
cur.execute(sql)
sql = "create index if not exists idx_strongly_connected on functions(strongly_connected)"
cur.execute(sql)
sql = "create index if not exists idx_strongly_connected_spp on functions(strongly_connected_spp)"
cur.execute(sql)
sql = "create index if not exists idx_loops on functions(loops)"
cur.execute(sql)
sql = "create index if not exists idx_rva on functions(rva)"
cur.execute(sql)
sql = "create index if not exists idx_tarjan_topological_sort on functions(tarjan_topological_sort)"
cur.execute(sql)
sql = "create index if not exists idx_mnemonics_spp on functions(mnemonics_spp)"
cur.execute(sql)
sql = "create index if not exists idx_clean_asm on functions(clean_assembly)"
cur.execute(sql)
sql = "create index if not exists idx_clean_pseudo on functions(clean_pseudo)"
cur.execute(sql)
sql = "create index if not exists idx_switches on functions(switches)"
cur.execute(sql)
sql = "create index if not exists idx_function_hash on functions(function_hash)"
cur.execute(sql)
sql = "create index if not exists idx_bytes_sum on functions(bytes_sum)"
cur.execute(sql)
sql = "create index if not exists idx_md_index on functions(md_index)"
cur.execute(sql)
sql = "create index if not exists idx_kgh_hash on functions(kgh_hash)"
cur.execute(sql)
sql = "create index if not exists idx_constants on functions(constants_count, constants)"
cur.execute(sql)
sql = "create index if not exists idx_mdindex_constants on functions(md_index, constants_count, constants)"
cur.execute(sql)
sql = "create index if not exists idx_instructions_address on instructions (address)"
cur.execute(sql)
sql = "create index if not exists idx_bb_relations on bb_relations(parent_id, child_id)"
cur.execute(sql)
sql = "create index if not exists idx_bb_instructions on bb_instructions (basic_block_id, instruction_id)"
cur.execute(sql)
sql = "create index if not exists id_function_blocks on function_bblocks (function_id, basic_block_id)"
cur.execute(sql)
sql = "create index if not exists idx_constants on constants (constant)"
cur.execute(sql)
sql = "analyze"
cur.execute(sql)
cur.close()
def attach_database(self, diff_db):
cur = self.db_cursor()
cur.execute('attach "%s" as diff' % diff_db)
cur.close()
def equal_db(self):
cur = self.db_cursor()
sql = "select count(*) total from program p, diff.program dp where p.md5sum = dp.md5sum"
cur.execute(sql)
row = cur.fetchone()
ret = row["total"] == 1
if not ret:
sql = "select count(*) total from (select * from functions except select * from diff.functions) x"
cur.execute(sql)
row = cur.fetchone()
ret = row["total"] == 0
else:
log("Same MD5 in both databases")
cur.close()
return ret
def add_program_data(self, type_name, key, value):
cur = self.db_cursor()
sql = "insert into main.program_data (name, type, value) values (?, ?, ?)"
values = (key, type_name, value)
cur.execute(sql, values)
cur.close()
def get_instruction_id(self, addr):
cur = self.db_cursor()
sql = "select id from instructions where address = ?"
cur.execute(sql, (str(addr),))
row = cur.fetchone()
rowid = None
if row is not None:
rowid = row["id"]
cur.close()
return rowid
def get_bb_id(self, addr):
cur = self.db_cursor()
sql = "select id from basic_blocks where address = ?"
cur.execute(sql, (str(addr),))
row = cur.fetchone()
rowid = None
if row is not None:
rowid = row["id"]
cur.close()
return rowid
def save_function(self, props):
if props == False:
log("WARNING: Trying to save a non resolved function?")
return
# Phase 1: Fix data types and insert the function row.
cur = self.db_cursor()
new_props = []
# The last 4 fields are callers, callees, basic_blocks_data & bb_relations
for prop in props[:len(props)-4]:
# XXX: Fixme! This is a hack for 64 bit architectures kernels
if type(prop) is int and (prop > 0xFFFFFFFF or prop < -0xFFFFFFFF):
prop = str(prop)
elif type(prop) is bytes:
prop = prop.encode("utf-8")
if type(prop) is list or type(prop) is set:
new_props.append(json.dumps(list(prop), ensure_ascii=False, cls=bytes_encoder))
else:
new_props.append(prop)
sql = """insert into main.functions (name, nodes, edges, indegree, outdegree, size,
instructions, mnemonics, names, prototype,
cyclomatic_complexity, primes_value, address,
comment, mangled_function, bytes_hash, pseudocode,
pseudocode_lines, pseudocode_hash1, pseudocode_primes,
function_flags, assembly, prototype2, pseudocode_hash2,
pseudocode_hash3, strongly_connected, loops, rva,
tarjan_topological_sort, strongly_connected_spp,
clean_assembly, clean_pseudo, mnemonics_spp, switches,
function_hash, bytes_sum, md_index, constants,
constants_count, segment_rva, assembly_addrs, kgh_hash,
userdata)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""
try:
cur.execute(sql, new_props)
except:
print("Props???", new_props)
raise
func_id = cur.lastrowid
# Phase 2: Save the callers and callees of the function
callers, callees = props[len(props)-4:len(props)-2]
sql = "insert into callgraph (func_id, address, type) values (?, ?, ?)"
for caller in callers:
cur.execute(sql, (func_id, str(caller), 'caller'))
for callee in callees:
cur.execute(sql, (func_id, str(callee), 'callee'))
# Phase 3: Insert the constants of the function
sql = "insert into constants (func_id, constant) values (?, ?)"
props_dict = self.create_function_dictionary(props)
for constant in props_dict["constants"]:
if type(constant) in [str, bytes] and len(constant) > 4:
cur.execute(sql, (func_id, constant))
# Phase 4: Save the basic blocks relationships
if not self.function_summaries_only:
# The last 2 fields are basic_blocks_data & bb_relations
bb_data, bb_relations = props[len(props)-2:]
instructions_ids = {}
sql = """insert into main.instructions (address, mnemonic, disasm,
comment1, comment2, name,
type, pseudocomment,
pseudoitp)
values (?, ?, ?, ?, ?, ?, ?, ?, ?)"""
self_get_instruction_id = self.get_instruction_id
cur_execute = cur.execute
for key in bb_data:
for insn in bb_data[key]:
addr, mnem, disasm, cmt1, cmt2, name, mtype = insn
db_id = self_get_instruction_id(str(addr))
if db_id is None:
pseudocomment = None
pseudoitp = None
if addr in self.pseudo_comments:
pseudocomment, pseudoitp = self.pseudo_comments[addr]
cur_execute(sql, (str(addr), mnem, disasm, cmt1, cmt2, name, mtype, pseudocomment, pseudoitp))
db_id = cur.lastrowid
instructions_ids[addr] = db_id
num = 0
bb_ids = {}
sql1 = "insert into main.basic_blocks (num, address) values (?, ?)"
sql2 = "insert into main.bb_instructions (basic_block_id, instruction_id) values (?, ?)"
self_get_bb_id = self.get_bb_id
for key in bb_data:
# Insert each basic block
num += 1
ins_ea = str(key)
last_bb_id = self_get_bb_id(ins_ea)
if last_bb_id is None:
cur_execute(sql1, (num, str(ins_ea)))
last_bb_id = cur.lastrowid
bb_ids[ins_ea] = last_bb_id
# Insert relations between basic blocks and instructions
for insn in bb_data[key]:
ins_id = instructions_ids[insn[0]]
cur_execute(sql2, (last_bb_id, ins_id))
# Insert relations between basic blocks
sql = "insert into main.bb_relations (parent_id, child_id) values (?, ?)"
for key in bb_relations:
for bb in bb_relations[key]:
bb = str(bb)
key = str(key)
try:
cur_execute(sql, (bb_ids[key], bb_ids[bb]))
except:
# key doesnt exist because it doesnt have forward references to any bb
log("Error: %s" % str(sys.exc_info()[1]))
# And finally insert the functions to basic blocks relations
sql = "insert into main.function_bblocks (function_id, basic_block_id) values (?, ?)"
for key in bb_ids:
bb_id = bb_ids[key]
cur_execute(sql, (func_id, bb_id))
cur.close()
def get_valid_definition(self, defs):
""" Try to get a valid structure definition by removing (yes) the
invalid characters typically found in IDA's generated structs."""
ret = defs.replace("?", "_").replace("@", "_")
ret = ret.replace("$", "_")
return ret
def prettify_asm(self, asm_source):
asm = []
for line in asm_source.split("\n"):
if not line.startswith("loc_"):
asm.append("\t" + line)
else:
asm.append(line)
return "\n".join(asm)
def re_sub(self, text, repl, string):
if text not in self.re_cache:
self.re_cache[text] = re.compile(text, flags=re.IGNORECASE)
re_obj = self.re_cache[text]
return re_obj.sub(repl, string)
def get_cmp_asm_lines(self, asm):
sio = StringIO(asm)
lines = []
get_cmp_asm = self.get_cmp_asm
for line in sio.readlines():
line = line.strip("\n")
lines.append(get_cmp_asm(line))
return "\n".join(lines)
def get_cmp_pseudo_lines(self, pseudo):
if pseudo is None:
return pseudo
# Remove all the comments
tmp = self.re_sub(" // .*", "", pseudo)
# Now, replace sub_, byte_, word_, dword_, loc_, etc...
for rep in CMP_REPS:
tmp = self.re_sub(rep + "[a-f0-9A-F]+", rep + "XXXX", tmp)
tmp = self.re_sub("v[0-9]+", "vXXX", tmp)
tmp = self.re_sub("a[0-9]+", "aXXX", tmp)
tmp = self.re_sub("arg_[0-9]+", "aXXX", tmp)
return tmp
def get_cmp_asm(self, asm):
if asm is None:
return asm
# Ignore the comments in the assembly dump
tmp = asm.split(";")[0]
tmp = tmp.split(" # ")[0]
# Now, replace sub_, byte_, word_, dword_, loc_, etc...
for rep in CMP_REPS:
tmp = self.re_sub(rep + "[a-f0-9A-F]+", "XXXX", tmp)
# Remove dword ptr, byte ptr, etc...
for rep in CMP_REMS:
tmp = self.re_sub(rep + "[a-f0-9A-F]+", "", tmp)
reps = ["\+[a-f0-9A-F]+h\+"]
for rep in reps:
tmp = self.re_sub(rep, "+XXXX+", tmp)
tmp = self.re_sub("\.\.[a-f0-9A-F]{8}", "XXX", tmp)
# Strip any possible remaining white-space character at the end of
# the cleaned-up instruction
tmp = self.re_sub("[ \t\n]+$", "", tmp)
# Replace aName_XXX with aXXX, useful to ignore small changes in
# offsets created to strings
tmp = self.re_sub("a[A-Z]+[a-z0-9]+_[0-9]+", "aXXX", tmp)
return tmp
def compare_graphs_pass(self, bblocks1, bblocks2, colours1, colours2, is_second = False):
dones1 = set()
dones2 = set()
# Now compare each basic block from the first function to all the
# basic blocks in the 2nd function
for key1 in bblocks1:
if key1 in dones1:
continue
for key2 in bblocks2:
if key2 in dones2:
continue
# Same number of instructions?
if len(bblocks1[key1]) == len(bblocks2[key2]):
mod = False
partial = True
i = 0
for ins1 in bblocks1[key1]:
ins2 = bblocks2[key2][i]
# Same mnemonic? The change can be only partial
if ins1[1] != ins2[1]:
partial = False
# Try to compare the assembly after doing some cleaning
cmp_asm1 = self.get_cmp_asm(ins1[2])
cmp_asm2 = self.get_cmp_asm(ins2[2])
if cmp_asm1 != cmp_asm2:
mod = True
if not partial:
continue
i += 1
if not mod:
# Perfect match, we discovered a basic block equal in both
# functions
colours1[key1] = 0xffffff
colours2[key2] = 0xffffff
dones1.add(key1)
dones2.add(key2)
break
elif not is_second and partial:
# Partial match, we discovered a basic block with the same
# mnemonics but something changed
#
# NOTE:
# Do not add the partial matches to the dones lists, as we
# can have complete matches after a partial match!
colours1[key1] = 0xCCffff
colours2[key2] = 0xCCffff
break
return colours1, colours2
def compare_graphs(self, g1, ea1, g2, ea2):
colours1 = {}
colours2 = {}
bblocks1 = g1[0]
bblocks2 = g2[0]
# Consider, by default, all blocks added, news
for key1 in bblocks1:
colours1[key1] = 0xCCCCFF
for key2 in bblocks2:
colours2[key2] = 0xCCCCFF
colours1, colours2 = self.compare_graphs_pass(bblocks1, bblocks2, colours1, colours2, False)
colours1, colours2 = self.compare_graphs_pass(bblocks1, bblocks2, colours1, colours2, True)
return colours1, colours2
def get_graph(self, ea1, primary=False):
if primary:
db = "main"
else:
db = "diff"
cur = self.db_cursor()
dones = set()
sql = """ select bb.address bb_address, ins.address ins_address,
ins.mnemonic ins_mnem, ins.disasm ins_disasm
from %s.function_bblocks fb,
%s.bb_instructions bbins,
%s.instructions ins,
%s.basic_blocks bb,
%s.functions f
where ins.id = bbins.instruction_id
and bbins.basic_block_id = bb.id
and bb.id = fb.basic_block_id
and f.id = fb.function_id
and f.address = ?
order by bb.address asc""" % (db, db, db, db, db)
cur.execute(sql, (str(ea1),))
bb_blocks = {}
for row in result_iter(cur):
bb_ea = str(int(row["bb_address"]))
ins_ea = str(int(row["ins_address"]))
mnem = row["ins_mnem"]
dis = row["ins_disasm"]
if ins_ea in dones:
continue
dones.add(ins_ea)
try:
bb_blocks[bb_ea].append([ins_ea, mnem, dis])
except KeyError:
bb_blocks[bb_ea] = [ [ins_ea, mnem, dis] ]
sql = """ select (select address
from %s.basic_blocks
where id = bbr.parent_id) ea1,
(select address
from %s.basic_blocks
where id = bbr.child_id) ea2
from %s.bb_relations bbr,
%s.function_bblocks fbs,
%s.basic_blocks bbs,
%s.functions f
where f.id = fbs.function_id
and bbs.id = fbs.basic_block_id
and fbs.basic_block_id = bbr.child_id
and f.address = ?
order by 1 asc, 2 asc""" % (db, db, db, db, db, db)
cur.execute(sql, (str(ea1), ))
rows = result_iter(cur)
bb_relations = {}
for row in rows:
bb_ea1 = str(row["ea1"])
bb_ea2 = str(row["ea2"])
try:
bb_relations[bb_ea1].add(bb_ea2)
except KeyError:
bb_relations[bb_ea1] = set([bb_ea2])
cur.close()
return bb_blocks, bb_relations
def delete_function(self, ea):
cur = self.db_cursor()
cur.execute("delete from functions where address = ?", (str(ea), ))
cur.close()
def is_auto_generated(self, name):
for rep in CMP_REPS:
if name.startswith(rep):
return True
return False
def check_callgraph(self):
cur = self.db_cursor()
sql = """select callgraph_primes, callgraph_all_primes from program
union all
select callgraph_primes, callgraph_all_primes from diff.program"""
cur.execute(sql)
rows = cur.fetchall()
if len(rows) == 2:
cg1 = decimal.Decimal(rows[0]["callgraph_primes"])
cg_factors1 = json.loads(rows[0]["callgraph_all_primes"])
cg2 = decimal.Decimal(rows[1]["callgraph_primes"])
cg_factors2 = json.loads(rows[1]["callgraph_all_primes"])
if cg1 == cg2:
self.equal_callgraph = True
log("Callgraph signature for both databases is equal, the programs seem to be 100% equal structurally")
Warning("Callgraph signature for both databases is equal, the programs seem to be 100% equal structurally")
else:
FACTORS_CACHE[cg1] = cg_factors1
FACTORS_CACHE[cg2] = cg_factors2
diff = difference(cg1, cg2)
total = sum(cg_factors1.values())
if total == 0 or diff == 0:
log("Callgraphs are 100% equal")
else:
percent = diff * 100. / total