Python capstone.CS_MODE_64 Examples

The following are 19 code examples of capstone.CS_MODE_64(). 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: cli.py    From debugger with MIT License 6 votes vote down vote up
def disasm1(data, addr):
	if not data: return
	arch_dis = get_arch_dis()

	#if 'binaryninja' in sys.modules:
	#	return utils.disasm1(data, addr, arch_dis)
	if arch == 'z80':
		from z80dis import z80
		decoded = z80.decode(data, addr)
		return (z80.disasm(decoded), decoded.len)
	else:
		import capstone
		if arch_dis == 'x86_64':
			md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
		elif arch_dis == 'x86':
			md = capstone.Cs(capstone.CS_ARCH_X86, 0)
		gen = md.disasm(data, addr)
		insn = next(gen)
		return ('%s %s' % (insn.mnemonic, insn.op_str), insn.size) 
Example #2
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 #3
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 #4
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 #5
Source File: code_parser.py    From writeups with GNU General Public License v3.0 6 votes vote down vote up
def find_rr_writes_capstone(address, data):
    #print 'Using capstone'
    cs = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
    cs.detail = True
    writes = []
    for insn in cs.disasm(data, address):
        if insn.mnemonic[:3] == 'ret':
            break
        if insn.mnemonic[:3] != 'mov':
            continue

        # potential write
        opnd = insn.operands[0]
        if opnd.type != csx86.X86_OP_MEM:
            continue
        if opnd.mem.base != csx86.X86_REG_RIP:
            continue
        # RIP-relative write
        writes.append((insn.address + insn.size + opnd.mem.disp, opnd.size))
    return writes

# Consolidate contiguous writes into single segments 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
Source File: translator.py    From reil with Apache License 2.0 4 votes vote down vote up
def __init__(self, use_rip=False):
        TranslationContext.__init__(self)

        self.registers = {
            capstone.x86.X86_REG_RAX:   r('rax', 64),
            capstone.x86.X86_REG_RBX:   r('rbx', 64),
            capstone.x86.X86_REG_RCX:   r('rcx', 64),
            capstone.x86.X86_REG_RDX:   r('rdx', 64),
            capstone.x86.X86_REG_RSI:   r('rsi', 64),
            capstone.x86.X86_REG_RDI:   r('rdi', 64),
            capstone.x86.X86_REG_RBP:   r('rbp', 64),
            capstone.x86.X86_REG_RSP:   r('rsp', 64),
            capstone.x86.X86_REG_R8:    r('r8', 64),
            capstone.x86.X86_REG_R9:    r('r9', 64),
            capstone.x86.X86_REG_R10:   r('r10', 64),
            capstone.x86.X86_REG_R11:   r('r11', 64),
            capstone.x86.X86_REG_R12:   r('r12', 64),
            capstone.x86.X86_REG_R13:   r('r13', 64),
            capstone.x86.X86_REG_R14:   r('r14', 64),
            capstone.x86.X86_REG_R15:   r('r15', 64),
            capstone.x86.X86_REG_RIP:   r('rip', 64),

            capstone.x86.X86_REG_FS:    r('fsbase', 64),
            capstone.x86.X86_REG_GS:    r('gsbase', 64),

            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),
            capstone.x86.X86_REG_XMM8:  r('xmm8', 128),
            capstone.x86.X86_REG_XMM9:  r('xmm9', 128),
            capstone.x86.X86_REG_XMM10: r('xmm10', 128),
            capstone.x86.X86_REG_XMM11: r('xmm11', 128),
            capstone.x86.X86_REG_XMM12: r('xmm12', 128),
            capstone.x86.X86_REG_XMM13: r('xmm13', 128),
            capstone.x86.X86_REG_XMM14: r('xmm14', 128),
            capstone.x86.X86_REG_XMM15: r('xmm15', 128),
        }

        self.word_size = 64
        self.accumulator = self.registers[capstone.x86.X86_REG_RAX]
        self.base = self.registers[capstone.x86.X86_REG_RBX]
        self.counter = self.registers[capstone.x86.X86_REG_RCX]
        self.data = self.registers[capstone.x86.X86_REG_RDX]
        self.source = self.registers[capstone.x86.X86_REG_RSI]
        self.destination = self.registers[capstone.x86.X86_REG_RDI]
        self.frame_ptr = self.registers[capstone.x86.X86_REG_RBP]
        self.stack_ptr = self.registers[capstone.x86.X86_REG_RSP]
        self.disassembler = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
        self.disassembler.detail = True
        self.use_rip = use_rip 
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: cli.py    From debugger with MIT License 4 votes vote down vote up
def disasm(data, addr):
	if not data: return
	arch_dis = get_arch_dis()

	#if 'binaryninja' in sys.modules:
	#	return utils.disasm(data, addr, arch_dis)
	if arch == 'z80':
		from z80dis import z80
		lines = []

		offset = 0
		while offset < len(data):
			try:
				decoded = z80.decode(data[offset:], addr)
			except Exception:
				break

			addrstr = '%s%04X%s' % (GREEN, addr+offset, NORMAL)
			bytestr = hexlify(data[offset:offset+decoded.len]).decode('utf-8').ljust(8)
			asmstr = z80.disasm(decoded)
			lines.append('%s: %s %s' % (addrstr, bytestr, asmstr))

			addr += decoded.len
			offset += decoded.len

		return '\n'.join(lines)
	else:
		import capstone
		offset = 0
		lines = []
		if arch_dis == 'x86_64':
			md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
		elif arch_dis == 'x86':
			md = capstone.Cs(capstone.CS_ARCH_X86, 0)
		for i in md.disasm(data, addr):
			addrstr = '%s%016X%s' % (GREEN, i.address, NORMAL)
			bytestr = hexlify(data[offset:offset+i.size]).decode('utf-8').ljust(16)
			asmstr = i.mnemonic + ' ' + i.op_str
			line = '%s: %s %s' % (addrstr, bytestr, asmstr)
			lines.append(line)
			offset += i.size
		return '\n'.join(lines) 
Example #19
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