Last active
August 29, 2015 14:06
-
-
Save moranned/277c802d77da722b8431 to your computer and use it in GitHub Desktop.
Create Yara rules based on unique peresources or sections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ConfigParser | |
import optparse | |
import binascii | |
import hashlib | |
import pefile | |
import sys | |
def dumpPEResource(f,r): | |
try: | |
pe = pefile.PE(f) | |
resourcesList = [] | |
if hasattr(pe,"DIRECTORY_ENTRY_RESOURCE"): | |
for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries: | |
type = pefile.RESOURCE_TYPE.get(entry.id, 'NA') | |
for e in entry.directory.entries: | |
for m in e.directory.entries: | |
rva = m.data.struct.OffsetToData | |
size = m.data.struct.Size | |
data = pe.get_data(rva,size) | |
name = entry.name | |
if r == hashlib.sha256(data).hexdigest(): | |
createRule(binascii.hexlify(bytearray(data))) | |
except: | |
return 'Not a valid PE file' | |
def dumpSection(f,s): | |
try: | |
pe = pefile.PE(f) | |
for section in pe.sections: | |
if s in section.get_hash_md5(): | |
data = pe.get_data(section.VirtualAddress,256) | |
createRule(binascii.hexlify(bytearray(data))) | |
except: | |
return 'Not a valid PE file' | |
def createRule(r): | |
ruleName = raw_input("Enter a rule name: ") | |
ruleDesc = raw_input("Enter a description: ") | |
refHash = raw_input("Enter a reference hash: ") | |
print 'rule %s' %ruleName | |
print '{' | |
print '\tmeta:' | |
print '\t\tauthor = "[ENTER YOUR NAME HERE]"' | |
print '\t\tversion = "1.0"' | |
print '\t\tdesciption = "%s"' %ruleDesc | |
print '\t\treference_hash = "%s"' %refHash | |
print '\tstrings:' | |
print '\t\t$a = {%s}' %r | |
print '\tcondition:' | |
print '\t\t(uint16(0) == 0x5A4D) and $a' | |
print '}' | |
def readConfig(args): | |
usage = "Usage: python %prog [options]" | |
parser = optparse.OptionParser(usage=usage) | |
parser.add_option('--file','-f', action='store', default=None, help='File to analyze') | |
parser.add_option('--resource','-r', action='store', default=None, help='PE Resource to dump') | |
parser.add_option('--section','-s',action='store', default=None, help='Section to dump') | |
global options | |
(options,resource) = parser.parse_args(args) | |
def main(args): | |
readConfig(args) | |
if options.file: | |
if options.resource: | |
dumpPEResource(options.file,options.resource) | |
if options.section: | |
dumpSection(options.file,options.section) | |
if __name__ == "__main__": | |
args = sys.argv[1:] | |
if args: | |
main(args) | |
else: | |
print "See help (-h) for details" | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script automates the creation of yara rules by dumping user-specified peresources or sections.