Postfix - 将未知收件人拒绝的电子邮件转发到 SPAM-learning 邮箱

Postfix - 将未知收件人拒绝的电子邮件转发到 SPAM-learning 邮箱

我在几个 Exchange 前运行 Postfix + BitDefender FRAMS 作为卫生网关。BD FRAMS 可以通过从专用邮箱下载垃圾邮件和 HAM 邮件来学习其 Baesian 过滤器。由于我们持续向未知收件人发送垃圾邮件,所以我想将这个有用的垃圾邮件来源直接重定向到垃圾邮件学习邮箱。

我的配置:

主文件:

myhostname = posfix.example.com
smtpd_banner = $myhostname
#myorigin = example.com
mydestination =
local_recipient_maps =
#virtual_alias_maps = hash:/etc/postfix/virtual
local_transport = error:local mail delivery is disabled

mynetworks = /etc/postfix/mynetworks

smtpd_use_tls = yes
#smtpd_tls_auth_only = yes
smtpd_tls_key_file = /etc/ssl/certs/posfix.example.com.pem
smtpd_tls_cert_file = /etc/ssl/certs/posfix.example.com.pem
smtpd_tls_CApath = /etc/ssl/certs
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s

relay_domains = mysql:/etc/postfix/relay_domains
transport_maps = mysql:/etc/postfix/transport
relay_recipient_maps = mysql:/etc/postfix/relay_recipient_maps

show_user_unknown_table_name = no
unknown_local_recipient_reject_code = 550

mailbox_size_limit = 102400000000
message_size_limit = 102400000

smtpd_delay_reject = yes
smtpd_helo_required = yes

#smtpd_helo_restrictions =
#  permit_mynetworks
#  reject_invalid_hostname
#  permit

smtpd_restriction_classes = verify_sender
verify_sender =
  reject_unverified_sender

smtpd_sender_restrictions =
  permit_mynetworks

smtpd_recipient_restrictions =
  reject_unknown_recipient_domain
  reject_non_fqdn_recipient
  permit_mynetworks
  reject_authenticated_sender_login_mismatch
  reject_unauth_destination
  check_recipient_access hash:/etc/postfix/recipient_access
  check_sender_access hash:/etc/postfix/sender_access
  #check_helo_access pcre:/etc/postfix/helo_access
  reject_non_fqdn_sender
  reject_unknown_sender_domain
  reject_unlisted_sender
  reject_invalid_hostname
  reject_unauth_pipelining
  check_sender_mx_access cidr:/etc/postfix/sender_mx_access
  #reject_non_fqdn_hostname
  #reject_unverified_sender
  #reject_multi_recipient_bounce
  permit

#smtpd_data_restrictions =
  #reject_multi_recipient_bounce

# Added by BitDefender on Mon Nov  3 15:27:43 EET 2014
smtpd_milters=unix:/var/spool/postfix/BitDefender/bdmilterd.sock
milter_protocol = 2
milter_default_action = tempfail
milter_connect_timeout = 30s
milter_command_timeout = 30s
milter_content_timeout = 30s
# End of added lines

在 /etc/postfix/relay_domains 中:

user = postfix
password = postfix
dbname = postfix
query = SELECT name FROM relay_domains WHERE name='%s'

在/etc/postfix/传输:

user = postfix
password = postfix
dbname = postfix
query = SELECT nexthop FROM relay_domains WHERE name='%s'

在/etc/postfix/relay_recipient_maps中:

user = postfix
password = postfix
dbname = postfix
query = SELECT email FROM relay_users WHERE email='%s'

我的用于从 AD 填充中继用户的脚本(请与您分享)用于 cron:

#!/usr/bin/python

__author__ = 'tiv'

import ldap
import MySQLdb

connections = {
    1: ['dc.example.com',  # AD domain controller
        'EXAMPLE\\user',  # AD user
        'password',  # AD user password
        'dc=example, dc=local',  # AD root DN
        'mail.example.com'],  # Exchange server

    2: ['dc.example1.com',  # AD domain controller
        'EXAMPLE1\\user',  # AD user
        'password',  # AD user password
        'dc=example1, dc=local',  # AD root DN
        'mail.example1.com'],  # Exchange server

    #3: 'dc.example2.com',  # AD domain controller
    #   'EXAMPLE2\\user',  # AD user
    #   'password',  # AD user password
    #   'dc=example2, dc=local',  # AD root DN
    #   'mail.example2.com'],  # Exchange server
}

mysql = ['localhost',  # host
         'postfix',  # user
         'postfix',  # password
         'postfix']  # schema

def main():
    try:
        emails = []
        domains = []
        for i in connections:
            connection = connections[i]
            print('Processing LDAP server ' + connection[0] + ':')
            basedn = connections[i][3]
            nexthop = connections[i][4]
            lc = ldapconnection(connection)
            ls = ldapsearch(lc, basedn)
            rl = resultlist(ls)
            emails.extend(rl[0])
            for domain in rl[1]:
                domains.append([domain, nexthop])
            print('Processing of LDAP server ' + connection[0] + ' completed.')
        createdb(emails, domains, mysql)
        print('Operation completed successfully!')
    except:
        print('Error processing of LDAP server ' + connection[0] + '!')
        pass

def ldapconnection(ldapserver):
    try:
        print(' Trying to connect to LDAP server ' + ldapserver[0] + '...')
        ldapconnection = ldap.initialize('ldap://' + ldapserver[0])
        ldapconnection.simple_bind_s(ldapserver[1], ldapserver[2])
        ldapconnection.protocol_version = ldap.VERSION3
        ldapconnection.set_option(ldap.OPT_REFERRALS, 0)
        print(' Connection to LDAP server ' + ldapserver[0] + ' succesfull.')
    except:
        print('Error connecting to LDAP server ' + ldapserver[0] + '!')
        pass
    return ldapconnection

def ldapsearch(ldapconnection, basedn):
    try:
        print(' Sending LDAP query request...')
        scope = ldap.SCOPE_SUBTREE
        filter = '(&(proxyAddresses=smtp:*)(!(objectClass=contact)))'
        attributes = ['proxyAddresses']
        searchresults = ldapconnection.search_s(basedn, scope, filter, attributes)
        print(' LDAP query request results received.')
    except:
        print('Error sending LDAP query request!')
        pass
    return searchresults

def resultlist(searchresults):
    try:
        print(' Processing LDAP query results...')
        emails = []
        domains = []
        for i in range(len(searchresults)):
            try:
                for j in range(len(searchresults[i][1]['proxyAddresses'])):
                    r = searchresults[i][1]['proxyAddresses'][j].lower()
                    if 'smtp:' in r:
                        email = r[5:]
                        emails.append(email)
                        domain = email.split("@")[1]
                        domains.append(domain)
            except:
                pass
        print(' LDAP query results processed.')
    except:
        print('Error processing LDAP query results!')
        pass
    return removedublicates(emails), removedublicates(domains)


def createdb(emails, domains, mysql):
    try:
        print('Connecting to DB ' + mysql[3] + '...')
        try:
            db = MySQLdb.connect(host=mysql[0], user=mysql[1], passwd=mysql[2])
            cursor = db.cursor()
            sql = 'CREATE SCHEMA IF NOT EXISTS ' + mysql[3]
            cursor.execute(sql)
            db.commit()
        except:
            pass
        try:
            db = MySQLdb.connect(host=mysql[0], user=mysql[1], passwd=mysql[2], db=mysql[3])
            cursor = db.cursor()
        except:
            print('Error connecting to DB ' + mysql[3] + '!')
        print(' Check schemas and tables...')
        sql = ['CREATE TABLE IF NOT EXISTS ' + mysql[3] + '.relay_users (id INT NOT NULL, email LONGTEXT NULL, PRIMARY KEY (id))',
               'CREATE TABLE IF NOT EXISTS ' + mysql[3] + '.relay_domains (id INT NOT NULL, name LONGTEXT NULL, nexthop LONGTEXT NULL, PRIMARY KEY (id))',
               'TRUNCATE ' + mysql[3] + '.relay_users',
               'TRUNCATE ' + mysql[3] + '.relay_domains']
        for i in range(len(sql)):
            cursor.execute(sql[i])
            db.commit()
        print(' Inserting domains...')
        for i in range(len(domains)):
            sql = 'INSERT INTO postfix.relay_domains (id, name, nexthop)' \
                  'VALUES ("' + str(i) + '", "' + domains[i][0] + '", "smtp:[' + domains[i][1] + ']")'
            cursor.execute(sql)
            db.commit()
        print(' Inserting emails...')
        for i in range(len(emails)):
            sql = 'INSERT INTO postfix.relay_users (id, email)' \
                  'VALUES ("' + str(i) + '", "' + emails[i] + '")'
            cursor.execute(sql)
            db.commit()
        db.close()
        print('Connection to DB ' + mysql[3] + ' closed.')
    except:
        print('Error while operating with DB ' + mysql[3] + '!')
        pass

def removedublicates(input):
    seen = set()
    seen_add = seen.add
    return [x for x in input if not (x in seen or seen_add(x))]

if __name__ == '__main__':
    main()

如果有人知道该怎么做,我将不胜感激。谢谢。

答案1

由于这件事,您的请求有点复杂。根据设计,Postfix 将根据地图的肯定结果执行某些操作。例如,在您的 中transport_maps,如果收件人从地图查找中获得肯定结果,它将向特定主机发送电子邮件。但是,如果您的查找结果为否定,则您想执行某些操作 - 重定向到另一个邮箱relay_recipient_maps。使用您的地图类型是哈希我认为没有其他办法除非涉及 sql/tcp map 来在map中实现负面结果逻辑。

对于 sql 解决方案,思路如下:

在此示例中,我将使用 sqlite。假设您有一个表,其中有一列名为relay_recipient。现在查询

select ifnull(select relay_recipient from mytable WHERE relay_recipient = %s, '[email protected]')

[email protected]每当收件人在relay_recipient_maps中不存在时,就会返回。将这些映射放在virtual_alias参数上。然后,每当电子邮件发送给未知用户时,它都会被别名为[电子邮件保护]

答案2

+1 @tmpl7 对如何使用 sqlite 实现你的场景有很好的想法

现在,问题是你还没有实现virtual_alias_maps参数中 ifnull 的 sql 查询。首先定义virtual_alias_mapsinmain.cf

virtual_alias_maps = mysql:/etc/postfix/redirect2spamlearning

的内容/etc/postfix/redirect2spamlearning

user = postfix
password = postfix
dbname = postfix
query = SELECT IFNULL((SELECT email FROM relay_users WHERE email='%s'), '[email protected]')

逻辑是:如果SELECT email FROM relay_users WHERE email='%s'没有返回任何内容(即空值),则电子邮件将被重定向到[电子邮件保护]

相关内容