Guest User

Gpg-mailgate Updated

a guest
Sep 22nd, 2013
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.78 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. #  untitled.py
  5. #  
  6. #  Copyright 2013 Bruce Markey <[email protected]>
  7. #  
  8. #  This program is free software; you can redistribute it and/or modify
  9. #  it under the terms of the GNU General Public License as published by
  10. #  the Free Software Foundation; either version 2 of the License, or
  11. #  (at your option) any later version.
  12. #  
  13. #  This program is distributed in the hope that it will be useful,
  14. #  but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. #  GNU General Public License for more details.
  17. #  
  18. #  You should have received a copy of the GNU General Public License
  19. #  along with this program; if not, write to the Free Software
  20. #  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  21. #  MA 02110-1301, USA.
  22. #  
  23. #  
  24.  
  25.  
  26. from ConfigParser import RawConfigParser
  27. from email.mime.base import MIMEBase
  28. import email
  29. import email.message
  30. import re
  31. import GnuPG
  32. import smtplib
  33. import sys
  34. import base64
  35.  
  36. # Read configuration from /etc/gpg-mailgate.conf
  37. _cfg = RawConfigParser()
  38. _cfg.read('/etc/gpg-mailgate.conf')
  39. cfg = dict()
  40. for sect in _cfg.sections():
  41.         cfg[sect] = dict()
  42.         for (name, value) in _cfg.items(sect):
  43.                 cfg[sect][name] = value
  44.  
  45. # Read e-mail from stdin
  46. raw = sys.stdin.read()
  47. raw_message = email.message_from_string( raw )
  48. from_addr = raw_message['From']
  49. to_addrs = sys.argv[1:]
  50.  
  51. #log = open(cfg['logging']['file'], 'a')
  52. #log.write(raw)
  53. #log.close()
  54.  
  55.  
  56. def send_msg( message, recipients = None ):
  57.         if recipients == None:
  58.                 recipients = to_addrs
  59.         if cfg.has_key('logging') and cfg['logging'].has_key('file'):
  60.                 log = open(cfg['logging']['file'], 'a')
  61.                 log.write("Sending email to: <%s>\n" % '> <'.join( recipients ))
  62.                 log.close()
  63.         relay = (cfg['relay']['host'], int(cfg['relay']['port']))
  64.         smtp = smtplib.SMTP(relay[0], relay[1])
  65.         smtp.sendmail( from_addr, recipients, message.as_string() )
  66.        
  67. def encrypt_payload( payload, gpg_to_cmdline ):
  68.         gpg = GnuPG.GPGEncryptor( cfg['gpg']['keyhome'], gpg_to_cmdline )
  69.         raw_payload = payload.get_payload(decode=True)
  70.         gpg.update( raw_payload )
  71.         if "-----BEGIN PGP MESSAGE-----" in raw_payload and "-----END PGP MESSAGE-----" in raw_payload:
  72.           return payload
  73.         payload.set_payload( gpg.encrypt() )
  74.         if payload['Content-Transfer-Encoding']:
  75.                 log = open(cfg['logging']['file'], 'a')
  76.                 log.write((payload['Content-Transfer-Encoding'])+"\n")
  77.                 log.close()
  78.         if payload['Content-Disposition']:
  79.                 payload.replace_header( 'Content-Disposition', re.sub(r'filename="([^"]+)"', r'filename="\1.pgp"', payload['Content-Disposition']) )
  80.         if payload['Content-Type']:
  81.                 payload.replace_header( 'Content-Type', re.sub(r'name="([^"]+)"', r'name="\1.pgp"', payload['Content-Type']) )
  82.                 if 'name="' in payload['Content-Type']:
  83.                         payload.replace_header( 'Content-Type', re.sub(r'^[a-z/]+;', r'application/octet-stream;', payload['Content-Type']) )
  84.                         payload.set_payload( "\n".join( filter( lambda x:re.search(r'^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$',x), payload.get_payload().split("\n") ) ) )
  85.         return payload
  86.  
  87. def encrypt_all_payloads( payloads, gpg_to_cmdline ):
  88.         encrypted_payloads = list()
  89.         if type( payloads ) == str:
  90.                 msg = email.message.Message()
  91.                 msg.set_payload( payloads )
  92.                 return encrypt_payload( msg, gpg_to_cmdline ).as_string()
  93.         for payload in payloads:
  94.                 if( type( payload.get_payload() ) == list ):
  95.                         encrypted_payloads.append( encrypt_all_payloads( payload.get_payload(), gpg_to_cmdline ) )
  96.                 else:
  97.                         encrypted_payloads.append( [encrypt_payload( payload, gpg_to_cmdline )] )
  98.         return sum(encrypted_payloads, [])
  99.  
  100. def get_msg( message ):
  101.         if not message.is_multipart():
  102.                 return message.get_payload()
  103.         return '\n\n'.join( [base64.decodestring(str(m)) for m in message.get_payload()] )
  104.  
  105. keys = GnuPG.public_keys( cfg['gpg']['keyhome'] )
  106. gpg_to = list()
  107. ungpg_to = list()
  108.  
  109. for to in to_addrs:
  110.         domain = to.split('@')[1]
  111.         if domain in cfg['default']['domains'].split(','):
  112.                 if to in keys:
  113.                         gpg_to.append( (to, to) )
  114.                 elif cfg.has_key('keymap') and cfg['keymap'].has_key(to):
  115.                         gpg_to.append( (to, cfg['keymap'][to]) )
  116.         else:
  117.                 ungpg_to.append(to)
  118.  
  119. if gpg_to == list():
  120.         if cfg['default'].has_key('add_header') and cfg['default']['add_header'] == 'yes':
  121.                 raw_message['X-GPG-Mailgate'] = 'Not encrypted, public key not found'
  122.         send_msg( raw_message )
  123.         exit()
  124.  
  125. if ungpg_to != list():
  126.         send_msg( raw_message, ungpg_to )
  127.  
  128. if cfg.has_key('logging') and cfg['logging'].has_key('file'):
  129.         log = open(cfg['logging']['file'], 'a')
  130.         log.write("Encrypting email to: %s\n" % ' '.join( map(lambda x: x[0], gpg_to) ))
  131.         log.close()
  132.  
  133. if cfg['default'].has_key('add_header') and cfg['default']['add_header'] == 'yes':
  134.         raw_message['X-GPG-Mailgate'] = 'Encrypted by GPG Mailgate'
  135.  
  136. gpg_to_cmdline = list()
  137. gpg_to_smtp = list()
  138. for rcpt in gpg_to:
  139.         gpg_to_smtp.append(rcpt[0])
  140.         gpg_to_cmdline.extend(rcpt[1].split(','))
  141.  
  142. encrypted_payloads = encrypt_all_payloads( raw_message.get_payload(), gpg_to_cmdline )
  143. raw_message.set_payload( encrypted_payloads )
  144.  
  145. send_msg( raw_message, gpg_to_smtp )
Advertisement
Add Comment
Please, Sign In to add comment