本文整理汇总了Python中elftools.elf.elffile.ELFFile方法的典型用法代码示例。如果您正苦于以下问题:Python elffile.ELFFile方法的具体用法?Python elffile.ELFFile怎么用?Python elffile.ELFFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类elftools.elf.elffile
的用法示例。
在下文中一共展示了elffile.ELFFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: binary_symbols
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def binary_symbols(binary):
"""
helper method for getting all binary symbols with SANDSHREW_ prepended.
We do this in order to provide the symbols Manticore should hook on to
perform main analysis.
:param binary: str for binary to instrospect.
:rtype list: list of symbols from binary
"""
def substr_after(string, delim):
return string.partition(delim)[2]
with open(binary, "rb") as f:
elffile = ELFFile(f)
for section in elffile.iter_sections():
if not isinstance(section, SymbolTableSection):
continue
symbols = [sym.name for sym in section.iter_symbols() if sym]
return [
substr_after(name, PREPEND_SYM) for name in symbols if name.startswith(PREPEND_SYM)
]
示例2: get_dynamic_features
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def get_dynamic_features(main, lib_path, feat_type='function'):
"""
Function to extract function/variable names from a shared library file.
"""
from elftools.elf.elffile import ELFFile
from elftools.common.exceptions import ELFError
count = 0
features = {}
try:
with open(lib_path, 'rb') as stream:
elffile = ELFFile(stream)
count += scan_section(main, features, feat_type, lib_path, elffile.get_section_by_name('.symtab'))
count += scan_section(main, features, feat_type, lib_path, elffile.get_section_by_name('.dynsym'))
return count, features
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
logger.error("[%s, %s, %s] Error extracting %ss: %s", exc_type, fname, exc_tb.tb_lineno, feat_type, str(e))
###########################################################
# Object extractor
###########################################################
示例3: process_binary
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def process_binary(bv, binfile):
with open(binfile, 'rb') as f:
elffile = ELFFile(f)
symbol_tables = [s for s in elffile.iter_sections() if isinstance(s, SymbolTableSection)]
for section in symbol_tables:
if not isinstance(section, SymbolTableSection):
continue
if section['sh_entsize'] == 0:
continue
for nsym, symbol in enumerate(section.iter_symbols()):
sym_addr = symbol['st_value']
sym_size = symbol['st_size']
if is_data_variable_section(bv, sym_addr):
dynamic_symbols[sym_addr] = sym_size
示例4: _check_binary
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def _check_binary(self, directory, layer_tar, image_tar, fileobj):
fileobj.seek(0)
if fileobj.read(4) != b"\x7fELF":
fileobj.seek(0)
return
fileobj.seek(0)
elf = ELFFile(fileobj)
for section in [
section
for section in elf.iter_sections()
if isinstance(section, DynamicSection)
]:
for library in [
tag.needed for tag in section.iter_tags() if hasattr(tag, "needed")
]:
if not [
file
for file in (layer_tar.getnames() + image_tar.getnames())
if Path(file).name == library
]:
self._find_library(directory, library, image_tar)
fileobj.seek(0)
示例5: get_func_address
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def get_func_address(self, name):
address = None
with open(self.path, 'rb') as stream:
elf = ELFFile(stream)
for section in elf.iter_sections():
if isinstance(section, SymbolTableSection):
for symbol in section.iter_symbols():
if symbol.name == name:
self.logger.debug('%s', symbol.entry)
address = symbol.entry['st_value']
break
if address:
break
else:
raise RuntimeError('Failed to find {}'.format(name))
return self.handle_address(address + self.libc.imageBase)
示例6: __init__
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def __init__(self, filename):
super().__init__(filename)
self.elf = ELFFile(open(filename, "rb"))
self.arch = {"x86": "i386", "x64": "amd64"}[self.elf.get_machine_arch()]
assert self.elf.header.e_type in ["ET_DYN", "ET_EXEC", "ET_CORE"]
# Get interpreter elf
self.interpreter = None
for elf_segment in self.elf.iter_segments():
if elf_segment.header.p_type != "PT_INTERP":
continue
self.interpreter = Elf(elf_segment.data()[:-1])
break
if self.interpreter is not None:
assert self.interpreter.arch == self.arch
assert self.interpreter.elf.header.e_type in ["ET_DYN", "ET_EXEC"]
示例7: do_symbols
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def do_symbols(self, *args):
"""
:= symbols
"""
# Locals
elf = None
try:
if self.target_library:
# Create a new ELFFile() instance
elf = ELFFile(self.target_library[0])
for section in elf.iter_sections():
# Once we find the symbol table, print each symbol
if isinstance(section, SymbolTableSection):
self.logger.binja_log("info", "Found symbol table (!)")
for i, symbol in enumerate(section.iter_symbols()):
self.logger.binja_log("info", symbol.name)
else:
self.logger.binja_log("info", "Target library not selected (!)")
except Exception as e:
BinjaError("function : {}".format(e))
示例8: add_tls_section
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def add_tls_section(fname,contents):
# This does not require ELFManip because it must
# be called earlier on, before we actually rewrite the
# binary, because I need the new TLS offset.
# We could obviously create the ELFManip object now,
# but it won't be used again until we write it out at
# the end.
global tls_section_added
global tls_section_contents
tls_section_added = True
#Pad contents to 4-byte alignment
tls_section_contents = contents+('\0'*(4-len(contents)%4))
with open(fname) as f:
elf = ELFFile(f)
for s in elf.iter_segments():
#Assume only one TLS segment exists (will fail on an already modified binary)
if s.header['p_type'] == 'PT_TLS':
tls_section_offset = s.header['p_memsz']+len(tls_section_contents)
print 'old section is 0x%x (%x with padding)'%(s.header['p_memsz'], s.header['p_memsz']+(4-s.header['p_memsz']%4))
print 'new content is 0x%x (%x with padding)'%(len(contents), len(contents)+(4-len(contents)%4))
print 'overall 0x%x (%x with padding)'%(tls_section_offset, tls_section_offset+(4-tls_section_offset%4))
return tls_section_offset + (4-tls_section_offset%4)
return len(contents) + (4-len(contents)%4) #If there is no TLS segment
示例9: __init__
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def __init__(self, elf, memory_map=None):
if isinstance(elf, six.string_types):
self._file = open(elf, 'rb')
self._owns_file = True
else:
self._file = elf
self._owns_file = False
self._elf = ELFFile(self._file)
self._memory_map = memory_map or MemoryMap()
self._symbol_decoder = None
self._address_decoder = None
self._extract_sections()
self._compute_regions()
## @brief Close the ELF file if it is owned by this instance.
示例10: __init__
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def __init__(self, elf):
assert isinstance(elf, ELFFile)
self.elffile = elf
if not self.elffile.has_dwarf_info():
raise Exception("No DWARF debug info available")
self.dwarfinfo = self.elffile.get_dwarf_info()
self.subprograms = None
self.function_tree = None
self.line_tree = None
# Build indices.
self._get_subprograms()
self._build_function_search_tree()
self._build_line_search_tree()
示例11: get_elf_files
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def get_elf_files(apk_path):
files = list()
if zipfile.is_zipfile(apk_path):
try:
with zipfile.ZipFile(apk_path, mode="r") as zf:
for name in zf.namelist():
try:
data = zf.read(name)
mime = Magic(data).get_type()
if mime == 'elf':
elf_data = io.BytesIO(data)
elf_file = ELFFile(elf_data)
files.append((name, elf_data, elf_file))
except Exception as ex:
continue
except Exception as ex:
raise ex
return files
示例12: __init__
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def __init__(self, file_path):
super(ELFExecutable, self).__init__(file_path)
self.helper = ELFFile(self.binary)
self.architecture = self._identify_arch()
if self.architecture is None:
raise Exception('Architecture is not recognized')
logging.debug('Initialized {} {} with file \'{}\''.format(self.architecture, type(self).__name__, file_path))
self.pack_endianness = '<' if self.helper.little_endian else '>'
self.address_pack_type = 'I' if self.helper.elfclass == 32 else 'Q'
self.sections = [section_from_elf_section(s) for s in self.helper.iter_sections()]
self.executable_segment = [s for s in self.helper.iter_segments() if s['p_type'] == 'PT_LOAD' and s['p_flags'] & 0x1][0]
dyn = self.helper.get_section_by_name('.dynamic')
if dyn:
self.libraries = [t.needed for t in dyn.iter_tags() if t['d_tag'] == 'DT_NEEDED']
self.next_injection_offset = None
示例13: recon
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def recon(self):
z = ZipFile(self.filename)
bundle = False
if 'lib/armeabi-v7a/libmonodroid.so' in z.namelist() and 'lib/armeabi-v7a/libmonodroid_bundle_app.so' in z.namelist():
bundle = 'lib/armeabi-v7a/libmonodroid_bundle_app.so'
elif 'lib/armeabi/libmonodroid.so' in z.namelist() and 'lib/armeabi/libmonodroid_bundle_app.so' in z.namelist():
bundle = 'lib/armeabi/libmonodroid_bundle_app.so'
if not bundle:
return False
self.bundle = bundle
f = z.open(bundle)
f = StringIO(f.read())
elffile = ELFFile(f)
section = elffile.get_section_by_name('.dynsym')
for symbol in section.iter_symbols():
if symbol['st_shndx'] != 'SHN_UNDEF' and symbol.name == 'mono_mkbundle_init':
return True
return False
示例14: extract
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def extract(self):
c2 = []
z = ZipFile(self.filename)
data = z.open(self.bundle).read()
f = StringIO(data)
elffile = ELFFile(f)
section = elffile.get_section_by_name('.dynsym')
for symbol in section.iter_symbols():
if symbol['st_shndx'] != 'SHN_UNDEF' and symbol.name.startswith('assembly_data_'):
if symbol.name[14:] in self.WHITELISTED_DLL:
continue
dll_data = data[symbol['st_value']:symbol['st_value']+symbol['st_size']]
dll_data = gzip.GzipFile(fileobj=StringIO(dll_data)).read()
regexp = """rule find_url {
strings:
$url = /http:\/\/[A-Za-z0-9\.\/$\-_+!\*'(),]*/ wide
condition:
$url}"""
compiled = yara.compile(source = regexp)
s = compiled.match(data = dll_data)
for entry in s['main'][0]['strings']:
cc = dll_data[entry['offset']:entry['offset']+len(entry['data'])].decode('utf-16')
c2.append(cc)
return {'c2': c2}
示例15: init_elf
# 需要导入模块: from elftools.elf import elffile [as 别名]
# 或者: from elftools.elf.elffile import ELFFile [as 别名]
def init_elf(self, filename):
if 'ELFFile' not in globals():
raise Exception('emu_helper: Please install pyelftools before loading ELF binaries')
self.elf = ELFFile(open(filename, 'rb'))
# loadable segments
segs = filter(lambda x: x.header.p_type == 'PT_LOAD', self.elf.iter_segments())
self.base = min(map(lambda x: x.header.p_vaddr, segs))
# FIXME
self.set_mode(UC_MODE_64)
self.mu = Uc(UC_ARCH_X86, self.mode)
mem_top = self.base
for seg in segs:
va = seg.header.p_vaddr
vbot = va & ~0xfff
vtop = (seg.header.p_vaddr + seg.header.p_memsz + 0xfff) & ~0xfff
print 'map 0x%08x .. 0x%08x' % (vbot, vtop)
self.mu.mem_map(vbot, vtop - vbot)
self.mu.mem_write(va, seg.data())
mem_top = max(mem_top, vtop)
self.shim_base = mem_top
self.stack_len = 0x10000
print 'shim_base at: 0x%08x' % self.shim_base
self.mu.mem_map(self.shim_base, self.shim_len + self.stack_len)
self.rsp0 = self.shim_base + self.shim_len + self.stack_len
self.init_stack()