-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyemulator.py
569 lines (473 loc) · 23.1 KB
/
pyemulator.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
import os
import sys
import importlib
import pefile
import struct
from unicorn.unicorn import Uc
from unicorn.unicorn_const import UC_ARCH_X86, UC_HOOK_CODE, UC_MODE_32, UC_ERR_EXCEPTION, UC_ERR_OK
from unicorn.unicorn_const import UC_HOOK_MEM_WRITE_UNMAPPED, UC_HOOK_MEM_READ_UNMAPPED, UC_HOOK_MEM_READ
from uc_handler.api_handler import ApiHandler
from uc_handler.cb_handler import logger
from uc_handler.err_handler import invalid_mem_access_cb
from pymanager.fsmanager.fs_emu_util import emu_path_join, convert_winpath_to_emupath
from pymanager.objmanager.coreobj import EmuProcess, EmuThread
from pymanager.fsmanager.windefs import DesiredAccess, CreationDisposition, FileAttribute
from pymanager.memmanager.windefs import PageAllocationType, PageProtect, PageType, ALLOCATION_GRANULARITY
from pymanager.memmanager import manager as mem_manager
from pymanager.objmanager.manager import ObjectManager
from pymanager.procmanager.manager import EmuThreadManager, EmuProcManager
import speakeasy.windows.windows.windows as windef
from pyfilesystem.emu_fs import WinVFS
import pydll
import speakeasy.windows.nt.ntoskrnl as ntos
from speakeasy.windows.windows.windows import CONTEXT
from unicorn.x86_const import *
from keystone import * # using keystone as assembler
from capstone import * # using capstone as disassembler
class WinX86Emu:
def __init__(self, parent=None):
if not parent:
# create new virtual FileSystem
self.emu_vfs = WinVFS()
self.obj_manager = ObjectManager()
self.mem_manager = mem_manager.MemoryManager()
else:
self.net_manager = parent.net_manager
self.obj_manager = parent.obj_manager
self.arch = UC_ARCH_X86
self.mode = UC_MODE_32
self.cur_thread = None
self.threads = []
self.ctx:CONTEXT = None
self.ptr_size = 0
self.api_handler = ApiHandler(self)
self.set_ptr_size()
self.emu_waiting_queue = []
self.winapi_info_dict = {}
self.running_process = None
self.__set_emulation_config()
def create_new_emu_engine(self):
return Uc(UC_ARCH_X86, UC_MODE_32)
def init_emulation_environment(self, phy_file_full_path):
def split_path(path):
sep = ""
if "\\" in path:
sep = "\\"
else:
sep = "/"
return path.split(sep)
def get_basename(file_path):
return split_path(file_path)[-1]
# creation emulation env
self.emu_vfs.create_home_dir(self.emu_home_dir)
virtual_file_full_path = emu_path_join(self.emu_home_dir, get_basename(phy_file_full_path).lower())
self.emu_vfs.copy(phy_file_full_path, virtual_file_full_path)
self.insert_emulation_processing_queue(virtual_file_full_path)
pass
def insert_emulation_processing_queue(self, argv):
proc_obj = None
if isinstance(argv, str):
proc_obj, _, _ = self.create_process(argv) # file_path
elif isinstance(argv, bytes) or isinstance(bytearray):
# TODO:
# CreateProcess with SectionHandle or FileHandle
pass
EmuProcManager.push_wait_queue(proc_obj.pid, proc_obj)
pass
def launch(self):
while not EmuProcManager.is_wait_empty():
po = EmuProcManager.deq_wait_queue()
self.running_process = po["obj"]
self.resume_thread(self.running_process)
pass
def resume_thread(self, proc_obj:EmuProcess, tid:int=-1):
thread_obj = None
pid = proc_obj.pid
wait_q = EmuThreadManager.get_wait_queue(pid)
while wait_q:
tid=-1
if tid == -1:
to = EmuThreadManager.deq_wait_queue(pid)
thread_obj = to["obj"]
tid = thread_obj.tid
else:
q = wait_q
if not q:
raise Exception('Fail to resume thread tid : %d' % (tid))
idx = 0
for o in q:
if o["tid"] == tid:
to = EmuThreadManager.deq_wait_queue(pid, idx)
thread_obj = to["obj"]
idx += 1
if not thread_obj:
raise Exception('Fail to resume thread tid : %d' % (tid))
EmuThreadManager.set_running_thread(pid, tid, thread_obj)
thread_obj.setup_context()
thread_obj.setup_ldt()
try:
thread_obj.uc_eng.emu_start(thread_obj.ctx.Eip, 0)
except Exception as e:
if e.args[0] == UC_ERR_EXCEPTION:
thread_obj.uc_eng.emu_stop()
elif e.args[0] == UC_ERR_OK:
thread_obj.uc_eng.emu_stop()
else:
print(e)
pass
# def resume(self):
# while len(self.threads) != 0:
# em_thread_handle = self.pop_waiting_queue()
# em_thread = ObjectManager.get_obj_by_handle(em_thread_handle)
# em_thread.setup_context()
# em_thread.setup_ldt()
# self.running_thread = em_thread
# try:
# self.emu_suspend_flag = False
# em_thread.uc_eng.emu_start(em_thread.ctx.Eip, 0)
# except Exception as e:
# if e.args[0] == UC_ERR_EXCEPTION:
# em_thread.uc_eng.emu_stop()
# elif e.args[1] == UC_ERR_OK:
# em_thread.uc_eng.emu_stop()
def init_vas(self, proc_obj:EmuProcess):
# This is actually done by ntoskrnl
self.mem_manager.alloc_page(pid=proc_obj.pid, alloc_base=0, size=0x10000, allocation_type= PageAllocationType.MEM_RESERVE)
peb_heap = self.mem_manager.create_heap(pid=proc_obj.pid, size=0x2000, max_size=0)
peb_base = self.mem_manager.alloc_heap(peb_heap, ntos.PEB(self.ptr_size).sizeof())
proc_default_heap = self.mem_manager.create_heap(pid=proc_obj.pid,size=1024*1024, max_size=1024*1024)
proc_obj.set_peb_heap(peb_heap)
proc_obj.set_peb_base(peb_base)
proc_obj.set_proc_default_heap(proc_default_heap)
pass
def load_target_proc(self, proc_obj:EmuProcess):
_pe_ = proc_obj.parsed_pe
if _pe_.DOS_HEADER.e_magic != struct.unpack("<H", b'MZ')[0]: # pylint: disable=no-member
raise Exception("Target file is not PE")
image_base = _pe_.OPTIONAL_HEADER.ImageBase
size_of_image = _pe_.OPTIONAL_HEADER.SizeOfImage
ep = image_base + _pe_.OPTIONAL_HEADER.AddressOfEntryPoint
image_pages = self.mem_manager.alloc_page(
pid=proc_obj.pid,
size=size_of_image,
allocation_type=PageAllocationType.MEM_COMMIT|PageAllocationType.MEM_RESERVE,
alloc_base=image_base,
protect=PageProtect.PAGE_EXECUTE_READWRITE,
page_type=PageType.MEM_IMAGE
)
image_base = image_pages.get_base_addr()
proc_obj.set_image_base(image_base)
proc_obj.set_ep(ep)
pe_image = _pe_.get_memory_mapped_image(ImageBase=image_base)
self.mem_manager.write_process_memory(proc_obj.pid, image_base, pe_image)
del pe_image
def load_import_mods(self, proc_obj:EmuProcess):
# will be changed
# cur : load all modules that was emulated
# todo : load specific modules which recorded in IAT
for dll_name in pydll.EMULATED_DLL_LIST:
self.load_library(dll_name, proc_obj)
def load_library(self, dll_name, proc_obj:EmuProcess):
if dll_name not in pydll.SYSTEM_DLL_BASE:
dll_name = self.api_handler.api_set_schema(dll_name)
if dll_name not in pydll.SYSTEM_DLL_BASE:
return 0xFFFFFFFF # Invalid Handle
if dll_name not in proc_obj.imports:
_sys_dll_init_base = pydll.SYSTEM_DLL_BASE[dll_name]
dll_page = self.mem_manager.alloc_page(
pid=proc_obj.pid,
size=ALLOCATION_GRANULARITY,
allocation_type=PageAllocationType.MEM_COMMIT | PageAllocationType.MEM_RESERVE,
alloc_base=_sys_dll_init_base,
page_type=PageType.MEM_IMAGE
)
pydll.SYSTEM_DLL_BASE[dll_name] = dll_page.get_base_addr()
self.setup_emulated_dllobj(dll_name, proc_obj)
# Fake load
# overwrite RET at entire dll memory region
self.mem_manager.write_process_memory(proc_obj.pid, dll_page.get_base_addr(), b'\xC3'*ALLOCATION_GRANULARITY)
self.add_module_to_peb(proc_obj, dll_name)
return pydll.SYSTEM_DLL_BASE[dll_name]
else:
return pydll.SYSTEM_DLL_BASE[dll_name]
def setup_emulated_dllobj(self, mod_name, proc_obj:EmuProcess):
def igetattr(obj, attr):
for a in dir(obj):
if a.lower() == attr.lower():
return getattr(obj, a)
raise AttributeError
if mod_name not in sys.modules:
mod_obj = importlib.import_module("pydll." + mod_name)
if mod_name not in proc_obj.e_dllobj:
proc_obj.add_e_dll_obj(mod_name, igetattr(mod_obj, mod_name)(self))
pass
def setup_import_tab(self, proc_obj:EmuProcess):
def rewrite_iat_table(uc, first_thunk_etry, addr):
addr = struct.pack("I", addr)
uc.mem_write(first_thunk_etry, addr)
for dll in proc_obj.parsed_pe.DIRECTORY_ENTRY_IMPORT: # pylint: disable=no-member
dll_name = dll.dll.decode("ascii").lower().split(".")[0]
proc_obj.set_imports(dll_name, [])
if dll_name not in pydll.SYSTEM_DLL_BASE:
dll_name = self.api_handler.api_set_schema(dll_name)
try:
dll_base = pydll.SYSTEM_DLL_BASE[dll_name]
except:
raise Exception("Unsupported DLL")
for imp_api in dll.imports:
api_name = imp_api.name.decode("ascii")
if "msvcp" in dll_name:
# MS cpp runtime lib
if not proc_obj.pid in self.api_handler.cpp_procedure:
self.api_handler.cpp_procedure[proc_obj.pid] = {}
self.api_handler.cpp_procedure[proc_obj.pid][imp_api.address] = api_name
else:
if dll_name not in proc_obj.imports:
proc_obj.set_imports(dll_name, [(api_name, dll_base + imp_api.hint)])
proc_obj.add_imports(dll_name, (api_name, dll_base + imp_api.hint))
proc_obj.set_api_va_dict(dll_base + imp_api.hint, (dll_name, api_name))
rewrite_iat_table(proc_obj.uc_eng, imp_api.address, dll_base + imp_api.hint)
pass
def init_peb(self, proc_obj:EmuProcess):
# create new PEB & PEB_LDR & Process Image LDR_ENTRY
peb = ntos.PEB(self.ptr_size)
new_ldte = ntos.LDR_DATA_TABLE_ENTRY(self.ptr_size)
peb_ldr_data = ntos.PEB_LDR_DATA(self.ptr_size)
peb.BeingDebugged = 0
peb.ImageBaseAddress = proc_obj.image_base
peb.ProcessHeap = proc_obj.proc_default_heap.get_base_addr()
# allocate memory space for PEB and PEB_LDR & Process Image LDR_ENTRY
peb.Ldr = self.mem_manager.alloc_heap(proc_obj.peb_heap, peb_ldr_data.sizeof())
pNew_ldte = self.mem_manager.alloc_heap(proc_obj.peb_heap, new_ldte.sizeof())
# setup Process Image LDR_ENTRY
new_ldte.SizeOfImage = proc_obj.parsed_pe.OPTIONAL_HEADER.SizeOfImage
new_ldte.DllBase = proc_obj.parsed_pe.OPTIONAL_HEADER.ImageBase
new_ldte.LoadCount = 1
self.new_unicode_string(proc_obj, new_ldte.BaseDllName, proc_obj.name)
self.new_unicode_string(proc_obj, new_ldte.FullDllName, proc_obj.path)
# link PEB_LDR and Process Image LDR_ENTRY
size_of_list_etry = ntos.LIST_ENTRY(self.ptr_size).sizeof()
peb_ldr_data.InLoadOrderModuleList.Flink = pNew_ldte
peb_ldr_data.InMemoryOrderModuleList.Flink = pNew_ldte + size_of_list_etry
new_ldte.InLoadOrderLinks.Flink = peb.Ldr + 0xC
new_ldte.InMemoryOrderLinks.Flink = peb.Ldr + 0xC + size_of_list_etry
proc_obj.write_mem_self(pNew_ldte, new_ldte.get_bytes())
proc_obj.write_mem_self(peb.Ldr, peb_ldr_data.get_bytes())
proc_obj.write_mem_self(proc_obj.peb_base, peb.get_bytes())
proc_obj.add_ldr_entry((pNew_ldte, new_ldte))
proc_obj.set_peb_ldr(peb_ldr_data)
proc_obj.set_peb(peb)
pass
def add_module_to_peb(self, proc_obj:EmuProcess, mod_name:str):
new_ldte = ntos.LDR_DATA_TABLE_ENTRY(self.ptr_size)
new_ldte.DllBase = pydll.SYSTEM_DLL_BASE[mod_name]
new_ldte.Length = ntos.LDR_DATA_TABLE_ENTRY(self.ptr_size).sizeof()
self.new_unicode_string(proc_obj, new_ldte.BaseDllName, mod_name)
self.new_unicode_string(proc_obj, new_ldte.FullDllName, "C:\\Windows\\System32\\" + mod_name + ".dll")
pNew_ldte = self.mem_manager.alloc_heap(proc_obj.peb_heap, new_ldte.sizeof())
list_type = ntos.LIST_ENTRY(self.ptr_size)
# Link created list_entry to LDR_MODULE
if not proc_obj.ldr_entries:
pEntry, prev = proc_obj.peb.Ldr, proc_obj.peb_ldr_data
prev.InLoadOrderModuleList.Flink = pNew_ldte
prev.InMemoryOrderModuleList.Flink = pNew_ldte + list_type.sizeof()
prev.InInitializationOrderModuleList.Flink = 0
else:
pEntry, prev = proc_obj.ldr_entries[-1]
prev.InLoadOrderLinks.Flink = pNew_ldte
prev.InMemoryOrderLinks.Flink = pNew_ldte + list_type.sizeof()
prev.InInitializationOrderLinks.Flink = 0
# Not implement Blink
new_ldte.InLoadOrderLinks.Flink = proc_obj.peb.Ldr + 0xC
new_ldte.InMemoryOrderLinks.Flink = proc_obj.peb.Ldr + 0xC + list_type.sizeof()
proc_obj.add_ldr_entry((pNew_ldte, new_ldte))
proc_obj.write_mem_self(pNew_ldte, new_ldte.get_bytes())
proc_obj.write_mem_self(pEntry, prev.get_bytes())
proc_obj.write_mem_self(proc_obj.peb_base, proc_obj.peb.get_bytes())
proc_obj.write_mem_self(proc_obj.peb.Ldr, proc_obj.peb_ldr_data.get_bytes())
pass
def setup_uc_hooks(self, proc_obj:EmuProcess):
h0 = proc_obj.uc_eng.hook_add(UC_HOOK_MEM_READ, self.api_handler.cpp_runtime_api_cb, (proc_obj, self.api_handler))
h3 = proc_obj.uc_eng.hook_add(UC_HOOK_CODE, logger)
h1 = proc_obj.uc_eng.hook_add(UC_HOOK_CODE, self.api_handler.pre_api_call_cb_wrapper, (self, proc_obj, self.get_arch(), self.get_ptr_size()))
h2 = proc_obj.uc_eng.hook_add(UC_HOOK_MEM_READ_UNMAPPED | UC_HOOK_MEM_WRITE_UNMAPPED, invalid_mem_access_cb)
#h2 = proc_obj.uc_eng.hook_add(UC_HOOK_CODE, self.code_cb_handler.logger, (proc_obj, self.get_arch(), self.get_ptr_size()))
#h3 = self.uc_eng.hook_add(UC_HOOK_MEM_UNMAPPED, self.code_cb_handler.unmap_handler, (self, self.get_arch(), self.get_ptr_size()))
pass
def switch_thread_context(self, proc_obj:EmuProcess, thread_obj:EmuThread, ret=0):
def context_switch_cb(proc_obj:EmuProcess, thread_handle):
proc_obj.running_thread.save_context()
proc_obj.push_waiting_queue(proc_obj.running_thread.handle)
proc_obj.push_waiting_queue(thread_handle)
proc_obj.uc_eng.hook_del(proc_obj.ctx_switch_hook)
proc_obj.running_thread.suspend_thread()
proc_obj.ctx_switch_hook = proc_obj.uc_eng.hook_add(UC_HOOK_CODE, self.api_handler.post_api_call_cb_wrapper, (proc_obj, (proc_obj, thread_obj.handle), 1, context_switch_cb))
pass
def create_thread(
self,
proc_obj:EmuProcess,
thread_entry,
param=None,
stack_size=1024*1024, # 1MB default stack size
creation=windef.CREATE_NEW
):
if stack_size == 0:
stack_size=1024*1024
thread_stack_region = self.mem_manager.alloc_page(proc_obj.pid, stack_size, PageAllocationType.MEM_COMMIT)
stack_limit, stack_base = thread_stack_region.get_page_region_range()
hThread = self.obj_manager.create_new_object(
'Thread',
proc_obj,
thread_entry,
stack_base-stack_size+0x1000,
stack_limit,
param
)
thread_obj:EmuThread = self.obj_manager.get_obj_by_handle(hThread)
thread_obj.set_thread_stack(thread_stack_region)
thread_obj.teb_heap = self.mem_manager.create_heap(proc_obj.pid, size=0x10000, max_size=0x10000)
if creation & windef.CREATE_SUSPENDED:
thread_obj.suspend_count += 1
teb_base = self.mem_manager.alloc_heap(thread_obj.teb_heap, ntos.TEB(self.ptr_size).sizeof())
gdt_page = self.mem_manager.alloc_page(proc_obj.pid, 0x1000, PageAllocationType.MEM_COMMIT)
selectors = proc_obj.gdt.setup_selector(gdt_addr=gdt_page.get_base_addr(), fs_base=teb_base, fs_limit=ALLOCATION_GRANULARITY)
thread_obj.set_selectors(selectors)
thread_obj.init_teb(proc_obj.peb_base)
thread_obj.init_context()
self.mem_manager.write_process_memory(proc_obj.pid, teb_base, thread_obj.get_bytes())
EmuThreadManager.push_wait_queue(proc_obj.pid, thread_obj.tid, thread_obj)
return hThread
def create_process(self, file_path):
def parse_pe_binary(pe_bin):
return pefile.PE(data=pe_bin)
"""
1.
"""
if os.path.basename(file_path) == file_path:
# input file_path is using alias
# search procedure
# 1. %home_dir%
# 2. c:/windows/system32
virtual_file_path = convert_winpath_to_emupath(emu_path_join(self.emu_home_dir, file_path))
virtual_file_path = emu_path_join(virtual_file_path["vl"], virtual_file_path["ps"])
if self.emu_vfs.check_file_exist(virtual_file_path):
pass
else:
virtual_file_path = convert_winpath_to_emupath(emu_path_join("c:/windows/system32", file_path))
virtual_file_path = emu_path_join(virtual_file_path["vl"], virtual_file_path["ps"])
if self.emu_vfs.check_file_exist(virtual_file_path):
pass
else:
"""
*** Copy Mock Application to Start
"""
mock_app_path = emu_path_join(self.emu_home_dir, file_path)
self.emu_vfs.vcopy(self.emu_vfs.dummpy_app, mock_app_path)
virtual_file_path = mock_app_path
else:
virtual_file_path = convert_winpath_to_emupath(file_path)
virtual_file_path = emu_path_join(virtual_file_path["vl"], virtual_file_path["ps"])
uc_eng = self.create_new_emu_engine()
hFile = self.obj_manager.get_object_handle('File', virtual_file_path, DesiredAccess.GENERIC_ALL, CreationDisposition.OPEN_EXISTING, 0, FileAttribute.FILE_ATTRIBUTE_NORMAL)
if hFile == windef.INVALID_HANDLE_VALUE:
raise Exception("There is no target file to execute")
pHandle = self.obj_manager.create_new_object(
'Process',
uc_eng,
self,
virtual_file_path,
hFile
)
proc_obj = self.obj_manager.get_obj_by_handle(pHandle)
file_obj = self.obj_manager.get_obj_by_handle(hFile)
rf = file_obj.im_read_file()
if not rf["success"]:
return None
pe_bin = rf["data"]
_pe_ = parse_pe_binary(pe_bin)
proc_obj.set_parsed_pe(_pe_)
self.mem_manager.register_new_process(proc_obj)
self.init_vas(proc_obj)
self.init_peb(proc_obj)
self.load_target_proc(proc_obj)
self.setup_uc_hooks(proc_obj)
self.load_import_mods(proc_obj)
self.setup_import_tab(proc_obj)
hThread = self.create_thread(proc_obj, proc_obj.entry_point)
return proc_obj, pHandle, hThread
def create_process_ex(self, section_handle):
pass
def __update_api_va_dict__(self, va, dll:str, api:str):
self.api_va_dict[va] = (dll, api)
pass
def __set_emulation_config(self, config=None):
"""
Parse the config to be used for emulation
"""
import json
if not config:
config_path = os.path.join(os.getcwd(), "env.config")
with open(config_path, 'r') as f:
self.config = json.load(f)
config = self.config
else:
self.config = config
if isinstance(config, str):
config = json.loads(config)
self.osversion = config.get('os_ver', {})
self.env = config.get('env', {})
self.user_config = config.get('user', {})
self.domain = config.get('domain')
self.hostname = config.get('hostname')
self.symlinks = config.get('symlinks', [])
self.drive_config = config.get('drives', [])
self.registry_config = config.get('registry', {})
self.network_config = config.get('network', {})
self.process_config = config.get('processes', [])
self.command_line = config.get('command_line', '')
self.img_name = config.get('image_name' '')
self.img_path = config.get('image_path', '')
self.emu_home_dir = config.get('home_dir', '').lower().replace("\\", "/")
self.parse_api_conf()
def parse_api_conf(self, conf_path="./winapi.config"):
with open(conf_path, "rt") as f:
confs = f.readlines()
for line in confs:
line = line[:-1]
if not line:
continue
if line[0] == "#":
continue
s = line.split("|")
rettype = s[0]
api_name = s[1]
if len(s) > 2:
args_types = s[2:]
else:
args_types = []
self.winapi_info_dict[api_name] = {
"rettype": rettype,
"argc": len(args_types),
"args_types": args_types
}
def new_unicode_string(self, proc_obj:EmuProcess, ustr, pystr:str):
uBytes = (pystr+"\x00").encode("utf-16le")
pMem = self.mem_manager.alloc_heap(proc_obj.proc_default_heap, len(uBytes)+1)
ustr.Length = len(uBytes)
ustr.MaximumLength = len(uBytes)+1
ustr.Buffer = pMem
self.mem_manager.write_process_memory(proc_obj.pid, pMem, uBytes)
pass
def get_ptr_size(self):
return self.ptr_size
def get_arch(self):
return self.arch
def set_ptr_size(self):
if self.arch == UC_ARCH_X86 and self.mode == UC_MODE_32:
self.ptr_size = 4
# elif self.arch == UC_ARCH_X86 and self.mode == UC_MODE_64: # reserved
# self.ptr_size = 8
else:
raise Exception("Unsupported architecture")
def get_param(self):
return self.command_line.split(" ")[1:]