-
Notifications
You must be signed in to change notification settings - Fork 10
/
__init__.py
422 lines (337 loc) · 13.7 KB
/
__init__.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
#!/usr/bin/env python
# Copyright 2017 Ryan Stortz (@withzombies)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from binaryninja import *
from collections import defaultdict
import re
Settings().register_group("bnil-graph", "BNIL Graph")
Settings().register_setting("bnil-graph.showCommon", """
{
"title" : "Show Common ILs",
"type" : "boolean",
"default" : true,
"description" : "Show common forms (non-SSA, non-mapped) in the output.",
"ignore" : ["SettingsProjectScope", "SettingsResourceScope"]
}
""")
Settings().register_setting("bnil-graph.showMapped", """
{
"title" : "Include MMLIL",
"type" : "boolean",
"default" : false,
"description" : "Show the MappedMediumLevelIL form in the output.",
"ignore" : ["SettingsProjectScope", "SettingsResourceScope"]
}
""")
Settings().register_setting("bnil-graph.showSSA", """
{
"title" : "Include SSA",
"type" : "boolean",
"default" : true,
"description" : "Include SSA forms in the output.",
"ignore" : ["SettingsProjectScope", "SettingsResourceScope"]
}
""")
# Support python 3 and python 2
if sys.version_info > (3,):
long = int
def show_graph_report(bv, g, name):
try:
# 1.3.2086-dev
# also 2.1.2260 Personal
version = binaryninja.core_version()
major, minor, patch, _ = re.match("(\d+)\.(\d+)\.(\d+)([- ]\w+)?", version).groups()
major = int(major)
minor = int(minor)
patch = int(patch)
if major == 1 and minor <= 3 and patch < 2086:
g.show(name)
return
except:
pass
bv.show_graph_report(name, g)
def graph_il_insn(g, head, il, label=None):
# type: (FlowGraph, FlowGraphNode, LowLevelILInstruction, Optional[str]) -> None
record = FlowGraphNode(g)
tokens = []
if label:
tokens.extend(
[
InstructionTextToken(
InstructionTextTokenType.KeywordToken, "{}".format(label)
),
InstructionTextToken(
InstructionTextTokenType.OperandSeparatorToken, ": "
),
]
)
if isinstance(il, (HighLevelILInstruction, MediumLevelILInstruction, LowLevelILInstruction)):
tokens.append(
InstructionTextToken(
InstructionTextTokenType.InstructionToken, il.operation.name
)
)
op_index = 0
ops = enumerate(il.operands)
for _, o in ops:
try:
edge_label, ty = il.ILOperations[il.operation][op_index]
except IndexError:
# Some operations don't have operations (like HLIL_NORET)
continue
# For var_ssa_dest_and_src, it has four operands while the ILOperations only records three
# >>> il
# <il: b#1.b1 = 0x61 @ b#0>
# >>> il.ILOperations[il.operation]
# [('prev', 'var_ssa_dest_and_src'), ('offset', 'int'), ('src', 'expr')]
# >>> il.operands
# [<ssa <var struct B b> version 1>, <ssa <var struct B b> version 0>, 0, <il: 0x61>]
if ty == 'reg_stack_ssa_dest_and_src' or ty == 'var_ssa_dest_and_src':
# handle the ssa_dest_and_src operand types
# This consumes two elements in ops, and only increase op_index once
next_label = 'next' if edge_label == 'prev' else 'dest'
graph_il_insn(g, record, o, next_label)
_, o2 = next(ops)
graph_il_insn(g, record, o2, edge_label)
op_index += 1
else:
# handle everything else
graph_il_insn(g, record, o, edge_label)
op_index += 1
elif isinstance(il, list):
tokens.append(
InstructionTextToken(
InstructionTextTokenType.IntegerToken, "List[{}]".format(len(il))
)
)
for i, item in enumerate(il):
edge_label = "[{:d}]".format(i)
graph_il_insn(g, record, item, edge_label)
else:
if isinstance(il, long):
tokens.append(
InstructionTextToken(
InstructionTextTokenType.IntegerToken, "{:#x}".format(il), value=il
)
)
elif isinstance(il, lowlevelil.SSARegister):
tokens.append(
InstructionTextToken(InstructionTextTokenType.TextToken, "<SSARegister>")
)
graph_il_insn(g, record, il.reg, "reg")
graph_il_insn(g, record, il.version, "version")
elif isinstance(il, mediumlevelil.SSAVariable):
tokens.append(
InstructionTextToken(InstructionTextTokenType.TextToken, "<SSAVariable>")
)
graph_il_insn(g, record, il.var, "var")
graph_il_insn(g, record, il.version, "version")
elif isinstance(il, function.Variable):
tokens.append(
InstructionTextToken(InstructionTextTokenType.TextToken, "<Variable>")
)
graph_il_insn(g, record, il.name, "name")
graph_il_insn(g, record, il.type, "type")
else:
tokens.append(
InstructionTextToken(InstructionTextTokenType.TextToken, str(il))
)
record.lines = [DisassemblyTextLine(tokens)]
g.append(record)
head.add_outgoing_edge(BranchType.UnconditionalBranch, record)
def graph_il(g, head, type, il):
# type: (FlowGraph, FlowGraphNode, str, LowLevelILInstruction) -> None
il_desc = binaryninja.FlowGraphNode(g)
lines = [
"{}".format(type),
"",
DisassemblyTextLine(
[
InstructionTextToken(
InstructionTextTokenType.AddressDisplayToken,
"{:#d}".format(il.instr_index),
value=il.instr_index,
),
InstructionTextToken(
InstructionTextTokenType.OperandSeparatorToken, " @ "
),
InstructionTextToken(
InstructionTextTokenType.AddressDisplayToken,
"{:#x}".format(il.address),
value=il.address,
),
]
),
]
if hasattr(il, 'lines'):
for line in il.lines:
lines.append(line.tokens)
else:
lines.append(il.tokens)
il_desc.lines = lines
graph_il_insn(g, il_desc, il, "operation")
g.append(il_desc)
head.add_outgoing_edge(BranchType.UnconditionalBranch, il_desc)
def graph_ils(bv, g, head, func, addr):
lookup = collect_ils(bv, func)
for il_type in sorted(lookup):
ils = lookup[il_type][addr]
for il in sorted(ils):
graph_il(g, head, il_type, il)
def collect_ils(bv, func):
lookup = defaultdict(lambda: defaultdict(list))
llil = func.llil_if_available
mlil = func.mlil_if_available
hlil = func.hlil_if_available
show_common = Settings().get_bool("bnil-graph.showCommon")
show_mapped = Settings().get_bool("bnil-graph.showMapped")
show_ssa = Settings().get_bool("bnil-graph.showSSA")
if show_common:
if llil is not None:
for block in llil:
for il in block:
lookup["LowLevelIL"][il.address].append(il)
if mlil is not None:
for block in mlil:
for mil in block:
lookup["MediumLevelIL"][mil.address].append(mil)
if hlil is not None:
for block in hlil:
for hil in block:
lookup["HighLevelIL"][hil.address].append(hil)
if show_ssa:
if llil is not None and llil.ssa_form is not None:
for block in llil.ssa_form:
for il in block:
lookup["LowLevelILSSA"][il.address].append(il)
if mlil is not None and mlil.ssa_form is not None:
for block in mlil.ssa_form:
for mil in block:
lookup["MediumLevelILSSA"][mil.address].append(mil)
if hlil is not None and hlil.ssa_form is not None:
for block in hlil.ssa_form:
for hil in block:
lookup["HighLevelILSSA"][hil.address].append(hil)
if show_mapped:
if llil is not None and llil.mapped_medium_level_il is not None:
mmlil = llil.mapped_medium_level_il
for block in mmlil:
for mil in block:
lookup["MappedMediumLevelIL"][mil.address].append(mil)
if show_ssa:
for block in mmlil.ssa_form:
for mil in block:
lookup["MappedMediumLevelILSSA"][mil.address].append(mil)
return lookup
def get_function_containing_instruction_at(bv, addr):
# Ensure that the `Function` returned contains an instruction starting at `addr`
# This is needed in the case of overlapping functions where instructions are not aligned
functions = bv.get_functions_containing(addr) # type: List[Function]
for func in functions:
instr_addrs = [instr_addr for _, instr_addr in func.instructions]
if addr in instr_addrs:
return func
# Should never be reached
log_error("Found no function with instruction at address {:#x})".format(addr))
def graph_bnil(bv, addr):
function = get_function_containing_instruction_at(bv, addr) # type: Function
g = binaryninja.FlowGraph()
(tokens,) = [
tokens for tokens, insn_addr in function.instructions if insn_addr == addr
]
head = binaryninja.FlowGraphNode(g)
head.lines = [tokens]
g.append(head)
graph_ils(bv, g, head, function, addr)
show_graph_report(bv, g, "Instruction Graph ({:#x})".format(addr))
def match_condition(name, o):
match = []
if isinstance(o, (LowLevelILInstruction, MediumLevelILInstruction, HighLevelILInstruction)):
if isinstance(o, LowLevelILInstruction):
operation_class = "LowLevelILOperation"
elif isinstance(o, MediumLevelILInstruction):
operation_class = "MediumLevelILOperation"
elif isinstance(o, HighLevelILInstruction):
operation_class = "HighLevelILOperation"
match += ["# {}".format(str(o))]
match += [
"if {}.operation != {}.{}:".format(name, operation_class, o.operation.name)
]
match += [" return False\n"]
ops = enumerate(o.operands)
for i, oo in ops:
oo_name, ty = o.ILOperations[o.operation][i]
if ty == 'reg_stack_ssa_dest_and_src' or ty == 'var_ssa_dest_and_src':
next_name = 'next' if oo_name == 'prev' else 'dest'
full_name = "{}.{}".format(name, next_name)
cond = match_condition(full_name, oo)
match += cond
i, oo = next(ops)
full_name = "{}.{}".format(name, oo_name)
cond = match_condition(full_name, oo)
match += cond
else:
full_name = "{}.{}".format(name, oo_name)
cond = match_condition(full_name, oo)
match += cond
elif isinstance(o, list):
match += ["if len({}) != {}:".format(name, len(o))]
match += [" return False\n"]
# match the sub conditions too
for i, sub_insn in enumerate(o):
full_name = "{}[{}]".format(name, i)
cond = match_condition(full_name, sub_insn)
match += cond
elif isinstance(o, (int, long)):
match += ["if {} != {:#x}:".format(name, o)]
match += [" return False\n"]
elif isinstance(o, ILRegister):
match += ["if {}.name != '{}':".format(name, o.name)]
match += [" return False\n"]
elif isinstance(o, SSARegister):
match += ["if {}.reg.name != '{}':".format(name, o.reg.name)]
match += [" return False\n"]
match += ["if {}.version != {}:".format(name, o.version)]
match += [" return False\n"]
elif isinstance(o, SSAVariable):
match += ["if {}.var.name != '{}':".format(name, o.var.name)]
match += [" return False\n"]
match += ["if {}.version != {}:".format(name, o.version)]
match += [" return False\n"]
else:
match += ["if {} != {}:".format(name, o)]
match += [" return False\n"]
return match
def match_bnil(bv, addr):
function = get_function_containing_instruction_at(bv, addr) # type: Function
lookup = collect_ils(bv, function)
report = ""
for ty in lookup.keys():
llil_insns = lookup[ty][addr]
for idx, insn in enumerate(sorted(llil_insns)):
f = "def match_{}_{:x}_{}(insn):\n".format(ty, addr, idx)
cond = match_condition("insn", insn)
f += "\n".join([" " + x for x in cond])
f += "\n return True\n"
report += f + "\n\n"
show_plain_text_report("BNIL Matcher", report)
PluginCommand.register_for_address(
"BNIL\\Instruction Graph", "View BNIL Instruction Information", graph_bnil
)
PluginCommand.register_for_address(
"BNIL\\Python Match Generator",
"Generate a python function to match the selection instructions",
match_bnil,
)