This repository has been archived by the owner on Apr 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmyexport.py
326 lines (266 loc) · 10.8 KB
/
myexport.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
#!/usr/bin/env python
"""
MyNav, a tool 'similar' to BinNavi
Copyright (C) 2010 Joxean Koret
Itsaslapurraren izenean, beti gogoan izango zaitugu.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""
# ------------------------------------------------
# Standard imports
import sys
import traceback
try:
import sqlite3
hasSqlite = True
except ImportError:
hasSqlite = False
# ------------------------------------------------
# IDA's imports
import idc
import idaapi
import idautils
# ------------------------------------------------
# Helper
def myexport_print(msg):
print "[+] %s" % msg
# ------------------------------------------------
# Symbol's exporter class
class CFunctionsMatcher(object):
def __init__(self):
self.initialize()
def __del__(self):
if self.db:
self.closeDatabase()
def initialize(self):
self.functions = {}
self.filename = None
self.db = None
self.start_ea = None
self.end_ea = None
def closeDatabase(self):
self.db.close()
self.db = None
def createSchema(self):
cur = self.db.cursor()
sql = """ create table if not exists functions (
id integer primary key,
name varchar(50),
processor varchar(50),
nodes integer,
edges integer,
points integer,
size integer,
instructions integer,
mnemonics text,
prototype text) """
cur.execute(sql)
self.db.commit()
cur.close()
return True
def openDatabase(self, filename):
self.db = sqlite3.connect(filename)
def createDatabase(self, filename):
self.openDatabase(filename)
self.createSchema()
def saveDatabase(self):
cur = self.db.cursor()
sql = """insert into functions (name, processor, nodes, edges, points, size, instructions, mnemonics, prototype)
values (?, ?, ?, ?, ?, ?, ?, ?, ?)"""
for row in self.functions:
name, nodes, edges, points, size, instructions, mnems, prototype = self.functions[row]
cur.execute(sql, (name, idaapi.get_idp_name(), nodes, edges, points, size, instructions, str(mnems), prototype))
self.db.commit()
cur.close()
return True
def search(self, f):
name, nodes, edges, points, size, instructions, mnems, prototype = f
cur = self.db.cursor()
sql = """ select name
from functions
where nodes = ?
and edges = ?
and points = ?
and size > 200 """
""" and size = ?
and instructions = ? """
cur.execute(sql, (nodes, edges, points))#, size, instructions))
res = None
for row in cur.fetchall():
res = row[0]
cur.close()
return res
def searchExact(self, f):
name, nodes, edges, points, size, instructions, mnems, prototype = f
cur = self.db.cursor()
sql = """ select name, prototype
from functions
where processor = ?
and nodes = ?
and edges = ?
and points = ?
and size = ?
and instructions = ?
and mnemonics = ? """
cur.execute(sql, (idaapi.get_idp_name(), nodes, edges, points, size, instructions, str(mnems)))
res = None
for row in cur.fetchall():
res = row[0], row[1]
cur.close()
return res
def makeName(self, f, match):
if idc.MakeNameEx(int(f), str(match), idc.SN_AUTO|idc.SN_PUBLIC):
return True
for i in range(100):
if idc.MakeNameEx(int(f), str(match) + "_%d" % i, idc.SN_AUTO|idc.SN_PUBLIC):
return True
return False
def searchAll(self):
if self.start_ea is not None:
l = list(idautils.Functions(idc.SegStart(self.start_ea), idc.SegEnd(self.end_ea)))
else:
l = list(idautils.Functions())
for f in l:
name = idc.GetFunctionName(f)
if not name.startswith("sub_"):
print "skipping %s" % name
continue
flags = idc.GetFunctionFlags(f)
if flags & idc.FUNC_LIB or flags == -1:
continue
x = self.readFunction(f, False)
if x:
ret = self.searchExact(x)
if ret:
match, prototype = ret
else:
match = None
if match:
print "%08x Function %s exact matches with %s" % (f, idc.GetFunctionName(f), match)
try:
self.makeName(int(f), str(match))
except:
print " %08x Cannot rename function" % f
print sys.exc_info()[1]
try:
pos = prototype.find("(")
if pos > -1:
if prototype.find(">(") > -1:
pos = prototype.find("<")
prototype = str(prototype[:pos] + " x" + prototype[pos:])
print repr(prototype)
print "%08x Function %s's type is %s" % (f, idc.GetFunctionName(f), prototype)
idc.SetType(int(f), prototype)
except:
print " %08x Cannot change the type of the function (type %s)" % (f, prototype)
print sys.exc_info()[1]
else:
match = self.search(x)
if match:
print "%08x Function %s partially matches with %s" % (f, idc.GetFunctionName(f), match)
try:
idc.MakeComm(f, str(match))
except:
print " %08x Cannot rename function" % f
print sys.exc_info()[1]
def readFunction(self, f, discard=True):
name = idc.GetFunctionName(f)
func = idaapi.get_func(f)
flow = idaapi.FlowChart(func)
size = func.endEA - func.startEA
if discard:
# Unnamed function, ignore it...
if name.startswith("sub_") or name.startswith("j_") or name.startswith("unknown"):
return False
# Already recognized runtime's function
flags = idc.GetFunctionFlags(f)
if flags & idc.FUNC_LIB or flags == -1:
return False
nodes = 0
edges = 0
points = 0
instructions = 0
mnems = []
dones = {}
for block in flow:
nodes += 1
indegree = 0
outdegree = 0
for succ_block in block.succs():
edges += 1
indegree += 1
if not dones.has_key(succ_block.id):
dones[succ_block] = 1
for x in list(idautils.Heads(succ_block.startEA, succ_block.endEA)):
instructions += 1
mnems.append(idc.GetMnem(x))
for pred_block in block.preds():
edges += 1
outdegree += 1
if not dones.has_key(succ_block.id):
dones[succ_block] = 1
for x in list(idautils.Heads(succ_block.startEA, succ_block.endEA)):
instructions += 1
mnems.append(idc.GetMnem(x))
if indegree > 0:
points += indegree
if outdegree > 0:
points += outdegree
if nodes > 1 and instructions > 0 and edges > 1:
myexport_print("Exporter: Current function 0x%08x %s" % (f, name))
return (name, nodes, edges, points, size, instructions, mnems, idc.GetType(f))
return False
def getFunctions(self):
for f in list(idautils.Functions()):
x = self.readFunction(f)
if x:
self.functions[f] = x
return self.functions
def export(self, filename=None):
self.initialize()
if filename is None:
f = idc.AskFile(1, "*.sqlite", "Select database to export")
else:
f = filename
if f:
myexport_print("Reading functions...")
self.getFunctions()
self.createDatabase(f)
myexport_print("Exporting functions...")
self.saveDatabase()
self.closeDatabase()
myexport_print("Done")
def doImport(self, filename=None):
self.initialize()
if filename is None:
f = idc.AskFile(0, "*.sqlite", "Select database to import")
else:
f = filename
if f:
print "file is", f
self.openDatabase(f)
self.searchAll()
# ------------------------------------------------
# Only called when accesed directly
def main():
try:
res = idaapi.askyn_c(1, "Do you want to export (YES) or import (NO)?")
exporter = CFunctionsMatcher()
if res == 1:
exporter.export()
elif res == 0:
exporter.doImport()
except:
print "Error:", sys.exc_info()[1]
traceback.print_exc(file=sys.stdout)
if __name__ == "__main__":
main()