Exim - Step2: exim + mysql

/etc/exim.conf
hide mysql_servers      = localhost/db/login/password
SMTP_IP                 = 12.34.56.78 # your server ip
LOCAL_IPS               = @ : @[] : localhost : 192.168.0.0/26
MAILDIR                 = /data/mail/
CONFIG_PREFIX           = /etc/exim/

# Максимальный размер письма
MESSAGE_SIZE_LIMIT      = 100M
# раcкомментируйте только после установки dpam\spamassasin\clamd
#CLAMD          = yes
#SPAMASSASSIN   = yes
#RSPAMD         = yes
#DSPAM          = yes

# (1-30 - врят ли спам, 31-45 - возможно спам, >45 - однозначно спам)
# помечать в заголовке (подозрительные письма)
SPAM_SCORE_MARK = 15
# перекладывать в папку .Junk (однозначно спам)
SPAM_SCORE_JUNK = 35
# убивать (нигерийский спам)
SPAM_SCORE_KILL = 70

# Как долго использовать для вайтлистинга адреса, на которые слали письма наши юзеры (2 месяца)
SENTKEEPALIVE   = 60*24*60*60
# сколько неправильных адресов в рассылке, после чего спамер блочится
ALLOWEDRCPTFAIL = 3

#########################################################################################################
# Ниже лучше ничего не трогать
#########################################################################################################

syslog_timestamp = no
log_file_path = syslog : /var/log/exim/%s-%D.log
log_selector = \
    +all_parents \
    +connection_reject \
    -incoming_interface \
    -host_lookup_failed \
    +lost_incoming_connection \
    +received_sender \
    +received_recipients \
    +smtp_confirmation \
    +smtp_syntax_error \
    +smtp_protocol_error \
    -queue_run

daemon_smtp_ports = 25 : 465 : 587 : 2525
.ifdef SPAMASSASSIN
spamd_address = 127.0.0.1 783
.endif
.ifdef RSPAMD
spamd_address = 127.0.0.1 11333
.endif
.ifdef CLAMD
av_scanner = clamd: /var/run/clamav/clamd.sock
.endif

domainlist      local_domains           = ${lookup mysql{SELECT domain FROM domains WHERE domain='${domain}' AND (type='LOCAL' OR type='VIRTUAL')}}
domainlist      relay_to_domains        = ${lookup mysql{SELECT domain FROM domains WHERE domain='${domain}' AND type='RELAY'}}
hostlist        rfc1918                 = 10.0.0.0/8 : 172.16.0.0/12 : 192.168.0.0/16
hostlist        relay_from_hosts        = 127.0.0.1

hostlist        whitelist               = LOCAL_IPS:${lookup mysql{SELECT address FROM whitelist WHERE address='${sender_host_address}'}}:net-iplsearch;CONFIG_PREFIX/whitelist.conf
hostlist        blacklist               = ${lookup mysql{SELECT address FROM blacklists WHERE address='${sender_host_address}' AND type='HOSTREJ'}}:net-iplsearch;CONFIG_PREFIX/blacklist.conf

ALIASES         = SELECT recipients FROM aliases WHERE local_part='${local_part}' AND domain='${domain}'
USERSFWD        = SELECT recipients FROM userforward WHERE local_part='${local_part}' AND domain='${domain}'
USERFORWARDLIST = SELECT local_part FROM userforward WHERE local_part='${local_part}' AND domain='${domain}'
GETUSERID       = SELECT CONCAT('MAILDIR',domain,'/',id) FROM users WHERE id='${local_part}' AND domain='${domain}' AND active='Y'
GETUSERDIR      = SELECT CONCAT('MAILDIR',domain,'/',id,'/Maildir') FROM users WHERE id='${local_part}' AND domain='${domain}'
GETUSERQUOTA    = SELECT quota FROM users WHERE id='${local_part}' AND domain='${domain}'
#KILLSPAM       = SELECT id FROM users WHERE id='${local_part}' AND domain='${domain}' AND active='Y' AND killspam='1' LIMIT 1
CHECKSENTMAIL   = SELECT mail_count FROM `sentmail` WHERE `from`<>'' AND `mail`='$sender_address' AND `last_mail_timestamp`<`last_mail_timestamp`+(SENTKEEPALIVE) LIMIT 1
ADDSENTMAIL     = INSERT IGNORE INTO `sentmail` (`from`, `mail`, `added_timestamp`, `last_mail_timestamp`, `mail_count`) \
                         VALUES (LCASE('${quote_mysql:$sender_address}'), LCASE('${quote_mysql:[email protected]$domain}'), UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 1) \
                         ON DUPLICATE KEY UPDATE `last_mail_timestamp` = UNIX_TIMESTAMP(), `from` = LCASE('${quote_mysql:$sender_address}'), `mail_count` = `mail_count` + 1

DOMAIN                          = ${lc:${domain:$h_from:}}
DKIM_FILE                       = CONFIG_PREFIX/dkim/dkim.key
DKIM_PRIVATE_KEY                = ${if exists{DKIM_FILE}{DKIM_FILE}{0}}
DKIM_KNOWN_SIGNERS              = ${readfile {CONFIG_PREFIX/dkim_only.conf}{:}}
dkim_verify_signers             = $dkim_signers : DKIM_KNOWN_SIGNERS

tls_advertise_hosts		= *
tls_on_connect_ports		= 465
tls_certificate			= CONFIG_PREFIX/ssl.pem
tls_privatekey			= CONFIG_PREFIX/ssl.key

system_filter                   = CONFIG_PREFIX/system-filter
system_filter_user              = mail
system_filter_file_transport    = address_file
system_filter_pipe_transport    = address_pipe
system_filter_directory_transport = dovecot_delivery

received_header_text = Received: \
  ${if def:sender_rcvhost {from $sender_rcvhost } {${if def:sender_ident {from ${quote_local_part:$sender_ident} }}}} \n\t\
  by $primary_hostname ${if def:tls_cipher {over $tls_cipher }}\
  with Microsoft Exchange 2000 Server SMTPSVC(5.0.2195.1600) id $message_exim_id\
  ${if def:received_for {\n\tfor $received_for}}

timezone                        = Europe/Moscow
smtp_banner                     = "Microsoft ESMTP MAIL Service, Version: 5.0.2195.1600 ready"
smtp_enforce_sync               = true
allow_domain_literals           = false
never_users                     = root:daemon:bin
host_lookup                     = * : !rfc1918 : !LOCAL_IPS
helo_allow_chars                = _ : -
trusted_users                   = mail
trusted_groups                  = mail
rfc1413_hosts                   = *
rfc1413_query_timeout           = 0s
helo_verify_hosts               = !*
helo_try_verify_hosts           = !*
helo_accept_junk_hosts          = !*
smtp_accept_max_nonmail_hosts   = *
ignore_bounce_errors_after      = 1d
timeout_frozen_after            = 3d
auto_thaw                       = 15m
message_body_visible            = 5000
message_size_limit              = MESSAGE_SIZE_LIMIT
smtp_accept_max                 = 500
smtp_accept_max_per_connection  = 25
smtp_accept_queue_per_connection= 20
smtp_connect_backlog            = 40
smtp_accept_max_per_host        = 10
recipients_max                  = 100
recipients_max_reject           = true
split_spool_directory           = true
message_logs                    = false
remote_max_parallel             = 15
smtp_load_reserve               = 40
smtp_accept_max_nonmail         = 7
smtp_max_unknown_commands       = 1
return_size_limit               = 70k
untrusted_set_sender            = *

acl_smtp_connect = acl_check_connect
acl_smtp_dkim    = acl_check_dkim
acl_smtp_mail    = acl_check_mail
acl_smtp_rcpt    = acl_check_rcpt
acl_smtp_data    = acl_check_data
acl_smtp_mime    = acl_check_mime

##########################################################################################################
begin acl
##########################################################################################################

acl_check_connect:
    accept      hosts           = +whitelist
    warn        delay           = 3s
    drop        hosts           = +blacklist
                message         = Your ip is in blacklist on this server.
                log_message     = Antispam: Host $sender_host_address in local blacklist
    accept

####################################
acl_check_mail:
    accept      hosts         = +whitelist
    drop        condition     = ${if eq{$sender_helo_name}{}}
                message       = Denied - HELO required before MAIL
    drop        condition     = ${if match{$sender_helo_name}{\N((\d{1,3}[.-]\d{1,3}[.-]\d{1,3}[.-]\d{1,3})|([0-9a-f]{8})|([0-9A-F]{8}))\N}{yes}{no}}
                condition     = ${if match {${lookup dnsdb{>: defer_never,ptr=$sender_host_address}}\}{$sender_helo_name}{no}{yes}}
                message       = Denied - Helo name contains a ip address (HELO was $sender_helo_name) and not is valid
                delay         = 40s
    drop        condition     = ${if eq{[$interface_address]}{$sender_helo_name}}
                message       = Denied - $interface_address is _my_ address
    warn        condition     = ${if isip{$sender_helo_name}}
                message       = Invalid HELO name (See RFC2821 4.1.3)
                set acl_c_spam = ${eval:$acl_c_spam+20}
    accept

####################################
acl_check_dkim:
        accept  hosts           = +whitelist
        accept  authenticated   = *
        warn
                condition       = ${if eq {$dkim_verify_status}{invalid}{yes}{no}}
                sender_domains  = $sender_address_domain:$dkim_signers.
                dkim_signers    = $sender_address_domain:$dkim_signers.
                dkim_status     = invalid
                logwrite        = X-DKIM-Status: $dkim_verify_status signature for known domain $dkim_cur_signer ($sender_host_address)
                add_header      = X-DKIM: $dkim_verify_status
                add_header      = X-DKIM-Status: $dkim_verify_status signature for known domain $dkim_cur_signer ($sender_host_address)
                add_header      = Authentication-Results: dkim=$dkim_verify_status
                set acl_c_spam  = ${eval:$acl_c_spam+50}

        warn
                condition       = ${if eq {$dkim_verify_status}{fail}{yes}{no}}
                sender_domains  = $sender_address_domain:$dkim_signers.
                dkim_signers    = $sender_address_domain:$dkim_signers.
                dkim_status     = fail
                logwrite        = X-DKIM-Status: $dkim_verify_status signature for known domain $dkim_cur_signer ($sender_host_address)
                add_header      = X-DKIM: $dkim_verify_status
                add_header      = X-DKIM-Status: $dkim_verify_status signature for known domain $dkim_cur_signer ($sender_host_address)
                add_header      = Authentication-Results: dkim=$dkim_verify_status
                set acl_c_spam  = ${eval:$acl_c_spam+50}

        warn
                condition       = ${if eq {$dkim_verify_status}{none}{yes}{no}}
                dkim_status     = none
                sender_domains  = $sender_address_domain:$dkim_signers
                dkim_signers    = $sender_address_domain:$dkim_signers
                logwrite        = X-DKIM-Status: $dkim_verify_status signature for known domain $dkim_cur_signer ($sender_host_address)
                add_header      = X-DKIM: $dkim_verify_status
                add_header      = X-DKIM-Status: $dkim_verify_status signature for known domain $dkim_cur_signer ($sender_host_address)
                add_header      = Authentication-Results: dkim=$dkim_verify_status
                set acl_c_spam  = ${eval:$acl_c_spam+50}

        accept
                condition       = ${if eq {$dkim_verify_status}{pass}{yes}{no}}
                dkim_status     = pass
                sender_domains  = $sender_address_domain:$dkim_signers
                dkim_signers    = $sender_address_domain:$dkim_signers
                logwrite        = X-DKIM-Status: $dkim_verify_status signature for $dkim_cur_signer ($sender_host_address)
                add_header      = X-DKIM: $dkim_verify_status
                add_header      = X-DKIM-Status: $dkim_verify_status signature for $dkim_cur_signer ($sender_host_address)
                add_header      = Authentication-Results: dkim=$dkim_verify_status
                add_header      = X-Whitelisted: Yes
        accept

####################################
acl_check_rcpt:
  # log our sent mail
  warn    domains       = !+local_domains
          sender_domains  = +local_domains:${lookup mysql{ADDSENTMAIL}}
  # allow local transports
  accept  hosts         = :

  deny    message       = Denied - Restricted characters in address
          domains       = +local_domains
          local_parts   = ^[.] : ^.*[@%!/|]

  deny    message       = Denied - Restricted characters in address
          domains       = !+local_domains
          local_parts   = ^[./|] : ^.*[@%!] : ^.*/\\.\\./

  accept  hosts         = +relay_from_hosts
          control       = submission/sender_retain

  accept  authenticated = *
          control       = submission/sender_retain

  # Рубаем дебилов, которые спамят по словарю
  drop  message         = Denied - Dictionnary attack ($rcpt_fail_count failed queries)
        condition       = ${if >{$rcpt_fail_count}{${eval:ALLOWEDRCPTFAIL-2}} {1}{0}}
        delay           = ${eval:30*$rcpt_fail_count}s
        domains         = +local_domains
        !verify         = recipient
  drop  message         = Denied - Too many failed recipients count = $rcpt_fail_count
        condition       = ${if > {${eval:$rcpt_fail_count}}{3}{yes}{no}}
        !verify         = recipient/callout=2m,defer_ok,use_sender

    # Блокируем, если без авторизации отправляют почту на адреса рассылки (сделанные для своих чуваков)
    drop        message         = Denied - You are not allowered to sent mails here
                condition       = ${lookup mysql{USERFORWARDLIST}{yes}{no}}
                hosts           = !+whitelist

    # проверка на существование ящика (вместо "require verify = sender")
    warn        sender_domains  = *:!+local_domains
                !verify         = sender/callout=90s,postmaster
                hosts           = !+whitelist
                log_message     = Antispam: Sender verify error ($sender_address from $sender_host_address)
                add_header      = X-Spam-Report: Sender verify error
                set acl_c_spam  = ${eval:$acl_c_spam+21}

    # Нет бэкрозолва - значит 99% спамер
    warn        condition       = ${if eq{$host_lookup_failed}{1}{yes}{no}}
                condition       = ${if or{\
                                {eq{${lookup dnsdb{ptr=$sender_host_address}}}{}}\
                                {eq{${lookup dnsdb{a=$sender_host_address}}}{}}}\
                                {yes}{no}}
                hosts           = !+whitelist
                log_message     = Antispam: no backresolve for $sender_host_address
                add_header      = X-Spam-Report: No backresolve!
                set acl_c_spam  = ${eval:$acl_c_spam+23}
    # Проверяем бэкрезолв на наличие признаков ненормальности
    warn        hosts           = wildlsearch;CONFIG_PREFIX/spam-hosts
                hosts           = !+whitelist
                log_message     = Antispam: $sender_host_name uses dynamic pool with lots of - and .
                add_header      = X-Spam-Report: Uses dynamic pool ($sender_host_name)
                set acl_c_spam  = ${eval:$acl_c_spam+34}
    # Задержка для тех, кто во внешних блоклистах
    warn        dnslists        = ${readfile{CONFIG_PREFIX/dnsbl.conf}{:}}
                hosts           = !+whitelist
                message         = X-Spam-Report: $sender_host_address is blacklisted at $dnslist_domain - $dnslist_text
                log_message     = Antispam: found in $dnslist_domain - $dnslist_text
                set acl_c_spam  = ${eval:$acl_c_spam+35}
    # SPF CHECKS ----
    warn        condition       = ${if eq{$spf_result}{}{no}{yes}}
                log_message     = Antispam: spf=$spf_result
                add_header      = Received-SPF: $spf_result ($sender_address_domain: $sender_host_name [$sender_host_address]) client-ip=$sender_host_address; envelope-from=$sender_address; helo=$sender_helo_name
    # Добавляем очки, если spf не соответствует
    warn        spf             = fail
                hosts           = *:!+whitelist
                log_message     = Antispam: spf not valid
                set acl_c_spam  = ${eval:$acl_c_spam+37}
    # сносим задержку, если с этим адресом народ переписывался хоть раз за последнее N время (см выше)
    warn        log_message     = Antispam: addr exists in sent mail lists, setting delay to 0
                condition       = ${lookup mysql{CHECKSENTMAIL}{yes}{no}}
                set acl_c_spam  = 0

    # убираем задержку вайтлисту
    warn        hosts           = +whitelist
                log_message     = Antispam: exists in whitelist
                add_header      = X-Whitelisted: Yes (Whitelist)
                set acl_c_spam  = 0

    # делаем саму задержку (если выживет, то мож еще почитаем письмо)
    warn        condition       = ${if <{$acl_c_spam}{SPAM_SCORE_KILL}{yes}{no}}
                condition       = ${if >{$acl_c_spam}{0}{yes}{no}}
                logwrite        = Antispam: Delay $acl_c_spam sec for $sender_host_name \
                                  [$sender_host_address] with HELO=$sender_helo_name. Mail \
                                  from $sender_address to [email protected]$domain.
                add_header      = X-Spam-Delay: $acl_c_spam
                delay           = ${eval:$acl_c_spam}s

    # добавляем в subject ***SPAM***
    warn        condition       = ${if >{$acl_c_spam}{${eval:SPAM_SCORE_MARK-1}}{yes}{no}}
                add_header      = X-Spam-Mark: Yes
                log_message     = Antispam: detected spam_mark (from $sender_address).
    # перекладываем в .Junk
    warn        condition       = ${if >{$acl_c_spam}{${eval:SPAM_SCORE_JUNK-1}}{yes}{no}}
                add_header      = X-Spam-Junk: Yes
                log_message     = Antispam: detected spam_junk (from $sender_address).
    # убиваем письмо
    warn        condition       = ${if >{$acl_c_spam}{${eval:SPAM_SCORE_KILL-1}}{yes}{no}}
                add_header      = X-Spam-Kill: Yes
                log_message     = Antispam: detected spam_kill (from $sender_address).

    # ----------------------------------------------------------------------
    # Блокируем всех, кто не авторизовался или шлет письма не нам
    require     message         = Denied - relay not permitted
                domains         = +local_domains : +relay_to_domains

    deny        message         = Denied - smtp auth requried
                sender_domains  = +local_domains
                !authenticated  = *

    require verify              = recipient

    accept

####################################
acl_check_data:
    # skip scanning for authenticated users
    accept      authenticated   = *
    # do not scan messages submitted from our own hosts and whitelist
    accept     hosts           = +whitelist
    deny        demime          = *
                condition       = ${if >{$demime_errorlevel}{2}{1}{0}}
                message         = Denied - Serious MIME defect detected ($demime_reason)
    .ifdef CLAMD
    deny        message         = Message contains a virus ($malware_name) and has been rejected
                demime          = *
                malware         = *
    .endif
    .ifdef RSPAMD
    # do not scan messages from submission port
    accept      condition       = ${if eq {$interface_port}{587} {yes}{no}}
    # add spam-score header
    warn        message         = X-Spam-Score: $spam_score ($spam_bar)
                spam            = nobody:true
    # add report header
    warn        message         = X-Spam-Report: $spam_report
                spam            = nobody:true
    .endif
    .ifdef SPAMASSASSIN
    warn
        hosts           = !+relay_from_hosts
        condition       = ${if < {$message_size}{1M}}
        spam            = nobody:true/defer_ok
        add_header      = X-Spam-Score: $spam_score_int
        add_header      = X-Spam-Bar: $spam_bar
        add_header      = X-Spam-Report: $spam_report
        set acl_m2      = $spam_score_int
    warn
        condition       = ${if >{$acl_m2}{${eval:SPAM_SCORE_MARK-1}}{yes}{no}}
        add_header      = X-Spam-Mark: Yes
        log_message     = Antispam: SpamAssassin detected spam_sa_mark (from $sender_address to $recipients).
    warn
        condition       = ${if >{$acl_m2}{${eval:SPAM_SCORE_JUNK-1}}{yes}{no}}
        add_header      = X-Spam-Junk: Yes
        log_message     = Antispam: SpamAssassin detected spam_sa_junk (from $sender_address to $recipients).
    warn
        condition       = ${if >{$acl_m2}{${eval:SPAM_SCORE_KILL-1}}{yes}{no}}
        add_header      = X-Spam-Kill: Yes
        log_message     = Antispam: SpamAssassin detected spam_sa_kill (from $sender_address to $recipients).
    .endif
    accept

####################################
acl_check_mime:
    accept  hosts        = +whitelist
    deny   message       = Denied - Blacklisted file extension detected
           condition     = ${if match {${lc:$mime_filename}}{\N(\.ade|\.adp|\.bat|\.chm|\.cmd|\.com|\.cpl|\.exe|\.hta|\.ins|\.isp|\.jse|\.lib|\.lnk|\.mde|\.msc|\.msp|\.mst|\.pif|\.scr|\.sct|\.shb|\.sys|\.vb|\.vbe|\.vbs|\.vxd|\.wsc|\.wsf|\.wsh)$\N}{1}{0}}
    accept

##########################################################################################################
begin authenticators
##########################################################################################################
dovecot_plain:
  driver = dovecot
  public_name = PLAIN
  server_socket = /var/run/dovecot/auth-client
  server_set_id = $auth1

dovecot_login:
  driver = dovecot
  public_name = LOGIN
  server_socket = /var/run/dovecot/auth-client
  server_set_id = $auth1

dovecot_cram_md5:
  driver = dovecot
  public_name = CRAM-MD5
  server_socket = /var/run/dovecot/auth-client
  server_set_id = $auth1

##########################################################################################################
begin routers
##########################################################################################################
dnslookup:
  driver = dnslookup
  domains = !+local_domains
  same_domain_copy_routing = yes
  transport = remote_smtp
  ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8 : +rfc1918
  no_more

system_aliases:
  driver = redirect
  allow_fail
  allow_defer
  data = ${lookup mysql{ALIASES}}

userforward:
  driver = redirect
  allow_fail
  allow_defer
  data = ${lookup mysql{USERSFWD}}

dovecot_user:
  driver = accept
  condition = ${if eq{} {${lookup mysql{GETUSERID}}}{no}{yes}}
  cannot_route_message = Unknown user
  transport = dovecot_delivery

##########################################################################################################
begin transports
##########################################################################################################

remote_smtp:
  driver = smtp
  .ifdef SMTP_IP
  interface = SMTP_IP
  .endif
  dkim_domain = DOMAIN
  dkim_selector = dkim
  dkim_private_key = DKIM_PRIVATE_KEY
  dkim_canon = relaxed
  dkim_strict = 0
  headers_remove = X-Whitelisted:X-Spam-Score:X-Spam-Detected:X-Spam-Mark:X-Spam-Junk:X-Spam-Kill:X-Spam-Delay:X-DKIM-Status:X-DKIM:Authentication-Results

dovecot_delivery:
  driver = pipe
  command = /usr/libexec/dovecot/dovecot-lda -d [email protected]$domain
  message_prefix =
  message_suffix =
  delivery_date_add
  envelope_to_add
  return_path_add
  log_output
  user = mail

address_pipe:
  driver = pipe
  return_output

address_file:
  driver = appendfile
  delivery_date_add
  envelope_to_add
  return_path_add

address_reply:
  driver = autoreply

devnull:
  driver = appendfile
  file = /dev/null

##########################################################################################################
begin retry
*                      *           F,2h,15m; G,16h,1h,1.5; F,4d,6h
##########################################################################################################
begin rewrite

##########################################################################################################

Системный фильтр, отрабатывающий после всего конфига:
/etc/exim/system-filter
# стоит метка убить это письмо
if $message_headers contain "X-Spam-Kill"
then
    seen finish
endif

# стоит метка пометить это письмо как спам
if $message_headers contain "X-Spam-Mark"
then
    headers add "X-New-Subject: $h_Subject:"
    headers remove subject
    headers add "Subject: ***SPAM*** $h_X-New-Subject:"
    headers remove X-New-Subject
endif

Список плохих бэкрезолвов:
/etc/exim/spam-hosts
\N^[a-fA-F0-9]{10,}(\.[^\.]+){2,}\N
\N^\d+\.\d+\.\d+\.\d+\.\w+\N
\N^.*?[\w\d]+[\.\-](\w*\d+[\-x]){2,}\w*\d+\.[\w\d]\N
\N^\w+\d{5,}[\w]*[\.\-]\N
\N^\d+\.ya1\.ru\N
nat.sitc.ru
\N^(\d+[\-\.]){2,}[\d\w]+\N
\N^.*?\b(client|dial(ed)?|vpn|modem|dhcp|[dD]ynamic|[iI][pP]|pool|catv|ppp|cable|[xav]?dsl)(\d+\w*)?(\.[^\.]+){2,}$\N
*.comcast.net
\N^([xav]?dsl|client|ppp|dial(ed)?|vpn|dhcp|di(al)?up|[xav]?dsl|modem|pool|catv|tomts|host|[uU][sS][eE][rR])[\d]*[\-\.]?\d+\.\N
*.merr.com
*.wanadoo.fr
\N^(\w+\d+[\-\.]){2,}\N
\N^\w+\d+\.neoline\.com\.br$\N
rsveg.plus.com
*.virtua.com.br
*.door.net
*.utoronto.ca
*.venti.pl
*.t-dialin.net
\N^([\d\w]+[\-\.]){2,}\d+[\-\.]\N
*.fortech.lv
*.tpnet.pl
*.1000lecie.pl
*.superb.net
*.chello.nl
*.mobille.tv
*.upc.cz
*.wroc.pl
*.vnet.ee
*.astral.ro
*.bellnexxia.net
*.mynet.net
*.sgci.com
*.shawcable.com
*.ne.jp
*.co.jp
*.oleane.fr
*.wanadoo.co.uk
*.pppool.de
*.bah-bonn.de
*.unict.it
*.interpc.pl
*.retevision.es
*.contactel.cz
*.ufmg.br
*.racsa.co.cr
mail.holzmann.de
*.hananet.net
*.dotnews.ru

Онлайн блэк-листы помещаем сюда - /etc/exim/dnsbl.conf
b.barracudacentral.org
blackholes.five-ten-sg.com
blacklist.woody.ch
bl.deadbeef.com
bl.emailbasura.org
bl.spamcannibal.org
bl.spamcop.net
bogons.cymru.com
cbl.abuseat.org
cdl.anti-spam.org.cn
combined.abuse.ch
combined.rbl.msrbl.net
db.wpbl.info
dnsbl-1.uceprotect.net
dnsbl-2.uceprotect.net
dnsbl-3.uceprotect.net
dnsbl.ahbl.org
dnsbl.inps.de
dnsbl.sorbs.net
drone.abuse.ch
duinv.aupads.org
dul.dnsbl.sorbs.net
dul.ru
dyna.spamrats.com
dynip.rothen.com
http.dnsbl.sorbs.net
images.rbl.msrbl.net
ips.backscatterer.org
ix.dnsbl.manitu.net
korea.services.net
misc.dnsbl.sorbs.net
multi.surbl.org
noptr.spamrats.com
orvedb.aupads.org
pbl.spamhaus.org
phishing.rbl.msrbl.net
proxy.bl.gweep.ca
psbl.surriel.com
rbl.interserver.net
recent.spam.dnsbl.sorbs.net
relays.bl.gweep.ca
relays.bl.kundenserver.de
relays.dnsbl.sorbs.net
relays.nether.net
sbl.spamhaus.org
sbl-xbl.spamhaus.org
short.rbl.jp
smtp.dnsbl.sorbs.net
socks.dnsbl.sorbs.net
spam.abuse.ch
spam.dnsbl.sorbs.net
spamlist.or.kr
spamrbl.imp.ch
spam.rbl.msrbl.net
spam.spamrats.com
tor.ahbl.org
tor.dnsbl.sectoor.de
torserver.tor.dnsbl.sectoor.de
ubl.lashback.com
ubl.unsubscore.com
virbl.bit.nl
virus.rbl.jp
virus.rbl.msrbl.net
web.dnsbl.sorbs.net
wormrbl.imp.ch
xbl.spamhaus.org
zen.spamhaus.org
zombie.dnsbl.sorbs.net

В файл /etc/exim/dkim_only.conf надо добавить все домены, серверы которых подписывают свои письма с помощью DKIM, тогда любой спамер, отправивший письмо будто бы с домена @gmail.com, пойдет лесом.
aol.com
bk.ru
chat.ru
ebay.com
ebox.ru
gmail.com
gmail.ru
hotbox.ru
hotmail.com
hotmail.ru
inbox.ru
list.ru
mail.com
mail.ru
megabox.ru
microsoft.com
e-mail.microsoft.com
msn.com
narod.ru
newmail.com
newmail.ru
nic.ru
nm.ru
ok.kz
online.com.ua
online.ua
paypal.com
pisem.net
pochta.ru
rambler.ru
smtp.ru
email.skype.com
skype.com
ukr.net
ukrpost.net
yahoo.com
yandex.ru
yandex.ua
ya.ru

MySQL


MySQL scheme
DELIMITER $$
CREATE FUNCTION `EXIM_GET_PWD`(p VARCHAR(128)) RETURNS varchar(64)
begin
 UPDATE `users` SET `lastactive`=CONCAT(curdate(),' ',curtime()) WHERE `login` = TRIM(p) LIMIT 1;
 RETURN (SELECT `passwd` FROM `users` WHERE `login` = TRIM(p) LIMIT 1); 
end$$
DELIMITER ;

CREATE TABLE IF NOT EXISTS `aliases` (
  `local_part` varchar(64) NOT NULL DEFAULT '',
  `domain` varchar(128) NOT NULL DEFAULT '',
  `recipients` text,
  PRIMARY KEY (`local_part`,`domain`)
) TYPE=MyISAM;

CREATE TABLE IF NOT EXISTS `blacklists` (
  `address` varchar(64) NOT NULL DEFAULT '',
  `type` enum('SENDER','HOSTREJ','REJRCPT') NOT NULL DEFAULT 'SENDER',
  `message` text,
  PRIMARY KEY (`address`,`type`)
) TYPE=MyISAM;


CREATE TABLE IF NOT EXISTS `domains` (
  `domain` varchar(128) NOT NULL DEFAULT 'domain1.ru',
  `type` enum('LOCAL','RELAY','VIRTUAL') DEFAULT 'LOCAL',
  PRIMARY KEY (`domain`)
) TYPE=MyISAM;


CREATE TABLE IF NOT EXISTS `sentmail` (
  `mail` varchar(256) NOT NULL,
  `added_timestamp` int(32) NOT NULL,
  `last_mail_timestamp` int(32) NOT NULL,
  `mail_count` int(6) NOT NULL,
  PRIMARY KEY (`mail`),
  UNIQUE KEY `user_from` (`mail`),
  KEY `mail` (`mail`)
) TYPE=MyISAM;

CREATE TABLE IF NOT EXISTS `userforward` (
  `local_part` varchar(64) NOT NULL DEFAULT '',
  `domain` varchar(128) NOT NULL DEFAULT 'domain1.ru',
  `recipients` text,
  PRIMARY KEY (`local_part`,`domain`)
) TYPE=MyISAM;

CREATE TABLE IF NOT EXISTS `users` (
  `id` varchar(64) NOT NULL DEFAULT '',
  `login` varchar(128) NOT NULL,
  `crypt` varchar(64) NOT NULL DEFAULT '',
  `passwd` varchar(64) NOT NULL DEFAULT '',
  `domain` varchar(128) NOT NULL DEFAULT 'domain.ru',
  `client_id` int(11) NOT NULL DEFAULT '0',
  `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `lastactive` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `ip` varchar(15) NOT NULL,
  `quota` int(4) DEFAULT '500',
  `active` enum('Y','N') NOT NULL DEFAULT 'Y',
  `about` varchar(255) NOT NULL,
  `killspam` smallint(6) NOT NULL DEFAULT '0',
  `vacation` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`,`domain`),
  UNIQUE KEY `login` (`login`)
) TYPE=MyISAM;

CREATE TABLE IF NOT EXISTS `whitelist` (
  `address` varchar(64) NOT NULL DEFAULT '',
  PRIMARY KEY (`address`)
) TYPE=MyISAM;
Edit with your fields
INSERT INTO `domains` (`domain`, `type`) VALUES
('domain1.ru', 'LOCAL'),
('domain2.ru', 'VIRTUAL');

INSERT INTO `users` (`id`, `login`, `crypt`, `passwd`, `domain`, `client_id`, `created`, `lastactive`, `ip`, `quota`, `active`, `about`, `killspam`, `vacation`) VALUES
('admin', '[email protected]', crypt('pass'), 'pass', 'domain1.ru', 0, '2012-01-01 00:00:00', '0000-00-00 00:00:00', '127.0.0.1', 1000, 'Y',  'First admin account', 0, 0);

INSERT INTO `blacklists` (`address`, `type`, `message`) VALUES
('94.180.195.7', 'HOSTREJ', 'Your host is a spam relay'),
('81.19.66.33', 'HOSTREJ', 'Your host is a spam relay');