Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
#!/usr/bin/env python
import pefile
import sys
fileName = sys.argv[1]
pe = pefile.PE(fileName)
for item in pe.DIRECTORY_ENTRY_IMPORT:
print "DLL File: %s"%item.dll.lower()
print "Functions: "
for import_fn in item.imports:
print hex(import_fn.address), import_fn.name
print '\n'
def _detect_cpu_arch_pe(mappings):
import pefile
# get the maps with read-only data
# find the executable image and get the PE header
pe = None
for m in mappings:
# volatility dumps VAD differently than winappdbg
# we have to look at all mappings
# if m.permissions != 'r--':
# continue
try:
head = m.readBytes(m.start, 0x1000)
pe = pefile.PE(data=head, fast_load=True)
# only get the dirst one that works
if pe is None:
continue
break
except pefile.PEFormatError as e:
pass
machine = pe.FILE_HEADER.Machine
arch = pe.OPTIONAL_HEADER.Magic
if arch == 0x10b:
return '32'
elif arch == 0x20b:
return '64'
else:
raise NotImplementedError('MACHINE is %s' % (pe.e_machine))
return
def run(self):
filebuf = self.reporter.data
try:
pe = pefile.PE(data=filebuf, fast_load=False)
image_base = pe.OPTIONAL_HEADER.ImageBase
except:
image_base = 0
table_ref = yara_scan(filebuf, '$ref1')
if table_ref:
table_ref_offset = int(table_ref['$ref1'])
table_delta = struct.unpack('i', filebuf[table_ref_offset+62:table_ref_offset+66])[0]
table_offset = table_ref_offset + table_delta + 66
table_loop = True
while table_loop:
c2_offset = 0
if image_base:
c2_rva = struct.unpack('Q', filebuf[table_offset:table_offset+8])[0] - image_base
if c2_rva < 0x8000:
if not pdb_name.endswith('.dll'):
pdb_name += '.dll'
logger.info('module {0} loaded at address 0x{1:x} with size 0x{2:x}'.format(pdb_name, image_context.image_addr, image_context.image_size))
### Get .text offset:
# When specifying a segment address, GDB uses segment relocation code.
# Whereas a PE32 has only a single segment, a Mach-O binary has 2 segments:
# .text and .data. So, gdb expects the segment address to be the address of
# the .text segment.
offset = 0
sections = []
peheader = self.read_memory(image_context.image_addr, 1, 1024)
try:
pe = pefile.PE(data = peheader)
for pesection in pe.sections:
if pesection.Name.strip(b'\x00') == b'.text':
offset = pesection.VirtualAddress
# section = gdbserver.Section(pesection.Name.strip(b'\x00'),
# pesection.VirtualAddress + image_context.image_addr,
# pesection.Misc_VirtualSize)
# if section.name == b'.text' or \
# section.name == b'.data':
# sections.append(section)
#
# logger.info('module {0} section {1!s} loaded at address 0x{2:x} with size 0x{3:x}'.format(pdb_name, section.name, image_context.image_addr + section.address, section.length))
except pefile.PEFormatError:
pass
self.libraries.append({'pdb_name': pdb_name,
def rich_header():
try:
pe = pefile.PE(idc.GetInputFilePath().decode("utf-8"))
except:
pe = pefile.PE(idc.GetInputFilePath())
rich_header = pe.parse_rich_header()
return hashlib.md5(rich_header['clear_data']).hexdigest()
def is_authenticode_signed(filename):
"""Returns True if the file is signed with authenticode"""
p = None
try:
p = pefile.PE(filename)
# Look for a 'IMAGE_DIRECTORY_ENTRY_SECURITY' entry in the optinal data
# directory
for d in p.OPTIONAL_HEADER.DATA_DIRECTORY:
if d.name == 'IMAGE_DIRECTORY_ENTRY_SECURITY' and d.VirtualAddress != 0:
return True
return False
except:
log.exception("Problem parsing file")
return False
finally:
if p:
p.close()
def extract_config(rawData):
try:
pe = pefile.PE(data=rawData)
try:
rt_string_idx = [
entry.id for entry in
pe.DIRECTORY_ENTRY_RESOURCE.entries].index(pefile.RESOURCE_TYPE['RT_RCDATA'])
except ValueError, e:
return None
except AttributeError, e:
return None
rt_string_directory = pe.DIRECTORY_ENTRY_RESOURCE.entries[rt_string_idx]
for entry in rt_string_directory.directory.entries:
if str(entry.name) == 'XTREME':
data_rva = entry.directory.entries[0].data.struct.OffsetToData
size = entry.directory.entries[0].data.struct.Size
data = pe.get_memory_mapped_image()[data_rva:data_rva+size]
return data
except:
def listsections(fname):
pe=pefile.PE(fname)
for sect in pe.sections:
print ("Sections: %8s" % filter(lambda k: '\x00' not in k, str(sect.Name))),
print ("%4.2f" % sect.get_entropy())
def main():
pp = argparse.ArgumentParser(description='Dump FSB5 vorbis headers from a 32-bit Windows executable')
pp.add_argument('file', help='path to executable file')
args = pp.parse_args()
pe = pefile.PE(args.file)
lookup = {}
base_addr = pe.OPTIONAL_HEADER.ImageBase
# reimplementation of get_memory_mapped_image because pefile did not survive
# the port to python 3 fully in tact...
mapped_data = pe.__data__[:]
for section in pe.sections:
# Miscellaneous integrity tests.
# Some packer will set these to bogus values to make tools go nuts.
if section.Misc_VirtualSize == 0 or section.SizeOfRawData == 0:
continue
if section.SizeOfRawData > len(pe.__data__):
continue