Tools‎ > ‎

PE Compile Time Sorter

Sometimes, you just wanna know when you compiled stuff!
#!/usr/bin/env python
"""
Author: Mike Smith (msmith --at-- blackfortressindustries.com)
Date: 09 Nov 2011
Version: 1.1
Prupose: Given a top-level directory, get all pe file header compile times and sort by that value.
    Because sometimes you just wanna know when you compiled all your junk. 
"""

import re
import os
import time
import sys

try:
  import argparse
except:
  print('argparse not found. Please install the appropriate module.')
  sys.exit(1)

try:
  import magic
except:
  print('magic not found. Please install the appropriate module.')
  sys.exit(1)

try:
  import pefile
except:
  print('pefile not found. Please install the appropriate module.')
  sys.exit(1)

try:
  import hashlib
except:
  print('hashlib not found. Please install the appropriate module.')
  sys.exit(1)


def getHash(path):
  md5 = hashlib.md5()
  targetFh = open(path, 'rb')
  while True:
    block = targetFh.read(8192)
    if not block:
      break
    md5.update(block)
  targetFh.close()
  return str(md5.hexdigest())

# parse args
parser = argparse.ArgumentParser(description='Sort PEs in all subdirectories by compile time')
parser.add_argument('-b','--basedir', help='The base directory to start the PE search. Defaults to current working dir', default=os.getcwd())
parser.add_argument('-H','--hashmd5', help='Display file MD5 hash in output', action='store_true')
parser.add_argument('-m','--magic', help='Display file magic in output', action='store_true')
parser.add_argument('-n','--numeric', help='Display the date in integer format', action='store_true')
args = parser.parse_args()

baseDir = args.basedir
magicRe = re.compile('.*executable for MS Windows.*', re.IGNORECASE)

# make outer list for storing [int(time), str(collectedJunk)] per item
datas = []
mag = magic.open(magic.MAGIC_RAW)
mag.load()

## decend given directory
for rootDir, sibDir, files in os.walk(baseDir):
  for f in files:
    fPath = os.path.join(rootDir, f)
    magStr = mag.file(fPath)
    
    # check for match of the magic pattern.
    magicMatch = magicRe.match(magStr)
    if (magicMatch) :
      pe = pefile.PE(fPath)
      # if found, add to datas list. 
      tempItem = [pe.FILE_HEADER.TimeDateStamp]
      if (not args.numeric) : 
        tempItem.append(time.strftime("%a %d %b %Y %H:%M:%S (GMT+0000)", time.gmtime((pe.FILE_HEADER.TimeDateStamp))))
      else:
        tempItem.append(str(pe.FILE_HEADER.TimeDateStamp))
      if (args.hashmd5) : tempItem[1] = tempItem[1] + ',' + getHash(fPath)
      tempItem[1] = tempItem[1] + ',' + fPath
      if (args.magic) : tempItem[1] = tempItem[1] + ',' + magStr
      datas.extend([tempItem])

## sort datas by each list's first element
datas.sort()
## print sorted list
for ts, line in datas:
  print line

Comments