How to use the pefile.PEFormatError function in pefile

To help you get started, we’ve selected a few pefile 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 PUNCH-Cyber / stoq-plugins-public / v2 / peinfo / peinfo / peinfo.py View on Github external
return

            rich_hdr['checksum'] = hex(rich_hdr['checksum'])

            # 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 None
                data = list(struct.unpack("<32I", rich_data))
            except pefile.PEFormatError as e:
                return None

            checksum = data[1]
            headervalues = []

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

            sha_256 = hashlib.sha256()
            for hv in headervalues:
                sha_256.update(struct.pack('
github doomedraven / VirusTotalApi / vt / vt.py View on Github external
def fileInfo(self, *args,  **kwargs):
        if PEFILE:
            files = kwargs.get('value')
            for file in files:
                try:
                    pe = pefile.PE(file)
                except pefile.PEFormatError:
                    print '[-] Not PE file'
                    return

                print "\nName: {0}".format(file.split("/")[-1])

                print "\n[+] Hashes"
                print "MD5: {0}".format(pe.sections[0].get_hash_md5())
                print "SHA1: {0}".format(pe.sections[0].get_hash_sha1())
                print "SHA256: {0}".format(pe.sections[0].get_hash_sha256())
                print "SHA512: {0}".format(pe.sections[0].get_hash_sha512())
                try:
                    print 'ImpHash: {0}'.format(pe.get_imphash())
                except:
                    pass

                if pe.FILE_HEADER.TimeDateStamp:
github fireeye / flare-ida / shellcode_hashes / make_sc_hash_db.py View on Github external
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
github fr0gger / unprotect / windows_unprotect / unprotect.py View on Github external
if len(sys.argv) == 2 and sys.argv[1] == "-h" or sys.argv[1] == "--help":
        help()
        exit(0)
		
    if len(sys.argv) == 2:

        print module.config.__asciiart__
        print "\t\t" + module.config.__copyright__ + " | " + module.config.__author__
        # print "\t\t\tUnprotect malware for the mass"

        try:
            exe = pefile.PE(exefile)
        except OSError as e:
            print(e)
            sys.exit()
        except pefile.PEFormatError as e:
            print  "[-] PEFormatError: %s" % e.value
            print  "[!] The file is not a valid PE"
            sys.exit()

        strings_list, decoded_strings = get_strings(exefile)

        concatenate_strings = strings_list + decoded_strings

        print "\nPE Summary"
        print "-" * 80

        fname, fsize, tsdate, dll, nsec = get_info(exe, exefile)

        #print  "File type:\t %s" % ftype
        print  "File name:\t %s" % fname
        print  "File size:\t %s Bytes" % fsize
github erocarrera / pefile / pefile.py View on Github external
if bnd_descr.all_zeroes():
                break
                
            rva += bnd_descr.sizeof()
            
            forwarder_refs = []
            for idx in range(bnd_descr.NumberOfModuleForwarderRefs):
                # Both structures IMAGE_BOUND_IMPORT_DESCRIPTOR and
                # IMAGE_BOUND_FORWARDER_REF have the same size.
                bnd_frwd_ref = self.__unpack_data__(
                    self.__IMAGE_BOUND_FORWARDER_REF_format__,
                    self.__data__[rva:rva+bnd_descr_size],
                    file_offset = rva)
                # OC Patch:
                if not bnd_frwd_ref:
                    raise PEFormatError(
                        "IMAGE_BOUND_FORWARDER_REF cannot be read")
                rva += bnd_frwd_ref.sizeof()
                
                forwarder_refs.append(BoundImportRefData(
                    struct = bnd_frwd_ref,
                    name =  self.get_string_from_data(
                        start+bnd_frwd_ref.OffsetModuleName, self.__data__)))
                
            bound_imports.append(
                BoundImportDescData(
                    struct = bnd_descr,
                    name = self.get_string_from_data(
                        start+bnd_descr.OffsetModuleName, self.__data__),
                    entries = forwarder_refs))
                    
        return bound_imports
github GDATAAdvancedAnalytics / r2graphity / graphityUtils.py View on Github external
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
github erocarrera / pefile / pefile.py View on Github external
if ( self.OPTIONAL_HEADER is None and 
                    len(self.__data__[optional_header_offset:])
                        >= MINIMUM_VALID_OPTIONAL_HEADER_RAW_SIZE ):
                
                    padding_length = 128
                    padded_data = self.__data__[optional_header_offset:] + (
                        '\0' * padding_length)
                    self.OPTIONAL_HEADER = self.__unpack_data__(
                        self.__IMAGE_OPTIONAL_HEADER64_format__,
                        padded_data,
                        file_offset = optional_header_offset)
        
        
        if not self.FILE_HEADER:
            raise PEFormatError('File Header missing')


        # OC Patch:
        # Die gracefully if there is no OPTIONAL_HEADER field
        # 975440f5ad5e2e4a92c4d9a5f22f75c1
        if self.PE_TYPE is None or self.OPTIONAL_HEADER is None:
            raise PEFormatError("No Optional Header found, invalid PE32 or PE32+ file")
            
        dll_characteristics_flags = self.retrieve_flags(DLL_CHARACTERISTICS, 'IMAGE_DLL_CHARACTERISTICS_')

        # Set the Dll Characteristics flags according the the DllCharacteristics member
        self.set_flags(
            self.OPTIONAL_HEADER,
            self.OPTIONAL_HEADER.DllCharacteristics,
            dll_characteristics_flags)
github erocarrera / pefile / pefile.py View on Github external
if self.DOS_HEADER.e_lfanew > len(self.__data__):
            raise PEFormatError('Invalid e_lfanew value, probably not a PE file')

        nt_headers_offset = self.DOS_HEADER.e_lfanew

        self.NT_HEADERS = self.__unpack_data__(
            self.__IMAGE_NT_HEADERS_format__,
            self.__data__[nt_headers_offset:],
            file_offset = nt_headers_offset)

        # We better check the signature right here, before the file screws
        # around with sections:
        # OC Patch:
        # Some malware will cause the Signature value to not exist at all
        if not self.NT_HEADERS or not self.NT_HEADERS.Signature:
            raise PEFormatError('NT Headers not found.')

        if self.NT_HEADERS.Signature != IMAGE_NT_SIGNATURE:
            raise PEFormatError('Invalid NT Headers signature.')
                
        self.FILE_HEADER = self.__unpack_data__(
            self.__IMAGE_FILE_HEADER_format__,
            self.__data__[nt_headers_offset+4:],
            file_offset = nt_headers_offset+4)
        image_flags = self.retrieve_flags(IMAGE_CHARACTERISTICS, 'IMAGE_FILE_')
        
        if not self.FILE_HEADER:
            raise PEFormatError('File Header missing')

        # Set the image's flags according the the Characteristics member
        self.set_flags(self.FILE_HEADER, self.FILE_HEADER.Characteristics, image_flags)
github erocarrera / pefile / pefile.py View on Github external
nt_headers_offset = self.DOS_HEADER.e_lfanew

        self.NT_HEADERS = self.__unpack_data__(
            self.__IMAGE_NT_HEADERS_format__,
            self.__data__[nt_headers_offset:],
            file_offset = nt_headers_offset)

        # We better check the signature right here, before the file screws
        # around with sections:
        # OC Patch:
        # Some malware will cause the Signature value to not exist at all
        if not self.NT_HEADERS or not self.NT_HEADERS.Signature:
            raise PEFormatError('NT Headers not found.')

        if self.NT_HEADERS.Signature != IMAGE_NT_SIGNATURE:
            raise PEFormatError('Invalid NT Headers signature.')
                
        self.FILE_HEADER = self.__unpack_data__(
            self.__IMAGE_FILE_HEADER_format__,
            self.__data__[nt_headers_offset+4:],
            file_offset = nt_headers_offset+4)
        image_flags = self.retrieve_flags(IMAGE_CHARACTERISTICS, 'IMAGE_FILE_')
        
        if not self.FILE_HEADER:
            raise PEFormatError('File Header missing')

        # Set the image's flags according the the Characteristics member
        self.set_flags(self.FILE_HEADER, self.FILE_HEADER.Characteristics, image_flags)
        
        optional_header_offset =    \
            nt_headers_offset+4+self.FILE_HEADER.sizeof()