Python pefile.PEFormatError() Examples

The following are 16 code examples of pefile.PEFormatError(). 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 pefile , or try the search function .
Example #1
Source File: static.py    From mac-a-mal-cuckoo with MIT License 6 votes vote down vote up
def run(self):
        """Run analysis.
        @return: analysis results dict or None.
        """
        if not os.path.exists(self.file_path):
            return {}

        try:
            self.pe = pefile.PE(self.file_path)
        except pefile.PEFormatError:
            return {}

        results = {}
        results["peid_signatures"] = self._get_peid_signatures()
        results["pe_imports"] = self._get_imported_symbols()
        results["pe_exports"] = self._get_exported_symbols()
        results["pe_sections"] = self._get_sections()
        results["pe_resources"] = self._get_resources()
        results["pe_versioninfo"] = self._get_versioninfo()
        results["pe_imphash"] = self._get_imphash()
        results["pe_timestamp"] = self._get_timestamp()
        results["pdb_path"] = self._get_pdb_path()
        results["signature"] = self._get_signature()
        results["imported_dll_count"] = len([x for x in results["pe_imports"] if x.get("dll")])
        return results 
Example #2
Source File: static.py    From CuckooSploit with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        """Run analysis.
        @return: analysis results dict or None.
        """
        if not os.path.exists(self.file_path):
            return None

        try:
            self.pe = pefile.PE(self.file_path)
        except pefile.PEFormatError:
            return None

        results = {}
        results["peid_signatures"] = self._get_peid_signatures()
        results["pe_imports"] = self._get_imported_symbols()
        results["pe_exports"] = self._get_exported_symbols()
        results["pe_sections"] = self._get_sections()
        results["pe_resources"] = self._get_resources()
        results["pe_versioninfo"] = self._get_versioninfo()
        results["pe_imphash"] = self._get_imphash()
        results["pe_timestamp"] = self._get_timestamp()
        results["imported_dll_count"] = len([x for x in results["pe_imports"] if x.get("dll")])
        return results 
Example #3
Source File: PEFileModule.py    From codex-backend with MIT License 6 votes vote down vote up
def initialize(self, sample):
        if(self.already_initialized):
            return self.library
        self.already_initialized = True
        try:
            self.library = pefile.PE(data=sample.getBinary(), fast_load=True)
            # see if this initializations can be done on plugins.
            self.library.parse_data_directories(directories=[
                pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT'],
                pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_EXPORT'],
                pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_TLS'],
                pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY'],
                pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_RESOURCE']])

        except pefile.PEFormatError:
            # print("parse fail")
            self.library = None
            # print(traceback.format_exc())
            logging.error("Error parsing pefileModule with sample:%s",
                          sample.getID(), exc_info=True) 
Example #4
Source File: bindiff.py    From ida_haru with Apache License 2.0 5 votes vote down vote up
def _get_machine_type(self, path):
        try:
            pe = pefile.PE(path)
            format_ = 'PE'
            if pefile.MACHINE_TYPE[pe.FILE_HEADER.Machine].find('I386') != -1:
                arch = '32-bit'
            else:
                arch = '64-bit'
        except pefile.PEFormatError, detail:
            try:
                self._dprint(detail)
                m = MachO(path)
                format_ = 'Mach-O'
                for header in m.headers:
                    if CPU_TYPE_NAMES.get(header.header.cputype,header.header.cputype) == 'x86_64':
                    #if header.MH_MAGIC == MH_MAGIC_64:
                        arch = '64-bit'
                    else:
                        arch = '32-bit'
            except:
                try:
                    elffile = ELFFile(open(path, 'rb'))
                    format_ = 'ELF'
                    e_ident = elffile.header['e_ident']
                    if e_ident['EI_CLASS'] == 'ELFCLASS64':
                        arch = '64-bit'
                    else:
                        arch = '32-bit'
                except:                    
                    return None, None
                    #format_ = 'shellcode'
                    #arch = '32-bit' # 32-bit fixed 
Example #5
Source File: pe.py    From CIRTKit with MIT License 5 votes vote down vote up
def __check_session(self):
        if not __sessions__.is_set():
            self.log('error', "No session opened")
            return False

        if not self.pe:
            try:
                self.pe = pefile.PE(__sessions__.current.file.path)
            except pefile.PEFormatError as e:
                self.log('error', "Unable to parse PE file: {0}".format(e))
                return False

        return True 
Example #6
Source File: graphityUtils.py    From r2graphity with MIT License 5 votes vote down vote up
def getAllAttributes(path):
	
	allAtts = {}
	
	allAtts['md5'] = md5hash(path)
	allAtts['sha1'] = sha1hash(path)
	allAtts['filename'] = getFilename(path)
	allAtts['filetype'] = getFiletype(path)
	allAtts['ssdeep'] = getSsdeep(path)
	allAtts['filesize'] = getFilesize(path)
	
	try:
		pe = pefile.PE(path)
		if (pe.DOS_HEADER.e_magic == int(0x5a4d) and pe.NT_HEADERS.Signature == int(0x4550)):
			allAtts['imphash'] = getImphash(pe)
			allAtts['compilationts'] = getCompilationTS(pe)
			allAtts['addressep'] = getEPAddress(pe)
			allAtts['sectionep'] = getEPSection(pe)
			allAtts['sectioncount'] = getSectionCount(pe)
			allAtts['sectioninfo'] = getSectionInfo(pe)
			allAtts['tlssections'] = getTLSSectionCount(pe)
			allAtts['originalfilename'] = getOriginalFilename(pe)
	
	except (pefile.PEFormatError):
		pass
	
	return allAtts 
Example #7
Source File: PEHeaderReader.py    From codex-backend with MIT License 5 votes vote down vote up
def getArquitecture(self):
        try:

            if(self.pe.OPTIONAL_HEADER.Magic == int("0x020B", 16)):
                return ("PE+")
            elif(self.pe.OPTIONAL_HEADER.Magic == int("0x010B", 16)):
                return ("PE")
            elif(self.pe.OPTIONAL_HEADER.Magic == int("0x0107", 16)):
                return ("IMG_ROM")
            else:
                return "UNKNOWN"
        except pefile.PEFormatError:
            return "FORMAT"

        return None 
Example #8
Source File: binary.py    From EasyROP with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file_name):
        try:
            self._binary = Pe(file_name)
        except PEFormatError:
            print("%s: '%s': Not a PE file" % (os.path.basename(__main__.__file__), os.path.realpath(file_name)))
            raise BinaryException 
Example #9
Source File: pefile_test.py    From pefile with MIT License 5 votes vote down vote up
def test_nt_headers_exception(self):
        """pefile should fail parsing invalid data (missing NT headers)"""

        # Take a known good file.
        control_file = os.path.join(REGRESSION_TESTS_DIR, 'MSVBVM60.DLL')
        pe = pefile.PE(control_file, fast_load=True)

        # Truncate it at the PE header and add invalid data.
        pe_header_offest = pe.DOS_HEADER.e_lfanew
        corrupted_data = pe.__data__[:pe_header_offest] + b'\0' * (1024*10)

        self.assertRaises(pefile.PEFormatError, pefile.PE, data=corrupted_data) 
Example #10
Source File: pefile_test.py    From pefile with MIT License 5 votes vote down vote up
def test_dos_header_exception_large_data(self):
        """pefile should fail parsing 10KiB of invalid data
        (missing DOS header).
        """

        # Generate 10KiB of zeroes
        data = b'\0' * (1024*10)

        # Attempt to parse data and verify PE header, a PEFormatError exception
        # is thrown.
        self.assertRaises(pefile.PEFormatError, pefile.PE, data=data) 
Example #11
Source File: pefile_test.py    From pefile with MIT License 5 votes vote down vote up
def test_dos_header_exception_small_data(self):
        """pefile should fail parsing 64 bytes of invalid data
        (missing DOS header).
        """

        # Generate 64 bytes of zeroes
        data = b'\0' * (64)

        # Attempt to parse data and verify PE header a PEFormatError exception
        # is thrown.
        self.assertRaises(pefile.PEFormatError, pefile.PE, data=data) 
Example #12
Source File: pefile_test.py    From pefile with MIT License 5 votes vote down vote up
def test_empty_file_exception(self):
        """pefile should fail parsing empty files."""

        # Take a known good file
        control_file = os.path.join(REGRESSION_TESTS_DIR, 'empty_file')
        self.assertRaises(pefile.PEFormatError, pefile.PE, control_file) 
Example #13
Source File: make_sc_hash_db.py    From flare-ida with Apache License 2.0 5 votes vote down vote up
def processDir(self, dirName):
        for fName in os.listdir(dirName):
            filePath = os.path.join(dirName, fName)
            if not os.path.isfile(filePath):
                #print "Could not find file: %s. Skipping" % fName
                continue
            try:
                peFile = pefile.PE(filePath)
                if ((not hasattr(peFile, "DIRECTORY_ENTRY_EXPORT")) or (peFile.DIRECTORY_ENTRY_EXPORT is None)):
                    if VERBOSE:
                        print "No exports: %s" % filePath
                else:
                    #add the library to the lib table
                    print "Processing file %s" % filePath
                    time1 = time.time()
                    libKey = self.addSourceLib(fName)
                    symCount = 0
                    for sym in peFile.DIRECTORY_ENTRY_EXPORT.symbols:
                        if sym.name is not None:
                            symCount += 1
                            for hashName in self.hashes.keys():
                                hashType, hashMeth = self.hashes[hashName]
                                #print "Trying to hash: %s:%s" % (hashName, sym.name)
                                symHash = hashMeth(sym.name,fName)
                                #print " Done hashing: %08x:%s" % (symHash, sym.name)
                                if symHash is not None:
                                    self.addSymbolHash(symHash, hashType, libKey, sym.name)
                    #commit outstanding transaction
                    self.conn.commit()
                    time2 = time.time()
                    timeDiff = time2 - time1
                    print "Processed %d export symbols in %.02f seconds: %s" % (symCount, timeDiff, filePath)

            except pefile.PEFormatError, err:
                if VERBOSE:
                    print "Skipping non-PE file %s: %s" % (filePath, str(err))
            except Exception, err:
                if VERBOSE:
                    print "Skipping %s: %s" % (filePath, str(err))
                raise 
Example #14
Source File: PEFile.py    From multiscanner with Mozilla Public License 2.0 5 votes vote down vote up
def _get_rich_header(pe):
    rich_hdr = pe.parse_rich_header()
    if not rich_hdr:
        return (None, None)
    data = {"raw": str(rich_hdr['values'])}
    richchecksum = hex(rich_hdr['checksum'])
    # self._add_result('rich_header', hex(rich_hdr['checksum']), data)

    # Generate a signature of the block. Need to apply checksum
    # appropriately. The hash here is sha256 because others are using
    # that here.
    #
    # Most of this code was taken from pefile but modified to work
    # on the start and checksum blocks.
    try:
        rich_data = pe.get_data(0x80, 0x80)
        if len(rich_data) != 0x80:
            return (richchecksum, None)
        data = list(struct.unpack("<32I", rich_data))
    except pefile.PEFormatError as e:
        return (richchecksum, None)

    checksum = data[1]
    headervalues = []

    for i in xrange(len(data) // 2):
        if data[2 * i] == 0x68636952:  # Rich
            if data[2 * i + 1] != checksum:
                # self._parse_error('Rich Header corrupted')
                return (richchecksum, None)
            break
        headervalues += [data[2 * i] ^ checksum, data[2 * i + 1] ^ checksum]

    sha_256 = hashlib.sha256()
    for hv in headervalues:
        sha_256.update(struct.pack('<I', hv))
    return (richchecksum, sha_256.hexdigest()) 
Example #15
Source File: windows_memory_patches.py    From MemoryPatchDetector with MIT License 5 votes vote down vote up
def get_relocations(pe, proc, module_base_address):
    try:
        relocations = []
        relocation_table = pe.NT_HEADERS.OPTIONAL_HEADER.DATA_DIRECTORY[
            pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_BASERELOC']]
        rva = relocation_table.VirtualAddress
        size = relocation_table.Size

        if size == 0:
            return []

        rlc_size = pefile.Structure(pe.__IMAGE_BASE_RELOCATION_format__).sizeof()
        end = rva + size
        while rva < end:
            try:
                rlc = pe.__unpack_data__(
                    pe.__IMAGE_BASE_RELOCATION_format__,
                    proc.read(module_base_address + rva, rlc_size),
                    file_offset=pe.get_offset_from_rva(rva))
            except pefile.PEFormatError:
                rlc = None

            if not rlc:
                break
            relocation_entries = parse_relocations(proc, module_base_address, pe, rva + rlc_size, rlc.VirtualAddress,
                                                   rlc.SizeOfBlock - rlc_size)

            relocations.append(
                pefile.BaseRelocationData(
                    struct=rlc,
                    entries=relocation_entries))

            if not rlc.SizeOfBlock:
                break
            rva += rlc.SizeOfBlock

        return relocations
    except Exception as ex:
        print(str(ex)) 
Example #16
Source File: ResourceEntriesPlug.py    From codex-backend with MIT License 4 votes vote down vote up
def process(self):
        pelib = self._getLibrary(PEFileModule().getName())
        if(pelib is None):
            return ""

        ret = []
        if hasattr(pelib, 'DIRECTORY_ENTRY_RESOURCE'):
            i = 0
            for resource_type in pelib.DIRECTORY_ENTRY_RESOURCE.entries:
                if resource_type.name is not None:
                    name = "%s" % resource_type.name
                else:
                    name = "%s" % pefile.RESOURCE_TYPE.get(
                        resource_type.struct.Id)
                if name is None:
                    name = "%d" % resource_type.struct.Id
                if hasattr(resource_type, 'directory'):
                    for resource_id in resource_type.directory.entries:
                        if hasattr(resource_id, 'directory'):
                            for resource_lang in resource_id.directory.entries:
                                try:
                                    data = pelib.get_data(
                                        resource_lang.data.struct.OffsetToData, resource_lang.data.struct.Size)
                                    # fd=open(name,'wb')
                                    # fd.write(data)
                                    # (data)
                                except pefile.PEFormatError:
                                    return "corrupt"
                                filetype = MIME_TYPE(data, False)
                                lang = pefile.LANG.get(
                                    resource_lang.data.lang, 'unknown')
                                sublang = pefile.get_sublang_name_for_lang(
                                    resource_lang.data.lang, resource_lang.data.sublang)
                                entry = {}
                                entry["name"] = self._normalize(name)
                                entry["rva"] = self._normalize(
                                    hex(resource_lang.data.struct.OffsetToData))
                                entry["size"] = self._normalize(
                                    hex(resource_lang.data.struct.Size))
                                entry["type"] = self._normalize(filetype)
                                entry["lang"] = self._normalize(lang)
                                entry["sublang"] = self._normalize(sublang)
                                entry["sha1"] = SHA1(data)
                                ret.append(entry)

        return ret