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
|
import os, sys
import logging
from argparse import ArgumentParser
from miasm2.analysis.machine import Machine
from miasm2.os_dep import win_api_x86_32, win_api_x86_32_seh
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
from miasm2.analysis import debugging
from miasm2.jitter.loader.utils import libimp
class Sandbox(object):
"""
Parent class for Sandbox abstraction
"""
@staticmethod
def code_sentinelle(jitter):
print 'Emulation stop'
jitter.run = False
return False
@classmethod
def _classes_(cls):
"""
Iterator on parent classes except Sanbox
"""
for base_cls in cls.__bases__:
# Avoid infinite loop
if base_cls == Sandbox:
continue
yield base_cls
classes = property(lambda x:x.__class__._classes_())
def __init__(self, fname, options, custom_methods = {}):
"""
Initialize a sandbox
@fname: str file name
@options: namespace instance of specific options
@custom_methods: { str => func } for custom API implementations
"""
# Initialize
self.fname = fname
self.options = options
for cls in self.classes:
if cls == Sandbox:
continue
if issubclass(cls, OS):
cls.__init__(self, custom_methods)
else:
cls.__init__(self)
# Logging options
if self.options.singlestep:
self.jitter.jit.log_mn = True
self.jitter.jit.log_regs = True
if not self.options.quiet_function_calls:
self.machine.log_jit.setLevel(logging.DEBUG)
if self.options.dumpblocs:
self.jitter.jit.log_newbloc = True
@classmethod
def parser(cls, *args, **kwargs):
"""
Return instance of instance parser with expecting options.
Extra parameters are passed to parser initialisation.
"""
parser = ArgumentParser(*args, **kwargs)
parser.add_argument('-a', "--address",
help="Force entry point address", default=None)
parser.add_argument('-x', "--dumpall", action="store_true",
help="Load base dll")
parser.add_argument('-b', "--dumpblocs", action="store_true",
help="Log disasm blocks")
parser.add_argument('-z', "--singlestep", action="store_true",
help="Log single step")
parser.add_argument('-d', "--debugging", action="store_true",
help="Debug shell")
parser.add_argument('-g', "--gdbserver", type=int,
help="Listen on port @port")
parser.add_argument("-j", "--jitter",
help="Jitter engine. Possible values are: tcc (default), llvm, python",
default="tcc")
parser.add_argument('-q', "--quiet-function-calls", action="store_true",
help="Don't log function calls")
for base_cls in cls._classes_():
base_cls.update_parser(parser)
return parser
def run(self, addr=None):
"""
Launch emulation (gdbserver, debugging, basic JIT).
@addr: (int) start address
"""
if addr is None and self.options.address is not None:
addr = int(self.options.address, 16)
if any([self.options.debugging, self.options.gdbserver]):
dbg = debugging.Debugguer(self.jitter)
self.dbg = dbg
dbg.init_run(addr)
if self.options.gdbserver is not False:
port = self.options.gdbserver
print "Listen on port %d" % port
gdb = self.machine.gdbserver(dbg, port)
self.gdb = gdb
gdb.run()
else:
cmd = debugging.DebugCmd(dbg)
self.cmd = cmd
cmd.cmdloop()
else:
print "Start emulation", hex(addr)
self.jitter.init_run(addr)
print self.jitter.continue_run()
class OS(object):
"""
Parent class for OS abstraction
"""
def __init__(self, custom_methods):
pass
@classmethod
def update_parser(cls, parser):
pass
class Arch(object):
"""
Parent class for Arch abstraction
"""
# Architecture name
_ARCH_ = None
def __init__(self):
self.machine = Machine(self._ARCH_)
self.jitter = self.machine.jitter(self.options.jitter)
@classmethod
def update_parser(cls, parser):
pass
class OS_Win(OS):
# DLL to import
ALL_IMP_DLL = ["ntdll.dll", "kernel32.dll", "user32.dll",
"ole32.dll", "urlmon.dll",
"ws2_32.dll", 'advapi32.dll', "psapi.dll",
]
def __init__(self, custom_methods, *args, **kwargs):
from miasm2.jitter.loader.pe import vm_load_pe, preload_pe
super(OS_Win, self).__init__(custom_methods, *args, **kwargs)
# Import manager
libs = libimp()
self.libs = libs
win_api_x86_32.winobjs.runtime_dll = libs
# Load library
if self.options.loadbasedll:
all_pe = []
# Load libs in memory
for dll_fname in self.ALL_IMP_DLL:
fname = os.path.join('win_dll', dll_fname)
e_lib = vm_load_pe(self.jitter.vm, fname)
libs.add_export_lib(e_lib, dll_fname)
all_pe.append(e_lib)
# Patch libs imports
for pe in all_pe:
preload_pe(self.jitter.vm, pe, libs)
# Load main pe
self.pe = vm_load_pe(self.jitter.vm, self.fname)
# Fix pe imports
preload_pe(self.jitter.vm, self.pe, libs)
# Library calls handler
self.jitter.add_lib_handler(libs, custom_methods)
# Manage SEH
if self.options.use_seh:
win_api_x86_32_seh.main_pe_name = self.fname
win_api_x86_32_seh.main_pe = self.pe
win_api_x86_32_seh.loaded_modules = self.ALL_IMP_DLL
win_api_x86_32_seh.init_seh(self.jitter)
win_api_x86_32_seh.set_win_fs_0(self.jitter)
self.entry_point = self.pe.rva2virt(self.pe.Opthdr.AddressOfEntryPoint)
@classmethod
def update_parser(cls, parser):
parser.add_argument('-o', "--loadhdr", action="store_true",
help="Load pe hdr")
parser.add_argument('-e', "--loadmainpe", action="store_true",
help="Load main pe")
parser.add_argument('-y', "--use-seh", action="store_true",
help="Use windows SEH")
parser.add_argument('-l', "--loadbasedll", action="store_true",
help="Load base dll (path './win_dll')")
parser.add_argument('-r', "--parse-resources",
action="store_true", help="Load resources")
class OS_Linux(OS):
def __init__(self, custom_methods, *args, **kwargs):
from miasm2.jitter.loader.elf import vm_load_elf, preload_elf
super(OS_Linux, self).__init__(custom_methods, *args, **kwargs)
# Import manager
libs = libimp()
self.libs = libs
elf = vm_load_elf(self.jitter.vm, self.fname)
self.elf = elf
preload_elf(self.jitter.vm, elf, libs)
# Library calls handler
self.jitter.add_lib_handler(libs, custom_methods)
class OS_Linux_str(OS):
def __init__(self, custom_methods, *args, **kwargs):
super(OS_Linux_str, self).__init__(custom_methods, *args, **kwargs)
# Import manager
libs = libimp()
self.libs = libs
data = open(self.fname).read()
self.options.load_base_addr = int(self.options.load_base_addr, 16)
self.jitter.vm.add_memory_page(self.options.load_base_addr, PAGE_READ | PAGE_WRITE, data)
# Library calls handler
self.jitter.add_lib_handler(libs, custom_methods)
@classmethod
def update_parser(cls, parser):
parser.add_argument("load_base_addr", help="load base address")
class Arch_x86_32(Arch):
_ARCH_ = "x86_32"
STACK_SIZE = 0x100000
def __init__(self):
super(Arch_x86_32, self).__init__()
if self.options.usesegm:
self.jitter.ir_arch.do_stk_segm= True
self.jitter.ir_arch.do_ds_segm= True
self.jitter.ir_arch.do_str_segm = True
self.jitter.ir_arch.do_all_segm = True
# Init stack
self.jitter.stack_size = self.STACK_SIZE
self.jitter.init_stack()
@classmethod
def update_parser(cls, parser):
parser.add_argument('-s', "--usesegm", action="store_true",
help="Use segments fs:")
class Arch_arml(Arch):
_ARCH_ = "arml"
STACK_SIZE = 0x100000
def __init__(self):
super(Arch_arml, self).__init__()
# Init stack
self.jitter.stack_size = self.STACK_SIZE
self.jitter.init_stack()
class Arch_armb(Arch):
_ARCH_ = "armb"
STACK_SIZE = 0x100000
def __init__(self):
super(Arch_armb, self).__init__()
# Init stack
self.jitter.stack_size = self.STACK_SIZE
self.jitter.init_stack()
class Sandbox_Win_x86_32(Sandbox, Arch_x86_32, OS_Win):
def __init__(self, *args, **kwargs):
Sandbox.__init__(self, *args, **kwargs)
# Pre-stack some arguments
self.jitter.push_uint32_t(2)
self.jitter.push_uint32_t(1)
self.jitter.push_uint32_t(0)
self.jitter.push_uint32_t(0x1337beef)
# Set the runtime guard
self.jitter.add_breakpoint(0x1337beef, self.__class__.code_sentinelle)
def run(self, addr = None):
"""
If addr is not set, use entrypoint
"""
if addr is None and self.options.address is None:
addr = self.entry_point
super(Sandbox_Win_x86_32, self).run(addr)
class Sandbox_Linux_x86_32(Sandbox, Arch_x86_32, OS_Linux):
def __init__(self, *args, **kwargs):
Sandbox.__init__(self, *args, **kwargs)
# Pre-stack some arguments
self.jitter.push_uint32_t(2)
self.jitter.push_uint32_t(1)
self.jitter.push_uint32_t(0)
self.jitter.push_uint32_t(0x1337beef)
# Set the runtime guard
self.jitter.add_breakpoint(0x1337beef, self.__class__.code_sentinelle)
def run(self, addr = None):
"""
If addr is not set, use entrypoint
"""
if addr is None:
addr = self.entry_point
super(Sandbox_Linux_x86_32, self).run(addr)
class Sandbox_Linux_arml(Sandbox, Arch_arml, OS_Linux):
def __init__(self, *args, **kwargs):
Sandbox.__init__(self, *args, **kwargs)
self.jitter.cpu.LR = 0x1337beef
# Set the runtime guard
self.jitter.add_breakpoint(0x1337beef, self.__class__.code_sentinelle)
def run(self, addr = None):
if addr is None and self.options.address is not None:
addr = int(self.options.address, 16)
super(Sandbox_Linux_arml, self).run(addr)
class Sandbox_Linux_armb_str(Sandbox, Arch_armb, OS_Linux_str):
def __init__(self, *args, **kwargs):
Sandbox.__init__(self, *args, **kwargs)
self.jitter.cpu.LR = 0x1337beef
# Set the runtime guard
self.jitter.add_breakpoint(0x1337beef, self.__class__.code_sentinelle)
def run(self, addr = None):
if addr is None and self.options.address is not None:
addr = int(self.options.address, 16)
super(Sandbox_Linux_armb_str, self).run(addr)
class Sandbox_Linux_arml_str(Sandbox, Arch_arml, OS_Linux_str):
def __init__(self, *args, **kwargs):
Sandbox.__init__(self, *args, **kwargs)
self.jitter.cpu.LR = 0x1337beef
# Set the runtime guard
self.jitter.add_breakpoint(0x1337beef, self.__class__.code_sentinelle)
def run(self, addr = None):
if addr is None and self.options.address is not None:
addr = int(self.options.address, 16)
super(Sandbox_Linux_arml_str, self).run(addr)
|