#!/usr/bin/env python
from __future__ import division

import os
import sys
import json
import pefile
import hashlib
from pprint import pprint
#This program will find out behavioural pattern for an unknown file submitted to it
#based on the signature database of windows apis used in malicious executables (pefiles)
#-----------------Written by Rakesh Sharma (techie.rakesh@gmail.com---------------------

verbose = False

#this code block will get all the imported APIs from pe file
def get_imports(pe):
    ret = []
    if not hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
       return ret
    for lib in pe.DIRECTORY_ENTRY_IMPORT:
        for imp in lib.imports:
            if (imp.name != None) and (imp.name != ""):
               ret.append(imp.name)
        return ret

#this code block will check if file is PE, then import signature database
def analyze(filename):
   try:
      pe = pefile.PE(filename)
   except Exception, ex:
      print "[-] Could not parse %s: %s" % (filename, ex)
      sys.exit(1)

   sigfile = "signatures.json"
   with open(sigfile) as f:
      try:
         sigs = json.load(f)
      except Exception, ex:
         print "[-] Could not load signatures from %s: %s" % (sigfile, ex)
         sys.exit(1)

   if len(sigs) <= 0:
      print "[-] Signatures file (%s) seems to be empty." % (sigfile)
      sys.exit(1)

#this code block will calculate hashes and perform malware analysis based on api imports from signature db
   target = open(filename, "rb")
   md5hash = hashlib.md5(target.read()).hexdigest()
   sha256hash = hashlib.sha256(target.read()).hexdigest()
   target.close()

   imports = get_imports(pe)

   print "------------------------------"
   print " Anti-Malware Static Analysis"
   print "  Author:  Rakesh Sharma     "
   print "-----------------------------\n"
   print "[+] Loaded %d signatures from %s" % (len(sigs), sigfile)
   print "[+] Filename: %s (MD5: %s, SHA256: %s)" % (filename, md5hash, sha256hash)
   print "[+] %s has %d imports. Checking against %d signatures." % (filename, len(imports), len(sigs))

   scores = []
   totscore = 0
#checking imported APIs in signature db
   if len(imports) < len(sigs):
      for api in imports:
         if verbose:
            print "[*] Testing %s in sigs (%d)" % (api, len(sigs))

         if api in sigs.keys():
            scores.append(sigs[api]["score"])
            totscore += sigs[api]["score"]
            print "\n[[+]] Found %s: %s (Score: %d)" % (api, sigs[api]["description"], sigs[api]["score"])
#checking APIs from signature DB in imported APIs of pe file
   else:
      for sig in sigs.keys():
         if verbose:
            print "[*] Testing %s in imports (%d)" % (sig, len(imports))

         if sig in imports:
            scores.append(sigs[sig]["score"])
            totscore += sigs[sig]["score"]
            print "[[+]] Found %s: %s (Score: %d)" % (sig, sigs[sig]["description"], sigs[sig]["score"])
#calculate scores of matched APIs
   if len(scores) > 0:
      minval = min(scores)
      maxval = max(scores)
      avgval = float(totscore / len(scores))

      print "\n[+] Found %d matches (MIN: %d, MAX: %d, AVG: %.2f)" % (len(scores), minval, maxval, avgval)

   else:
     print "[+] No matches found!"


if __name__ == "__main__":
   if len(sys.argv) != 2:
      print "USAGE: %s <pefile>" % (sys.argv[0])
      sys.exit(1)

   analyze(sys.argv[1])

Create malwareid.py