-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdelphi_analyser.py
346 lines (231 loc) · 8.99 KB
/
delphi_analyser.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
#!/usr/bin/env python
import re
import copy
from binaryninja import BinaryReader, BinaryView, LogLevel
from typing import Callable, List, Mapping, Union
from .constants import VMTOffsets
from .bnlogger import BNLogger
MATCH_CLASS_NAME = re.compile(rb'^[\w.:]+$')
class DelphiVMT(object):
'''
TODO: Doc
'''
def __init__(self, bv: BinaryView, delphi_version: int, address: int):
# 64 bits is currently not supported
address_size = bv.arch.address_size
assert address_size == 4
self._vmt_address = address
self._is_valid = False
self._bv = bv
self._br = BinaryReader(bv)
self._code_section = bv.sections['CODE']
self._vmt_offsets = VMTOffsets(delphi_version)
self._class_name = ''
self._instance_size = 0
self._parent_vmt = 0
self._table_list: Mapping[int, str] = {}
self._virtual_methods: Mapping[int, str] = {}
if not self._check_self_ptr():
return
if not self._resolve_name():
return
if not self._resolve_instance_size():
return
if not self._resolve_parent_vmt():
return
if not self._resolve_table_list():
return
if not self._resolve_virtual_methods():
return
self._is_valid = True
def __repr__(self):
return str(self)
def __str__(self):
if not self._is_valid:
return f'<InvalidVmt address=0x{self._vmt_address:08X}>'
return (f'<{self._class_name} start=0x{self.start:08X} '
f'instance_size=0x{self._instance_size:X}>')
## Properties
@property
def vmt_address(self) -> int:
return self._vmt_address
@property
def is_valid(self) -> bool:
return self._is_valid
@property
def class_name(self) -> str:
return self._class_name
@property
def instance_size(self) -> int:
return self._instance_size
@property
def parent_vmt(self) -> int:
return self._parent_vmt
@property
def table_list(self) -> Mapping[int, str]:
return self._table_list
@property
def virtual_methods(self) -> Mapping[int, str]:
return self._virtual_methods
@property
def vmt_offsets(self) -> VMTOffsets:
return copy.copy(self._vmt_offsets)
@property
def start(self) -> int:
return self._vmt_address + self._vmt_offsets.cVmtSelfPtr
@property
def size(self) -> int:
end = 0 # ????
return end - self.start
@property
def br_offset(self) -> int:
return self._br.offset
## Public API
def seek_to_code(self, address: int) -> bool:
if not self._is_valid_code_addr(address):
return False
self._br.seek(address)
return True
def seek_to_code_offset(self, offset: int) -> bool:
if not self._is_valid_code_addr(self._code_section.start + offset):
return False
self._br.seek(self._code_section.start + offset)
return True
def seek_to_vmt_offset(self, offset: int) -> bool:
if not self._is_valid_code_addr(self._vmt_address + offset):
return False
self._br.seek(self._vmt_address + offset)
return True
def read8(self) -> Union[None, int]:
return self._br.read8()
def read32(self) -> Union[None, int]:
return self._br.read32()
## Protected methods
def _check_self_ptr(self) -> bool:
if not self.seek_to_vmt_offset(self._vmt_offsets.cVmtSelfPtr):
return False
self_ptr = self._br.read32()
return self_ptr == self._vmt_address
def _resolve_name(self) -> bool:
class_name_addr = self._get_class_name_addr()
if class_name_addr is None:
return False
self._br.seek(class_name_addr)
name_len = self._br.read8()
if name_len == 0:
BNLogger.log(
f'Care, VMT without name (len: 0) detected at 0x{self._vmt_address:08X}',
LogLevel.WarningLog
)
class_name = self._br.read(name_len)
if MATCH_CLASS_NAME.match(class_name) is None:
return False
self._class_name = class_name.decode()
return True
def _resolve_instance_size(self) -> bool:
if not self.seek_to_vmt_offset(self._vmt_offsets.cVmtInstanceSize):
return False
self._instance_size = self._br.read32()
return True
def _resolve_parent_vmt(self) -> bool:
if not self.seek_to_vmt_offset(self._vmt_offsets.cVmtParent):
return False
self._parent_vmt = self._br.read32()
return True
def _resolve_virtual_methods(self) -> bool:
class_name_addr = self._get_class_name_addr()
if class_name_addr is None:
return False
address_size = self._bv.address_size
offsets = self.vmt_offsets.__dict__.items()
offset_map = {y:x for x, y in offsets}
tables_addr = self._table_list.keys()
if not self.seek_to_vmt_offset(self._vmt_offsets.cVmtParent + address_size):
return False
while self._br.offset < class_name_addr and self._br.offset not in tables_addr:
field_value = self._br.read32()
if field_value == 0:
continue
if not self._is_valid_code_addr(field_value):
prev_offset = self._br.offset - address_size
raise RuntimeError(f'Invalid code address deteted at 0x{prev_offset:08X} '
'({self.class_name})\n If you think it\'s a bug, please open an issue on '
'Github with the used binary or the full VMT (fields + VMT) as an attachment')
field_offset = self._br.offset - self._vmt_address - address_size
if field_offset in offset_map:
# Remove `cVmt` prefix
method_name = f'{self.class_name}.{offset_map[field_offset][4:]}'
else:
method_name = f'{self.class_name}.sub_{field_value:x}'
self._virtual_methods[field_value] = method_name
return True
def _resolve_table_list(self) -> bool:
if not self.seek_to_vmt_offset(self.vmt_offsets.cVmtIntfTable):
return False
offsets = self._vmt_offsets.__dict__.items()
offset_map = {y:x[4:] for x, y in offsets}
stop_at = self._vmt_address + self._vmt_offsets.cVmtClassName
while self._br.offset != stop_at:
prev_br_offset = self._br.offset
address = self._br.read32()
if address < 1:
continue
if not self._is_valid_code_addr(address):
raise RuntimeError('Invalid table address detected')
self._table_list[address] = offset_map[prev_br_offset - self._vmt_address]
return True
def _is_valid_code_addr(self, addy: int, allow_null=False) -> bool:
if addy == 0:
return allow_null
return addy >= self._code_section.start and addy < self._code_section.end
def _get_class_name_addr(self) -> Union[None, int]:
if not self.seek_to_vmt_offset(self._vmt_offsets.cVmtClassName):
return None
class_name_addr = self._br.read32()
if not self._is_valid_code_addr(class_name_addr):
return None
return class_name_addr
class DelphiAnalyzer(object):
'''
TODO: Doc
'''
def __init__(self, bv: BinaryView, delphi_version: int):
self._vmt_list: List[DelphiVMT] = []
self._bv = bv
self._br = BinaryReader(bv)
self._code_section = bv.sections['CODE']
self._delphi_version = delphi_version
self._vmt_offsets = VMTOffsets(delphi_version)
## Properties
@property
def delphi_version(self) -> int:
return self._delphi_version
@property
def vmt_list(self) -> List[DelphiVMT]:
return self._vmt_list
## Public API
def update_analysis_and_wait(self, callback: Callable[[DelphiVMT], None] = None):
self._vmt_list = []
self._seek_to_code_offset(0)
while True:
addy = self._get_possible_vmt()
if not addy:
break
delphi_vmt = DelphiVMT(self._bv, self._delphi_version, addy)
if not delphi_vmt.is_valid:
continue
self._vmt_list.append(delphi_vmt)
if callback is not None:
callback(delphi_vmt)
## Protected methods
def _seek_to_code_offset(self, offset: int):
self._br.seek(self._code_section.start + offset)
def _get_possible_vmt(self) -> int:
address_size = self._bv.arch.address_size
if address_size != 4:
raise RuntimeError('Only 32 bits architectures are currently supported')
while self._br.offset <= self._code_section.end - address_size:
begin = self._br.offset
class_vmt = self._br.read32()
if begin == class_vmt + self._vmt_offsets.cVmtSelfPtr:
return class_vmt