Python源码示例:idaapi.get_inf_structure()
示例1
def get_arch_dynamic():
"""
Determine the execution environments architecture.
:return: 'x64' or 'x86' if arch could be determined, else None
"""
info = idaapi.get_inf_structure()
if info.is_64bit():
return 64
elif info.is_32bit():
return 32
else:
env = idaapi.dbg_get_registers()
if env[17][0] == 'RAX':
return 64
elif env[17][0] == 'EAX':
return 32
else:
return None
###############################
# LIB DETECTION FUNCTIONALITY #
###############################
示例2
def get_native_size():
"""
Get the native OS size
@return: 16, 32, 64 value indicating the native size or None if failed.
"""
try:
inf = idaapi.get_inf_structure()
if inf.is_32bit():
return 32
elif inf.is_64bit():
return 64
else:
# Native size is neither 32 or 64 bit. assuming 16 bit.
return 16
except Exception as ex:
raise RuntimeError("Could not Could not retrieve native OS size: %s" %ex)
示例3
def get_arch_info():
info = idaapi.get_inf_structure()
proc = info.procName.lower()
bits = get_inf_structure_bitness(info)
instruction_set = None
instruction_mode = None
if proc == 'metapc':
instruction_set = CS_ARCH_X86
if bits == 16:
instruction_mode = CS_MODE_16
elif bits == 32:
instruction_mode = CS_MODE_32
elif bits == 64:
instruction_mode = CS_MODE_64
return instruction_set, instruction_mode
示例4
def __init__(self):
self.flags = idaapi.ph_get_flag()
# instead of checking ph flags, should __EA64__ be used?
self.is_64bit = (self.flags & idaapi.PR_USE64) != 0
self.is_32bit = (self.flags & idaapi.PR_USE32) != 0
self.is_stack_up = (self.flags & idaapi.PR_STACK_UP) != 0
self.id = idaapi.ph_get_id()
self.is_assemble_supported = (self.flags & idaapi.PR_ASSEMBLE) != 0
self.is_delayslot_proc = (self.flags & idaapi.PR_DELAYED) != 0
# processor default ret instruction (icode, not opcode!)
self.ret_icodes = [idaapi.ph_get_icode_return()]
# ptrsize in bytes
self.ptrsize = 2
if self.is_32bit:
self.ptrsize = 4
if self.is_64bit:
self.ptrsize = 8
self.ptrsize_pyfmt_mapper = {2:"H", 4:"I", 8:"Q"}
self.ptrsize_mask_mapper = {2:0xFFFF, 4:0xFFFFFFFF, 8:0xFFFFFFFFFFFFFFFF}
self.datafmt_mapper = {2:"%04X", 4:"%08X", 8:"%016X"}
self.endianness = idaapi.get_inf_structure().mf
示例5
def createAnalyzer(logger, is_elf):
"""Create a CPU-based analyzer to be used by the program.
Args:
logger (logger): logger instance
is_elf (bool): True iff analysing an ELF file
Return Value:
Created analyzer instance (None if CPU isn't supported yet)
"""
# Code taken from:
# https://reverseengineering.stackexchange.com/questions/11396/how-to-get-the-cpu-architecture-via-idapython
# Kudos to tmr232
info = idaapi.get_inf_structure()
if info.is_64bit():
bits = 64
elif info.is_32bit():
bits = 32
# quite rare
else:
bits = 16
# At the moment we don't care about the processors endianness.
# Check if we support this CPU
proc_name = info.procName
logger.info("Processor: %s, %dbit", proc_name, bits)
if proc_name not in analyzers_factory:
logger.error("Processor %s is NOT supported yet :(", proc_name)
return None
# Can now create the analyzer instance
return analyzers_factory[proc_name](logger, bits, is_elf)
示例6
def get_file_mask():
mask = "*.dd32"
if idaapi.get_inf_structure().is_64bit():
mask = "*.dd64"
return mask
示例7
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))
示例8
def get_arch_ptrsize():
info = idaapi.get_inf_structure()
ptr_size = None
if info.is_64bit():
ptr_size = 8
elif info.is_32bit():
ptr_size = 4
else:
raise Exception("Invalid arch")
return ptr_size
# --------------------------------------------------------------------------
示例9
def get_native_size():
info = idaapi.get_inf_structure()
if info.is_64bit():
return 8
elif info.is_32bit():
return 4
else:
return 2
示例10
def get_native_size():
info = idaapi.get_inf_structure()
if info.is_64bit():
return 8
elif info.is_32bit():
return 4
else:
return 2
示例11
def get_proc_type():
"""
Get processor type
@return: Returns the processor type or None on failure.
"""
try:
inf = idaapi.get_inf_structure()
return inf.procName()
except Exception as ex:
raise RuntimeError("Could not retrieve processor type: %s" %ex)
示例12
def get_native_size():
"""Get the native word size in normal 8-bit bytes."""
info = idaapi.get_inf_structure()
if info.is_64bit():
return 8
elif info.is_32bit():
return 4
else:
return 2
示例13
def _initialize(self):
if self.op_t.type not in (idaapi.o_displ, idaapi.o_phrase):
raise exceptions.OperandNotPhrase('Operand is not of type o_phrase or o_displ.')
proc_name = idaapi.get_inf_structure().procName
if proc_name != 'metapc':
raise exceptions.PhraseProcessorNotSupported(
'Phrase analysis not supported for processor {}'.format(proc_name))
specflag1 = self.op_t.specflag1
specflag2 = self.op_t.specflag2
scale = 1 << ((specflag2 & 0xC0) >> 6)
offset = self.op_t.addr
if specflag1 == 0:
index = None
base_ = self.op_t.reg
elif specflag1 == 1:
index = (specflag2 & 0x38) >> 3
base_ = (specflag2 & 0x07) >> 0
if self.op_t.reg == 0xC:
if base_ & 4:
base_ += 8
if index & 4:
index += 8
else:
raise exceptions.PhraseNotSupported('o_displ, o_phrase : Not implemented yet : %x' % specflag1)
# HACK: This is a really ugly hack. For some reason, phrases of the form `[esp + ...]` (`sp`, `rsp` as well)
# set both the `index` and the `base` to `esp`. This is not significant, as `esp` cannot be used as an
# index, but it does cause issues with the parsing.
# This is only relevant to Intel architectures.
if (index == base_ == idautils.procregs.sp.reg) and (scale == 1):
index = None
self.scale = scale
self.index_id = index
self.base_id = base_
self.offset = offset
示例14
def indexing_mode(self):
if idaapi.get_inf_structure().procName != 'ARM':
return IndexingMode()
return IndexingMode(pre=bool(self.insn_t.auxpref & 0x20),
post=bool(self.insn_t.auxpref & 0x80))
示例15
def create_runtime_ms():
debug('Attempting to find runtime_morestack function for hooking on...')
text_seg = get_text_seg()
if text_seg is None:
debug('Failed to get text segment')
return None
# Opcodes for "mov large dword ptr ds:1003h, 0", binary search is faster than text search
opcodes = 'c7 05 03 10 00 00 00 00 00 00'
if idaapi.get_inf_structure().is_64bit():
# Opcodes for "mov qword ptr ds:dword_1000+3, 0"
opcodes = '48 c7 04 25 03 10 00 00 00 00 00 00'
runtime_ms_end = idaapi.find_binary(text_seg.start_ea, text_seg.end_ea, opcodes, 0, SEARCH_DOWN)
if runtime_ms_end == BADADDR:
debug('Failed to find opcodes associated with runtime_morestack: %s' % opcodes)
return None
runtime_ms = idaapi.get_func(runtime_ms_end)
if runtime_ms is None:
debug('Failed to get runtime_morestack function from address @ 0x%x' % runtime_ms_end)
return None
if idc.set_name(runtime_ms.start_ea, "runtime_morestack", SN_PUBLIC):
debug('Successfully found runtime_morestack')
else:
debug('Failed to rename function @ 0x%x to runtime_morestack' % runtime_ms.start_ea)
return runtime_ms
示例16
def create_pointer(addr, force_size=None):
if force_size is not 4 and (idaapi.get_inf_structure().is_64bit() or force_size is 8):
ida_bytes.create_data(addr, FF_QWORD, 8, ida_idaapi.BADADDR)
return idc.get_qword(addr), 8
else:
ida_bytes.create_data(addr, FF_DWORD, 4, ida_idaapi.BADADDR)
return idc.get_wide_dword(addr), 4
示例17
def get_processor_architecture():
arch = "Intel"
info = idaapi.get_inf_structure()
if info.procName == "ARM":
arch = "ARM"
if info.is_64bit():
return arch, True
elif info.is_32bit():
return arch, False
else:
return "Error", False
示例18
def _initialize():
# https://reverseengineering.stackexchange.com/questions/11396/how-to-get-the-cpu-architecture-via-idapython
global WORD_SIZE, LITTLE_ENDIAN, BIG_ENDIAN
info = idaapi.get_inf_structure()
if info.is_64bit():
WORD_SIZE = 8
elif info.is_32bit():
WORD_SIZE = 4
else:
WORD_SIZE = 2
try:
BIG_ENDIAN = info.is_be()
except:
BIG_ENDIAN = info.mf
LITTLE_ENDIAN = not BIG_ENDIAN
示例19
def output_segments(out):
"""Dump binary segmentation."""
info = idaapi.get_inf_structure()
size = "r32" if info.is_32bit else "r64"
out.writelines(('(', info.get_proc_name()[1], ' ', size, ' ('))
for seg in idautils.Segments():
out.write("\n({} {} {:d} ({:#x} {:d}))".format(
get_segm_name(seg),
"code" if idaapi.segtype(seg) == idaapi.SEG_CODE else "data",
idaapi.get_fileregion_offset(seg),
seg, idaapi.getseg(seg).size()))
out.write("))\n")
示例20
def __newprc__(cls, pnum):
info = idaapi.get_inf_structure()
bits = 64 if info.is_64bit() else 32 if info.is_32bit() else None
if bits is None: return
typemap.integermap[None] = typemap.integermap[bits/8]
typemap.decimalmap[None] = typemap.decimalmap[bits/8]
typemap.ptrmap[None] = typemap.ptrmap[bits/8]
typemap.stringmap[None] = typemap.stringmap[str]
示例21
def __bounds__(cls):
info = idaapi.get_inf_structure()
return info.minEA, info.maxEA
示例22
def graphview(cls):
'''Returns true if the current function is being viewed in graph view mode.'''
res = idaapi.get_inf_structure()
if idaapi.__version__ < 7.0:
return res.graph_view != 0
return res.is_graph_view()
示例23
def database_inited(self, is_new_db, idc_script):
# A file was loaded, reset vars
self.plugin.filename = idaapi.get_input_file_path()
self.plugin.cfg = None
self.plugin.angr_proj = None
self.plugin.global_vars = None
self.plugin.opaque_predicates = dict()
self.plugin.extra_constraints = dict()
self.plugin.symbolic_vars = dict()
# Check if it (still) exists
if not isfile(self.plugin.filename):
print("### Drop error: original input file no longer exists, unable to load it into angr. ###")
return
# Load the file into angr
try:
# This is a bit inefficient, but figure out if it's PIC by loading twice
p = angr.Project(self.plugin.filename, load_options={'auto_load_libs': False})
if p.loader.main_bin.pic:
# Load with IDA's imagebase as base_addr
base_addr = idaapi.get_imagebase()
else:
# Load with 0 as base_addr
base_addr = 0
del p
self.plugin.angr_proj = angr.Project(self.plugin.filename,
load_options={'auto_load_libs': False, 'main_opts': {
'custom_base_addr': base_addr}})
# get and store the file bitness
# Don't use idaapi.get_inf_structure().is_32bit(), it will give True for MIPS64...
self.plugin.bitness = self.plugin.angr_proj.arch.bits
# Save the list of all recognized variables in .bss, .data and .rodata (TODO: why these? any others?)
# TODO: Other segments as well?
self.plugin.global_vars = [var for s in sark.segments() for var in get_segment_names(s) if s.name in [".bss", ".data", ".rodata"]]
print("### Loaded file into angr succesfully! ###")
except:
import traceback
print("ERROR: Failed to load file into angr: {}".format(traceback.format_exc()))
示例24
def getArchitecture(self):
# https://reverseengineering.stackexchange.com/a/11398
info = ida_idaapi.get_inf_structure()
procname = info.procName
if procname in self._processor_map:
return self._processor_map[procname]
else:
raise ValueError("Unsupported Architecture")
示例25
def getBitness(self):
# https://reverseengineering.stackexchange.com/a/11398
bits = None
info = ida_idaapi.get_inf_structure()
if info.is_64bit():
bits = 64
elif info.is_32bit():
bits = 32
else:
bits = 16
return bits
示例26
def getArchitecture(self):
# https://reverseengineering.stackexchange.com/a/11398
info = idaapi.get_inf_structure()
procname = info.procName
if procname in self._processor_map:
return self._processor_map[procname]
else:
raise ValueError("Unsupported Architecture")
示例27
def getBitness(self):
# https://reverseengineering.stackexchange.com/a/11398
bits = None
info = idaapi.get_inf_structure()
if info.is_64bit():
bits = 64
elif info.is_32bit():
bits = 32
else:
bits = 16
return bits
示例28
def get_ptrsize():
info = idaapi.get_inf_structure()
ptr_size = None
if info.is_64bit():
ptr_size = 8
elif info.is_32bit():
ptr_size = 4
return ptr_size
示例29
def get_hardware_info():
is_be = idaapi.cvar.inf.mf
info = idaapi.get_inf_structure()
cpuname = info.procname.lower()
#TODO
示例30
def supported_cpu():
info = idaapi.get_inf_structure()
cpuname = info.procname.lower()
if cpuname == "metapc" or cpuname.startswith("arm") or cpuname.startswith("mips"):
return True
return False