Python capstone.Cs() Examples
The following are 30
code examples of capstone.Cs().
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 |
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: disassembler.py From chiasm-shell with MIT License | 6 votes |
def _set_arch(self, arch, *modes): """ Try and set the current architecture """ try: a = self.valid_archs[''.join(['CS_ARCH_', arch.upper()])] if a is None: l.error("Invalid architecture selected - run lsarch for valid options") return False ms = [self.modes[''.join(['CS_MODE_', m.upper()])] for m in modes] except KeyError: l.error("ERROR: Invalid architecture or mode string specified") return False try: _cs = cs.Cs(a, sum(ms)) self._arch = (arch, modes) l.debug("Architecture set to %s, mode(s): %s", arch, ', '.join(modes)) self._cs = _cs except cs.CsError as e: l.error("ERROR: %s", e) return False return True
Example #3
Source File: cortexm.py From rainbow with GNU Lesser General Public License v3.0 | 6 votes |
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 #4
Source File: x64.py From rainbow with GNU Lesser General Public License v3.0 | 6 votes |
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: m68k.py From rainbow with GNU Lesser General Public License v3.0 | 6 votes |
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: aarch64.py From rainbow with GNU Lesser General Public License v3.0 | 6 votes |
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 #7
Source File: arm.py From rainbow with GNU Lesser General Public License v3.0 | 6 votes |
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 #8
Source File: code_parser.py From writeups with GNU General Public License v3.0 | 6 votes |
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 #9
Source File: emu_helper.py From writeups with GNU General Public License v3.0 | 6 votes |
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 #10
Source File: disassembler.py From barf-project with BSD 2-Clause "Simplified" License | 6 votes |
def __setup_available_disassemblers(self): arch_map = { ARCH_ARM_MODE_ARM: CS_MODE_ARM, ARCH_ARM_MODE_THUMB: CS_MODE_THUMB, } self._available_disassemblers = { ARCH_ARM_MODE_ARM: Cs(CS_ARCH_ARM, arch_map[ARCH_ARM_MODE_ARM]), ARCH_ARM_MODE_THUMB: Cs(CS_ARCH_ARM, arch_map[ARCH_ARM_MODE_THUMB]), } self._available_disassemblers[ARCH_ARM_MODE_ARM].detail = True self._available_disassemblers[ARCH_ARM_MODE_THUMB].detail = True # Casptone to BARF translation # ======================================================================== #
Example #11
Source File: disassembler.py From barf-project with BSD 2-Clause "Simplified" License | 6 votes |
def _cs_disassemble_one(self, data, address): """Disassemble the data into an instruction in string form. """ disasm = list(self._disassembler.disasm(bytes(data), address)) # TODO: Improve this check. if len(disasm) > 0: return disasm[0] else: cs_arm = Cs(CS_ARCH_ARM, CS_MODE_ARM) cs_arm.detail = True disasm = list(cs_arm.disasm(bytes(data), address)) if len(disasm) > 0: return disasm[0] else: raise InvalidDisassemblerData("CAPSTONE: Unknown instruction (Addr: {:s}).".format(hex(address)))
Example #12
Source File: __base__.py From deen with Apache License 2.0 | 6 votes |
def __init__(self): super(AsmBase, self).__init__() # Initialize keystone and capstone as soon as an instance # of this plugin will be created. if not keystone: self.log.debug('Keystone is required for ' + self.__class__.__name__) return if not capstone: self.log.debug('Capstone is required for ' + self.__class__.__name__) return if getattr(self, 'args', None) and self.args and getattr(self.args, 'bigendian', None) \ and self.args.bigendian: self.ks = keystone.Ks(self.keystone_arch, self.keystone_mode + keystone.KS_MODE_BIG_ENDIAN) self.cs = capstone.Cs(self.capstone_arch, capstone.CS_MODE_BIG_ENDIAN) else: self.ks = keystone.Ks(self.keystone_arch, self.keystone_mode + keystone.KS_MODE_LITTLE_ENDIAN) self.cs = capstone.Cs(self.capstone_arch, capstone.CS_MODE_LITTLE_ENDIAN)
Example #13
Source File: mips_rsp.py From ios_mips_gdb with GNU Affero General Public License v3.0 | 6 votes |
def OnDisas(command): lex = command.rstrip().split(' ') regs = DisplayRegistersMIPS(GdbCommand('g')) pc = hex2int(regs[reg_map_rev['pc']]) for lexem in lex[1:]: if lexem != 'aslr': if not isValidDword(lexem): logger.error('Invalid address supplied') return pc = hex2int(lexem) logger.debug('OnDisas PC = {}'.format(pc)) buf = OnReadMem(int2hex(pc - 20 * 4), 40 * 4) md = cs.Cs(cs.CS_ARCH_MIPS, cs.CS_MODE_MIPS32 | cs.CS_MODE_BIG_ENDIAN) if len(lex) > 1: if lex[1] == 'aslr' and aslr_offset != None: pc -= aslr_offset for i in md.disasm(buf.decode('hex'), pc - 20 * 4): color = 'green' if i.address == pc else 'blue' print("0x%x:\t%s\t%s" %(i.address, colored(i.mnemonic, color), colored(i.op_str, color)))
Example #14
Source File: gadgets.py From rop-chainer with GNU General Public License v3.0 | 6 votes |
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 #15
Source File: cli.py From debugger with MIT License | 6 votes |
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 #16
Source File: DisasmViewMode.py From qiew with GNU General Public License v2.0 | 6 votes |
def init_disassembler_engine(self): # init state for disasambler # set capstone, lexer, asmline arch, mode = self.plugin.hintDisasm() self.disasm_engine = capstone.Cs(arch, mode) self.disasm_engine.detail = True if arch == capstone.CS_ARCH_X86: Lexer = X86_Lexer() if arch == capstone.CS_ARCH_ARM and mode in [capstone.CS_MODE_ARM, capstone.CS_MODE_THUMB]: Lexer = ARM_Lexer() if arch == capstone.CS_ARCH_ARM64: Lexer = ARM64_Lexer() # todo: ASM_ARM_Line? self.ASMLine = ASMx86Line Lexer.build() self.lexer = Lexer.lexer()
Example #17
Source File: disassembler.py From grap with MIT License | 6 votes |
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 #18
Source File: unicorefuzz.py From unicorefuzz with Apache License 2.0 | 6 votes |
def __init__(self, config: [str, "configspec"]) -> None: if isinstance(config, str): from unicorefuzz.configspec import load_config config = load_config(config) self.config = config # type: configspec self.arch = get_arch(config.ARCH) # type: Architecture self._mapped_page_cache = {} # type: Dict[int, bytes] self.cs = Cs(self.arch.capstone_arch, self.arch.capstone_mode) # type: Cs self.statedir = os.path.join(config.WORKDIR, "state") # type: str self.requestdir = os.path.join(config.WORKDIR, "requests") # type: str self.exits = None # type: Optional[List[int]] # fore some things like the fuzz child we want to disable logging, In this case, we set should_log to False. self.should_log = True # type: bool
Example #19
Source File: IntelDisassembler.py From smda with BSD 2-Clause "Simplified" License | 5 votes |
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 #20
Source File: arch_arm.py From archinfo with BSD 2-Clause "Simplified" License | 5 votes |
def capstone_thumb(self): if _capstone is None: l.warning("Capstone is not installed!") return None if self._cs_thumb is None: self._cs_thumb = _capstone.Cs(self.cs_arch, self.cs_mode + _capstone.CS_MODE_THUMB) self._cs_thumb.detail = True return self._cs_thumb
Example #21
Source File: FunctionCandidateManager.py From smda with BSD 2-Clause "Simplified" License | 5 votes |
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 #22
Source File: arch.py From archinfo with BSD 2-Clause "Simplified" License | 5 votes |
def capstone(self): """ A Capstone instance for this arch """ if _capstone is None: l.warning("Capstone is not installed!") return None if self.cs_arch is None: raise ArchError("Arch %s does not support disassembly with Capstone" % self.name) if self._cs is None: self._cs = _capstone.Cs(self.cs_arch, self.cs_mode) self._configure_capstone() self._cs.detail = True return self._cs
Example #23
Source File: IdaExporter.py From smda with BSD 2-Clause "Simplified" License | 5 votes |
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 #24
Source File: idapython.py From python-idb with Apache License 2.0 | 5 votes |
def _load_dis(self, arch, mode): import capstone if self.bit_dis is None: self.bit_dis = {} if self.bit_dis.get((arch, mode)) is None: r = capstone.Cs(arch, mode) self.bit_dis[(arch, mode)] = r return self.bit_dis[(arch, mode)]
Example #25
Source File: bootcode_parser.py From bootcode_parser with GNU General Public License v3.0 | 5 votes |
def _checkCode(self, code): md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_16) md.detail = True for i in md.disasm(code, 0): # Check for unknown interrupt if i.mnemonic == 'int' and i.bytes[1] not in (0x10, 0x13, 0x18, 0x1a): self._suspiciousBehaviour.append('Unknown Interrupt : {0:#x}'.format(i.bytes[1]))
Example #26
Source File: bootcode_parser.py From bootcode_parser with GNU General Public License v3.0 | 5 votes |
def _checkCode(self, code): md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_16) md.detail = True for i in md.disasm(code, 0): # Check for unknown interrupt if i.mnemonic == 'int' and i.bytes[1] not in (0x10, 0x13, 0x18, 0x1a): self._suspiciousBehaviour.append('Unknown Interrupt : {0:#x}'.format(i.bytes[1]))
Example #27
Source File: bootcode_parser.py From bootcode_parser with GNU General Public License v3.0 | 5 votes |
def _checkCode(self, rawCode): md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_16) md.detail = True checkJmp = True for i in md.disasm(rawCode, 0): # Check for JUMPs and CALLs before the first PUSH/RET. if checkJmp and len(i.groups) > 0: # Group check if available if hasattr(capstone.x86, 'X86_GRP_CALL') and hasattr(capstone.x86, 'X86_GRP_RET'): if capstone.x86.X86_GRP_CALL in i.groups or capstone.x86.X86_GRP_JUMP in i.groups: self._suspiciousBehaviour.append('JMP or CALL before relocation') checkJmp = False elif capstone.x86.X86_GRP_RET in i.groups: # Stop search after the first PUSH/RET checkJmp = False # Manual check in case capstone version doesn't support CALL and RET groups else: if i.mnemonic[0] == 'j' or i.mnemonic == 'call': self._suspiciousBehaviour.append('JMP or CALL before relocation') checkJmp = False elif i.mnemonic[:3] == 'ret': # Stop search after the first PUSH/RET checkJmp = False # Check for unknown interrupt if i.mnemonic == 'int' and i.bytes[1] not in (0x10, 0x13, 0x18, 0x1a): self._suspiciousBehaviour.append('Unknown Interrupt : {0:#x}'.format(i.bytes[1]))
Example #28
Source File: database.py From bootloader_instrumentation_suite with MIT License | 5 votes |
def mdarm(self): if self._mdarm is None: self._mdarm = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM + capstone.CS_MODE_V8) self._mdarm.detail = True return self._mdarm
Example #29
Source File: database.py From bootloader_instrumentation_suite with MIT License | 5 votes |
def mdthumb(self): if self._mdthumb is None: self._mdthumb = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB + capstone.CS_MODE_V8) self._mdthumb.detail = True return self._mdthumb
Example #30
Source File: brute_force_disassembler.py From multiverse with GNU Lesser General Public License v3.0 | 5 votes |
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