Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Split file while preserving PE format
#!/usr/bin/env python
# DiabloHorn
# blank out bytes taking into account the PE file format
# input file: base64 malware.exe | rev > enc.txt
import sys
import os
#pip install pefile
import pefile
import argparse
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class PeModifier:
def __init__(self, bindata, outputpath):
self.bindata = bindata
self.opath = outputpath = pefile.PE(data=self.bindata)
self.filename = 'split.{}.exe'
self.namecounter = -1
def genName(self):
self.namecounter +=1
return self.filename.format(self.namecounter)
def writePE(self):
finalpath = os.path.join(self.opath, self.genName())"File written {}".format(finalpath))
def getSection(self, sectionname):
for section in
if sectionname in section.Name:
return section.get_data()
def writeSection(self, sectionname, bindata):
for section in
if sectionname in section.Name:
section_file_offset = section.PointerToRawData, bindata)
def blankSectionData(self):
for section in"blanking secion {}".format(section.Name))
bindata = self.getSection(section.Name)
bindatalen = len(bindata)
#restores in memory pe file to original state
def blankSectionDataBytes(self, sectionname, blanklen):
bindata = self.getSection(sectionname)
bindatalen = len(bindata)"blanking byte in {}".format(sectionname))
for i in range(0,bindatalen,blanklen):
moddata = bindata[0:i]
moddata += ('\x00' * (bindatalen - i))
#restores in memory pe file to original state
moddata = ''
def enc2bin(filepath):
memfile = ""
with open(filepath,'rb') as encfile:
for line in encfile:
memfile += line.strip()[::-1]
return memfile.decode('base64')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='split file in a PE aware manner')
parser.add_argument('targetfile',type=str,help='target file to split')
parser.add_argument('outputfolder',type=str,help='output folder for splitted files')
parser.add_argument('--bytes',type=int,help='amount of bytes to blank')
parser.add_argument('--section',type=str,help='section to blank bytes')
myargs = parser.parse_args()
if myargs.bytes is None:
myargs.bytes = 1000
if myargs.section is None:
myargs.section = '.text'
bindata = enc2bin(myargs.targetfile)"Creating in memory binary data")
pemod = PeModifier(bindata,myargs.outputfolder)"Blanking sections")
pemod.blankSectionData()"Blanking bytes in section")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment