How to use the lief.PE.parse function in lief

To help you get started, we’ve selected a few lief examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lief-project / LIEF / tests / api / test_python.py View on Github external
self.assertIsNotNone(ls.abstract.header)

        with io_open(lspath, 'r') as f:
            ls = lief.parse(f)
            self.assertIsNotNone(ls.abstract.header)

        with io_open(lspath, 'rb') as f:
            ls = lief.parse(f)
            self.assertIsNotNone(ls.abstract.header)

        with io_open(lspath, 'rb') as f:
            ls = lief.ELF.parse(f)
            self.assertIsNotNone(ls.abstract.header)

        with io_open(get_sample('PE/PE64_x86-64_binary_HelloWorld.exe'), 'rb') as f:
            binary = lief.PE.parse(f)
            self.assertIsNotNone(binary.abstract.header)

        with io_open(get_sample('MachO/MachO64_x86-64_binary_dd.bin'), 'rb') as f:
            binary = lief.MachO.parse(f)[0]
            self.assertIsNotNone(binary.abstract.header)

        with open(lspath, 'rb') as f:  # As bytes
            ls = lief.parse(f.read())
            self.assertIsNotNone(ls.abstract.header)

        with open(lspath, 'rb') as f:  # As io.BufferedReader
            ls = lief.parse(f)
            self.assertIsNotNone(ls.abstract.header)

        with open(lspath, 'rb') as f:  # As io.BytesIO object
            bytes_stream = io.BytesIO(f.read())
github lief-project / LIEF / examples / python / pe_reader.py View on Github external
optparser.add_option('--exception-functions',
            action='store_true', dest='show_pfunctions',
            help='Display functions found in the exception directory')



    options, args = optparser.parse_args()

    if len(args) == 0:
        optparser.print_help()
        sys.exit(1)

    binary = None
    try:
        binary = PE.parse(args[0])
    except lief.exception as e:
        print(e)
        sys.exit(1)


    print_information(binary)

    if options.show_data_directories or options.show_all:
        print_data_directories(binary)

    if options.show_headers or options.show_all:
        print_header(binary)

    if (options.show_imports or options.show_all) and binary.has_imports:
        print_imports(binary, resolve=options.resolve_ordinals)
github endgameinc / gym-malware / gym_malware / envs / controls / manipulate2.py View on Github external
# FAILS if there's insufficient room to add to the section 
    print('section_append')
    manip = MalwareManipulator(bytez)    
    bytez2 = manip.section_append(bytez)
    binary2 = lief.PE.parse(bytez2)
    oldsections = [len(s.content) for s in binary.sections]
    newsections = [len(s.content) for s in binary2.sections]
    print(oldsections)
    print(newsections)
    assert sum(newsections) != sum(oldsections), "no appended section"

    print('create_new_entry') # note: also adds a new section
    manip = MalwareManipulator(bytez)    
    bytez2 = manip.create_new_entry(bytez)
    binary2 = lief.PE.parse(bytez2)
    print(binary.entrypoint)
    print(binary2.entrypoint)
    assert binary.entrypoint != binary2.entrypoint, "no new entry point"

    print('remove_signature')
    manip = MalwareManipulator(bytez)    
    bytez2 = manip.remove_signature(bytez)
    binary2 = lief.PE.parse(bytez2)
    if binary.has_signature:
        assert binary2.has_signature == False, "failed to remove signature"

    print('remove_debug')
    manip = MalwareManipulator(bytez)    
    bytez2 = manip.remove_debug(bytez)
    binary2 = lief.PE.parse(bytez2)
    if binary.has_debug:
github endgameinc / gym-malware / gym_malware / envs / controls / manipulate2.py View on Github external
print('section_add')
    manip = MalwareManipulator(bytez)    
    bytez2 = manip.section_add(bytez)
    binary2 = lief.PE.parse(bytez2)
    oldsections = [s.name for s in binary.sections]
    newsections = [s.name for s in binary2.sections]
    print(oldsections)
    print(newsections)
    assert len(newsections) != len(oldsections), "no new sections"

    # FAILS if there's insufficient room to add to the section 
    print('section_append')
    manip = MalwareManipulator(bytez)    
    bytez2 = manip.section_append(bytez)
    binary2 = lief.PE.parse(bytez2)
    oldsections = [len(s.content) for s in binary.sections]
    newsections = [len(s.content) for s in binary2.sections]
    print(oldsections)
    print(newsections)
    assert sum(newsections) != sum(oldsections), "no appended section"

    print('create_new_entry') # note: also adds a new section
    manip = MalwareManipulator(bytez)    
    bytez2 = manip.create_new_entry(bytez)
    binary2 = lief.PE.parse(bytez2)
    print(binary.entrypoint)
    print(binary2.entrypoint)
    assert binary.entrypoint != binary2.entrypoint, "no new entry point"

    print('remove_signature')
    manip = MalwareManipulator(bytez)
github evilsocket / ergo-pe-av / encoder.py View on Github external
def encode_pe(filepath):
    log.debug("encoding %s ...", filepath)

    if hasattr(filepath, 'read'):
        raw = filepath.read()
        
    else:
        with open(filepath, 'rb') as fp:
            raw = fp.read()
    
    sz       = len(raw)
    pe       = lief.PE.parse(list(raw)) 
    ep_bytes = [0] * 64
    try:
        ep_offset = pe.entrypoint - pe.optional_header.imagebase
        ep_bytes  = [int(b) for b in raw[ep_offset:ep_offset+64]]
    except Exception as e:
        log.warning("can't get entrypoint bytes from %s: %s", filepath, e)

    v = np.concatenate([ \
        encode_properties(pe),
        encode_entrypoint(ep_bytes),
        encode_histogram(raw),
        encode_libraries(pe),
        [ min(sz, pe.virtual_size) / max(sz, pe.virtual_size)],
        encode_sections(pe)
    ])
github h2oai / driverlessai-recipes / transformers / executables / pe_section_characteristics.py View on Github external
def get_section_characteristics(self, file_path):
        import lief
        try:
            pe_bytez = self.load_pe(file_path) 
            lief_binary = lief.PE.parse(list(pe_bytez))
            X = self.section_features(lief_binary)
        
            return X

        except:
            X = np.zeros(92, dtype=np.float32)

            return X
github conda / conda-build / conda_build / os_utils / liefldd.py View on Github external
obj_ends = sorted(list(obj_ends))[1:]
        if debug_static_archives > 1:
            print('obj_starts: {}'.format(" ".join('0x{:05x}'.format(o) for o in obj_starts)))
        if debug_static_archives > 1:
            print('  obj_ends: {}'.format(" ".join('0x{:05x}'.format(o) for o in obj_ends)))
        for obj_start, obj_end in zip(obj_starts, obj_ends):
            IMAGE_FILE_MACHINE_I386 = 0x014c
            IMAGE_FILE_MACHINE_AMD64 = 0x8664
            MACHINE_TYPE, = struct.unpack(' 0:
                print(hex(obj_start), hex(obj_end), obj_end - obj_start)
            if MACHINE_TYPE in (IMAGE_FILE_MACHINE_I386, IMAGE_FILE_MACHINE_AMD64):
                # 'This file is not a PE binary' (yeah, fair enough, it's a COFF file).
                # Reported at https://github.com/lief-project/LIEF/issues/233#issuecomment-452580391
                try:
                    obj = lief.PE.parse(raw=content[obj_start:obj_end - 1])
                except:
                    if debug_static_archives > 0:
                        print("get_static_lib_exports failed, PECOFF not supported by LIEF nor pyldd.")
                    pass
                    obj = None
            elif MACHINE_TYPE == 0xfacf:
                obj = lief.parse(raw=content[obj_start:obj_end])

                # filename = '/Users/rdonnelly/conda/conda-build/macOS-libpython2.7.a/getbuildinfo.o'
                # obj = lief.parse(filename)
                # syms_a = get_symbols(obj, defined=True, undefined=False)
                # obj = lief.parse(filename)
                # syms_b = get_symbols(obj, defined=True, undefined=False)
                # print(syms_b)
            else:
                obj = lief.ELF.parse(raw=content[obj_start:obj_end])
github MISP / PyMISP / pymisp / tools / peobject.py View on Github external
def __init__(self, parsed=None, filepath=None, pseudofile=None, standalone=True, **kwargs):
        # Python3 way
        # super().__init__('pe')
        super(PEObject, self).__init__('pe', standalone=standalone, **kwargs)
        if not HAS_PYDEEP:
            logger.warning("Please install pydeep: pip install git+https://github.com/kbandla/pydeep.git")
        if not HAS_LIEF:
            raise ImportError('Please install lief, documentation here: https://github.com/lief-project/LIEF')
        if pseudofile:
            if isinstance(pseudofile, BytesIO):
                self.__pe = lief.PE.parse(raw=pseudofile.getvalue())
            elif isinstance(pseudofile, bytes):
                self.__pe = lief.PE.parse(raw=pseudofile)
            else:
                raise InvalidMISPObject('Pseudo file can be BytesIO or bytes got {}'.format(type(pseudofile)))
        elif filepath:
            self.__pe = lief.PE.parse(filepath)
        elif parsed:
            # Got an already parsed blob
            if isinstance(parsed, lief.PE.Binary):
                self.__pe = parsed
            else:
                raise InvalidMISPObject('Not a lief.PE.Binary: {}'.format(type(parsed)))
        self.generate_attributes()
github MISP / PyMISP / pymisp / tools / peobject.py View on Github external
def __init__(self, parsed=None, filepath=None, pseudofile=None, standalone=True, **kwargs):
        # Python3 way
        # super().__init__('pe')
        super(PEObject, self).__init__('pe', standalone=standalone, **kwargs)
        if not HAS_PYDEEP:
            logger.warning("Please install pydeep: pip install git+https://github.com/kbandla/pydeep.git")
        if not HAS_LIEF:
            raise ImportError('Please install lief, documentation here: https://github.com/lief-project/LIEF')
        if pseudofile:
            if isinstance(pseudofile, BytesIO):
                self.__pe = lief.PE.parse(raw=pseudofile.getvalue())
            elif isinstance(pseudofile, bytes):
                self.__pe = lief.PE.parse(raw=pseudofile)
            else:
                raise InvalidMISPObject('Pseudo file can be BytesIO or bytes got {}'.format(type(pseudofile)))
        elif filepath:
            self.__pe = lief.PE.parse(filepath)
        elif parsed:
            # Got an already parsed blob
            if isinstance(parsed, lief.PE.Binary):
                self.__pe = parsed
            else:
                raise InvalidMISPObject('Not a lief.PE.Binary: {}'.format(type(parsed)))
        self.generate_attributes()
github endgameinc / gym-malware / gym_malware / envs / controls / manipulate2.py View on Github external
def break_optional_header_checksum(self, seed=None):
        binary = lief.PE.parse(self.bytez)
        binary.optional_header.checksum = 0
        self.bytez = self.__binary_to_bytez(binary)
        return self.bytez