Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
#!/usr/bin/env python
"""https://github.com/unicorn-engine/unicorn/issues/165"""
import unicorn
def hook_mem_read_unmapped(mu, access, address, size, value, user_data):
pass
mu = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)
try:
for x in range(0, 1000):
mu.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED, hook_mem_read_unmapped, None)
except unicorn.UcError as e:
print("ERROR: %s" % e)
imp_struct_list.append(imp_struct)
if read_values:
try:
dll_name = get_string(getattr(imp_struct, "Name") + base_addr, uc, break_on_unprintable=True)
imp_names = []
rva_to_iat = getattr(imp_struct, "FirstThunk")
while True:
new_val = struct.unpack("
self.stop_reason = self.state.unicorn.stop_reason
self.success = self.state.unicorn.steps > 0
try:
self.end_addr = self.state.scratch.bbl_addr_list[-1]
except IndexError:
self.end_addr = self.addr
if self.state.unicorn.error is not None:
# error from hook
self.success = False
raise SimUnicornError(self.state.unicorn.error)
if self.state.unicorn.errno:
# error from unicorn
self.success = False
err = str(unicorn.UcError(self.state.unicorn.errno))
raise SimUnicornError(err)
self.state.scratch.executed_block_count += self.state.unicorn.steps
if self.state.unicorn.jumpkind.startswith('Ijk_Sys'):
self.state.ip = self.state.unicorn._syscall_pc
self.add_successor(self.state, self.state.ip, self.state.se.true, self.state.unicorn.jumpkind)
def read_mem(self,start,size):
try:
mem = self.mu.mem_read(start,size)
except unicorn.UcError,e:
print "Waring:[%s] read bad address=0x%x size=0x%x" % (e,start,size)
return None
return mem
# print(">>> Tracing instruction at 0x%x, instruction size = 0x%x, data=%r" %(address, size, uc.mem_read(address, size)))
# uc.hook_add(U.UC_HOOK_CODE, hook_code)
# For Intel, set the value of EBX
if elf.arch == 'i386':
uc.reg_write(U.x86_const.UC_X86_REG_EBX, got)
# Special case for MIPS, which is the most silly architecture
# https://sourceware.org/ml/binutils/2004-11/msg00116.html
if elf.arch == 'mips' and elf.bits == 32:
OFFSET_GP_GOT = 0x7ff0
uc.reg_write(U.mips_const.UC_MIPS_REG_GP, got + 0x7ff0)
try:
uc.emu_start(pc, until=-1, count=5)
except U.UcError as error:
UC_ERR = (k for k,v in \
U.unicorn_const.__dict__.items()
if error.errno == v and k.startswith('UC_ERR_')).next()
log.debug("%#x: %s (%s)", pc, error, UC_ERR)
if elf.arch == 'mips':
pc = uc.reg_read(U.mips_const.UC_MIPS_REG_PC)
if pc+1 == magic_addr:
t8 = uc.reg_read(U.mips_const.UC_MIPS_REG_T8)
stopped_addr.append(elf._mips_got.get(t8, 0))
retval = 0
if stopped_addr:
retval = stopped_addr.pop()
return retval
emulator.call_symbol(lib_module, 'JNI_OnLoad', emulator.java_vm.address_ptr, 0x00)
emulator.mu.hook_add(UC_HOOK_MEM_UNMAPPED, debug_utils.hook_unmapped)
# Do native stuff.
emulator.mu.hook_add(UC_HOOK_CODE, debug_utils.hook_code)
main_activity = MainActivity()
logger.info("Response from JNI call: %s" % main_activity.string_from_jni(emulator))
# Dump natives found.
logger.info("Exited EMU.")
logger.info("Native methods registered to MainActivity:")
for method in MainActivity.jvm_methods.values():
if method.native:
logger.info("- [0x%08x] %s - %s" % (method.native_addr, method.name, method.signature))
except UcError as e:
print("Exit at %x" % emulator.mu.reg_read(UC_ARM_REG_PC))
raise
print(''.join(['%02x' % b for b in result]))
# 037d560d0000903e34fb093f1d21e78f3bdf3fbebe00b124becc
# 036d2a7b000010f4d05395b7df8b0ec2b5ec085b938a473a6a51
# 036d2a7b000010f4d05395b7df8b0ec2b5ec085b938a473a6a51
# 0300000000002034d288fe8d6b95b778105cc36eade709d2b500
# 0300000000002034d288fe8d6b95b778105cc36eade709d2b500
# 0300000000002034d288fe8d6b95b778105cc36eade709d2b500
# Dump natives found.
# for method in MainActivity.jvm_methods.values():
# if method.native:
# logger.info("- [0x%08x] %s - %s" % (method.native_addr, method.name, method.signature))
except UcError as e:
print("Exit at %x" % emulator.mu.reg_read(UC_ARM_REG_PC))
raise
# memory write count in current basic block
userData["mem_write_count"] = 0
# cache previous address to count instructions that are executed multiple times, e.g. rep prefixed
userData["prevAddress"] = 0
# number same instruction has been executed in a row
userData["repCount"] = 0
cnt_functions += 1
try:
# emulate various paths through function via flare-emu, use hooks to reconstruct strings
eh.iterateAllPaths(fva, noop, hookData=userData, callHook=call_hook, instructionHook=instr_hook,
memAccessHook=hook_mem_write, hookApis=False, maxPaths=MAX_CODE_PATHS)
except unicorn.UcError as e:
errors.append("Error analyzing function 0x{:X}: {}".format(fva, str(e)))
else:
cnt_analyzed += 1
# print stackstrings found in this function
f_ss = list(filter(lambda s: s.fva == fva, userData["stackstrings"]))
cnt_found_ss += len(f_ss)
for ss in sorted(f_ss, key=lambda s: s.written_at):
print_string(ss.fva, ss.written_at, ss.offset, ss.s)
# IMPROVEMENT adjust stack frame member size in IDA view
# print globalstrings found in this function
f_gs = list(filter(lambda g: g.fva == fva, userData["globalstrings"]))
cnt_found_ss += len(f_gs)
for gs in sorted(f_gs, key=lambda g: g.written_at):
print_string(gs.fva, gs.written_at, gs.offset, gs.s)
def start(self, count=0, timeout=0):
"""Start the emulation phase with the parameters previously defined."""
#
# Proceed to the emulation phase.
#
try:
self.logger.info("Starting emulation at 0x%08X (count=%d)" % (
self.start_address, count))
self.__uc.emu_start(self.start_address,
self.return_address,
timeout,
count)
except uc.UcError, err:
self.logger.debug(format_exc())
self.logger.error("Emulation error : %s" % err)
self.__show_regs()