Commit 018dab6d authored by Felix Bilstein's avatar Felix Bilstein

project

parent c90021ee
import pefile
import sys
if len(sys.argv) != 2:
print "Program requires exact one parameter,\n" + \
"the name of the PE File you want to fix!"
exit()
INfile = sys.argv[1]
pe = pefile.PE(INfile)
for section in pe.sections:
#print (section.Name, hex(section.VirtualAddress),hex(section.Misc_VirtualSize), section.SizeOfRawData )
print "We will update the following section:"
print section
section.PointerToRawData = section.VirtualAddress
section.SizeOfRawData = section.Misc_VirtualSize
print
print "This is the new section in your PE File:"
print section
print
pe.write(INfile + ".patched")
import pefile
import sys
if len(sys.argv) != 2:
print "Program requires exact one parameter,\n" + \
"the name of the PE File you want to analyze!"
exit()
INfile = sys.argv[1]
pe = pefile.PE(INfile)
open(INfile + ".info.txt", 'wb').write(pe.dump_info())
"""
Code snippet forked from Daniel Plohmann
"""
class PyMdmpOutput():
"""
Wrapper class for pymdmp results
"""
def __init__(self, pymdmp_tuple, yara_result=""):
if len(pymdmp_tuple) == 5:
self.process_name = pymdmp_tuple[0]
self.name = pymdmp_tuple[1]
self.pid = pymdmp_tuple[2]
self.addr = pymdmp_tuple[3]
self.data = pymdmp_tuple[4]
else:
raise Exception("Invalid parameter used for construction of new PyMdmpOutput object. Type: %s." % type(pymdmp_tuple))
____ _ ____
| _ \ ___| |_ _ __ ___ | _ \ _ _ _ __ ___ _ __
| |_) / _ \ __| '__/ _ \| | | | | | | '_ ` _ \| '_ \
| _ < __/ |_| | | (_) | |_| | |_| | | | | | | |_) |
|_| \_\___|\__|_| \___/|____/ \__,_|_| |_| |_| .__/
|_|
=== Malware Dumping Toolkit 0.1 beta ===
Ingredients:
-> dump.py: The Tool you will use to dump the memory of a process. Run dump.py to start the assistance mode.
-> FixPE.py: You will use this script to fix the PE Header from your dump.
-> InfoPE.py: This will write a txt file with all informations you can gather from the PE File.
--- dump.py ---
Just run dump.py in the directory, usage is really simple. You need to install the following libraries:
psutil
https://pypi.python.org/pypi/psutil/
pymdmp
https://code.google.com/p/mdmp/wiki/pymdmp
--- FixPE.py ---
Run the script with 1 argument containing the file you want to fix. We will create a new file (same filename, appended '.patched'), you do not have to bother about backups.
You need to install the library pefile:
https://pypi.python.org/pypi/pefile
--- InfoPE.py ---
Run the script with the PE file as argument you want to scan. We will create a file with the same name appending '.PEinfo.txt' where you can read the output.
You need to install the library pefile:
https://pypi.python.org/pypi/pefile
=== Contact ===
fxb@cocacoding.com
#!/usr/bin/env python2
import sys
import time
import imp
import os
import psutil
import pymdmp
import malwrDumpLib
import getpass
import pefile
def getProcessNameByPID(pid):
process = psutil.Process(int(pid)) # Get the process info using PID
pname = process.name() # Here is the process name
#print pname
return pname
def doAllAsUser(pids, currentPID, currentUser, currentDir, timestamp):
ret = []
for i in pids:
p = psutil.Process(i)
try:
puser = p.username()
puser = puser[puser.find('\\')+1:]
if currentUser == puser and int(currentPID) != i:
ret.append(i)
elif int(currentPID) == i:
print "We do not dump our own process " + "(" + str(currentPID) + ")" + " as this will result in an endless loop..."
except:
print "Access Denied at " + str(i) + " - " + getProcessNameByPID(i) + "! Seems not to be yours."
print ret
for i in ret:
print "Working with " + str(i) + " now"
print doOne(i, currentDir)
print "Finished the list.."
def doList(input_value, currentDir):
print "Working with a List: [" + input_value + "]"
input_value = input_value.replace(' ', '')
pids=[]
while 1==1:
next_end = input_value.find(',')
if next_end != -1: # real C style
pids.append(int(input_value[0:next_end]))
input_value = input_value[next_end+1:]
else:
pids.append(int(input_value))
break
print pids
for i in pids:
print "Working with " + str(i) + " now"
print doOne(i, currentDir)
def doOne(input_value, currentDir):
modName = getProcessNameByPID(int(input_value))
memory = pymdmp.dump(pymdmp.SEL_BY_PID, pymdmp.DUMP_ALL_MEM, 0, processID=int(input_value))
special = malwrDumpLib.glueMemoryBlobs(int(input_value), memory)
os.chdir(currentDir)
os.mkdir(str(input_value) + "-" + modName)
currentDir = os.path.join(currentDir, str(input_value) + "-" + modName)
if isinstance(special, list):
log = ""
for spec in special:
filename = os.path.join(currentDir, '%s-%d-%08X-%s.dump' % (spec.process_name, spec.pid, spec.addr, spec.name))
log = log + filename + "\n"
open(filename, 'wb').write(spec.data)
open(currentDir + "/dumping_log.txt", 'w').write(log)
else:
print "Error occured by dumping " + str(input_value) + " - " + modname + "! Send me the traceback.."
"""
if isinstance(results, list):
for res in results:
filename = os.path.join(currentDir, '%08X-%s-%d-%s.dmp' % (res[3] , res[1] , res[2] ,res[0]))
open(filename, 'wb').write(res[-1])
else:
print "no idea what went wrong"
if isinstance(results, list):
for res in results:
#print res[0] -> calc.exe
#print res[1] -> other[RW]
#print res[2] -> processID (2160>
#print res[3] -> memory
#print res[4] -> memory
filename = str(res[3]) + str(res[1]) + str(res[2]) + str(res[0])
#filename = os.path.join(currentDir, '%s-%s-%d-%08X.dmp' % res[:-1])
filename = os.path.join(currentDir, '%08X-%s-%d-%s.dmp' % (res[3] , res[1] , res[2] ,res[0]))
print filename
open(filename, 'wb').write(res[-1])
# produces something similar to calc.exe-pe[kernel32.dll]-3720-7C800000.dump
else:
print "Some problem occured.."
print results
"""
return currentDir + "\\dumping_log.txt"
def main():
currentDir = os.getcwd()
clock = time.strftime("%c").replace('/','-').replace(' ', '_').replace(':', '-')
clock = "malwareDumper-" + clock
currentUser = getpass.getuser()
currentPID = os.getpid()
print
print "+----------------------------------------------------+"
print "| MALWARE DUMPING TOOKLKIT - Retro Edition (XP only) |"
print "+----------------------------------------------------+"
print
print "We are working at: " + currentDir
print "We will use " + clock + " as timestamp"
os.mkdir(clock)
currentDir = os.path.join(currentDir, clock)
print "Building environment... " + currentDir + " was created!"
print "Switching into " + currentDir + " as current workspace..."
print
print "Version of pymdmp " + pymdmp.ver()
print
print "Getting the env.."
print "Current PID: " + str(currentPID)
print "Current user: "+ currentUser
print
print "TESTING... GETTING ALL!"
print
psutil.test()
print
print
allPIDs = psutil.pids()
print allPIDs
print
print "Select one PID, a list seperated per ',' char or press Enter to get every process"
print "(not the one pid we use and only user privileges processes.. as we are not hacking around here) "
inp = raw_input('Your choice: ')
try:
if inp == "":
print "Empty - We are about to dump all processes memory."
print "BUT: We dump only the processes with your users (" + currentUser + ") privilege."
print "If you want to dump processes from other users (ie. if you got a SYSTEM shell) do it as a list."
print "I recommend you to not dump process 0 and 4 as they are not real processes.."
doAllAsUser(allPIDs, currentPID, currentUser, currentDir, clock)
else:
print inp
if inp.find(",") != -1:
doList(inp, currentDir)
else:
print "Working with " + str(inp)
print "We will dump now... "
modName = getProcessNameByPID(inp)
print inp + " is called " + modName
print doOne(inp, currentDir)
except:
print "Exception was handled! Error:"
print sys.exc_info()
if os.path.isdir(currentDir): #True/False: check if this is a directory
if os.listdir(currentDir) == []:
print "Your session has no results, we will delete the empty folder " + currentDir;
os.rmdir(currentDir)
else:
print "Your session has some stuff in your workspace, so we will not delete the folder."
print os.listdir(currentDir) #gets you a list of all files and directories under dir_in
print "Done!"
"""
pe = pefile.PE("C:/Documents and Settings/user/malwareDumper-10-09-15_23-31-16/4004-calc.exe/calc.exe-4004-01000000-PE_[RO]_[RX]_[RW]_[RO].dump")
for section in pe.sections:
print (section.Name, hex(section.VirtualAddress),
hex(section.Misc_VirtualSize), section.SizeOfRawData )
print
print
print "Actual section:"
print section
print
section.PointerToRawData = section.VirtualAddress
section.SizeOfRawData = section.Misc_VirtualSize
print
print section
pe.write("C:/Documents and Settings/user/malwareDumper-10-09-15_23-31-16/4004-calc.exe/calc.exe-4004-01000000-PE_[RO]_[RX]_[RW]_[RO].dump.exe")
"""
if __name__ == "__main__":
main()
import pymdmp
from PyMdmpOutput import PyMdmpOutput
import struct
"""
Code snippet forked from Daniel Plohmann
"""
def checkPeHeader(buf):
if buf.startswith("MZ") and len(buf) > 0x3c + 2:
pe_offset = struct.unpack("H", buf[0x3c:0x3c + 2])[0]
if len(buf) > pe_offset + 4:
if buf[pe_offset:pe_offset + 4] == "PE\x00\x00":
return True
return False
def glueMemoryBlobs(pid, memory):
# we need to treat RWX blobs specially, as they will only show up as "RW" when dumped with DUMP_ALL_MEM
all_memory = pymdmp.dump(pymdmp.SEL_BY_PID, pymdmp.DUMP_EXECUTABLE, 0, processID=pid)
if not isinstance(all_memory, list):
print "glueMemoryBlobs: No List obtained"
return []
executable_blobs = []
try:
for blob in all_memory:
executable_blobs.append(blob[3])
except:
print "glueMemoryBlobs: appending to executable blobs failed."
return []
glued_blobs = []
current_blob = None
for index in xrange(len(memory)):
# if has another memory blob
if index + 1 < len(memory):
if not current_blob:
current_blob = PyMdmpOutput(memory[index])
current_blob.name = current_blob.name[5:]
# if current_blob.addr in executable_blobs:
# print "current blob 0x%x is in executable, current name is: %s" % (current_blob.addr, current_blob.name)
# current_blob.name = "other[RWX]"
next_blob = PyMdmpOutput(memory[index + 1])
# if next_blob.addr in executable_blobs:
# print "next blob 0x%x is in executable, current name is: %s" % (next_blob.addr, next_blob.name)
# next_blob.name = "other[RWX]"
# take care of heap etc. where executable memory might get combined with non-executable (not desired)
if current_blob.addr + len(current_blob.data) == next_blob.addr and not checkPeHeader(next_blob.data):
# print " blobs stick together: 0x%x (0x%x), 0x%x (0x%x)" % (current_blob.addr, len(current_blob.data), next_blob.addr, len(next_blob.data))
current_blob.data += next_blob.data
current_blob.name += "_" + next_blob.name[5:]
# treat PE header sections differently
else:
# print " space between blobs for blob: 0x%x (0x%x), 0x%x (0x%x)" % (current_blob.addr, len(current_blob.data), next_blob.addr, len(next_blob.data))
if checkPeHeader(current_blob.data):
current_blob.name = "PE_" + current_blob.name
glued_blobs.append(current_blob)
current_blob = None
if len(memory) == 1:
glued_blobs = memory
return glued_blobs
This diff is collapsed.
This diff is collapsed.
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError, excp:
from distutils.core import setup
import pefile
import os
os.environ['COPY_EXTENDED_ATTRIBUTES_DISABLE'] = 'true'
os.environ['COPYFILE_DISABLE'] = 'true'
setup(name = 'pefile',
version = pefile.__version__,
description = 'Python PE parsing module',
author = pefile.__author__,
author_email = pefile.__contact__,
url = 'http://code.google.com/p/pefile/',
download_url = 'http://pefile.googlecode.com/files/pefile-%s.tar.gz' % pefile.__version__,
platforms = ['any'],
classifiers = ['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'],
long_description = "\n".join(pefile.__doc__.split('\n')),
py_modules = ['pefile', 'peutils'],
packages = ['ordlookup'] )
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment