-
Notifications
You must be signed in to change notification settings - Fork 7
/
inp_ida.py
391 lines (306 loc) · 12.1 KB
/
inp_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
# Copyright (c) 2012-2015
# Vasilis Pappas <vpappas@cs.columbia.edu>
# Hyungjoon Koo <hykoo@cs.stonybrook.edu>
# This file is part of Orp http://nsl.cs.columbia.edu/projects/orp
import func
import bbl
import insn
import cPickle
import util
import idautils
import idaapi
import idc
__all__ = ["get_functions", "dump_data", "get_code_heads", "code_search",
"max_ea", "byte_at", "bytes_at", "seg_start", "seg_end", "get_func_of"]
code_heads = set()
def get_typed_imports():
"""Queries IDA for functions in the import table that do have a type.
Returns a set of (func_ea, func_type) tuples."""
imp_funcs = set()
def imp_cb(ea, name, ordn):
ftype = idc.GetType(ea)
if ftype:
imp_funcs.add((ea, ftype))
return True
for i in xrange(idaapi.get_import_module_qty()):
idaapi.enum_import_names(i, imp_cb)
return imp_funcs
def get_export_list():
"""Returns a set of the exported function addresses"""
exports = set()
for i, ordn, ea, name in idautils.Entries():
exports.add(ea)
return exports
def get_code_and_blocks(ea):
"""Extracts the control flow graph for the function at the given address.
Returns a dictionary with the instructions (ea->insn.Instruction) and a list
of the basic blocs (bbl.BasicBlock)."""
code = {}
blocks = {}
ida_blocks = set(idaapi.FlowChart(idaapi.get_func(ea)))
for bb in ida_blocks:
# XXX: it seems that it's not a bug but inter-function jumps!
if bb.startEA == bb.endEA: # skip that .. it's IDA's bug
#print "skipping block %x : %x in func %x"%(bb.startEA, bb.endEA, ea)
continue
blocks[bb.startEA] = bbl.BasicBlock(bb.startEA, bb.endEA, {})
for head in idautils.Heads(bb.startEA, bb.endEA):
ibytes = idc.GetManyBytes(head, idc.ItemEnd(head) - head)
spd = idc.GetSpd(head)
code[head] = insn.Instruction(head, ibytes, spd)
blocks[bb.startEA].instrs.append(code[head])
next_head = idc.NextHead(head, bb.endEA)
if idaapi.isFlow(idc.GetFlags(next_head)):
code[head].succ.add(next_head)
for suc_bb in (s for s in bb.succs() if s.startEA != s.endEA):
#assume head is the last instruction of the block
code[head].succ.add(suc_bb.startEA)
for bb in (b for b in ida_blocks if b.startEA != b.endEA):
for suc_bb in (s for s in bb.succs() if s.startEA != s.endEA):
# a jump with zero offset (like, jz 0) gives two succs to the same bb
if blocks[suc_bb.startEA] not in blocks[bb.startEA].successors:
blocks[bb.startEA].successors.append(blocks[suc_bb.startEA])
blocks[bb.startEA].successors.sort(key=lambda x: x.begin, reverse=True)
#FIXME: find a better way ..
for block in blocks.itervalues():
if block.instrs[0].addr == ea:
#print "found the entry!:", block.instrs
block.instrs[0].f_entry = True
block.type |= bbl.BasicBlock.ENTRY
break
else:
print "BUG: could not find function entry in instrs!!"
#print "blocks:", blocks
return code, blocks.values()
#XXX: good test function in 0x070016E7 (BIB.dll)
def get_func_code_refs_from(func_ea, iaddrs):
"""Returns a set with the code references from this function"""
code_refs = set()
for addr in iaddrs:
ref = idaapi.BADADDR
for r in idautils.XrefsFrom(addr, idaapi.XREF_FAR):
if r.iscode:
to_func = idaapi.get_func(r.to)
if not to_func or to_func.startEA != func_ea:
ref = r.to
else:
ref = r.to
if (ref != idaapi.BADADDR or idaapi.is_call_insn(addr) or idaapi.is_indirect_jump_insn(addr)):
#print hex(i.addr), i, hex(ref)
code_refs.add(ref)
return code_refs
def get_func_code_refs_to(func_ea):
"""Returns a set with the code references to this function"""
code_refs = set()
for ref in idautils.CodeRefsTo(func_ea, 0): #callers
func_ida = idaapi.get_func(ref)
if not func_ida:
#print "BUG?: coderef came from no function! %X->%X"%(ref, addr)
continue
#if func_ida.startEA not in functions:
# print "BUG?: function %X not in our set (r=%X)!"%(func_ida.startEA, ref)
# continue
code_refs.add((ref, func_ida.startEA))
return code_refs
def get_functions(): #same prototype as in inp_dump..
"""Extracts useful data from the file being processed.
Returns a dictionary (ea->func.Function) containing all
the functions that where disassembled by IDA."""
functions = dict()
for f in functions_iter():
functions[f.addr] = f
return functions
def functions_iter():
functions = set()
exports = get_export_list()
for func_ea in idautils.Functions():
if func_ea in functions:
continue # functions with chunks appear once for each of them..
functions.add(func_ea)
code, blocks = get_code_and_blocks(func_ea)
crefs_to = get_func_code_refs_to(func_ea)
crefs_from = get_func_code_refs_from(func_ea, code.iterkeys())
f = func.Function(func_ea, code, blocks, crefs_to, crefs_from)
f.ftype = idc.GetType(func_ea)
f.name = idc.GetFunctionName(func_ea)
if func_ea in exports:
f.exported = True
yield f
typed_imports = get_typed_imports()
for imp_ea, ftype in typed_imports:
crefs_to = get_func_code_refs_to(imp_ea)
f = func.Function(imp_ea, None, None, crefs_to, None)
f.ftype = ftype
f.level = -1 # special level for imported functions
yield f
def _get_blocks_codes_per_func_iter():
"""
Iterative function to generate all blocks and opcodes
:return: N/A
"""
all_blocks = {}
all_codes = {}
all_opcodes = []
for func in idautils.Functions():
# blocks_in_func contains
# <idaapi.BasicBlock object at 0x0545F3F0>, ...
blocks_in_func = idaapi.FlowChart(idaapi.get_func(func))
blocks = []
for block in blocks_in_func:
# IDA BUG! block.startEA == block.endEA??
# Should be in the range "block.startEA <= block < block.endEA"
if block.startEA != block.endEA:
blocks.append((block.startEA, block.endEA))
for head in idautils.Heads(block.startEA, block.endEA):
ibytes = idc.GetManyBytes(head, idc.ItemEnd(head) - head)
spd = idc.GetSpd(head)
all_codes[head] = insn.Instruction(head, ibytes, spd)
# IDA BUG! all_codes[head].bytes == 0??
# The size of the code should be positive
if all_codes[head].bytes != 0:
all_opcodes.append((all_codes[head].addr, all_codes[head].addr + len(all_codes[head].bytes)))
all_blocks[func] = blocks
yield (all_blocks, all_opcodes)
def dump_data():
"""Extracts and dumps useful data from the file being processed.
The output is written using pickle and it consists of a set with all the
code heads followed by func.Function objects (ended with a None)."""
def __dump(out, type, lb=0, ub=0):
if type == 'code_head':
cPickle.dump(get_code_heads(), out, cPickle.HIGHEST_PROTOCOL)
for f in functions_iter():
cPickle.dump(f, out, cPickle.HIGHEST_PROTOCOL)
if type == 'code_blk':
for bc in _get_blocks_codes_per_func_iter():
cPickle.dump(bc, out, cPickle.HIGHEST_PROTOCOL)
cPickle.dump(None, out)
out.close()
__dump(util.open_dump(idaapi.get_input_file_path(), 'wb', 'dmp'), 'code_head')
__dump(util.open_dump(idaapi.get_input_file_path(), 'wb', 'code_blk'), 'code_blk')
def get_code_heads():
"""Returns a set with all the recognized code heads from all the
code sections."""
global code_heads
if len(code_heads) == 0:
for begin, end, name in code_segments_iter():
code_heads |= set(filter(lambda x: idaapi.isCode(idc.GetFlags(x)), idautils.Heads(begin, end)))
return code_heads
def code_segments_iter():
"""Iterates over the possible code sections within an input binary."""
for i in range(idaapi.get_segm_qty()):
seg = idaapi.getnseg(i)
if not seg: continue
seg_class = idaapi.get_segm_class(seg)
if seg_class != "CODE": continue
seg_name = idaapi.get_segm_name(seg.startEA)
yield seg.startEA, seg.endEA, seg_name
def code_search(ea, val):
"""Search forward for the next occurance of val. Return None if no match."""
res = idc.FindBinary(ea, idc.SEARCH_DOWN, val)
if res == idaapi.BADADDR:
return None
else:
return res
def byte_at(ea):
"""Returns the byte at the given address."""
return idc.Byte(ea)
def max_ea(): # TODO: check!!
"""Returns the max effective address for this binary."""
return idc.MaxEA()
def bytes_at(ea, num):
"""Returns num of bytes at the given address."""
return idc.GetManyBytes(ea, num)
def seg_start(ea):
"""Returns the start of the segment that ea belongs in."""
return idc.SegStart(ea)
def seg_end(ea):
"""Returns the end of the segment that ea belongs in."""
return idc.SegEnd(ea)
def get_func_of(ea):
"""Return the function that this address belongs to, if any."""
func = idaapi.get_func(ea)
if func:
return func.startEA
else:
return None
def get_input_file_path():
"""Return the name of the currently processed file."""
return idaapi.get_input_file_path()
def show_blocks(blocks):
"""
Enumerate all blocks belonging to each function
:param blocks: {func1:[b1, b2, ...], func2:[b1, b2, ...], ...}
:return:
"""
cnt = 0
for f in sorted(blocks):
print hex(f)
for (start, end) in blocks[f]:
print "\t%s - %s" % (hex(start), hex(end))
cnt += 1
print "All functions: %d, blocks: %d" % (len(blocks), cnt)
"""
def get_functions():
return idautils.Functions()
def get_function_name(func_ea):
return idc.GetFunctionName(func_ea)
def get_function_by_name(func_name):
for func_ea in idautils.Functions():
if func_name in idc.GetFunctionName(func_ea):
break
return func_ea
def get_input_file_path():
return idaapi.get_input_file_path()
def get_fileregion_offset(ea):
return idaapi.get_fileregion_offset(ea)
def get_code_heads(start, end):
return filter(lambda x: idaapi.isCode(idc.GetFlags(x)), idautils.Heads(start, end))
def get_func_of(ea):
func = idaapi.get_func(ea)
if func:
return func.startEA
return None
def reanalyze():
ea = next(idautils.Functions(), None)
if ea != None:
idc.AnalyzeArea(idc.SegStart(ea), idc.SegEnd(ea))
def get_func_type(func_ea):
return idc.GetType(func_ea)
def find_and_dump_gadgets():
import gadget
dump_out = open("%s.gadgets" % get_input_file_path(), "wb")
step = 512*1024
for begin, end, name in code_segments_iter():
while begin < end:
gadgets = gadget.find_gadgets5(begin, min(begin+step, end))
simple_gadgets = set((g.dump_simple(extra=True) for g in gadgets))
pickle.dump(simple_gadgets, dump_out)
begin += step
pickle.dump(None, dump_out)
dump_out.close()
def dump_exp_gadgets():
import gadget
exp_gadgets = gadget.find_exp_gadgets()
with open("%s.payload.gadgets" % get_input_file_path(), "wb") as f:
pickle.dump(exp_gadgets, f)
return
def load_exp_gadgets(dump_file):
with open(dump_file, "rb") as f:
exp_gadgets = pickle.load(f)
return exp_gadgets
def disasm(ea):
return idc.GetDisasm(ea)
"""
if __name__ == "__main__":
import sys
sys.setrecursionlimit(40000)
idc.Wait() # Wait for IDA to complete its auto analysis
print '-------- DUMP start -----------'
dump_data()
print '-------- DUMP end -----------'
'''
(all_blocks, all_opcodes) = load_codes_blocks(target_file)
show_blocks(all_blocks)
print all_opcodes
'''
idc.Exit(0) # Exit IDA when done;