Python unicorn.Uc() Examples

The following are 25 code examples of unicorn.Uc(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module unicorn , or try the search function .
Example #1
Source File: config.py    From unicorefuzz with Apache License 2.0 6 votes vote down vote up
def place_input_skb(ucf: Unicorefuzz, uc: Uc, input: bytes) -> None:
    """
    Places the input in memory and alters the input.
    This is an example for sk_buff in openvsswitch
    """

    if len(input) > 1500:
        import os

        os._exit(0)  # too big!

    # read input to the correct position at param rdx here:
    rdx = uc.reg_read(UC_X86_REG_RDX)
    rdi = uc.reg_read(UC_X86_REG_RDI)
    ucf.map_page(uc, rdx)  # ensure sk_buf is mapped
    bufferPtr = struct.unpack("<Q", uc.mem_read(rdx + 0xD8, 8))[0]
    ucf.map_page(uc, bufferPtr)  # ensure the buffer is mapped
    uc.mem_write(rdi, input)  # insert afl input
    uc.mem_write(rdx + 0xC4, b"\xdc\x05")  # fix tail 
Example #2
Source File: cortexm.py    From rainbow with GNU Lesser General Public License v3.0 6 votes vote down vote up
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, self.intr_hook) 
Example #3
Source File: arm.py    From rainbow with GNU Lesser General Public License v3.0 6 votes vote down vote up
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)
        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.reset_stack() 
Example #4
Source File: aarch64.py    From rainbow with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, trace=True, sca_mode=False, local_vars=[]):
        super().__init__(trace, sca_mode)
        self.emu = uc.Uc(uc.UC_ARCH_ARM64, uc.UC_MODE_ARM)
        self.disasm = cs.Cs(cs.CS_ARCH_ARM64, cs.CS_MODE_ARM)
        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.arm64_const.UC_ARM64_REG_PC

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

        self.stubbed_functions = local_vars
        self.setup(sca_mode)
        
        self.reset_stack() 
Example #5
Source File: m68k.py    From rainbow with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, trace=True, sca_mode=False, local_vars={}):
        super().__init__(trace, sca_mode)
        self.emu = uc.Uc(uc.UC_ARCH_M68K, uc.UC_MODE_BIG_ENDIAN)
        self.disasm = cs.Cs(cs.CS_ARCH_M68K, cs.CS_MODE_M68K_000)
        self.disasm.detail = True
        self.word_size = 4
        self.endianness = "big"
        self.page_size = self.emu.query(uc.UC_QUERY_PAGE_SIZE)
        self.page_shift = self.page_size.bit_length() - 1
        self.pc = uc.m68k_const.UC_M68K_REG_PC

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

        self.stubbed_functions = local_vars
        self.setup(sca_mode)

        self.reset_stack() 
Example #6
Source File: x64.py    From rainbow with GNU Lesser General Public License v3.0 6 votes vote down vote up
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.reset_stack() 
Example #7
Source File: arch_arm.py    From archinfo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def unicorn_thumb(self):
        if _unicorn is None:
            l.warning("Unicorn is not installed!")
            return None
        return _unicorn.Uc(self.uc_arch, self.uc_mode + _unicorn.UC_MODE_THUMB) 
Example #8
Source File: qemu.py    From Sibyl with GNU General Public License v3.0 5 votes vote down vote up
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.ask_arch = ask_arch
        self.ask_attrib = ask_attrib

        self.mu = unicorn.Uc(arch, mode)
        self.vm = UcWrapVM(self.mu)
        self.cpu = cpucls(self.mu) 
Example #9
Source File: arch.py    From archinfo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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) 
Example #10
Source File: angr_harness.py    From unicorefuzz with Apache License 2.0 5 votes vote down vote up
def angr_load_mapped_pages(
        self, uc: Uc, state: angr.SimState
    ) -> List[Tuple[int, int, int]]:
        """
        Loads all currently mapped unicorn mem regions into angr
        :param uc: The uc instance to load from
        :param state: the angr instance to load to
        :returns Lst of pages mapped
        """
        mapped = []
        for begin, end, perms in uc.mem_regions():
            mapped += (begin, end - begin + 1, perms)
            angr_store_mem(state, begin, bytes(uc.mem_read(begin, end - begin + 1)))
        return mapped 
Example #11
Source File: angr_harness.py    From unicorefuzz with Apache License 2.0 5 votes vote down vote up
def angr_load_registers(self, uc: Uc, state: angr.SimState) -> None:
        """
        Load registers to angr
        """
        # Not using the fetched registers -> the init func could have changed regs.
        #  regs = self.fetch_all_regs()
        # for reg in state.arch.register_names.values():
        angr_regs = dir(state.regs)  # state.regs. arch.register_names.values()
        unicorn_regs = self.arch.reg_names

        # These regs have either different names in angr or some special way to set them
        if self.arch == X86:
            angr_regs += ["cr0", "mxcsr"]
        elif self.arch == X86_64:
            angr_regs += ["cr0", "mxcsr", "fs_base", "gs_base"]
        supported_regs = set(angr_regs)

        for reg in unicorn_regs:
            if reg not in supported_regs:
                print("Unicorn reg not supported in angr(?): {}".format(reg))
            else:
                name = reg
                value = self.uc_reg_read(uc, reg)
                if name == "mxcsr":
                    # TODO: found this somewhere in angr's cgc sources. Probably wrong.
                    state.regs.sseround = (value & 0x600) >> 9
                    # alt solution, somewhere from deep inside angr's sources that looks good but crashes:
                    # state.regs.sseround = amd64g_check_ldmxcsr(state, value)
                elif name == "cr0":
                    # Found this also somewhere, sets the state's archinfo according to cr0. Might work.
                    # Other cr regs don't seem to be supported
                    x86g_dirtyhelper_write_cr0(state, value)
                else:
                    # `fs_base` and `gs_base` are called `fs_const` and `gs_const` in angr...
                    # Let's hope no other regs ever end on `_base` or this breaks ;)
                    name = name.replace("_base", "_const")
                    try:
                        state.registers.store(name, value)
                    except Exception as ex:
                        print("Failed to retrieve register {}: {}".format(reg, ex)) 
Example #12
Source File: angr_harness.py    From unicorefuzz with Apache License 2.0 5 votes vote down vote up
def mark_input_symbolic(ucf: "AngrHarness", uc: Uc, state: angr.SimState, input):
    """
    Marks the right place symbolic
    :param ucf: The angr harness
    :param uc: fully loaded unicorn instance
    :param state: fully loaded angr instance
    :param input: the input from file
    """
    raise Exception("TODO :)") 
Example #13
Source File: config.py    From unicorefuzz with Apache License 2.0 5 votes vote down vote up
def place_input(ucf: Unicorefuzz, uc: Uc, input: bytes) -> None:
    rax = uc.reg_read(UC_X86_REG_RAX)
    # make sure the parameter memory is mapped
    ucf.map_page(uc, rax)
    uc.mem_write(rax, input)  # insert afl input 
Example #14
Source File: unicorn_trace.py    From bootloader_instrumentation_suite with MIT License 5 votes vote down vote up
def create_emulator(self):
        o = Main.shell.run_cmd("%sreadelf -h %s| grep Machine" % (Main.cc,
                                                                  self.stage.elf))
        machine = o.split(" ", 2)[-1].strip()
        ms = {
            "ARM": ArmEmulator(),
            "AArch64": Aarch64Emulator(),
            "Advanced Micro Devices X86-64": X86_64Emulator(),
            "Intel 80386": X86Emulator()
        }
        self.machine = ms[machine]
        self.emu = unicorn.Uc(self.machine.arch,
                              self.machine.mode)
        self.stop = False 
Example #15
Source File: emulator.py    From cemu with MIT License 5 votes vote down vote up
def create_new_vm(self) -> None:
        """
        Create a new VM, and sets up the hooks
        """
        arch, mode, endian = get_arch_mode("unicorn", self.root.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.root.arch):
            self.vm.hook_add(unicorn.UC_HOOK_INSN, self.hook_syscall, None, 1, 0, unicorn.x86_const.UC_X86_INS_SYSCALL)
        return 
Example #16
Source File: unicorn_engine.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setup(self):
        if self._is_mips32 and options.COPY_STATES not in self.state.options:
            # we always re-create the thread-local UC object for MIPS32 even if COPY_STATES is disabled in state
            # options. this is to avoid some weird bugs in unicorn (e.g., it reports stepping 1 step while in reality it
            # did not step at all).
            self.delete_uc()
        self._setup_unicorn()
        try:
            self.set_regs()
        except SimValueError:
            # reset the state and re-raise
            self.uc.reset()
            raise
        # tricky: using unicorn handle from unicorn.Uc object
        self._uc_state = _UC_NATIVE.alloc(self.uc._uch, self.cache_key)

        # set (cgc, for now) transmit syscall handler
        if UNICORN_HANDLE_TRANSMIT_SYSCALL in self.state.options and self.state.has_plugin('cgc'):
            if self.transmit_addr is None:
                l.error("You haven't set the address for concrete transmits!!!!!!!!!!!")
                self.transmit_addr = 0
            _UC_NATIVE.set_transmit_sysno(self._uc_state, 2, self.transmit_addr)

        # activate gdt page, which was written/mapped during set_regs
        if self.gdt is not None:
            _UC_NATIVE.activate(self._uc_state, self.gdt.addr, self.gdt.limit, None) 
Example #17
Source File: unicorn_engine.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hook_reset(self):
        #l.debug("Resetting hooks.")
        for h in self.wrapped_hooks:
            #l.debug("Clearing hook %s", h)
            unicorn.Uc.hook_del(self, h)
        self.wrapped_hooks.clear() 
Example #18
Source File: unicorn_engine.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def mem_reset(self):
        #l.debug("Resetting memory.")
        for addr,size in self.wrapped_mapped:
            #l.debug("Unmapping %d bytes at %#x", size, addr)
            unicorn.Uc.mem_unmap(self, addr, size)
        self.wrapped_mapped.clear() 
Example #19
Source File: unicorn_engine.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def mem_map(self, addr, size, perms=7):
        #l.debug("Mapping %d bytes at %#x", size, addr)
        m = unicorn.Uc.mem_map(self, addr, size, perms=perms)
        self.wrapped_mapped.add((addr, size))
        return m 
Example #20
Source File: unicorn_engine.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hook_del(self, h):
        #l.debug("Clearing hook %s", h)
        h = unicorn.Uc.hook_del(self, h)
        self.wrapped_hooks.discard(h)
        return h 
Example #21
Source File: unicorn_engine.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hook_add(self, htype, callback, user_data=None, begin=1, end=0, arg1=0):
        h = unicorn.Uc.hook_add(self, htype, callback, user_data=user_data, begin=begin, end=end, arg1=arg1)
        #l.debug("Hook: %s,%s -> %s", htype, callback.__name__, h)
        self.wrapped_hooks.add(h)
        return h 
Example #22
Source File: unicorn_engine.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, arch, cache_key):
        l.debug("Creating unicorn state!")
        self.arch = arch
        self.cache_key = cache_key
        self.wrapped_mapped = set()
        self.wrapped_hooks = set()
        self.id = None
        unicorn.Uc.__init__(self, arch.uc_arch, arch.uc_mode) 
Example #23
Source File: unicorn_engine.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, addr):
        claripy.SimplificationAvoidanceAnnotation.__init__(self)
        self.unicorn_start_addr = addr

#
# Because Unicorn leaks like crazy, we use one Uc object per thread...
# 
Example #24
Source File: unicorn_protocol.py    From avatar2 with Apache License 2.0 4 votes vote down vote up
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() 
Example #25
Source File: gdb_tools.py    From bootloader_instrumentation_suite with MIT License 4 votes vote down vote up
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)