-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcfg.py
300 lines (257 loc) · 11.5 KB
/
cfg.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
"""A class to analyze a Control Flow Graph."""
from __future__ import print_function
import collections
import logging
from typing import Any, DefaultDict, Dict, Iterable, List, Optional, Set, Tuple
import capstone # type: ignore
_UNCONDITIONAL_JUMP_MNEMONICS = ['jmp', 'jmpq']
_HALT_MNEMONICS = ['hlt']
# A mapping of registers to its widest equivalent.
_REGISTER_EQUIVALENCES = {
capstone.CS_ARCH_X86: {
# RAX
capstone.x86.X86_REG_AH: capstone.x86.X86_REG_RAX,
capstone.x86.X86_REG_AL: capstone.x86.X86_REG_RAX,
capstone.x86.X86_REG_AX: capstone.x86.X86_REG_RAX,
capstone.x86.X86_REG_EAX: capstone.x86.X86_REG_RAX,
capstone.x86.X86_REG_RAX: capstone.x86.X86_REG_RAX,
# RBX
capstone.x86.X86_REG_BH: capstone.x86.X86_REG_RBX,
capstone.x86.X86_REG_BL: capstone.x86.X86_REG_RBX,
capstone.x86.X86_REG_BX: capstone.x86.X86_REG_RBX,
capstone.x86.X86_REG_EBX: capstone.x86.X86_REG_RBX,
capstone.x86.X86_REG_RBX: capstone.x86.X86_REG_RBX,
# RCX
capstone.x86.X86_REG_CH: capstone.x86.X86_REG_RCX,
capstone.x86.X86_REG_CL: capstone.x86.X86_REG_RCX,
capstone.x86.X86_REG_CX: capstone.x86.X86_REG_RCX,
capstone.x86.X86_REG_ECX: capstone.x86.X86_REG_RCX,
capstone.x86.X86_REG_RCX: capstone.x86.X86_REG_RCX,
# RDX
capstone.x86.X86_REG_DH: capstone.x86.X86_REG_RDX,
capstone.x86.X86_REG_DL: capstone.x86.X86_REG_RDX,
capstone.x86.X86_REG_DX: capstone.x86.X86_REG_RDX,
capstone.x86.X86_REG_EDX: capstone.x86.X86_REG_RDX,
capstone.x86.X86_REG_RDX: capstone.x86.X86_REG_RDX,
# RSI
capstone.x86.X86_REG_SIL: capstone.x86.X86_REG_RSI,
capstone.x86.X86_REG_SI: capstone.x86.X86_REG_RSI,
capstone.x86.X86_REG_ESI: capstone.x86.X86_REG_RSI,
capstone.x86.X86_REG_RSI: capstone.x86.X86_REG_RSI,
# RDI
capstone.x86.X86_REG_DIL: capstone.x86.X86_REG_RDI,
capstone.x86.X86_REG_DI: capstone.x86.X86_REG_RDI,
capstone.x86.X86_REG_EDI: capstone.x86.X86_REG_RDI,
capstone.x86.X86_REG_RDI: capstone.x86.X86_REG_RDI,
# RBP
capstone.x86.X86_REG_BPL: capstone.x86.X86_REG_RBP,
capstone.x86.X86_REG_BP: capstone.x86.X86_REG_RBP,
capstone.x86.X86_REG_EBP: capstone.x86.X86_REG_RBP,
capstone.x86.X86_REG_RBP: capstone.x86.X86_REG_RBP,
# RSP
capstone.x86.X86_REG_SPL: capstone.x86.X86_REG_RSP,
capstone.x86.X86_REG_SP: capstone.x86.X86_REG_RSP,
capstone.x86.X86_REG_ESP: capstone.x86.X86_REG_RSP,
capstone.x86.X86_REG_RSP: capstone.x86.X86_REG_RSP,
# R8
capstone.x86.X86_REG_R8B: capstone.x86.X86_REG_R8,
capstone.x86.X86_REG_R8W: capstone.x86.X86_REG_R8,
capstone.x86.X86_REG_R8D: capstone.x86.X86_REG_R8,
capstone.x86.X86_REG_R8: capstone.x86.X86_REG_R8,
# R9
capstone.x86.X86_REG_R9B: capstone.x86.X86_REG_R9,
capstone.x86.X86_REG_R9W: capstone.x86.X86_REG_R9,
capstone.x86.X86_REG_R9D: capstone.x86.X86_REG_R9,
capstone.x86.X86_REG_R9: capstone.x86.X86_REG_R9,
# R10
capstone.x86.X86_REG_R10B: capstone.x86.X86_REG_R10,
capstone.x86.X86_REG_R10W: capstone.x86.X86_REG_R10,
capstone.x86.X86_REG_R10D: capstone.x86.X86_REG_R10,
capstone.x86.X86_REG_R10: capstone.x86.X86_REG_R10,
# R11
capstone.x86.X86_REG_R11B: capstone.x86.X86_REG_R11,
capstone.x86.X86_REG_R11W: capstone.x86.X86_REG_R11,
capstone.x86.X86_REG_R11D: capstone.x86.X86_REG_R11,
capstone.x86.X86_REG_R11: capstone.x86.X86_REG_R11,
# R12
capstone.x86.X86_REG_R12B: capstone.x86.X86_REG_R12,
capstone.x86.X86_REG_R12W: capstone.x86.X86_REG_R12,
capstone.x86.X86_REG_R12D: capstone.x86.X86_REG_R12,
capstone.x86.X86_REG_R12: capstone.x86.X86_REG_R12,
# R13
capstone.x86.X86_REG_R13B: capstone.x86.X86_REG_R13,
capstone.x86.X86_REG_R13W: capstone.x86.X86_REG_R13,
capstone.x86.X86_REG_R13D: capstone.x86.X86_REG_R13,
capstone.x86.X86_REG_R13: capstone.x86.X86_REG_R13,
# R14
capstone.x86.X86_REG_R14B: capstone.x86.X86_REG_R14,
capstone.x86.X86_REG_R14W: capstone.x86.X86_REG_R14,
capstone.x86.X86_REG_R14D: capstone.x86.X86_REG_R14,
capstone.x86.X86_REG_R14: capstone.x86.X86_REG_R14,
# R15
capstone.x86.X86_REG_R15B: capstone.x86.X86_REG_R15,
capstone.x86.X86_REG_R15W: capstone.x86.X86_REG_R15,
capstone.x86.X86_REG_R15D: capstone.x86.X86_REG_R15,
capstone.x86.X86_REG_R15: capstone.x86.X86_REG_R15,
# RIP
capstone.x86.X86_REG_EIP: capstone.x86.X86_REG_RIP,
capstone.x86.X86_REG_RIP: capstone.x86.X86_REG_RIP,
},
}
def _prune_unreachable(blocks: Dict[str, Dict[str, List[Any]]],
address_range: Tuple[int, int]) -> None:
reachable: Set[str] = set()
queue = ['%x' % address_range[0]]
while queue:
addr = queue.pop()
if addr in reachable:
continue
reachable.add(addr)
for edge in blocks[addr]['edges']:
queue.append(edge['target'])
for unreachable in sorted(set(blocks.keys()) - reachable):
del blocks[unreachable]
def reverse_postorder(
blocks: Dict[str, Dict[str, List[Any]]]
) -> Iterable[Tuple[str, Dict[str, List[Any]], Set[str]]]:
"""Visit the block graph in reverse postorder.
This is useful to perform data-flow analysis on the block graph.
"""
reverse_edges: DefaultDict[str, Set[str]] = collections.defaultdict(set)
order: List[str] = []
seen: Set[str] = set()
def _visit(address: str) -> None:
if address in seen:
return
seen.add(address)
block = blocks[address]
for edge in block['edges']:
reverse_edges[edge['target']].add(address)
_visit(edge['target'])
order.append(address)
# Start the visiting on the first address of the function.
_visit(min(blocks.keys()))
for address in order[::-1]:
yield (address, blocks[address], reverse_edges[address])
class Disassembler:
"""A control flow graph from a disassembled code."""
def __init__(self,
isa: str,
*,
syntax: int = capstone.CS_OPT_SYNTAX_ATT,
raw_instructions: bool = False):
if isa == 'x86':
self._arch = capstone.CS_ARCH_X86
self._mode = capstone.CS_MODE_32
elif isa == 'x86_64':
self._arch = capstone.CS_ARCH_X86
self._mode = capstone.CS_MODE_64
elif isa == 'arm':
self._arch = capstone.CS_ARCH_ARM
self._mode = capstone.CS_MODE_32
elif isa == 'aarch64':
self._arch = capstone.CS_ARCH_ARM64
self._mode = capstone.CS_MODE_64
else:
raise Exception('Unknown ISA: %s' % isa)
self._disassembler = capstone.Cs(self._arch, self._mode)
self._disassembler.detail = True
self._disassembler.syntax = syntax
self._raw_instructions = raw_instructions
def disassemble(
self,
code: bytes,
address_range: Tuple[int, int],
) -> Dict[str, Dict[str, List[str]]]:
"""A JSON-friendly representation of this graph."""
cuts, edges = self._calculate_edges(code, address_range)
blocks = self._fill_basic_blocks(code, address_range, cuts, edges)
_prune_unreachable(blocks, address_range)
return blocks
def normalize_register(self, register: int) -> Optional[int]:
"""Return the widest register for this register, if known."""
return _REGISTER_EQUIVALENCES[self._arch].get(register)
def _get_jump_target(self, instruction: capstone.CsInsn) -> int:
op = instruction.operands[0]
if self._arch == capstone.CS_ARCH_X86:
if op.type == capstone.x86.X86_OP_IMM:
return int(op.imm)
if op.type == capstone.x86.X86_OP_MEM:
if op.mem.base in (capstone.x86.X86_REG_RIP,
capstone.x86.X86_REG_IP):
return int(instruction.address + op.mem.disp)
logging.debug('Unsupported jump addressing mode: %s %s',
instruction.mnemonic, instruction.op_str)
return -1
def _calculate_edges(
self, code: bytes, address_range: Tuple[int, int]
) -> Tuple[Set[int], Dict[int, List[Tuple[int, str]]]]:
cuts = set([address_range[0]])
edges: DefaultDict[int,
List[Tuple[int,
str]]] = collections.defaultdict(list)
for i in self._disassembler.disasm(code, address_range[0]):
if capstone.CS_GRP_JUMP in i.groups:
cuts.add(i.address + i.size)
cuts.add(i.operands[0].value.imm)
if i.mnemonic in _UNCONDITIONAL_JUMP_MNEMONICS:
edges[i.address] = [(self._get_jump_target(i),
'unconditional')]
else:
edges[i.address] = [(i.address + i.size, 'fallthrough'),
(i.operands[0].value.imm, 'jump')]
elif (capstone.CS_GRP_RET in i.groups
or i.mnemonic in _HALT_MNEMONICS):
cuts.add(i.address + i.size)
else:
edges[i.address] = [(i.address + i.size, 'unconditional')]
# Some amount of padding might have been added to the code to
# ensure that the last instruction is read fully.
if i.address >= address_range[1]:
break
return cuts, edges
def _fill_basic_blocks(
self, code: bytes, address_range: Tuple[int, int], cuts: Set[int],
edges: Dict[int, List[Tuple[int, str]]]
) -> Dict[str, Dict[str, List[Any]]]:
blocks: DefaultDict[str, Dict[
str, List[Any]]] = collections.defaultdict(lambda: {
'edges': [],
'external_edges': [],
'instructions': [],
})
current_block: Dict[str, List[Any]] = {
'edges': [],
'external_edges': [],
'instructions': [],
}
for i in self._disassembler.disasm(code, address_range[0]):
if i.address in cuts:
current_block = blocks['%x' % i.address]
if i.address in edges:
for dst, edgetype in edges[i.address]:
if dst not in cuts:
if not address_range[0] <= dst < address_range[1]:
current_block['external_edges'].append(
{'target': '%x' % dst})
continue
current_block['edges'].append({
'type': edgetype,
'target': '%x' % dst
})
if self._raw_instructions:
instruction = i
else:
instruction = {
'address': '%x' % i.address,
'bytes': [x for x in i.bytes],
'mnemonic': i.mnemonic,
'op': i.op_str,
}
current_block['instructions'].append(instruction)
# Some amount of padding was added to the code to ensure that the
# last instruction is read fully.
if i.address >= address_range[1]:
break
return blocks
# vi: tabstop=4 shiftwidth=4