Advertisement
opexxx

extachment.py

Apr 9th, 2015
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.41 KB | None | 0 0
  1. The MIT License (MIT)
  2. Copyright (c) 2014 Patrick Olsen
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. Author: Patrick Olsen
  19. Email: patrick.olsen@sysforensics.org
  20. Twitter: @patrickrolsen
  21. Version 0.2
  22. '''
  23. import os, re
  24. import email
  25. import argparse
  26. import olefile
  27.  
  28. def extractAttachment(msg, eml_files, output_path):
  29.    if len(msg.get_payload()) > 2:
  30.        if isinstance(msg.get_payload(), str):
  31.            try:
  32.                extractOLEFormat(eml_files, output_path)
  33.            except IOError:
  34.                #print 'Could not process %s. Try manual extraction.' % (eml_files)
  35.                #print '\tHeader of file: %s\n' % (msg.get_payload()[:8])
  36.                pass
  37.  
  38.        elif isinstance(msg.get_payload(), list):
  39.            count = 0
  40.            while count < len(msg.get_payload()):
  41.                payload = msg.get_payload()[count]
  42.                filename = payload.get_filename()
  43.                if filename is not None:
  44.                    magic = payload.get_payload(decode=True)[:4]
  45.                    # Print the magic deader and the filename for reference.
  46.                    printIT(eml_files, magic, filename)
  47.                    # Write the payload out.
  48.                    writeFile(filename, payload, output_path)
  49.                count += 1
  50.  
  51.    elif len(msg.get_payload()) == 2:
  52.        payload = msg.get_payload()[1]
  53.        filename = payload.get_filename()
  54.        magic = payload.get_payload(decode=True)[:4]
  55.        # Print the magic deader and the filename for reference.
  56.        printIT(eml_files, magic, filename)
  57.        # Write the payload out.
  58.        writeFile(filename, payload, output_path)        
  59.  
  60.    elif len(msg.get_payload()) == 1:
  61.        attachment = msg.get_payload()[0]
  62.        payload = attachment.get_payload()[1]
  63.        filename = attachment.get_payload()[1].get_filename()
  64.        magic = payload.get_payload(decode=True)[:4]
  65.        # Print the magic deader and the filename for reference.
  66.        printIT(eml_files, magic, filename)
  67.        # Write the payload out.
  68.        writeFile(filename, payload, output_path)
  69.    #else:
  70.    #    print 'Could not process %s\t%s' % (eml_files, len(msg.get_payload()))
  71.  
  72. #Reference: http://www.decalage.info/python/oletools
  73. #Reference: https://github.com/mattgwwalker/msg-extractor
  74. def extractOLEFormat(eml_files, output_path):
  75.    data = '__substg1.0_37010102'
  76.    filename = olefile.OleFileIO(eml_files)
  77.    msg = olefile.OleFileIO(eml_files)
  78.    attachmentDirs = []
  79.    for directories in msg.listdir():
  80.        if directories[0].startswith('__attach') and directories[0] not in attachmentDirs:
  81.            attachmentDirs.append(directories[0])
  82.  
  83.    for dir in attachmentDirs:
  84.        filename = [dir, data]
  85.        if isinstance(filename, list):
  86.            filenames = "/".join(filename)
  87.            filename = msg.openstream(dir + '/' + '__substg1.0_3707001F').read().replace('\000', '')
  88.            payload = msg.openstream(filenames).read()
  89.            magic = payload[:4]
  90.            # Print the magic deader and the filename for reference.
  91.            printIT(eml_files, magic, filename)
  92.            # Write the payload out.
  93.            writeOLE(filename, payload, output_path)
  94.  
  95. def printIT(eml_files, magic, filename):
  96.    print 'Email Name: %s\n\tMagic: %s\n\tSaved File as: %s\n' % (eml_files, magic, filename)
  97.  
  98. def writeFile(filename, payload, output_path):
  99.    open(os.path.join(output_path + filename), 'wb').write(payload.get_payload(decode=True))
  100.  
  101. def writeOLE(filename, payload, output_path):
  102.    open(os.path.join(output_path + filename), 'wb')
  103.  
  104. def main():
  105.    parser = argparse.ArgumentParser(description='Attempt to parse the attachment from EML messages.')
  106.    parser.add_argument('-p', '--path', help='Path to EML files.')
  107.    parser.add_argument('-o', '--out', help='Path to write attachments to.')
  108.    args = parser.parse_args()    
  109.  
  110.    if args.path:
  111.        input_path = args.path
  112.    else:
  113.        print "You need to specify a path to your EML files."
  114.        exit(0)
  115.  
  116.    if args.out:
  117.        output_path = args.out
  118.    else:
  119.        print "You need to specify a path to write your attachments to."
  120.        exit(0)
  121.  
  122.    for root, subdirs, files in os.walk(input_path):
  123.        for file_names in files:
  124.            eml_files = os.path.join(root, file_names)
  125.            msg = email.message_from_file(open(eml_files))
  126.            extractAttachment(msg, eml_files, output_path)
  127.  
  128. if __name__ == "__main__":
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement