#!/usr/bin/python
from optparse import OptionParser
import sys
import os, os.path
import subprocess
import base64
import email
import mimetypes
import hashlib
outputdirectory="./report"
def decode_base64(data):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = 4 - len(data) % 4
if missing_padding:
data += b'='* missing_padding
return base64.decodestring(data)
def primaoperazione(pcap):
if os.path.exists(outputdirectory):
print "Errore: directory esistente, rimuoverla prima di procedere"
exit()
if not os.path.exists(outputdirectory):
os.makedirs(outputdirectory)
subprocess.call("(cd %s && tcpflow -r %s)"%(outputdirectory, pcap), shell=True)
def smtpinfo():
report = open(os.path.join(outputdirectory, "report.txt"), 'wb')
for file in os.listdir(outputdirectory):
report.write("-"*50+"\n")
report.write(("Filename %s\n\n")%file)
message = []
a = open(os.path.join(outputdirectory,file)).readlines()
for i in range(len(a)):
if "AUTH LOGIN" in a[i]:
report.write("Dati LOGIN\n")
report.write(decode_base64(str(a[i+1]))+"\n")
report.write(decode_base64(str(a[i+2]))+"\n")
if "MAIL FROM" in a[i]:
report.write(a[i]+"\n")
if "RCPT TO" in a[i]:
report.write(a[i]+"\n")
if "DATA" in a[i]:
b="".join(a[(i+1):(len(a)-1)])
msg = email.message_from_string(b)
for part in msg.walk():
if part.get_content_type() == 'text/plain':
report.write("Testo del messaggio\n")
report.write(part.get_payload()+"\n")
filename = part.get_filename()
if filename == None:
continue
else:
fp = open(os.path.join(outputdirectory, filename), 'wb')
fp.write(part.get_payload(decode=1))
fp.close()
report.write("Il nome dell'allegato:"+filename+"\n")
fp = open(os.path.join(outputdirectory, filename), 'rb')
data = fp.read()
fp.close()
msgmd5 = hashlib.md5(data).hexdigest()
report.write("L'hash MD5 del file:"+msgmd5+ "\n")
report.close()
if __name__ == '__main__':
usage = "Usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option("-p",dest="pcapfile",help="Complete path to pcap file")
(options, args) = parser.parse_args(sys.argv)
if not options.pcapfile:
parser.error("-p is required, see --help for details")
primaoperazione(options.pcapfile)
smtpinfo()