当前位置: 首页>>代码示例>>Python>>正文


Python lief.parse方法代码示例

本文整理汇总了Python中lief.parse方法的典型用法代码示例。如果您正苦于以下问题:Python lief.parse方法的具体用法?Python lief.parse怎么用?Python lief.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lief的用法示例。


在下文中一共展示了lief.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: find_main_arena

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def find_main_arena(libc_file):
	binary = lief.parse(libc_file)
	section = binary.get_section(".data")
	data = bytearray(section.content)
	m_type = binary.header.machine_type
	arch_info = machine_types.get(m_type)

	if arch_info is None:
		return None

	u_fmt, ptr_size = arch_info

	ea = 0
	while ea < section.size:
		ptr = unpack(u_fmt, data[ea:ea+ptr_size])[0]
		offset = ptr-section.virtual_address
		if offset < ea:
			if (ea-offset) in offsets[ptr_size]:
				return ptr
		ea += ptr_size
	return None 
开发者ID:danigargu,项目名称:heap-viewer,代码行数:23,代码来源:main_arena_lief.py

示例2: scan

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def scan(self, payload: Payload, request: Request) -> WorkerResponse:
        """
        Scan a payload using LIEF

        """
        filename = payload.results.payload_meta.extra_data.get(
            'filename', payload.results.payload_id
        )

        try:
            binary = lief.parse(raw=payload.content, name=filename)
        except lief.exception as err:
            raise StoqPluginException(f'Unable to parse payload: {err}')

        if binary is None:
            raise StoqPluginException('The file type isn\'t supported by LIEF')

        if self.abstract == True:
            results = lief.to_json_from_abstract(binary.abstract)
        else:
            results = lief.to_json(binary)

        return WorkerResponse(json.loads(results)) 
开发者ID:PUNCH-Cyber,项目名称:stoq-plugins-public,代码行数:25,代码来源:lief.py

示例3: _analyze_elf

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def _analyze_elf(self, file_object):
        elf_dict = {}
        try:
            parsed_binary = lief.parse(file_object.file_path)
            binary_json_dict = json.loads(lief.to_json_from_abstract(parsed_binary))
            if parsed_binary.exported_functions:
                binary_json_dict['exported_functions'] = normalize_lief_items(parsed_binary.exported_functions)
            if parsed_binary.imported_functions:
                binary_json_dict['imported_functions'] = normalize_lief_items(parsed_binary.imported_functions)
            if parsed_binary.libraries:
                binary_json_dict['libraries'] = normalize_lief_items(parsed_binary.libraries)
        except (TypeError, lief.bad_file) as error:
            logging.error('Bad file for lief/elf analysis {}. {}'.format(file_object.uid, error))
            return elf_dict

        self.get_final_analysis_dict(binary_json_dict, elf_dict)
        return elf_dict, parsed_binary 
开发者ID:fkie-cad,项目名称:FACT_core,代码行数:19,代码来源:elf_analysis.py

示例4: _verify_file

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def _verify_file(self, filename):
        self._filename = filename
        self._binary = lief.parse(filename)

        if not self._binary:
            self._output.info('file "%s" is not a executable, skipping...' % filename)
            return

        if self._binary.format != self._expected_format:
            self._output.error('"%s" invalid executable format %s, expected %s'
                               % (self._filename, self._binary.format, self._expected_format))
            return

        self._binary = self._binary.concrete
        self._output.info('checking file "%s"' % filename)

        {
            lief.EXE_FORMATS.ELF: self._verify_elf,
            lief.EXE_FORMATS.PE: self._verify_pe,
            lief.EXE_FORMATS.MACHO: self._verify_macho
        }.get(self._binary.format)()

        if self._shared is not None and not self._shared:
            if self._is_shared_library:
                self._output.error('"%s" is shared library, but option "shared" is set to "False"' % self._filename) 
开发者ID:conan-io,项目名称:hooks,代码行数:27,代码来源:binary_linter.py

示例5: peloader

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def peloader(exe_file, emu, verbose=False):
    """ Load a .exe file into emu's memory using LIEF """
    pefile = lief.parse(exe_file)
    if verbose:
        print(f"[x] Loading .exe ...")

    imagebase = pefile.optional_header.imagebase
    for section in pefile.sections:
        if verbose:
            print(
                f"[=] Writing {section.name} on {imagebase+section.virtual_address:x} - {imagebase+section.virtual_address+section.size:x}"
            )
        emu.map_space(imagebase+section.virtual_address, imagebase+section.virtual_address + section.size)
        emu.emu.mem_write(imagebase+section.virtual_address, bytes(section.content))

    emu.functions = {}

    ## Handle relocations
    for r in pefile.relocations:
        if r.symbol.is_function:
            if r.symbol.value == 0:
                rsv = r.address - (r.address & 1)
            else:
                rsv = r.symbol.value - (r.symbol.value & 1)
            emu.functions[r.symbol.name] = rsv
            if verbose:
                print(f"Relocating {r.symbol.name} at {r.address:x} to {rsv:x}")
            emu[r.address] = rsv

    emu.function_names = {emu.functions[x]: x for x in emu.functions.keys()}
    return pefile.entrypoint 
开发者ID:Ledger-Donjon,项目名称:rainbow,代码行数:33,代码来源:peloader.py

示例6: __get_imports_with_library

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def __get_imports_with_library(self, filepath):
        """
            Helper function to get the list of imported function calls for a binary
        :param filepath: binary's absolute filepath
        :return: the list of functions called/imported appended by their libraries.
        """
        binary = lief.parse(filepath)
        return [lib.name.lower() + ':' + e.name for lib in binary.imports for e in lib.entries] 
开发者ID:ALFA-group,项目名称:robust-adv-malware-detection,代码行数:10,代码来源:datasets.py

示例7: __init__

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def __init__(self, binaryPath):
        self.binary = lief.parse(binaryPath)
        self.section = self.binary.get_section(".rdata")
        self.imgBase = self.binary.optional_header.imagebase
        self.ptr_size = 8 if self.binary.header.machine == lief.PE.MACHINE_TYPES.AMD64 else 4
        self.content = self.section.content
        self.sectionAddr = self.imgBase + self.section.virtual_address
        self.pattern = b'W\x00N\x00F\x00_\x00' # key pattern used to find th wnf table

        self.tableAddr = self.SearchForTable()


    # Small generator providing the addresses of strings containing the [pattern] 
开发者ID:ionescu007,项目名称:wnfun,代码行数:15,代码来源:WnfNameDumper.py

示例8: load_binary

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def load_binary(self):
        import lief
        binary = lief.parse(GdbUtil().file)
        phdrs = binary.segments
        for phdr in phdrs:
            size = phdr.physical_size
            vaddr = phdr.virtual_address
            self.log('[+] Loading 0x%06x - 0x%06x' % (vaddr, vaddr + size))
            TritonContext.setConcreteMemoryAreaValue(vaddr, phdr.content) 
开发者ID:SQLab,项目名称:symgdb,代码行数:11,代码来源:symgdb.py

示例9: evaluateImportTable

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def evaluateImportTable(self, binary, is_unmapped=True):
        self._binary_length = len(binary)
        results = {"import_table": []}
        if lief:
            lief_binary = lief.parse(bytearray(binary))
            bitness = 32 if lief_binary.header.machine == lief.PE.MACHINE_TYPES.I386 else 64
            for imported_library in lief_binary.imports:
                for func in imported_library.entries:
                    if func.name:
                        results["import_table"].append((func.iat_address + self.load_offset, 0xFFFFFFFF, imported_library.name.lower() + "_0x0", func.name, bitness, True, 1))
        else:
            # fallback using the old method and out own import table parser
            mapped_binary = binary
            if is_unmapped:
                LOG.debug("Mapping unmapped binary before processing")
                mapped_binary = PeTools.mapBinary(binary)
            bitness = PeTools.getBitness(mapped_binary)
            self._import_table = None
            self._parseImportTable(mapped_binary)
            references = self._getCodeReferences(mapped_binary)
            for offset, import_entry in sorted(self._import_table.items()):
                ref_count = 1
                if bitness:
                    ref_count = 1 + references[bitness][offset] if offset in references[bitness] else 1
                results["import_table"].append((offset + self.load_offset, 0xFFFFFFFF, import_entry["dll_name"].lower() + "_0x0", import_entry["name"], bitness, True, ref_count))
        return results 
开发者ID:danielplohmann,项目名称:apiscout,代码行数:28,代码来源:ApiScout.py

示例10: get_imphash

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def get_imphash(file_object):
    if _is_elf_file(file_object):
        try:
            with suppress_stdout():
                functions = normalize_lief_items(lief.parse(file_object.file_path).imported_functions)
            return md5(','.join(sorted(functions)).encode()).hexdigest()
        except Exception:
            logging.error('Could not compute imphash for {}'.format(file_object.file_path), exc_info=True)
    return None 
开发者ID:fkie-cad,项目名称:FACT_core,代码行数:11,代码来源:hash.py

示例11: process_object

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def process_object(self, file_object):
        try:
            elf_dict, parsed_binary = self._analyze_elf(file_object)
            file_object.processed_analysis[self.NAME] = {'Output': elf_dict}
            self.create_tags(parsed_binary, file_object)
            file_object.processed_analysis[self.NAME]['summary'] = list(elf_dict.keys())
        except RuntimeError:
            logging.error('lief could not parse {}'.format(file_object.uid))
            file_object.processed_analysis[self.NAME] = {'Output': {}}
        return file_object 
开发者ID:fkie-cad,项目名称:FACT_core,代码行数:12,代码来源:elf_analysis.py

示例12: getCodeAreas

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def getCodeAreas(binary):
        pefile = lief.parse(bytearray(binary))
        code_areas = []
        base_address = PeFileLoader.getBaseAddress(binary)
        if pefile and pefile.sections:
            for section in pefile.sections:
                if section.characteristics & lief.PE.SECTION_CHARACTERISTICS.MEM_EXECUTE:
                    section_start = base_address + section.virtual_address
                    section_size = section.virtual_size
                    if section_size % 0x1000 != 0:
                        section_size += 0x1000 - (section_size % 0x1000)
                    section_end = section_start + section_size
                    code_areas.append([section_start, section_end])
        return PeFileLoader.mergeCodeAreas(code_areas) 
开发者ID:danielplohmann,项目名称:smda,代码行数:16,代码来源:PeFileLoader.py

示例13: getBaseAddress

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def getBaseAddress(binary):
        elffile = lief.parse(bytearray(binary))
        # Determine base address of binary
        #
        base_addr = 0
        candidates = [0xFFFFFFFFFFFFFFFF]
        for section in elffile.sections:
            if section.virtual_address:
                candidates.append(section.virtual_address - section.offset)
        if len(candidates) > 1:
            base_addr = min(candidates)
        return base_addr 
开发者ID:danielplohmann,项目名称:smda,代码行数:14,代码来源:ElfFileLoader.py

示例14: mapBinary

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def mapBinary(binary):
        # ELFFile needs a file-like object...
        # Attention: for Python 2.x use the cStringIO package for StringIO
        elffile = lief.parse(bytearray(binary))
        base_addr = ElfFileLoader.getBaseAddress(binary)
        LOGGER.debug("Assuming base address 0x%x for inference of reference counts (based on ELF header)", base_addr)

        # find begin of the first and end of the last section
        max_virt_section_offset = 0
        min_raw_section_offset = 0xFFFFFFFFFFFFFFFF
        for section in elffile.sections:
            # print("{:20s} 0x{:08x} - 0x{:08x} / 0x{:08x}".format(section.name, section.header.sh_addr, section.header.sh_offset, section.header.sh_size))
            if section.virtual_address:
                max_virt_section_offset = max(max_virt_section_offset, section.size + section.virtual_address)
                min_raw_section_offset = min(min_raw_section_offset, section.virtual_address)

        # copy binary to mapped_binary
        if max_virt_section_offset:
            mapped_binary = bytearray([0] * (max_virt_section_offset - base_addr))
            mapped_binary[0:min_raw_section_offset] = binary[0:min_raw_section_offset]
        for section in elffile.sections:
            if section.virtual_address:
                rva = section.virtual_address - base_addr
                mapped_binary[rva:rva + section.size] = section.content

        return bytes(mapped_binary) 
开发者ID:danielplohmann,项目名称:smda,代码行数:28,代码来源:ElfFileLoader.py

示例15: getBitness

# 需要导入模块: import lief [as 别名]
# 或者: from lief import parse [as 别名]
def getBitness(binary):
        # TODO add machine types whenever we add more architectures
        elffile = lief.parse(bytearray(binary))
        machine_type = elffile.header.machine_type
        if machine_type == lief.ELF.ARCH.x86_64:
            return 64
        elif machine_type == lief.ELF.ARCH.i386:
            return 32
        return 0 
开发者ID:danielplohmann,项目名称:smda,代码行数:11,代码来源:ElfFileLoader.py


注:本文中的lief.parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。