本文整理汇总了Python中pefile.PEFormatError方法的典型用法代码示例。如果您正苦于以下问题:Python pefile.PEFormatError方法的具体用法?Python pefile.PEFormatError怎么用?Python pefile.PEFormatError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pefile
的用法示例。
在下文中一共展示了pefile.PEFormatError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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
示例2: run
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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
示例3: initialize
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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)
示例4: _get_machine_type
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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
示例5: __check_session
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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
示例6: getAllAttributes
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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
示例7: getArquitecture
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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
示例8: __init__
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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
示例9: test_nt_headers_exception
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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)
示例10: test_dos_header_exception_large_data
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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)
示例11: test_dos_header_exception_small_data
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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)
示例12: test_empty_file_exception
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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)
示例13: processDir
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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
示例14: _get_rich_header
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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())
示例15: get_relocations
# 需要导入模块: import pefile [as 别名]
# 或者: from pefile import PEFormatError [as 别名]
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))