Python capstone.CS_MODE_32 Examples

The following are 19 code examples of capstone.CS_MODE_32(). 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 capstone , or try the search function .
Example #1
Source File: disassembler.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, mode, **kwargs):
        super(Capstone, self).__init__(mode, **kwargs)

        if self.mode == "I386":
            self.cs = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
        elif self.mode == "AMD64":
            self.cs = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
        elif self.mode == "MIPS":
            self.cs = capstone.Cs(capstone.CS_ARCH_MIPS, capstone.CS_MODE_32 +
                                  capstone.CS_MODE_BIG_ENDIAN)
        # This is not really supported yet.
        elif self.mode == "ARM":
            self.cs = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM)
        else:
            raise NotImplementedError(
                "No disassembler available for this arch.")

        self.cs.detail = True
        self.cs.skipdata_setup = ("db", None, None)
        self.cs.skipdata = True 
Example #2
Source File: emu_helper.py    From writeups with GNU General Public License v3.0 6 votes vote down vote up
def set_mode(self, mode):
        if mode == UC_MODE_32:
            self.md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
            self.reg_rsp = UC_X86_REG_ESP
            self.reg_rbp = UC_X86_REG_EBP
            self.reg_rip = UC_X86_REG_EIP
        elif mode == UC_MODE_64:
            self.md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
            self.reg_rsp = UC_X86_REG_RSP
            self.reg_rbp = UC_X86_REG_RBP
            self.reg_rip = UC_X86_REG_RIP
        elif mode == UC_MODE_16:
            self.md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_16)
            self.reg_rsp = UC_X86_REG_SP
            self.reg_rbp = UC_X86_REG_BP
            self.reg_rip = UC_X86_REG_IP
        else:
            raise Exception('Unknown x86 mode: %d' % mode)
        self.mode = mode 
Example #3
Source File: x86.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_32)
        self.disasm = cs.Cs(cs.CS_ARCH_X86, cs.CS_MODE_32)
        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.x86_const.UC_X86_REG_EIP

        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 #4
Source File: disassembler.py    From grap with MIT License 6 votes vote down vote up
def __init__(self, arch, mode):
        self.arch = arch
        self.mode = mode
        self.capstone = Cs(self.arch, self.mode)

        self.prologues = {
            # Triple backslash (\\\) are needed to escape bytes in the compiled regex
            CS_MODE_32: [
                b"\x55\x89\xE5",  # push ebp & mov ebp, esp
                b"\x55\x8B\xEC",  # push ebp & mov ebp, esp
                b"\x55\x8b\x6c\x24",  # push ebp & mov ebp, [esp+?]
            ],
            CS_MODE_64: [
                b"\x55\x48\x89\xE5",  # push rbp & mov rbp, rsp
            ]
        }[mode]

        self.conditional_jmp_mnemonics = {'jz', 'je', 'jcxz', 'jecxz', 'jrcxz', 'jnz', 'jp', 'jpe', 'jnp', 'ja', 'jae', 'jb', 'jbe', 'jg', 'jge', 'jl', 'jle', 'js', 'jns', 'jo', 'jno', 'jecxz', 'loop', 'loopne', 'loope', 'jne'}
        self.x86_32_registers = {'eax', 'ebx', 'ecx', 'edx', 'esi', 'edi', 'esp', 'ebp'}
        self.max_instruction_size = 16 
Example #5
Source File: gadgets.py    From rop-chainer with GNU General Public License v3.0 6 votes vote down vote up
def _locate_gadgets(self, section, terminals, gadget_type):
        disassembler = cs.Cs(cs.CS_ARCH_X86, cs.CS_MODE_32)
        for terminal in terminals:
            matches = [match.start() for match in re.finditer(terminal[0],
                                                              section["data"])]
            for index in matches:
                for i in range(self._options.depth):
                    gadget = ""
                    instructions = disassembler.disasm_lite(
                        section["data"][index-i:index+terminal[1]],
                        section["vaddr"]+index)
                    for instruction in instructions:
                        gadget += (str(instruction[2]) + " " +
                                   str(instruction[3])   + " ; ")

                    if gadget:
                        gadget = gadget.replace("  ", " ")
                        gadget = gadget[:-3]
                        self._gadgets += [{"vaddr" : section["vaddr"]+index-i,
                                           "insts" : gadget,
                                           "gadget_type" : gadget_type}] 
Example #6
Source File: Graph.py    From grap with MIT License 5 votes vote down vote up
def extract(self):
        """Extract the control flow graph from the binary."""
        # Allocate a new graph
        self.graph = graph_alloc(0)
        
        # Initialize binary info
        self.info = get_inf_structure()
        
        # Initialize Capstone
        if self.info.is_64bit():
            mode = capstone.CS_MODE_64
        else:
            mode = capstone.CS_MODE_32
        self.capstone = capstone.Cs(capstone.CS_ARCH_X86, mode)
        
        # Get the Entry Point
        entry = None
        try:
            start_ea = self.info.start_ea
            if start_ea != 0xffffffff:
                entry = start_ea
        except:
            try:
                entry = BeginEA()
            except:
                pass
                
        if entry is None:
            print("WARNING: Could not determine entrypoint")
        else:
            self.dis(ea=entry, is_child1=None, ifrom=None)

        # Scan all the functions
        for ea in Functions():
            self.dis(ea=ea, is_child1=None, ifrom=None)

        update_children_fathers_number(self.graph)

        # Information
        print("%s graph has %d nodes" % (get_root_filename(),
                                         self.graph.nodes.size)) 
Example #7
Source File: disasm.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def _import_dependencies(self):

        # Load the Capstone bindings.
        global capstone
        if capstone is None:
            import capstone

        # Load the constants for the requested architecture.
        self.__constants = {
            win32.ARCH_I386:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_32),
            win32.ARCH_AMD64:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_64),
            win32.ARCH_THUMB:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_THUMB),
            win32.ARCH_ARM:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_ARM),
            win32.ARCH_ARM64:
                (capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM),
        }

        # Test for the bug in early versions of Capstone.
        # If found, warn the user about it.
        try:
            self.__bug = not isinstance(
                capstone.cs_disasm_quick(
                    capstone.CS_ARCH_X86, capstone.CS_MODE_32, "\x90", 1)[0],
                capstone.capstone.CsInsn)
        except AttributeError:
            self.__bug = False
        if self.__bug:
            warnings.warn(
                "This version of the Capstone bindings is unstable,"
                " please upgrade to a newer one!",
                RuntimeWarning, stacklevel=4) 
Example #8
Source File: disassembler.py    From grap with MIT License 5 votes vote down vote up
def disassemble_raw(raw_data = None, raw_path = None, dot_path = None, print_listing=False, readable=False,
                    raw_64=False, entrypoint=None, verbose=False):
    if raw_data is None and raw_path is None:
        print("ERROR: Missing PE path or data.")
        return None

    if raw_data is None:
        raw_data = open(raw_path, "rb").read()

    arch = CS_ARCH_X86
    mode = CS_MODE_64 if raw_64 else CS_MODE_32

    if entrypoint is not None:
        oep_offset = entrypoint
    else:
        oep_offset = 0

    iat_dict = dict()

    disass = RawDisassembler(arch=arch, mode=mode)
    insts = disass.dis(data=raw_data, offset=oep_offset, iat_api=iat_dict, bin_instance=None, verbose=verbose)

    if dot_path is not None:
        dot = disass.export_to_dot(insts=insts, oep_offset=oep_offset, displayable=readable)
        write_to_file(dot_path, dot)

    if print_listing:
        disass.display(insts, offset_from=0)

    return True 
Example #9
Source File: translator.py    From reil with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        TranslationContext.__init__(self)

        self.registers = {
            capstone.x86.X86_REG_EAX:   r('eax', 32),
            capstone.x86.X86_REG_EBX:   r('ebx', 32),
            capstone.x86.X86_REG_ECX:   r('ecx', 32),
            capstone.x86.X86_REG_EDX:   r('edx', 32),
            capstone.x86.X86_REG_ESI:   r('esi', 32),
            capstone.x86.X86_REG_EDI:   r('edi', 32),
            capstone.x86.X86_REG_EBP:   r('ebp', 32),
            capstone.x86.X86_REG_ESP:   r('esp', 32),

            capstone.x86.X86_REG_FS:    r('fsbase', 32),
            capstone.x86.X86_REG_GS:    r('gsbase', 32),
            capstone.x86.X86_REG_CS:    r('csbase', 32),
            capstone.x86.X86_REG_SS:    r('ssbase', 32),
            capstone.x86.X86_REG_DS:    r('dsbase', 32),
            capstone.x86.X86_REG_ES:    r('esbase', 32),

            capstone.x86.X86_REG_XMM0:  r('xmm0', 128),
            capstone.x86.X86_REG_XMM1:  r('xmm1', 128),
            capstone.x86.X86_REG_XMM2:  r('xmm2', 128),
            capstone.x86.X86_REG_XMM3:  r('xmm3', 128),
            capstone.x86.X86_REG_XMM4:  r('xmm4', 128),
            capstone.x86.X86_REG_XMM5:  r('xmm5', 128),
            capstone.x86.X86_REG_XMM6:  r('xmm6', 128),
            capstone.x86.X86_REG_XMM7:  r('xmm7', 128),
        }

        self.word_size = 32
        self.accumulator = self.registers[capstone.x86.X86_REG_EAX]
        self.base = self.registers[capstone.x86.X86_REG_EBX]
        self.counter = self.registers[capstone.x86.X86_REG_ECX]
        self.data = self.registers[capstone.x86.X86_REG_EDX]
        self.source = self.registers[capstone.x86.X86_REG_ESI]
        self.destination = self.registers[capstone.x86.X86_REG_EDI]
        self.frame_ptr = self.registers[capstone.x86.X86_REG_EBP]
        self.stack_ptr = self.registers[capstone.x86.X86_REG_ESP]
        self.disassembler = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
        self.disassembler.detail = True 
Example #10
Source File: disasm.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, arch = None):
        super(CapstoneEngine, self).__init__(arch)

        # Load the constants for the requested architecture.
        self.__constants = {
            win32.ARCH_I386:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_32),
            win32.ARCH_AMD64:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_64),
            win32.ARCH_THUMB:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_THUMB),
            win32.ARCH_ARM:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_ARM),
            win32.ARCH_ARM64:
                (capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM),
        }

        # Test for the bug in early versions of Capstone.
        # If found, warn the user about it.
        try:
            self.__bug = not isinstance(
                list(capstone.cs_disasm_quick(
                    capstone.CS_ARCH_X86, capstone.CS_MODE_32, "\x90", 1
                ))[0],
                capstone.capstone.CsInsn
            )
        except AttributeError:
            self.__bug = False
        if self.__bug:
            warnings.warn(
                "This version of the Capstone bindings is unstable,"
                " please upgrade to a newer one!",
                RuntimeWarning, stacklevel=4) 
Example #11
Source File: core.py    From unipacker with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, sample):
        self.sample = sample
        self.clients = []

        self.emulator_event = threading.Event()
        self.single_instruction = False

        self.breakpoints = set()
        self.mem_breakpoints = []
        self.data_lock = threading.Lock()
        self.single_instruction = False
        self.apicall_handler = None

        self.log_mem_read = False
        self.log_mem_write = False
        self.log_instr = False
        self.log_apicalls = False

        self.sections_read = {}
        self.sections_written = {}
        self.write_targets = []
        self.sections_executed = {}
        self.apicall_counter = {}

        self.start = 0

        self.uc = None
        self.HOOK_ADDR = 0
        self.STACK_ADDR = 0
        self.STACK_SIZE = 0
        self.PEB_BASE = 0
        self.TEB_BASE = 0

        self.disassembler = Cs(CS_ARCH_X86, CS_MODE_32)
        self.disassembler.detail = True

        self.init_uc() 
Example #12
Source File: brute_force_disassembler.py    From multiverse with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self,arch):
    if arch == 'x86':
      self.md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
    elif arch == 'x86-64':
      self.md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
    else:
      raise NotImplementedError( 'Architecture %s is not supported'%arch )
    self.md.detail = True 
Example #13
Source File: disasm.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def _import_dependencies(self):

        # Load the Capstone bindings.
        global capstone
        if capstone is None:
            import capstone

        # Load the constants for the requested architecture.
        self.__constants = {
            win32.ARCH_I386:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_32),
            win32.ARCH_AMD64:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_64),
            win32.ARCH_THUMB:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_THUMB),
            win32.ARCH_ARM:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_ARM),
            win32.ARCH_ARM64:
                (capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM),
        }

        # Test for the bug in early versions of Capstone.
        # If found, warn the user about it.
        try:
            self.__bug = not isinstance(
                capstone.cs_disasm_quick(
                    capstone.CS_ARCH_X86, capstone.CS_MODE_32, "\x90", 1)[0],
                capstone.capstone.CsInsn)
        except AttributeError:
            self.__bug = False
        if self.__bug:
            warnings.warn(
                "This version of the Capstone bindings is unstable,"
                " please upgrade to a newer one!",
                RuntimeWarning, stacklevel=4) 
Example #14
Source File: IntelDisassembler.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _initCapstone(self):
        self.capstone = Cs(CS_ARCH_X86, CS_MODE_64) if self.disassembly.binary_info.bitness == 64 else Cs(CS_ARCH_X86, CS_MODE_32) 
Example #15
Source File: FunctionCandidateManager.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def init(self, disassembly):
        if disassembly.binary_info.code_areas:
            self._code_areas = disassembly.binary_info.code_areas
        self.disassembly = disassembly
        self.lang_analyzer = LanguageAnalyzer(disassembly)
        self.disassembly.language = self.lang_analyzer.identify()
        self.bitness = disassembly.binary_info.bitness
        self.capstone = Cs(CS_ARCH_X86, CS_MODE_32)
        if self.bitness == 64:
            self.capstone = Cs(CS_ARCH_X86, CS_MODE_64)
        self.locateCandidates()
        self.disassembly.identified_alignment = self.identified_alignment
        self._buildQueue() 
Example #16
Source File: IdaExporter.py    From smda with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _initCapstone(self):
        self.capstone = Cs(CS_ARCH_X86, CS_MODE_32)
        if self.bitness == 64:
            self.capstone = Cs(CS_ARCH_X86, CS_MODE_64) 
Example #17
Source File: disassembler.py    From grap with MIT License 4 votes vote down vote up
def disassemble_elf(elf_data = None, elf_path = None, dot_path = None, print_listing=False, readable=False, verbose=False):
    if elf_path is None:
        print("ERROR: Missing ELF path.")
        return None

    from elftools.elf.elffile import ELFFile
    if elf_data is None:
        elf_data = open(elf_path, "rb").read()

    elf = ELFFile(io.BytesIO(elf_data))

    arch = CS_ARCH_X86
    mode = CS_MODE_64 if elf.elfclass == 64 else CS_MODE_32

    oep_rva = elf.header.e_entry

    def get_offset_from_rva(elf, offset):
        for section in elf.iter_sections():
            try:
                if section['sh_addr'] <= oep_rva < section['sh_addr'] + section['sh_size']:
                    return section['sh_offset'] + (oep_rva - section['sh_addr'])
            except Exception as e:
                if verbose:
                    print("WARNING:", repr(e))
                continue
        return None

    oep_offset = get_offset_from_rva(elf, oep_rva)

    if oep_offset is None:
        print("ERROR: Cannot retrieve entry point offset from RVA (0x%08X)." % (elf.header.e_entry))
        return None

    disass = ELFDisassembler(arch=arch, mode=mode, elf=elf)
    insts = disass.dis(data=elf_data, offset=oep_offset, iat_api={}, bin_instance=elf, verbose=verbose)

    if dot_path is not None:
        dot = disass.export_to_dot(insts=insts, oep_offset=oep_offset, displayable=readable)
        write_to_file(dot_path, dot)

    if print_listing:
        disass.display(insts, offset_from=0)

    return True 
Example #18
Source File: metadata.py    From hsdecomp with MIT License 4 votes vote down vote up
def read_settings(opts):
    elffile = ELFFile(open(opts.file, "rb"))

    if elffile.elfclass == 32:
        capstone_mode = capstone.CS_MODE_32
        runtime = Runtime(
            halfword = WordDesc(size = 2, lg_size = 1, struct = '<H'),
            word = WordDesc(size = 4, lg_size = 2, struct = '<I'),
            stack_register = capstone.x86.X86_REG_RBP,
            heap_register = capstone.x86.X86_REG_RDI,
            main_register = capstone.x86.X86_REG_RSI,
            arg_registers = []
        )
    elif elffile.elfclass == 64:
        capstone_mode = capstone.CS_MODE_64
        runtime = Runtime(
            halfword = WordDesc(size = 4, lg_size = 2, struct = '<I'),
            word = WordDesc(size = 8, lg_size = 3, struct = '<Q'),
            stack_register = capstone.x86.X86_REG_RBP,
            heap_register = capstone.x86.X86_REG_R12,
            main_register = capstone.x86.X86_REG_RBX,
            arg_registers = [capstone.x86.X86_REG_R14, capstone.x86.X86_REG_RSI, capstone.x86.X86_REG_RDI, capstone.x86.X86_REG_R8, capstone.x86.X86_REG_R9]
        )

    settings = Settings(
        opts = opts,
        rt = runtime,
        version = (7, 10, 3),
        name_to_address = {},
        address_to_name = {},
        binary = open(opts.file, "rb").read(),
        capstone = capstone.Cs(capstone.CS_ARCH_X86, capstone_mode),
        text_offset = elffile.get_section_by_name('.text')['sh_offset'] - elffile.get_section_by_name('.text')['sh_addr'],
        data_offset = elffile.get_section_by_name('.data')['sh_offset'] - elffile.get_section_by_name('.data')['sh_addr'],
        rodata_offset = elffile.get_section_by_name('.rodata')['sh_offset'] - elffile.get_section_by_name('.rodata')['sh_addr']
    )

    symtab = elffile.get_section_by_name('.symtab')
    for sym in symtab.iter_symbols():
        try:
            name = str(sym.name)
            offset = sym['st_value']
            settings.name_to_address[name] = offset
            settings.address_to_name[offset] = name
        except:
            pass

    settings.capstone.detail = True

    parsed_version = read_version(settings)
    if parsed_version != None:
        settings = settings._replace(version = parsed_version)

    return settings 
Example #19
Source File: shell.py    From unipacker with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self):
        try:
            Cmd.__init__(self)
            self.allow_cli_args = False
            self.register_cmdfinalization_hook(self.finalize_hook)
            builtins.print = self.shell_print
            self.histfile = ".unpacker_history"
            self.clear_queue = False
            self.sample = None
            self.disassembler = Cs(CS_ARCH_X86, CS_MODE_32)
            self.disassembler.detail = True
            parser = argparse.ArgumentParser(
                prog='unipacker',
                description='Automatic and platform-independent unpacker for Windows binaries based on emulation')
            parser.add_argument('samples', metavar='sample', type=file_or_dir, nargs='*',
                                help='The path to a sample (or directory containing samples) you want unpacked')
            parser.add_argument('-d', '--dest', nargs='?', default='.',
                                help='The destination directory for unpacked binaries')
            parser.add_argument('-p', '--partition-by-packer', action='store_true',
                                help='Group the unpacked files by packer')
            parser.add_argument('-i', '--interactive', action='store_true',
                                help='Open the chosen sample(s) in the un{i}packer shell')
            parser.add_argument('--version', action='store_true', help='Show version information and exit')

            args = parser.parse_args()
            if args.version:
                print_version_and_exit()
            if args.samples:
                samples = []
                for s in args.samples:
                    if os.path.exists(s):
                        samples.extend(Sample.get_samples(s, interactive=args.interactive))
                    else:
                        print(f"Path does not exist: {s}")
                if args.interactive:
                    while True:
                        self.sample_loop(samples)
                        self.shell_event.wait()
                        samples = None
                else:
                    IOHandler(samples, args.dest, args.partition_by_packer)
            else:
                while True:
                    self.sample_loop()
                    self.shell_event.wait()

        except (EOFError, KeyboardInterrupt):
            with open(f"{os.path.dirname(unipacker.__file__)}/fortunes") as f:
                fortunes = f.read().splitlines()
            print(f"\n{Fore.LIGHTRED_EX}{choice(fortunes)}{Fore.RESET}\n")
            sys.exit(0)