コード例 #1
0
ファイル: emulator.py プロジェクト: zbx91/Dwarf
    def __setup(self):
        if self.dwarf.arch == 'arm':
            self.thumb = self.context.pc.thumb
            if self.thumb:
                self.cs = Cs(CS_ARCH_ARM, CS_MODE_THUMB)
                self.uc = unicorn.Uc(unicorn.UC_ARCH_ARM,
                                     unicorn.UC_MODE_THUMB)
                self._current_cpu_mode = unicorn.UC_MODE_THUMB
                # Enable VFP instr
                self.uc.mem_map(0x1000, 1024)
                self.uc.mem_write(0x1000, binascii.unhexlify(VFP))
                self.uc.emu_start(0x1000 | 1, 0x1000 + len(VFP))
                self.uc.mem_unmap(0x1000, 1024)
            else:
                self.cs = Cs(CS_ARCH_ARM, CS_MODE_ARM)
                self.uc = unicorn.Uc(unicorn.UC_ARCH_ARM, unicorn.UC_MODE_ARM)
                self._current_cpu_mode = unicorn.UC_MODE_ARM
        elif self.dwarf.arch == 'arm64':
            self.uc = unicorn.Uc(unicorn.UC_ARCH_ARM64,
                                 unicorn.UC_MODE_LITTLE_ENDIAN)
            self.cs = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN)

            self._current_cpu_mode = unicorn.UC_MODE_LITTLE_ENDIAN
        elif self.dwarf.arch == 'ia32':
            self.uc = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)
        elif self.dwarf.arch == 'x64':
            self.uc = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_64)
        else:
            # unsupported arch
            return 5

        # enable capstone details
        self.cs.detail = True

        err = self.map_range(self.context.pc.value)
        if err > 0:
            return err

        self.current_context = EmulatorContext(self.dwarf)
        for reg in self.current_context._unicorn_registers:
            if reg in self.context.__dict__:
                self.uc.reg_write(self.current_context._unicorn_registers[reg],
                                  self.context.__dict__[reg].value)

        self.uc.hook_add(unicorn.UC_HOOK_CODE, self.hook_code)
        self.uc.hook_add(unicorn.UC_HOOK_MEM_WRITE | unicorn.UC_HOOK_MEM_READ,
                         self.hook_mem_access)
        self.uc.hook_add(
            unicorn.UC_HOOK_MEM_FETCH_UNMAPPED
            | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED
            | unicorn.UC_HOOK_MEM_READ_UNMAPPED, self.hook_unmapped)
        self.current_context.set_context(self.uc)
        return err
コード例 #2
0
    def test_seg1(self):
        u = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)
        u.mem_map(0x2000, 0x1000)
        u.mem_read(0x2000, 1)

        for i in range(50):
            u = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)
            u.mem_map(i*0x1000, 0x1000)
            u.mem_read(i*0x1000, 1)

        for i in range(20):
            with self.assertRaises(UcError):
                u = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)
                u.mem_map(i*0x1000, 5)
                u.mem_read(i*0x1000, 1)
コード例 #3
0
 def setup_arm(self):
     self.thumb = self.context.pc.thumb
     if self.thumb:
         self._current_cpu_mode = unicorn.UC_MODE_THUMB
         self.cs = Cs(CS_ARCH_ARM, CS_MODE_THUMB)
         self.uc = unicorn.Uc(unicorn.UC_ARCH_ARM, unicorn.UC_MODE_THUMB)
         # Enable VFP instr
         self.uc.mem_map(0x1000, 1024)
         self.uc.mem_write(0x1000, binascii.unhexlify(VFP))
         self.uc.emu_start(0x1000 | 1, 0x1000 + len(VFP))
         self.uc.mem_unmap(0x1000, 1024)
     else:
         self.cs = Cs(CS_ARCH_ARM, CS_MODE_ARM)
         self.uc = unicorn.Uc(unicorn.UC_ARCH_ARM, unicorn.UC_MODE_ARM)
         self._current_cpu_mode = unicorn.UC_MODE_ARM
コード例 #4
0
    def __init__(self):
        self.__handle = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_64)
        self.__handle.mem_map(self._stack_ptr, self._stack_size)
        self.__handle.reg_write(unicorn.x86_const.UC_X86_REG_RSP, self._stack_ptr + int(self._stack_size / 2))

        self.on_create()
        pass
コード例 #5
0
ファイル: arm.py プロジェクト: davidelbaze/rainbow
    def __init__(self, trace=True, sca_mode=False, local_vars=[]):
        super().__init__(trace, sca_mode)
        self.emu = uc.Uc(uc.UC_ARCH_ARM, uc.UC_MODE_ARM | uc.UC_MODE_THUMB)
        self.disasm = cs.Cs(cs.CS_ARCH_ARM, cs.CS_MODE_ARM | cs.CS_MODE_THUMB)
        self.disasm.detail = True
        self.word_size = 4
        self.endianness = "little"
        self.page_size = self.emu.query(uc.UC_QUERY_PAGE_SIZE)
        self.page_shift = self.page_size.bit_length() - 1
        self.pc = uc.arm_const.UC_ARM_REG_PC

        known_regs = [
            i[len('UC_ARM_REG_'):] for i in dir(uc.arm_const) if '_REG' in i
        ]
        self.reg_map = {
            r.lower(): getattr(uc.arm_const, 'UC_ARM_REG_' + r)
            for r in known_regs
        }

        self.stubbed_functions = local_vars
        self.setup(sca_mode)

        self.emu.reg_write(uc.arm_const.UC_ARM_REG_SP, self.STACK_ADDR)
        self.emu.reg_write(uc.arm_const.UC_ARM_REG_FP, self.STACK_ADDR)
        self.emu.reg_write(uc.arm_const.UC_ARM_REG_APSR, 0)  ## ?
コード例 #6
0
    def __init__(self, trace=True, sca_mode=False, local_vars={}):
        super().__init__(trace, sca_mode)
        self.emu = uc.Uc(uc.UC_ARCH_X86, uc.UC_MODE_64)
        self.disasm = cs.Cs(cs.CS_ARCH_X86, cs.CS_MODE_64)
        self.disasm.detail = True
        self.word_size = 8
        self.endianness = "little"
        self.page_size = self.emu.query(uc.UC_QUERY_PAGE_SIZE)
        self.page_shift = self.page_size.bit_length() - 1
        self.pc = uc.x86_const.UC_X86_REG_RIP

        # workaround for capstone 4
        uc.x86_const.UC_X86_REG_RFLAGS = uc.x86_const.UC_X86_REG_EFLAGS

        known_regs = [
            i[len('UC_X86_REG_'):] for i in dir(uc.x86_const) if '_REG' in i
        ]
        self.reg_map = {
            r.lower(): getattr(uc.x86_const, 'UC_X86_REG_' + r)
            for r in known_regs
        }

        self.stubbed_functions = local_vars
        self.setup(sca_mode)

        self.emu.reg_write(uc.x86_const.UC_X86_REG_RBP, self.STACK_ADDR)
        self.emu.reg_write(uc.x86_const.UC_X86_REG_RSP, self.STACK_ADDR)
コード例 #7
0
    def __init__(self):
        self.arch = pwndbg.arch.current
        if self.arch not in arch_to_UC:
            raise NotImplementedError('Cannot emulate code for %s' % self.arch)
        self.consts = arch_to_UC_consts[self.arch]
        self.mode = self.get_mode()
        self.cs = C.Cs(arch_to_CS[self.arch], self.mode)
        self.uc = U.Uc(arch_to_UC[self.arch], self.mode)
        self.regs = pwndbg.regs.current
        for reg in list(self.regs.misc) + list(self.regs.common) + list(
                self.regs.flags):
            enum = self.get_reg_enum(reg)
            if not reg:
                print 'Could not set register %r' % reg
                continue
            value = getattr(pwndbg.regs, reg)
            if value is None:
                print '# Could not set register %r' % reg
                continue
            else:
                name = 'U.x86_const.UC_X86_REG_%s' % reg.upper()
                print 'uc.reg_write(%(name)s, %(value)r)' % locals()
            self.uc.reg_write(enum, value)

        self.uc.hook_add(
            U.UC_HOOK_MEM_READ_UNMAPPED | U.UC_HOOK_MEM_WRITE_UNMAPPED,
            self.hook_mem_invalid)
        self.uc.hook_add(U.UC_HOOK_INTR, self.hook_intr)
        self.map_page(self.pc)
コード例 #8
0
    def test_eflags(self):
        # imul eax, ebx
        CODE = '\x0f\xaf\xc3'

        uc = U.Uc(U.UC_ARCH_X86, U.UC_MODE_32)
        uc.reg_write(U.x86_const.UC_X86_REG_EAX, 16)
        uc.reg_write(U.x86_const.UC_X86_REG_EBX, 1)
        uc.reg_write(U.x86_const.UC_X86_REG_EFLAGS, 0x292)

        uc.mem_map(0x600000, 0x1000)
        uc.mem_write(0x6000b0, CODE)
        uc.emu_start(0x6000b0, 0, count=1)

        # Here's the original execution trace for this on actual hardware.
        #
        # (gdb) x/i $eip
        # => 0x804aae5:   imul   eax,DWORD PTR [ebp-0x8]
        # (gdb) p/x $eax
        # $2 = 0x10
        # (gdb) x/wx $ebp-8
        # 0xbaaaad4c:     0x00000001
        # (gdb) p/x $eflags
        # $3 = 0x292
        # (gdb) si
        # 0x0804aae9 in ?? ()
        # (gdb) p/x $eflags
        # $4 = 0x202

        self.assertEqual(0x202, uc.reg_read(U.x86_const.UC_X86_REG_EFLAGS))
コード例 #9
0
    def test_eflags(self):
        # 0:    4d 31 f6                 xor    r14, r14
        # 3:    45 85 f6                 test   r14d, r14d
        # 6:    75 fe                    jne    0x6
        # 8:    f4                       hlt
        CODE = 'M1\xf6E\x85\xf6u\xfe\xf4'

        uc = U.Uc(U.UC_ARCH_X86, U.UC_MODE_64)
        uc.reg_write(U.x86_const.UC_X86_REG_RIP, 0x6000b0)
        uc.reg_write(U.x86_const.UC_X86_REG_EFLAGS, 0x246)

        uc.mem_map(0x600000, 0x1000)
        uc.mem_write(0x6000b0, CODE)

        uc.emu_start(0x6000b0 + 6, 0, count=1)

        # Here's the original execution trace for this on qemu-user.
        #
        # $ SC='xor r14,r14; test r14d, r14d; jne $; hlt'
        # $ asm --context amd64 --format elf $SC > example
        # $ qemu-x86_64-static -d cpu,in_asm -singlestep ./test \
        #   | grep -E 'RFL|^0x'
        # 0x00000000006000b0:  xor    %r14,%r14
        # RIP=00000000006000b0 RFL=00000202 [-------] CPL=3 II=0 A20=1 SMM=0 HLT=0
        # 0x00000000006000b3:  test   %r14d,%r14d
        # RIP=00000000006000b3 RFL=00000246 [---Z-P-] CPL=3 II=0 A20=1 SMM=0 HLT=0
        # 0x00000000006000b6:  jne    0x6000b6
        # RIP=00000000006000b6 RFL=00000246 [---Z-P-] CPL=3 II=0 A20=1 SMM=0 HLT=0
        # 0x00000000006000b8:  hlt
        # RIP=00000000006000b8 RFL=00000246 [---Z-P-] CPL=3 II=0 A20=1 SMM=0 HLT=0
        self.assertEqual(0x6000b0 + 8, uc.reg_read(U.x86_const.UC_X86_REG_RIP))
コード例 #10
0
    def __init__(self):
        '''初始化 instance 初始化模拟器参数 only x86'''
        # Initialize emulator in X86-32bit mode
        self.vm = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32 | unicorn.UC_MODE_LITTLE_ENDIAN)
        self.asb = keystone.Ks(keystone.KS_ARCH_X86, keystone.KS_MODE_32 | keystone.KS_MODE_LITTLE_ENDIAN)
        self.disas = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32 | capstone.CS_MODE_LITTLE_ENDIAN)
		self.__reinit__()
コード例 #11
0
def set_arch(arch=None, default=None):
    """Sets the current architecture."""
    module = sys.modules[__name__]
    if arch:
        try:
            module.CURRENT_ARCH = unigdb.regs.arch_to_regs[arch]()
            uc_arch = getattr(unicorn, 'UC_ARCH_%s' % module.CURRENT_ARCH.arch)
            uc_mode = getattr(unicorn, 'UC_MODE_%s' % module.CURRENT_ARCH.mode)
            if module.endian == 'little':
                uc_mode += unicorn.UC_MODE_LITTLE_ENDIAN
            else:
                uc_mode += unicorn.UC_MODE_BIG_ENDIAN
            module.UC = unicorn.Uc(uc_arch, uc_mode)
            unigdb.proc.init = True
            return module.CURRENT_ARCH
        except KeyError:
            raise OSError("Specified arch {:s} is not supported".format(arch))
    try:
        module.CURRENT_ARCH = unigdb.regs.arch_to_regs[module.current]()
    except KeyError:
        if default:
            try:
                module.CURRENT_ARCH = unigdb.regs.arch_to_regs[
                    default.lower()]()
            except KeyError:
                raise OSError(
                    "CPU not supported, neither is default {:s}".format(
                        default))
        else:
            raise OSError("CPU type is currently not supported: {:s}".format(
                module.current))
    return module.CURRENT_ARCH
コード例 #12
0
    def __init__(self, trace=True, sca_mode=False, local_vars={}):
        super().__init__(trace, sca_mode)
        self.emu = uc.Uc(uc.UC_ARCH_ARM, uc.UC_MODE_THUMB | uc.UC_MODE_MCLASS)
        self.disasm = cs.Cs(cs.CS_ARCH_ARM,
                            cs.CS_MODE_THUMB | cs.CS_MODE_MCLASS)
        self.disasm.detail = True
        self.word_size = 4
        self.endianness = "little"
        self.page_size = self.emu.query(uc.UC_QUERY_PAGE_SIZE)
        self.page_shift = self.page_size.bit_length() - 1
        self.pc = uc.arm_const.UC_ARM_REG_PC

        known_regs = [
            i[len('UC_ARM_REG_'):] for i in dir(uc.arm_const) if '_REG' in i
        ]
        self.reg_map = {
            r.lower(): getattr(uc.arm_const, 'UC_ARM_REG_' + r)
            for r in known_regs
        }

        self.stubbed_functions = local_vars
        self.setup(sca_mode)

        self.reset_stack()
        # Force mapping of those addresses so that
        # exception returns can be caught in the base
        # block hook rather than a code fetch hook
        self.map_space(0xfffffff0, 0xffffffff)

        self.emu.hook_add(uc.UC_HOOK_INTR, HookWeakMethod(self.intr_hook))
コード例 #13
0
    def __init__(self, runtime: Runtime, *, context: Context = {}) -> None:
        self.emu = uc.Uc(uc.UC_ARCH_ARM, uc.UC_MODE_THUMB)

        self.runtime = runtime
        self.context = context

        #self.emu.hook_add(uc.UC_HOOK_CODE,
        #        lambda uc, addr, size, sim: sim.trace(addr), self)
        self.emu.hook_add(uc.UC_HOOK_INTR,
                          lambda uc, intno, sim: sim.intr(intno), self)

        self.emu.mem_map(0xfffff000, 0x1000)  # special (return from interrupt)
        self.emu.hook_add(
            uc.UC_HOOK_BLOCK,
            lambda uc, address, size, sim: sim.irq_return(address),
            self,
            begin=0xfffff000,
            end=0xffffffff)

        self.emu.mem_map(Simulation.RAM_BASE,
                         context.get('sim.ramsz', 16 * 1024))
        self.emu.mem_map(Simulation.FLASH_BASE,
                         context.get('sim.flashsz', 128 * 1024))
        if (eesz := context.get('sim.eesz', 8 * 1024)):
            self.emu.mem_map(Simulation.EE_BASE, eesz)
コード例 #14
0
    def test_eflags(self):
        # xor r14,r14
        CODE = 'M1\xf6'

        uc = U.Uc(U.UC_ARCH_X86, U.UC_MODE_64)
        uc.reg_write(U.x86_const.UC_X86_REG_RIP, 0x6000b0)
        uc.reg_write(U.x86_const.UC_X86_REG_EFLAGS, 0x200)

        uc.mem_map(0x600000, 0x1000)
        uc.mem_write(0x6000b0, CODE)
        uc.emu_start(0x6000b0, 0, count=1)

        # Here's the original execution trace for this on actual hardware.
        #
        # (gdb) x/i $pc
        # => 0x6000b0:    xor    %r14,%r14
        # (gdb) p/x $eflags
        # $1 = 0x200
        # (gdb) p $eflags
        # $2 = [ IF ]
        # (gdb) si
        # 0x00000000006000b3 in ?? ()
        # (gdb) p/x $eflags
        # $3 = 0x246
        # (gdb) p $eflags
        # $4 = [ PF ZF IF ]

        self.assertEqual(0x6000b3, uc.reg_read(U.x86_const.UC_X86_REG_RIP))
        self.assertEqual(0x246, uc.reg_read(U.x86_const.UC_X86_REG_EFLAGS))
コード例 #15
0
ファイル: runner.py プロジェクト: kostic2000/pycortexmtests
    def __init__(self,
                 mem_map,
                 firmware,
                 semihosting_handler=None,
                 gdb_server=None):
        self.firmware = firmware
        self.semihosting_handler = semihosting_handler
        self.gdb_backend = None
        self.running = False
        self.err = None
        self.exit_code = None
        self.mu = uc.Uc(uc.UC_ARCH_ARM, uc.UC_MODE_THUMB | uc.UC_MODE_MCLASS)

        for m in mem_map:
            self.mu.mem_map(m[0], m[1], m[2])

        for seg in firmware.get_segments():
            self.mu.mem_write(seg[0], seg[1])

        self.mu.hook_add(uc.UC_HOOK_CODE, self.__hook_code)
        self.mu.hook_add(uc.UC_HOOK_INTR, self.__hook_intr)

        if gdb_server is not None:
            self.gdb_backend = gdbbackend.GdbBackend(self.mu, gdb_server)

        sp = struct.unpack("<I", self.mu.mem_read(0, 4))[0]
        self.mu.reg_write(arm.UC_ARM_REG_SP, sp)
        pc = struct.unpack("<I", self.mu.mem_read(4, 4))[0]
        self.mu.reg_write(arm.UC_ARM_REG_PC, pc)
コード例 #16
0
    def __init__(self, archstring, debug=False):
        self.debug = debug
        self.arch = globals()[archstring]()
        self.ks = keystone.Ks(self.arch.ks_arch[0], self.arch.ks_arch[1])
        self.mu = unicorn.Uc(self.arch.uc_arch[0], self.arch.uc_arch[1])
        self.md = capstone.Cs(self.arch.cs_arch[0], self.arch.cs_arch[1])

        self.pc_reg = self.arch.pc_reg
        self.state_reg = self.arch.state_reg
        self.cpu_regs = self.arch.cpu_regs
        self.mem_regs = {}
        self.mem_addrs = {}

        self.mu.mem_map(self.arch.code_addr, self.arch.code_mem)
        self._mem_invalid_hook = self.mu.hook_add(
            UC_HOOK_MEM_READ_UNMAPPED | UC_HOOK_MEM_WRITE_UNMAPPED,
            self._invalid_mem)
        #self._mem_invalid_hook2 = self.mu.hook_add(UC_HOOK_MEM_FETCH_UNMAPPED, self._invalid_mem_fetch)
        self._code_hook = self.mu.hook_add(
            UC_HOOK_CODE, self._code_hook, None, self.arch.code_addr,
            self.arch.code_addr + self.arch.code_mem)

        self.pages = set()

        # TODO: have to figure out how to remove this state... :(
        self.rw_struct = [[0, 0], [None, None, None], False]
        self._mem_rw_hook = self.mu.hook_add(
            UC_HOOK_MEM_WRITE | UC_HOOK_MEM_READ, self._mem_hook,
            self.rw_struct)
        pass
コード例 #17
0
ファイル: arch.py プロジェクト: shingarov/archinfo
 def unicorn(self):
     """
     A Unicorn engine instance for this arch
     """
     if _unicorn is None or self.uc_arch is None:
         raise ArchError("Arch %s does not support with Unicorn" % self.name)
     # always create a new Unicorn instance
     return _unicorn.Uc(self.uc_arch, self.uc_mode)
コード例 #18
0
 def runTest(self):
     ADDR = 0x10101000
     mu = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)
     mu.mem_map(ADDR, 1024 * 4)
     mu.mem_write(ADDR, b'\x41')
     mu.emu_start(ADDR, ADDR + 1, count=1)
     # The following should not trigger a null pointer dereference
     self.assertEqual(None, mu.emu_stop())
コード例 #19
0
    def _setup(self,
               user_arch=None,
               user_mode=None,
               cs_arch=None,
               cs_mode=None):
        if user_arch is not None and user_mode is not None:
            try:
                self.uc = unicorn.Uc(user_arch, user_mode)
                self.cs = Cs(cs_arch, cs_mode)

                self.thumb = user_mode == unicorn.UC_MODE_THUMB
            except:
                raise self.EmulatorSetupFailedError('Unsupported arch')
        else:
            if self.dwarf.arch == 'arm':
                self.setup_arm()
            elif self.dwarf.arch == 'arm64':
                self.setup_arm64()
            elif self.dwarf.arch == 'ia32':
                self.setup_x86()
            elif self.dwarf.arch == 'x64':
                self.setup_x64()
            else:
                # unsupported arch
                raise self.EmulatorSetupFailedError('Unsupported arch')

        if not self.uc or not self.cs:
            raise self.EmulatorSetupFailedError('Unicorn or Capstone missing')

        # enable capstone details
        if self.cs is not None:
            self.cs.detail = True

        if not self.context.is_native_context:
            raise self.EmulatorSetupFailedError(
                'Cannot run emulator on non-native context')

        err = self.map_range(self.context.pc.value)
        if err:
            raise self.EmulatorSetupFailedError('Mapping failed')

        self.current_context = EmulatorContext(self.dwarf)
        for reg in self.current_context._unicorn_registers:
            if reg in self.context.__dict__:
                if reg not in self._blacklist_regs:
                    self.uc.reg_write(
                        self.current_context._unicorn_registers[reg],
                        self.context.__dict__[reg].value)

        self.uc.hook_add(unicorn.UC_HOOK_CODE, self.hook_code)
        self.uc.hook_add(unicorn.UC_HOOK_MEM_WRITE | unicorn.UC_HOOK_MEM_READ,
                         self.hook_mem_access)
        self.uc.hook_add(
            unicorn.UC_HOOK_MEM_FETCH_UNMAPPED
            | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED
            | unicorn.UC_HOOK_MEM_READ_UNMAPPED, self.hook_unmapped)
        self.current_context.set_context(self.uc)
        return 0
コード例 #20
0
ファイル: emulator.py プロジェクト: jakuta-tech/pwndbg
    def __init__(self):
        self.arch = pwndbg.arch.current

        if self.arch not in arch_to_UC:
            raise NotImplementedError("Cannot emulate code for %s" % self.arch)

        self.consts = arch_to_UC_consts[self.arch]
        self.mode = self.get_mode()
        self.cs = C.Cs(arch_to_CS[self.arch], self.mode)

        debug("# Instantiating Unicorn for %s" % self.arch)
        debug("uc = U.Uc(%r, %r)" % (arch_to_UC[self.arch], self.mode))
        self.uc = U.Uc(arch_to_UC[self.arch], self.mode)
        self.regs = pwndbg.regs.current

        # Jump tracking state
        self._prev = None
        self._prevsize = None
        self._curr = None

        # Initialize the register state
        for reg in list(self.regs.misc) + list(self.regs.common) + list(
                self.regs.flags):
            enum = self.get_reg_enum(reg)

            if not reg:
                debug("# Could not set register %r" % reg)
                continue

            if reg in blacklisted_regs:
                debug("Skipping blacklisted register %r" % reg)
                continue
            value = getattr(pwndbg.regs, reg)
            if None in (enum, value):
                if reg not in blacklisted_regs:
                    debug("# Could not set register %r" % reg)
                continue

            # All registers are initialized to zero.
            if value == 0:
                continue

            name = 'U.x86_const.UC_X86_REG_%s' % reg.upper()
            debug("uc.reg_write(%(name)s, %(value)#x)" % locals())
            self.uc.reg_write(enum, value)

        # Add a hook for unmapped memory
        self.hook_add(U.UC_HOOK_MEM_UNMAPPED, self.hook_mem_invalid)

        # Always stop executing as soon as there's an interrupt.
        self.hook_add(U.UC_HOOK_INTR, self.hook_intr)

        # Map in the page that $pc is on
        self.map_page(pwndbg.regs.pc)

        # Instruction tracing
        if DEBUG:
            self.hook_add(U.UC_HOOK_CODE, self.trace_hook)
コード例 #21
0
    def __init__(self, controller, r, stage):
        # controller.gdb_print("creating longwrite break\n")
        self.emptywrite = {'start': None, 'end': None, 'pc': None}
        self.writeinfo = self.emptywrite
        self.breakaddr = r['breakaddr']
        self.contaddr = r['contaddr']
        self.writeaddr = r['writeaddr']
        self.thumb = r['thumb']
        r2.gets(stage.elf, "s 0x%x" % self.writeaddr)
        if self.thumb:
            self.emu = unicorn.Uc(unicorn.UC_ARCH_ARM, unicorn.UC_MODE_THUMB)
            r2.gets(stage.elf, "ahb 16")
            r2.gets(stage.elf, "e asm.bits=16")
            self.cs = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB)
        else:
            self.emu = unicorn.Uc(unicorn.UC_ARCH_ARM, unicorn.UC_MODE_ARM)
            r2.gets(stage.elf, "ahb 32")
            r2.gets(stage.elf, "e asm.bits=32")
            self.cs = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM)
        r2.get(stage.elf, "pdj 1")

        self.cs.detail = True
        self.info = staticanalysis.LongWriteInfo(stage.elf, r['start'],
                                                 r['end'], self.thumb)
        self.inss = []
        self.regs = set()
        self.bytes = b""
        self.dst_addrs = []
        self.write_size = r['writesize']
        for i in self.info.bbs:
            self.inss.append(i)
            bs = i["bytes"].decode("hex")
            self.bytes += b"%s" % bs
            ci = next(self.cs.disasm(bs, i["offset"], 1))
            if i["offset"] == self.writeaddr:
                self.write_ins = ci
            (read, write) = ci.regs_access()
            for rs in (read, write):
                self.regs.update(
                    [ci.reg_name(rn).encode('ascii') for rn in rs])
        self.emu.mem_map(0, 0xFFFFFFFF + 1, unicorn.UC_PROT_ALL)
        self.emu.mem_write(self.inss[0]["offset"], self.bytes)
        self.emu.hook_add(unicorn.UC_HOOK_MEM_WRITE, self.write_hook)
        self.spec = "*(0x%x)" % r['breakaddr']
        TargetBreak.__init__(self, self.spec, controller, True, stage, r=r)
コード例 #22
0
ファイル: savestate.py プロジェクト: olivierh59500/usercorn
def load(filename):
    arch, mode, pc, regs, regions = read(filename)
    uc = unicorn.Uc(arch, mode)
    for enum, val in regs:
        uc.reg_write(enum, val)
    for addr, size, prot, data in regions:
        uc.mem_map(addr, size, prot)
        uc.mem_write(addr, data)
    return uc, pc
コード例 #23
0
 def create_new_vm(self):
     arch, mode, endian = get_arch_mode("unicorn", self.mode)
     self.vm = unicorn.Uc(arch, mode | endian)
     self.vm.hook_add(unicorn.UC_HOOK_BLOCK, self.hook_block)
     self.vm.hook_add(unicorn.UC_HOOK_CODE, self.hook_code)
     self.vm.hook_add(unicorn.UC_HOOK_INTR, self.hook_interrupt)
     self.vm.hook_add(unicorn.UC_HOOK_MEM_WRITE, self.hook_mem_access)
     self.vm.hook_add(unicorn.UC_HOOK_MEM_READ, self.hook_mem_access)
     return
コード例 #24
0
    def __init__(self,
                 hexfiles: List[str],
                 debug: Optional[TraceWriter] = None,
                 traffic: Optional[TrafficTrace] = None,
                 ramsz: int = 16 * 1024,
                 flashsz: int = 128 * 1024,
                 eesz: int = 8 * 1024) -> None:

        self.upm: Optional[UpMedium] = None
        self.dnm: Optional[DnMedium] = None

        self.emu = uc.Uc(uc.UC_ARCH_ARM, uc.UC_MODE_THUMB)

        #self.emu.hook_add(uc.UC_HOOK_CODE,
        #        lambda uc, addr, size, sim: sim.trace(addr), self)
        self.emu.hook_add(uc.UC_HOOK_INTR,
                          lambda uc, intno, sim: sim.intr(intno), self)
        self.emu.hook_add(
            uc.UC_HOOK_BLOCK,
            lambda uc, address, size, sim: sim.block_special(address),
            self,
            begin=0xfffff000,
            end=0xffffffff)

        self.emu.mem_map(Simulation.RAM_BASE, ramsz)
        self.emu.mem_map(Simulation.FLASH_BASE, flashsz)
        self.emu.mem_map(Simulation.EE_BASE, eesz)
        self.emu.mem_map(0xfffff000, 0x1000)  # special

        self.ex: Optional[BaseException] = None

        # Peripherals
        self.event = SimEvent()
        self.ic = InterruptController(self.event)
        self.gpio = GPIO(self.ic, 0)
        self.uart = UART(self.ic, 1)

        # Load firmware
        for hf in hexfiles:
            self.load_hexfile(hf)

        # Debug settings
        self.debug = debug
        self.traffic = traffic

        # read SP and entry point address from header in flash
        (sp, ep) = struct.unpack('<II',
                                 self.emu.mem_read(Simulation.FLASH_BASE, 8))
        self.isp = sp
        self.ipc = ep

        self.ticks = 0
        self.reset()

        self.rxparams: MutableMapping[str, int] = {}
        self.rxmsg: Optional[LoraMsg] = None
コード例 #25
0
    def runTest(self):
        mu = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)
        mu.reg_write(unicorn.x86_const.UC_X86_REG_EBX, ADDR)

        mu.mem_map(0x10000000, 1024 * 4)
        # jmp ebx
        mu.mem_write(0x10000000, b'\xff\xe3')

        mu.hook_add(unicorn.UC_HOOK_MEM_FETCH_UNMAPPED | unicorn.UC_HOOK_MEM_FETCH_PROT, hook_mem_invalid)
        mu.emu_start(0x10000000, 0x10000000 + 2, count=1)
コード例 #26
0
 def create_new_vm(self):
     arch, mode, endian = get_arch_mode("unicorn", self.parent.arch)
     self.vm = unicorn.Uc(arch, mode | endian)
     self.vm.hook_add(unicorn.UC_HOOK_BLOCK, self.hook_block)
     self.vm.hook_add(unicorn.UC_HOOK_CODE, self.hook_code)
     self.vm.hook_add(unicorn.UC_HOOK_INTR, self.hook_interrupt)
     self.vm.hook_add(unicorn.UC_HOOK_MEM_WRITE, self.hook_mem_access)
     self.vm.hook_add(unicorn.UC_HOOK_MEM_READ, self.hook_mem_access)
     if is_x86(self.parent.arch):
         self.vm.hook_add(unicorn.UC_HOOK_INSN, self.hook_syscall, None, 1, 0, unicorn.x86_const.UC_X86_INS_SYSCALL)
     return
コード例 #27
0
ファイル: qemu.py プロジェクト: graux-pierre/Sibyl
    def renew(self):
        ask_arch, ask_attrib = self.ira.arch.name, self.ira.attrib
        cpucls = UcWrapCPU.available_cpus.get((ask_arch, ask_attrib), None)
        if not cpucls:
            raise ValueError("Unimplemented architecture (%s, %s)" %
                             (ask_arch, ask_attrib))
        arch, mode = cpucls.uc_arch, cpucls.uc_mode

        self.mu = unicorn.Uc(arch, mode)
        self.vm = UcWrapVM(self.mu)
        self.cpu = cpucls(self.mu)
コード例 #28
0
ファイル: unicorn_protocol.py プロジェクト: ssdemajia/vxafl
    def __init__(self, avatar, arch=ARM, origin=None):
        """Construct the protocol, along with its Unicorn instance and worker.

        :param avatar: the Avatar object
        :param arch:   the architecture
        :param origin: the target utilizing this protocol
        """
        self.uc = unicorn.Uc(arch.unicorn_arch, arch.unicorn_mode)
        self.log = logging.getLogger((origin.log.name +
                                      '.' if origin is not None else '') +
                                     self.__class__.__name__)
        self.arch = arch
        self.pending_bp = set()
        self._avatar_queue = avatar.queue
        self._avatar_fast_queue = avatar.fast_queue
        self._origin = origin
        self._breakpoints = []
        self._rmp_queue = queue.Queue()
        self._alive = True

        for start, end, mr in avatar.memory_ranges:
            perms = unicorn.UC_PROT_NONE
            if 'r' in mr.permissions:
                perms |= unicorn.UC_PROT_READ
            if 'w' in mr.permissions:
                perms |= unicorn.UC_PROT_WRITE
            if 'x' in mr.permissions:
                perms |= unicorn.UC_PROT_EXEC

            self.uc.mem_map(start, end - start, perms=perms)

            if hasattr(mr, 'file') and mr.file is not None:
                with open(mr.file, 'rb') as data:
                    self.uc.mem_write(start, data.read())

            if mr.forwarded:
                self.uc.hook_add(unicorn.UC_HOOK_MEM_VALID,
                                 self._forward_hook,
                                 begin=start,
                                 end=end)

        self._avatar_fast_queue.put(
            UpdateStateMessage(self._origin, TargetStates.INITIALIZED))

        self._worker_queue = queue.Queue()
        self._worker_queue.put(
            UnicornWorkerUpdateStateMessage(TargetStates.STOPPED))

        self._worker = UnicornWorker(self._origin, self, self.uc,
                                     self._worker_queue,
                                     self._avatar_fast_queue)
        self._worker.start()
コード例 #29
0
ファイル: jmp_ebx_hang.py プロジェクト: yewang15215/unicorn
    def runTest(self):
        mu = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)
        mu.mem_map(CODE_ADDR, 1024 * 4)
        mu.mem_write(CODE_ADDR, CODE)
        # If EBX is zero then an exception is raised, as expected
        mu.reg_write(unicorn.x86_const.UC_X86_REG_EBX, 0x0)

        print(">>> jmp ebx (ebx = 0)")
        with self.assertRaises(UcError) as m:
            mu.emu_start(CODE_ADDR, CODE_ADDR + 2, count=1)

        self.assertEqual(m.exception.errno, unicorn.UC_ERR_FETCH_UNMAPPED)

        print(">>> jmp ebx (ebx = 0xaa96a47f)")
        mu = unicorn.Uc(unicorn.UC_ARCH_X86, unicorn.UC_MODE_32)
        mu.mem_map(CODE_ADDR, 1024 * 4)
        # If we write this address to EBX then the emulator hangs on emu_start
        mu.reg_write(unicorn.x86_const.UC_X86_REG_EBX, 0xaa96a47f)
        mu.mem_write(CODE_ADDR, CODE)
        with self.assertRaises(UcError) as m:
            mu.emu_start(CODE_ADDR, CODE_ADDR + 2, count=1)

        self.assertEqual(m.exception.errno, unicorn.UC_ERR_FETCH_UNMAPPED)
コード例 #30
0
    def init_engine(self, eng_arch, mode):
        """Initialize cpu engine"""
        if eng_arch == arch.ARCH_X86 or eng_arch == arch.ARCH_AMD64:
            _arch = uc.UC_ARCH_X86
        else:
            raise Exception("Invalid architecture")

        if mode == arch.BITS_32:
            _mode = uc.UC_MODE_32
        elif mode == arch.BITS_64:
            _mode = uc.UC_MODE_64
        else:
            raise Exception("Invalid bitness")

        self.emu = uc.Uc(_arch, _mode)