Skip to content

Instantly share code, notes, and snippets.

@alexander-hanel
Created December 26, 2018 23:40
Show Gist options
  • Save alexander-hanel/063dc4ddd46af05bba516d014958bf61 to your computer and use it in GitHub Desktop.
Save alexander-hanel/063dc4ddd46af05bba516d014958bf61 to your computer and use it in GitHub Desktop.
pefile common usage examples
import pefile
import sys
import datetime
import zlib
"""
Author: Alexander Hanel
Summary: Most common pefile usage examples
Date: 20181226
"""
def pefile_example(_file, file_path=True):
try:
if file_path:
# load executable from file path to create PE class
pe = pefile.PE(_file)
else:
# load executable from buffer/string to create PE class
pe = pefile.PE(data=_file)
except Exception as e:
print "pefile load error: %s" % e
return
print "IMAGE_OPTIONAL_HEADER32.AddressOfEntryPoint=0x%x" % pe.OPTIONAL_HEADER.AddressOfEntryPoint
print "IMAGE_OPTIONAL_HEADER32.ImageBase=0x%x" % pe.OPTIONAL_HEADER.ImageBase
# Now use AddressOfEntryPoint to get the preferred Virtual Address of Entry Point
print "RVA (preferred) Entry Point=0x%x" % (pe.OPTIONAL_HEADER.ImageBase + pe.OPTIONAL_HEADER.AddressOfEntryPoint)
print "CPU TYPE=%s" % pefile.MACHINE_TYPE[pe.FILE_HEADER.Machine]
print "Subsystem=%s" % pefile.SUBSYSTEM_TYPE[pe.OPTIONAL_HEADER.Subsystem]
print "Compile Time=%s" % datetime.datetime.fromtimestamp(pe.FILE_HEADER.TimeDateStamp)
ext = ""
if pe.is_dll():
ext = ".dll"
elif pe.is_driver():
ext = '.sys'
elif pe.is_exe():
ext = '.exe'
if ext:
print "FileExt=%s" % ext
# parse sections
print "Number of Sections=%s" % pe.FILE_HEADER.NumberOfSections
print "Section VirtualAddress VirtualSize SizeofRawData CRC Hash"
for index, section in enumerate(pe.sections):
# how to read the section data
sec_data = pe.sections[index].get_data()
# simple usage
crc_hash = zlib.crc32(sec_data) & 0xffffffff
print "%s 0x%x 0x%x 0x%x 0x%x" % (section.Name, section.VirtualAddress, section.Misc_VirtualSize, section.SizeOfRawData, crc_hash)
print "Imported DLLSs"
for entry in pe.DIRECTORY_ENTRY_IMPORT:
# print dll name
print entry.dll
"\tImport Address, Name, File Offset"
for imp in entry.imports:
# calculate virtual address to file offset
file_offset = pe.get_offset_from_rva(imp.address - pe.OPTIONAL_HEADER.ImageBase)
# print symbol name
print "\t0x%x %s 0x%x" % (imp.address, imp.name, file_offset)
path = sys.argv[1]
pefile_example(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment