2019-12-18 14:25:09 +01:00
|
|
|
import time
|
|
|
|
import sys
|
|
|
|
import logging
|
|
|
|
|
|
|
|
import Milter
|
|
|
|
|
2019-12-18 15:12:33 +01:00
|
|
|
import re
|
|
|
|
|
2019-12-19 11:34:18 +01:00
|
|
|
from email.header import decode_header
|
|
|
|
from email.utils import getaddresses
|
|
|
|
|
|
|
|
|
2019-12-18 14:25:09 +01:00
|
|
|
# Basic logger that also logs to stdout
|
|
|
|
# TODO: Improve this a lot.
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
logger.setLevel(logging.DEBUG)
|
|
|
|
|
|
|
|
handler = logging.StreamHandler(sys.stdout)
|
|
|
|
handler.setLevel(logging.DEBUG)
|
2019-12-18 15:35:23 +01:00
|
|
|
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
|
2019-12-18 14:25:09 +01:00
|
|
|
handler.setFormatter(formatter)
|
|
|
|
|
|
|
|
logger.addHandler(handler)
|
|
|
|
|
2019-12-18 15:35:23 +01:00
|
|
|
address_domain_regex = re.compile('.*@(?P<domain>[\.\w-]+)')
|
|
|
|
|
2019-12-18 15:12:33 +01:00
|
|
|
|
2019-12-19 11:34:18 +01:00
|
|
|
def get_decoded_header(value):
|
|
|
|
decoded_header_items = decode_header(value)
|
|
|
|
decoded_header_value = ''
|
|
|
|
for item in decoded_header_items:
|
|
|
|
decoded_item = item[0].decode(item[1]) if item[1] is not None else item[0]
|
|
|
|
if isinstance(decoded_item, bytes):
|
|
|
|
decoded_item = decoded_item.decode('ascii')
|
|
|
|
decoded_header_value += decoded_item
|
|
|
|
return getaddresses([decoded_header_value])[0]
|
2019-12-18 16:41:55 +01:00
|
|
|
|
|
|
|
|
2019-12-19 11:34:18 +01:00
|
|
|
def normalizeRawFromHeader(value):
|
|
|
|
return value.replace('\n', '').replace('\r', '').strip()
|
2019-12-18 15:35:23 +01:00
|
|
|
|
|
|
|
|
2019-12-19 11:34:18 +01:00
|
|
|
def getDomainFromValue(value):
|
2019-12-18 15:35:23 +01:00
|
|
|
""" Check whether given 'From:' header label contains something that looks like an email address."""
|
2019-12-19 11:34:18 +01:00
|
|
|
match = address_domain_regex.match(value)
|
2019-12-18 16:33:54 +01:00
|
|
|
return match.group('domain').strip() if match is not None else None
|
2019-12-18 15:35:23 +01:00
|
|
|
|
2019-12-18 15:12:33 +01:00
|
|
|
|
2019-12-18 14:25:09 +01:00
|
|
|
class SuspiciousFrom(Milter.Base):
|
|
|
|
def __init__(self):
|
|
|
|
self.id = Milter.uniqueID()
|
2019-12-18 16:33:54 +01:00
|
|
|
self.reset()
|
2019-12-18 16:43:59 +01:00
|
|
|
logger.debug(f"({self.id}) Instanciated.")
|
2019-12-18 16:33:54 +01:00
|
|
|
|
|
|
|
def reset(self):
|
2019-12-18 15:35:23 +01:00
|
|
|
self.final_result = Milter.ACCEPT
|
2019-12-18 15:12:33 +01:00
|
|
|
self.new_headers = []
|
2019-12-18 14:25:09 +01:00
|
|
|
|
|
|
|
def header(self, field, value):
|
2019-12-18 15:35:23 +01:00
|
|
|
"""Header hook gets called for every header within the email processed."""
|
2019-12-18 15:12:33 +01:00
|
|
|
if field.lower() == 'from':
|
2019-12-18 16:33:54 +01:00
|
|
|
logger.debug(f"({self.id}) Got \"From:\" header raw value: '{value}'")
|
2019-12-18 16:41:55 +01:00
|
|
|
value = normalizeRawFromHeader(value)
|
2019-12-18 16:33:54 +01:00
|
|
|
if value == '':
|
2019-12-19 11:34:18 +01:00
|
|
|
logger.warn(f"Got empty from header value! WTF! Skipping.")
|
2019-12-18 16:33:54 +01:00
|
|
|
return Milter.CONTINUE
|
2019-12-19 11:34:18 +01:00
|
|
|
data = get_decoded_header(value)
|
|
|
|
logger.info(f"({self.id}) Label: '{data[0]}', Address: '{data[1]}'")
|
|
|
|
if data[0] == '':
|
|
|
|
logger.info(f"({self.id}) No label in from header, OK!")
|
|
|
|
self.new_headers.append({'name': 'X-From-Checked', 'value': 'OK - No label specified'})
|
2019-12-18 15:12:33 +01:00
|
|
|
else:
|
2019-12-19 11:34:18 +01:00
|
|
|
label_domain = getDomainFromValue(data[0])
|
|
|
|
address_domain = getDomainFromValue(data[1])
|
|
|
|
logger.info(f"({self.id})Extracted label_domain '{label_domain}' and address_domain '{address_domain}'")
|
|
|
|
if label_domain is not None:
|
|
|
|
logger.debug(f"({self.id}) Label '{data[0]}' contains an address with domain '{label_domain}'.")
|
|
|
|
if label_domain.lower() == address_domain.lower():
|
|
|
|
logger.info(f"({self.id}) Label domain '{label_domain}' matches address domain '{address_domain}'. Good!")
|
|
|
|
self.new_headers.append({'name': 'X-From-Checked', 'value': 'OK - Label domain matches address domain'})
|
|
|
|
else:
|
|
|
|
logger.info(f"({self.id}) Label domain '{label_domain}' did NOT match address domain '{address_domain}'. BAD!")
|
|
|
|
self.new_headers.append({'name': 'X-From-Checked', 'value': 'FAIL - Label domain does NOT match address domain'})
|
|
|
|
else:
|
|
|
|
logger.info(f"({self.id}) No domain found in label. Good!")
|
|
|
|
self.new_headers.append({'name': 'X-From-Checked', 'value': 'OK - No domain found in label.'})
|
2019-12-18 15:35:23 +01:00
|
|
|
# Use continue here, so we can reach eom hook.
|
|
|
|
# TODO: Log and react if multiple From-headers are found?
|
|
|
|
return Milter.CONTINUE
|
2019-12-18 15:12:33 +01:00
|
|
|
|
|
|
|
def eom(self):
|
2019-12-18 15:35:23 +01:00
|
|
|
"""EOM hook gets called at the end of message processed. Headers and final verdict are applied only here."""
|
2019-12-18 16:33:54 +01:00
|
|
|
logger.info(f"({self.id}) EOM: Final verdict is {self.final_result}. New headers: {self.new_headers}")
|
2019-12-18 15:12:33 +01:00
|
|
|
for new_header in self.new_headers:
|
|
|
|
self.addheader(new_header['name'], new_header['value'])
|
2019-12-18 16:43:59 +01:00
|
|
|
logger.debug(f"({self.id}) EOM: Reseting self.")
|
2019-12-18 16:33:54 +01:00
|
|
|
self.reset()
|
2019-12-18 15:35:23 +01:00
|
|
|
return self.final_result
|
2019-12-18 15:12:33 +01:00
|
|
|
|
2019-12-18 14:25:09 +01:00
|
|
|
|
|
|
|
def main():
|
2019-12-18 15:35:23 +01:00
|
|
|
# TODO: Move this into configuration of some sort.
|
2019-12-18 14:25:09 +01:00
|
|
|
milter_socket = "inet:7777@127.0.0.1"
|
|
|
|
milter_timeout = 60
|
|
|
|
Milter.factory = SuspiciousFrom
|
|
|
|
logger.info(f"Starting Milter.")
|
|
|
|
# This call blocks the main thread.
|
2019-12-18 15:35:23 +01:00
|
|
|
# TODO: Improve handling CTRL+C
|
2019-12-18 14:25:09 +01:00
|
|
|
Milter.runmilter("SuspiciousFromMilter", milter_socket, milter_timeout, rmsock=False)
|
|
|
|
logger.info(f"Milter finished running.")
|
|
|
|
|
2019-12-18 15:35:23 +01:00
|
|
|
|
2019-12-18 14:25:09 +01:00
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|