Debian: Postfix + Amavis(Spamassassin/Clamav) + Postgrey + SPF

Postfix + postscreen + SPF + Postgrey + OpenDKIM + OpenDMARC + Amavis (ClamAV / SpamAssassin) + DANE / MTA-STS

This guide builds an internet-facing MX gateway for mydomain.com. It:

  • accepts inbound mail from the internet, filters it hard, and relays clean mail to an internal mailbox server (Exchange, Dovecot, Zimbra and so on);
  • lets the internal mail server (and only the hosts you list) relay outbound mail through it, with the mail scanned, DKIM-signed and sent over DANE-verified TLS where the receiver supports it;
  • does not create backscatter, is not an open relay, and rejects as much as it can at SMTP time, before it takes responsibility for a message.

Tested against Debian 13 “trixie” (Postfix 3.10, SpamAssassin 4.0, ClamAV 1.4, amavisd-new 2.13). Debian 12 works too, with the small differences noted.

0. Placeholders used throughout

Replace these everywhere:

PlaceholderMeaning
mydomain.comYour mail domain
mx1.mydomain.comFQDN of this gateway (also its PTR and HELO name)
203.0.113.10Gateway public IPv4
10.0.0.5Gateway internal IPv4
10.0.0.20Internal mailbox server
10.0.0.0/24Internal LAN

1. Architecture

Inbound and outbound mail flow through the MX gateway

Design decisions, and why:

  • Two listeners. The public listener has zero trust: mynetworks there is loopback only. The internal listener sits on a separate IP with its own allow-list. You can’t accidentally open the relay by touching one mynetworks line.
  • After-queue Amavis, discard and quarantine, never bounce. Inbound spam and viruses carry forged senders. Bouncing them (D_BOUNCE) sends backscatter to innocent people and gets your IP blocklisted. Everything we can reject, we reject during SMTP (postscreen, SPF, DMARC, recipient validation). What Amavis catches afterwards is quarantined.
  • Recipient validation at the edge. The gateway knows which addresses exist and rejects the rest with a 550. Without that you accept mail for unknown users and then bounce it, which is backscatter again.
  • A local validating resolver (Unbound). DNSBLs (Spamhaus refuses queries that arrive through public resolvers), SpamAssassin URI blocklists and DANE all need it.

2. Prerequisites (the boring part that decides your deliverability)

  1. A static IPv4 with reverse DNS (PTR) set to mx1.mydomain.com. The A record for mx1.mydomain.com must point back to the same IP (forward-confirmed rDNS). Your hosting provider sets the PTR.
  2. Outbound TCP/25 unblocked by your provider. Many clouds block it by default.
  3. A clean IP. Check it on Spamhaus (it must not be on the PBL) and on the common blocklists before you start.
  4. IPv6: all or nothing. Either give IPv6 an AAAA, a PTR, and SPF coverage, or disable it (inet_protocols = ipv4). Gmail and Microsoft are much stricter with IPv6 senders. This guide uses IPv4 only; see §18 to add IPv6.
  5. Set the hostname:
hostnamectl set-hostname mx1.mydomain.com
# /etc/hosts
127.0.0.1    localhost
203.0.113.10 mx1.mydomain.com mx1Code language: JavaScript (javascript)

3. Base OS

3.1 Packages

apt update && apt full-upgrade
apt install postfix postfix-pcre postfix-policyd-spf-python postgrey \
    amavisd-new spamassassin clamav-daemon clamav-freshclam \
    razor pyzor opendkim opendkim-tools opendmarc publicsuffix \
    unbound dns-root-data certbot nftables swaks unattended-upgrades \
    arj bzip2 cabextract cpio file gzip lhasa lzop nomarch 7zip pax \
    rpm2cpio unrar-free unzip xz-utils zip zstdCode language: JavaScript (javascript)

When debconf asks for the Postfix configuration type, choose Internet Site and system mail name mx1.mydomain.com. We replace main.cf anyway.

(On Debian 12, use p7zip-full instead of 7zip.)

3.2 Automatic security updates

dpkg-reconfigure -plow unattended-upgrades

3.3 Firewall (nftables)

/etc/nftables.conf:

#!/usr/sbin/nft -f
flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;

        iif lo accept
        ct state established,related accept
        ct state invalid drop
        meta l4proto { icmp, ipv6-icmp } accept

        # Public MX
        ip daddr 203.0.113.10 tcp dport 25 accept

        # Internal relay listener: ONLY the internal mail server
        ip saddr 10.0.0.20 ip daddr 10.0.0.5 tcp dport 25 accept

        # SSH from the admin LAN only
        ip saddr 10.0.0.0/24 tcp dport 22 accept

        # certbot http-01 (remove this if you use DNS-01)
        ip daddr 203.0.113.10 tcp dport 80 accept
    }
    chain forward { type filter hook forward priority 0; policy drop; }
    chain output  { type filter hook output  priority 0; policy accept; }
}Code language: PHP (php)
systemctl enable --now nftables

Ports 10023 to 10026, 8891 and 8893 are bound to loopback only. The firewall is the second layer.

3.4 Local validating resolver (Unbound)

/etc/unbound/unbound.conf.d/local.conf:

server:
    interface: 127.0.0.1
    interface: ::1
    access-control: 127.0.0.0/8 allow
    access-control: ::1/128 allow
    hide-identity: yes
    hide-version: yes
    harden-glue: yes
    harden-dnssec-stripped: yes
    harden-below-nxdomain: yes
    qname-minimisation: yes
    prefetch: yes
    num-threads: 2

Do not add a forward-zone pointing at 8.8.8.8, 1.1.1.1 and the like. Spamhaus and URIBL refuse queries that arrive through public resolvers, and your DNSBL checks would silently stop working.

/etc/resolv.conf:

nameserver 127.0.0.1
options edns0 trust-adCode language: CSS (css)

trust-ad is required. Without it, glibc strips the DNSSEC “AD” bit and Postfix DANE silently degrades. If DHCP or cloud-init rewrites this file, fix it at the source (for example supersede domain-name-servers 127.0.0.1; in dhclient.conf, or your netplan/ifupdown config).

systemctl enable --now unbound
dig +dnssec mydomain.com @127.0.0.1 | grep flags     # must contain "ad"
dig +short 2.0.0.127.zen.spamhaus.org               # must return 127.0.0.xCode language: CSS (css)

If the Spamhaus test returns 127.255.255.x, your queries are being refused. Check that nothing forwards upstream.


4. TLS certificate (Let’s Encrypt)

certbot certonly --standalone --reuse-key \
    -d mx1.mydomain.com \
    --deploy-hook "systemctl reload postfix"Code language: CSS (css)
  • --reuse-key keeps the same private key across renewals. You need that if you publish a DANE TLSA 3 1 1 record for your own MX (§15); otherwise every renewal breaks DANE for senders that check it.
  • certbot 2.x and later issue ECDSA keys by default. Every relevant MTA handles ECDSA. If you must serve a few ancient senders, add a second RSA certificate to smtpd_tls_chain_files.
  • Check renewal: certbot renew --dry-run.

5. Postfix main.cf

Back up the original, then replace /etc/postfix/main.cf with this:

cp /etc/postfix/main.cf /etc/postfix/main.cf.orig

Map types: run postconf -h default_database_type. If it prints lmdb, replace every hash: below with lmdb:.

# =====================================================================
#  IDENTITY
# =====================================================================
compatibility_level = 3.6
myhostname          = mx1.mydomain.com
mydomain            = mydomain.com
myorigin            = $myhostname
mydestination       = $myhostname, localhost.$mydomain, localhost
smtpd_banner        = $myhostname ESMTP
biff                = no
append_dot_mydomain = no
readme_directory    = no

inet_interfaces     = 127.0.0.1, 203.0.113.10, 10.0.0.5
inet_protocols      = ipv4

# Outbound mail to the internet leaves from the public IP.
# (Overridden for the amavis and relay-internal transports in master.cf.)
smtp_bind_address   = 203.0.113.10

# Public side trusts ONLY loopback. The internal listener overrides this.
mynetworks          = 127.0.0.0/8 [::1]/128

alias_maps          = hash:/etc/aliases
alias_database      = hash:/etc/aliases

# =====================================================================
#  INBOUND RELAY DOMAIN (gateway for mydomain.com)
# =====================================================================
relay_domains        = mydomain.com
relay_recipient_maps = hash:/etc/postfix/relay_recipients
transport_maps       = hash:/etc/postfix/transport
smtpd_reject_unlisted_recipient     = yes
unknown_relay_recipient_reject_code = 550

# =====================================================================
#  PROTOCOL HYGIENE
# =====================================================================
smtpd_helo_required            = yes
disable_vrfy_command           = yes
strict_rfc821_envelopes        = yes
smtpd_delay_reject             = yes
smtpd_forbid_bare_newline      = normalize
smtpd_forbid_bare_newline_exclusions = $mynetworks
smtpd_forbid_unauth_pipelining = yes
message_size_limit             = 52428800
smtpd_recipient_limit          = 100
smtpd_error_sleep_time         = 1s
smtpd_soft_error_limit         = 5
smtpd_hard_error_limit         = 10
smtpd_junk_command_limit       = 20

# Rate limiting (anvil). Loopback/internal are exempt via $mynetworks.
anvil_rate_time_unit                     = 60s
smtpd_client_connection_count_limit      = 20
smtpd_client_connection_rate_limit       = 60
smtpd_client_message_rate_limit          = 100
smtpd_client_recipient_rate_limit        = 300
smtpd_client_new_tls_session_rate_limit  = 60
smtpd_client_event_limit_exceptions      = $mynetworks

# Strip forged Authentication-Results claiming to be us (protects DMARC)
header_checks = pcre:/etc/postfix/header_checks.pcre

# Don't spam the postmaster with every 5xx
notify_classes = resource, software

# =====================================================================
#  PUBLIC SMTPD RESTRICTIONS
# =====================================================================
smtpd_client_restrictions =
    permit_mynetworks,
    reject_unknown_reverse_client_hostname

smtpd_helo_restrictions =
    permit_mynetworks,
    reject_invalid_helo_hostname,
    reject_non_fqdn_helo_hostname,
    check_helo_access pcre:/etc/postfix/helo_access.pcre

smtpd_sender_restrictions =
    permit_mynetworks,
    reject_non_fqdn_sender,
    reject_unknown_sender_domain

# Relay control: the ONLY place that decides "may this client relay?"
smtpd_relay_restrictions =
    permit_mynetworks,
    reject_unauth_destination

# Expensive checks run last, and only for mail that is allowed to be here
smtpd_recipient_restrictions =
    reject_non_fqdn_recipient,
    reject_unknown_recipient_domain,
    reject_unlisted_recipient,
    check_policy_service unix:private/policyd-spf,
    check_policy_service inet:127.0.0.1:10023

smtpd_data_restrictions =
    reject_unauth_pipelining,
    reject_multi_recipient_bounce

policyd-spf_time_limit = 3600

# Internal listener sender policy (referenced from master.cf)
internal_sender_restrictions =
    reject_non_fqdn_sender,
    check_sender_access hash:/etc/postfix/internal_senders,
    reject

# =====================================================================
#  POSTSCREEN
# =====================================================================
postscreen_access_list           = permit_mynetworks,
                                   cidr:/etc/postfix/postscreen_access.cidr
postscreen_denylist_action       = drop
postscreen_greet_action          = enforce
postscreen_dnsbl_action          = enforce
postscreen_dnsbl_threshold       = 3
postscreen_dnsbl_allowlist_threshold = -2
postscreen_dnsbl_sites =
    zen.spamhaus.org=127.0.0.[2..11]*3
    b.barracudacentral.org=127.0.0.2*2
    bl.spamcop.net=127.0.0.2*2
    psbl.surriel.com=127.0.0.2*1
    list.dnswl.org=127.0.[0..255].0*-2
    list.dnswl.org=127.0.[0..255].1*-3
    list.dnswl.org=127.0.[0..255].[2..3]*-4

# Deep protocol tests are OFF: they force a reconnect (= greylisting) and
# we already greylist with postgrey. See §9 for the alternative.
postscreen_pipelining_enable     = no
postscreen_non_smtp_command_enable = no
postscreen_bare_newline_enable   = no

# =====================================================================
#  TLS — SERVER (inbound)
# =====================================================================
smtpd_tls_chain_files =
    /etc/letsencrypt/live/mx1.mydomain.com/privkey.pem,
    /etc/letsencrypt/live/mx1.mydomain.com/fullchain.pem
# Public MX MUST be opportunistic (RFC 3207). Never "encrypt" on port 25.
smtpd_tls_security_level      = may
smtpd_tls_auth_only           = yes
smtpd_tls_loglevel            = 1
smtpd_tls_received_header     = yes
smtpd_tls_protocols           = >=TLSv1.2
smtpd_tls_mandatory_protocols = >=TLSv1.2
smtpd_tls_ciphers             = high
smtpd_tls_mandatory_ciphers   = high
smtpd_tls_exclude_ciphers     = aNULL, eNULL, MD5, RC4, DES, 3DES, EXPORT, PSK, SRP
tls_preempt_cipherlist        = no
tls_ssl_options               = NO_COMPRESSION, NO_RENEGOTIATION

# =====================================================================
#  TLS — CLIENT (outbound): DANE where published, opportunistic otherwise
# =====================================================================
smtp_dns_support_level        = dnssec
smtp_tls_security_level       = dane
smtp_tls_loglevel             = 1
smtp_tls_note_starttls_offer  = yes
smtp_tls_mandatory_protocols  = >=TLSv1.2
smtp_tls_mandatory_ciphers    = high
smtp_tls_CApath               = /etc/ssl/certs

# =====================================================================
#  MILTERS (assigned per listener in master.cf)
# =====================================================================
milter_protocol       = 6
# tempfail = if a milter is down, defer instead of accepting mail that
# is unsigned / unchecked. Monitor your milters!
milter_default_action = tempfail
milter_mail_macros    = i {mail_addr} {client_addr} {client_name} {auth_authen}
smtpd_milters         =
non_smtpd_milters     =
public_milters        = inet:127.0.0.1:8891, inet:127.0.0.1:8893
internal_milters      = inet:127.0.0.1:8891Code language: PHP (php)

Notes:

  • reject_unknown_reverse_client_hostname rejects clients with no PTR at all. It is safe on a modern MX. The stricter reject_unknown_client_hostname (forward-confirmed rDNS required) blocks too much legitimate mail; don’t use it.
  • There is no content_filter in main.cf on purpose. Each listener sets its own in master.cf, so local sendmail (cron mail and the like) never loops through Amavis, and the internal and public paths get different Amavis policies.
  • Barracuda’s BRBL requires a free registration of your resolver IP. Spamhaus is free only for low-volume and non-commercial use. Above those limits, get a free or paid Spamhaus DQS key and use the DQS zone names.

In practice, the restrictions above and the services from the next sections stop an inbound message at one of these points:

Where an inbound message can be stopped

6. Postfix master.cf

Comment out Debian’s default smtp inet ... smtpd line, then add the blocks below. Keep the rest of the stock file (pickup, cleanup, qmgr and so on).

# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
# ==========================================================================

# ---------- PUBLIC MX: postscreen in front of smtpd ----------
203.0.113.10:smtp inet n -      y       -       1       postscreen
smtpd     pass  -       -       y       -       -       smtpd
  -o syslog_name=postfix/public
  -o smtpd_milters=$public_milters
  -o content_filter=smtp-amavis:[127.0.0.1]:10024
dnsblog   unix  -       -       y       -       0       dnsblog
tlsproxy  unix  -       -       y       -       0       tlsproxy

# ---------- INTERNAL RELAY LISTENER ----------
10.0.0.5:smtp inet n    -       y       -       -       smtpd
  -o syslog_name=postfix/internal
  -o mynetworks=cidr:/etc/postfix/internal_clients.cidr
  -o smtpd_client_restrictions=permit_mynetworks,reject
  -o smtpd_helo_restrictions=
  -o smtpd_sender_restrictions=$internal_sender_restrictions
  -o smtpd_relay_restrictions=permit_mynetworks,reject
  -o smtpd_recipient_restrictions=
  -o smtpd_data_restrictions=reject_unauth_pipelining
  -o smtpd_milters=$internal_milters
  -o content_filter=smtp-amavis:[127.0.0.1]:10026

# ---------- AMAVIS: delivery to the filter ----------
smtp-amavis unix -      -       n       -       4       smtp
  -o syslog_name=postfix/amavis
  -o smtp_bind_address=127.0.0.1
  -o smtp_data_done_timeout=1200
  -o smtp_send_xforward_command=yes
  -o smtp_dns_support_level=disabled
  -o smtp_tls_security_level=none
  -o max_use=20

# ---------- AMAVIS: re-injection (already checked, no more filtering) ----------
127.0.0.1:10025 inet n  -       n       -       -       smtpd
  -o syslog_name=postfix/reinject
  -o content_filter=
  -o smtpd_milters=
  -o local_recipient_maps=
  -o relay_recipient_maps=
  -o smtpd_restriction_classes=
  -o smtpd_delay_reject=no
  -o smtpd_client_restrictions=permit_mynetworks,reject
  -o smtpd_helo_restrictions=
  -o smtpd_sender_restrictions=
  -o smtpd_relay_restrictions=permit_mynetworks,reject
  -o smtpd_recipient_restrictions=
  -o smtpd_data_restrictions=reject_unauth_pipelining
  -o smtpd_end_of_data_restrictions=
  -o mynetworks=127.0.0.0/8
  -o smtpd_error_sleep_time=0
  -o smtpd_soft_error_limit=1001
  -o smtpd_hard_error_limit=1000
  -o smtpd_client_connection_count_limit=0
  -o smtpd_client_connection_rate_limit=0
  -o smtpd_client_message_rate_limit=0
  -o smtpd_client_recipient_rate_limit=0
  -o smtpd_tls_security_level=none
  -o smtpd_authorized_xforward_hosts=127.0.0.0/8
  -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_milters,no_address_mappings

# ---------- Delivery to the internal mailbox server ----------
relay-internal unix -   -       y       -       -       smtp
  -o syslog_name=postfix/relay-internal
  -o smtp_bind_address=10.0.0.5
  -o smtp_tls_security_level=may

# ---------- SPF policy daemon ----------
policyd-spf unix -      n       n       -       0       spawn
  user=policyd-spf argv=/usr/bin/policyd-spfCode language: PHP (php)

Why each override matters:

  • no_milters on 10025: without it, every message is DKIM-verified (or signed) and DMARC-checked a second time after Amavis.
  • no_address_mappings on 10025: canonical and virtual rewriting already ran before the filter. Running it twice can duplicate or misroute mail.
  • smtp_bind_address=127.0.0.1 on smtp-amavis and =10.0.0.5 on relay-internal: the global bind address is the public IP, and you cannot reach 127.0.0.1 or the LAN from it.
  • smtpd_authorized_xforward_hosts: Amavis passes the original client IP and HELO via XFORWARD, so your logs show the real sender, not 127.0.0.1.
  • maxproc 4 on smtp-amavis must equal $max_servers in Amavis (§13).

If the internal server has a proper certificate, change relay-internal to -o smtp_tls_security_level=encrypt. Use secure if it’s issued by a CA you trust.


7. Postfix lookup tables

/etc/postfix/transport

mydomain.com    relay-internal:[10.0.0.20]:25Code language: CSS (css)

/etc/postfix/relay_recipients — list of valid addresses

alice@mydomain.com        OK
bob@mydomain.com          OK
postmaster@mydomain.com   OK
abuse@mydomain.com        OK
dmarc-reports@mydomain.com OK
tlsrpt@mydomain.com       OKCode language: CSS (css)

postmaster@ and abuse@ must exist (RFC 5321 and RFC 2142). Large blocklist operators check for them.

Alternatives to a static list:

  • Directory lookup: relay_recipient_maps = ldap:/etc/postfix/ldap-recipients.cf against AD or OpenLDAP. This is best when the list changes often.
  • Recipient address verification: leave relay_recipient_maps empty and add reject_unverified_recipient to smtpd_recipient_restrictions, directly after reject_unlisted_recipient. Postfix then probes 10.0.0.20 and caches the result. Set unverified_recipient_reject_code = 550.

/etc/postfix/helo_access.pcre — “you are not me”

/^mx1\.mydomain\.com$/        REJECT You are not me
/^mydomain\.com$/             REJECT You are not me
/^\[?203\.0\.113\.10\]?$/     REJECT You are not me

/etc/postfix/header_checks.pcre

/^Authentication-Results:\s*mx1\.mydomain\.com\b/   IGNORE

/etc/postfix/internal_clients.cidr — who may relay out

10.0.0.20/32    OK

List single hosts, not whole subnets. A compromised printer must not be able to turn into a spam cannon. Anything that isn’t a fixed server should authenticate against the internal mail server and relay through it.

/etc/postfix/internal_senders — internal hosts may only send as us

mydomain.com    OK
<>              OKCode language: HTML, XML (xml)

/etc/postfix/postscreen_access.cidr

# 192.0.2.0/24      permit    # a partner that keeps getting listed
# 198.51.100.66     rejectCode language: PHP (php)

Build the maps:

postmap /etc/postfix/transport /etc/postfix/relay_recipients /etc/postfix/internal_senders
newaliases

Make sure /etc/aliases sends root’s mail to a real person:

postmaster: root
root:       admin@mydomain.comCode language: HTTP (http)

8. SPF: postfix-policyd-spf-python

/etc/postfix-policyd-spf-python/policyd-spf.conf:

debugLevel = 1
TestOnly = 1                 # 1 = normal operation (yes, really)

HELO_reject       = Fail
Mail_From_reject  = Fail
PermError_reject  = False
TempError_Defer   = False

skip_addresses = 127.0.0.0/8,::ffff:127.0.0.0/104,::1,10.0.0.0/24

Header_Type = SPFCode language: PHP (php)
  • Hard fail (-all) is rejected at RCPT time. Softfail (~all) is passed on, and SpamAssassin and DMARC score it.
  • The check runs after reject_unauth_destination, so it never runs for relay attempts.
  • OpenDMARC (§11) evaluates SPF itself for DMARC alignment, so it does not have to trust a header.

9. Greylisting: Postgrey

/etc/default/postgrey:

POSTGREY_OPTS="--inet=127.0.0.1:10023 --delay=60 --max-age=35 --auto-allowlist-clients=5 --privacy"Code language: JavaScript (javascript)

(On Debian 12 the option is spelled --auto-whitelist-clients.)

Add known-good bulk senders that retry from rotating IP pools to /etc/postgrey/whitelist_clients.local, one per line (for example /\.outbound\.protection\.outlook\.com$/). Debian already ships a good base list in /etc/postgrey/whitelist_clients.

systemctl enable --now postgrey

Alternative to postgrey: turn on postscreen’s deep protocol tests (postscreen_pipelining_enable, postscreen_non_smtp_command_enable and postscreen_bare_newline_enable all = yes, with action enforce) and remove the postgrey line from smtpd_recipient_restrictions. That has the same effect, because a new client must reconnect. Clients with a good DNSWL score (postscreen_dnsbl_allowlist_threshold) skip it, and you have one fewer daemon. Don’t run both. Senders would be delayed twice.


10. DKIM: OpenDKIM (verifies inbound, signs outbound)

The full OpenDKIM setup (key generation, key and signing tables, DNS record, testing) is in my separate guide: Debian Postfix DKIM.

On this gateway, OpenDKIM must also be set up as follows, because main.cf and master.cf rely on these settings:

  • Socket inet:8891@localhost: public_milters and internal_milters point here. Make sure the SOCKET= line in /etc/default/opendkim doesn’t override it.
  • Mode sv: a single instance verifies inbound mail and signs outbound mail.
  • InternalHosts and ExternalIgnoreList contain only 127.0.0.1, ::1 and 10.0.0.20. Only mail from these hosts gets signed.
  • AuthservID mx1.mydomain.com: this must match OpenDMARC’s TrustedAuthservIDs and the rule in header_checks.pcre.
  • OversignHeaders From: nobody can add a second From: header to your signed mail without breaking the signature.
  • RequireSafeKeys yes, a 2048-bit key, and a selector named by date (for example 2026a), so that rotating the key yearly is painless.

11. DMARC: OpenDMARC (enforces inbound)

The full OpenDMARC setup is in my separate guide: Debian Postfix DMARC.

On this gateway, OpenDMARC must also be set up as follows:

  • Socket inet:8893@localhost: public_milters points here. Check the SOCKET= line in /etc/default/opendmarc.
  • AuthservID mx1.mydomain.com and TrustedAuthservIDs mx1.mydomain.com.
  • RejectFailures true: mail from domains that publish p=reject and fail both SPF and DKIM alignment is rejected. That stops exact-domain spoofing of banks, PayPal, and your own domain.
  • RequiredHeaders true: messages without exactly one valid From: header are rejected.
  • SPFSelfValidate true and SPFIgnoreResults true: OpenDMARC checks SPF itself instead of trusting a header someone else may have added.
  • IgnoreHosts contains 127.0.0.1, ::1 and 10.0.0.0/24, so outbound mail from your own network isn’t DMARC-checked.

Caveat: badly behaved mailing lists and forwarders break DMARC for senders that publish p=reject. That is the sender’s chosen policy, but expect the occasional “why didn’t the list mail arrive?” ticket.


12. ClamAV

adduser clamav amavis
adduser amavis clamav

Settings worth tightening in /etc/clamav/clamd.conf. On Debian it’s generated by debconf, so either run dpkg-reconfigure clamav-daemon or edit the file and keep your edits:

DetectPUA yes
HeuristicAlerts yes
AlertBrokenExecutables yes
AlertEncryptedArchive yes      # password-protected ZIPs: classic malware vector
AlertOLE2Macros yes            # hardcore: blocks ALL legacy Office macros
MaxFileSize 50M
MaxScanSize 100MCode language: PHP (php)

Turn AlertOLE2Macros and AlertEncryptedArchive off if your users legitimately exchange macro files or encrypted archives.

Better signatures: install fangfrisch (packaged in Debian) for the free Sanesecurity, URLhaus and similar feeds. They catch far more current phishing and malspam than the stock signatures alone.

systemctl enable --now clamav-freshclam
# wait until the first signature download has finished:
journalctl -u clamav-freshclam -f
systemctl enable --now clamav-daemon      # the Debian service name is clamav-daemon, not clamdCode language: PHP (php)

13. SpamAssassin (used as a library by Amavis)

Amavis does not use spamd. It loads SpamAssassin in-process. It does read /etc/spamassassin/*.cf and *.pre, so rules, plugins, trust paths and Bayes settings belong there. The score thresholds (tag, tag2, kill) are set in Amavis, and required_score in local.cf is ignored.

Don’t enable or run spamd.

/etc/spamassassin/local.cf

# Amavis handles message modification
report_safe 0

# Trust path: this gateway + the internal network
trusted_networks  203.0.113.10 10.0.0.0/24
internal_networks 203.0.113.10 10.0.0.0/24

# Bayes (DB lives in ~amavis/.spamassassin/)
use_bayes 1
bayes_auto_learn 1
bayes_auto_learn_threshold_nonspam 0.1
bayes_auto_learn_threshold_spam    12.0

# Network checks (need the Unbound resolver from §3.4)
dns_available yes
use_razor2 1
use_pyzor 1

normalize_charset 1

ifplugin Mail::SpamAssassin::Plugin::Shortcircuit
  shortcircuit USER_IN_WELCOMELIST      on
  shortcircuit USER_IN_DEF_WELCOMELIST  on
  shortcircuit USER_IN_BLOCKLIST        on
endifCode language: PHP (php)

(SpamAssassin 4 renamed whitelist/blacklist to welcomelist/blocklist. The old names still work as aliases.)

Check that these plugins are loaded (not commented out):

grep -E '^loadplugin.*(Razor2|Pyzor|Shortcircuit|DKIM|SPF)' /etc/spamassassin/*.preCode language: JavaScript (javascript)

Razor and Pyzor, as the amavis user

su - amavis -s /bin/bash
razor-admin -create
razor-admin -register
pyzor ping
exitCode language: PHP (php)

Rule updates (and restarting Amavis afterwards)

Amavis loads the rules at startup, so after sa-update it must restart. sa-update exits 0 only when new rules were installed:

systemctl disable --now spamassassin-maintenance.timer 2>/dev/null
cat > /etc/cron.d/sa-update-amavis <<'EOF'
37 3 * * * root /usr/bin/sa-update && /usr/bin/systemctl restart amavis
EOF
sa-update -vCode language: JavaScript (javascript)

Lint check

su amavis -s /bin/sh -c 'spamassassin --lint -D 2>&1' | grep -Ei 'razor|pyzor|error|warn'Code language: JavaScript (javascript)

14. Amavis

/etc/amavis/conf.d/15-content_filter_mode

This turns scanning on. The bypass maps must be uncommented, which looks backwards but is correct:

use strict;

@bypass_virus_checks_maps = (
   \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);

@bypass_spam_checks_maps = (
   \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);

1;Code language: CSS (css)

/etc/amavis/conf.d/50-user

use strict;

$myhostname = 'mx1.mydomain.com';
$mydomain   = 'mydomain.com';
@local_domains_maps = ( ['.mydomain.com'] );   # .mydomain.com = domain + subdomains
@mynetworks = qw( 127.0.0.0/8 [::1] 10.0.0.0/24 );

# ---- listeners ----
$inet_socket_bind = '127.0.0.1';
$inet_socket_port = [10024, 10026];
$interface_policy{'10026'} = 'ORIGINATING';
$forward_method = 'smtp:[127.0.0.1]:10025';
$notify_method  = $forward_method;

$max_servers = 4;          # == maxproc of smtp-amavis in master.cf

# ---- spam levels (inbound, local recipients) ----
$sa_tag_level_deflt  = -999;   # always add X-Spam-Status/Score headers
$sa_tag2_level_deflt = 5.0;    # >= 5: X-Spam-Flag: YES + subject tag -> user's Junk folder
$sa_kill_level_deflt = 10.0;   # >= 10: quarantine, not delivered
$sa_dsn_cutoff_level = 10;
$sa_spam_subject_tag = '[SPAM] ';
$sa_mail_body_size_limit = 512*1024;

# ---- destinies: NEVER bounce inbound (backscatter) ----
$final_virus_destiny      = D_DISCARD;
$final_banned_destiny     = D_DISCARD;
$final_spam_destiny       = D_DISCARD;
$final_bad_header_destiny = D_PASS;

# ---- quarantine (files in /var/lib/amavis/virusmails) ----
$virus_quarantine_to  = 'virus-quarantine';
$banned_quarantine_to = 'banned-quarantine';
$spam_quarantine_to   = 'spam-quarantine';

# Don't notify (forged) senders. Only the admin, and only for viruses.
$virus_admin = 'postmaster@mydomain.com';
$spam_admin  = undef;
$warnvirussender  = 0;
$warnbannedsender = 0;
$warnspamsender   = 0;

# ---- DKIM: OpenDKIM signs; amavis verifies to feed SpamAssassin ----
$enable_dkim_verification = 1;
$enable_dkim_signing      = 0;

# ---- dangerous attachments ----
$banned_filename_re = new_RE(
  # double extensions: invoice.pdf.exe
  qr'\.[^./]*[A-Za-z][^./]*\.\s*(exe|vbs|pif|scr|bat|cmd|com|cpl|dll)[.\s]*$'i,
  # real Windows executables, whatever the name (detected by file(1))
  qr'^\.(exe-ms|dll)$',
  # risky extensions, including modern initial-access vectors
  qr'.\.(exe|vbs|vbe|pif|scr|bat|cmd|com|cpl|dll|hta|jse?|wsf|wsh|wsc|sct|lnk|msc|msi|msp|ps1|reg|scf|shb|shs|chm|jar|iso|img|vhdx?|one|xll|appx|msix|appref-ms)$'i,
  qr'^application/x-msdownload$'i,
  qr'^application/x-msdos-program$'i,
  qr'^application/hta$'i,
);

# ---- outbound mail from the internal server ----
$policy_bank{'ORIGINATING'} = {
  originating          => 1,
  allow_disclaimers    => 0,
  final_virus_destiny  => D_DISCARD,
  final_banned_destiny => D_BOUNCE,   # sender is OUR user: tell them why
  final_spam_destiny   => D_DISCARD,  # likely a compromised account
  virus_admin_maps     => ['postmaster@mydomain.com'],
  spam_admin_maps      => ['postmaster@mydomain.com'],
  banned_admin_maps    => ['postmaster@mydomain.com'],
  warnbannedsender     => 1,
};

#------------ Do not modify anything below this line -------------
1;  # ensure a defined returnCode language: PHP (php)

Notes:

  • Don’t set @decoders in 50-user. That replaces Debian’s complete decoder list (zip, gz, rar, 7z and the rest), and Amavis then stops looking inside most archives. Install the tools from §3.1 and Amavis finds them on its own. Check with amavisd-new showkeys or by looking for “Found decoder” lines in the journal after a restart.
  • You don’t need to define @av_scanners. Debian’s 15-av_scanners already points ClamAV-clamd at /var/run/clamav/clamd.ctl.
  • Spam between 5 and 10 is delivered with X-Spam-Flag: YES. Add a rule on the mailbox server (a Sieve rule, or an Exchange transport rule matching that header) to file it into Junk.
  • D_DISCARD combined with quarantine is the right after-queue choice. If you want spammers to get an SMTP reject instead, you need a before-queue filter (smtpd_proxy_filter). That costs one Amavis process per concurrent SMTP session and a lot of RAM, so only consider it on hardware that has the headroom.
systemctl enable amavis
systemctl restart clamav-daemon amavis

15. DNS records

RecordValue
mydomain.com. MX10 mx1.mydomain.com.
mx1.mydomain.com. A203.0.113.10
PTR for 203.0.113.10mx1.mydomain.com. (set at your IP provider)
mydomain.com. TXT (SPF)"v=spf1 ip4:203.0.113.10 -all"
mx1.mydomain.com. TXT (HELO SPF)"v=spf1 a -all"
2026a._domainkey.mydomain.com. TXTcontents of /etc/opendkim/keys/mydomain.com/2026a.txt
_dmarc.mydomain.com. TXT"v=DMARC1; p=none; rua=mailto:dmarc-reports@mydomain.com"
_smtp._tls.mydomain.com. TXT"v=TLSRPTv1; rua=mailto:tlsrpt@mydomain.com"
_mta-sts.mydomain.com. TXT"v=STSv1; id=20261122000000"
_25._tcp.mx1.mydomain.com. TLSA3 1 1 <hash> (only if the zone is DNSSEC-signed)
The mail DNS records and what each one proves

SPF: list every service that sends as @mydomain.com (newsletter tool, CRM, ticket system, and so on) before you publish -all. Stay under the limit of 10 DNS lookups.

DMARC rollout: start with p=none. Read the aggregate reports for 2 to 4 weeks and fix any legitimate sources that fail. Then move to p=quarantine; pct=25, then p=quarantine, and finally:

"v=DMARC1; p=reject; sp=reject; adkim=s; aspf=s; rua=mailto:dmarc-reports@mydomain.com"Code language: JSON / JSON with Comments (json)

Domains that never send mail should get "v=spf1 -all" and "v=DMARC1; p=reject".

MTA-STS: serve this file at https://mta-sts.mydomain.com/.well-known/mta-sts.txt, with a valid certificate:

version: STSv1
mode: testing
mx: mx1.mydomain.com
max_age: 604800Code language: HTTP (http)

Switch to mode: enforce once your TLS-RPT reports are clean, and change the id= in the TXT record every time you edit the policy.

DANE TLSA for your own MX (requires a DNSSEC-signed zone and certbot’s --reuse-key):

openssl x509 -in /etc/letsencrypt/live/mx1.mydomain.com/cert.pem -noout -pubkey \
  | openssl pkey -pubin -outform DER | sha256sum

Key rollover: publish the TLSA record for the new key next to the old one, wait at least two TTLs, switch the certificate, and only then remove the old record.


16. Bring-up and testing

Start the services in order

postfix check && postconf -n > /dev/null
systemctl restart unbound
systemctl restart clamav-daemon amavis opendkim opendmarc postgrey
systemctl restart postfixCode language: JavaScript (javascript)

Is everything listening where it should?

ss -tlnp | grep -E ':(25|10023|10024|10025|10026|8891|8893)\b'Code language: JavaScript (javascript)

Expect port 25 on 203.0.113.10 and 10.0.0.5 only, and everything else on 127.0.0.1 only.

Logs

Debian 13 logs to journald by default, and there is no /var/log/mail.log unless you install rsyslog:

journalctl -f -u postfix@- -u amavis -u opendkim -u opendmarc -u postgrey -u clamav-daemon
# or:  apt install rsyslog   -> /var/log/mail.log (needed by pflogsumm, fail2ban file backend)Code language: CSS (css)

Test Amavis directly (bypasses Postfix)

# GTUBE: must be tagged/quarantined as spam
swaks --server 127.0.0.1:10024 --from test@example.net --to alice@mydomain.com \
  --body 'XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X'

# EICAR: must be discarded as a virus (Clam detects it in the body)
swaks --server 127.0.0.1:10024 --from test@example.net --to alice@mydomain.com \
  --body 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*'Code language: PHP (php)

Look for Blocked SPAM and Blocked INFECTED (Eicar-Signature) in the Amavis log, and for files in /var/lib/amavis/virusmails/.

From an external host

# Open-relay test: MUST be "554 5.7.1 Relay access denied"
swaks --server mx1.mydomain.com --from x@example.net --to someone@gmail.com

# Unknown user: MUST be 550 at RCPT
swaks --server mx1.mydomain.com --from x@example.net --to nobody-here@mydomain.com

# Normal delivery: first attempt is greylisted (450), retry after 60s succeeds
swaks --server mx1.mydomain.com --from you@yourmail.example --to alice@mydomain.com -tlsCode language: CSS (css)

TLS and DANE

posttls-finger -c -l secure -P /etc/ssl/certs "[mx1.mydomain.com]"    # your cert chain
posttls-finger -c -l dane mail.ietf.org                                # outbound DANE worksCode language: PHP (php)

External checks

  • internet.nl, mail test: STARTTLS, DANE, SPF, DKIM, DMARC and IPv6 in one report.
  • checktls.com: inbound TLS from the outside.
  • Send a message from the internal server to a mail-tester.com address: outbound SPF, DKIM, DMARC, rDNS and blocklist status.
  • Send to a Gmail account, then “Show original”: SPF, DKIM and DMARC should all show PASS.

17. Operations

TaskCommand
Show queuepostqueue -p / qshape deferred
Flush queuepostqueue -f
Delete one messagepostsuper -d <QUEUEID>
What is postscreen blocking?journalctl -u postfix@- | grep -E 'DNSBL rank|PREGREET'
Release from quarantinezcat /var/lib/amavis/virusmails/spam-XXXX.gz | sendmail -i -f '<>' alice@mydomain.com
Purge old quarantinecron: find /var/lib/amavis/virusmails -type f -mtime +30 -delete
Train Bayes (spam)su amavis -s /bin/sh -c 'sa-learn --spam /path/to/spam-maildir'
Train Bayes (ham)su amavis -s /bin/sh -c 'sa-learn --ham /path/to/ham-maildir'
Bayes statussu amavis -s /bin/sh -c 'sa-learn --dump magic'
Daily reportapt install pflogsumm (with rsyslog)
Renewal checkcertbot renew --dry-run
Config sanity checkpostfix check; postconf -n; amavisd-new debug (Ctrl-C)

Bayes only starts scoring once it has learned at least 200 spam and 200 ham messages. Feed it real mail from users’ Junk and Inbox folders, for example with a nightly job that pulls from shared “learn-spam” and “learn-ham” folders on the mailbox server.

Monitor these, or you’ll find out from users

  • Queue size (more than about 100 deferred messages means something is wrong).
  • Whether OpenDKIM, OpenDMARC, Amavis and clamd are running. Because of milter_default_action = tempfail, a dead milter defers all inbound mail.
  • Certificate expiry, and that the TLSA record still matches.
  • Your IP on the blocklists (Spamhaus, Barracuda, Microsoft SNDS, Google Postmaster Tools).
  • DMARC aggregate reports and TLS-RPT reports.

18. Hardening checklist

  • ☐ Open-relay test fails from outside and from a LAN host that isn’t in internal_clients.cidr.
  • ☐ PTR = A = myhostname = HELO name. All four match.
  • ☐ postmaster@ and abuse@ are delivered and read.
  • ☐ No SASL/AUTH offered on public port 25 (swaks --server mx1... --quit-after EHLO shows no AUTH). Client submission (587/465) belongs on the mailbox server, not the gateway.
  • ☐ smtpd_tls_security_level = may on the public listener (never encrypt).
  • ☐ /etc/resolv.conf points to 127.0.0.1 with trust-ad, and the Spamhaus test record resolves.
  • ☐ DKIM private keys are mode 600 and owned by opendkim, and they’re in your backups.
  • ☐ Backups cover /etc/postfix, /etc/amavis, /etc/opendkim, /etc/opendmarc, /etc/spamassassin, /etc/letsencrypt and ~amavis/.spamassassin (the Bayes DB).
  • ☐ SSH is key-only, PermitRootLogin no, and reachable only from the admin LAN.
  • ☐ unattended-upgrades is active.
  • ☐ DMARC has moved from none to reject on a schedule, and MTA-STS from testing to enforce.
  • ☐ The DKIM key is rotated yearly (new selector, overlap period, then remove the old one).
  • ☐ IPv6, if you enable it: AAAA + PTR for mx1, add ip6: to SPF, inet_protocols = all, smtp_bind_address6, an [2001:db8::10]:smtp postscreen line in master.cf, and v6 addresses in trusted_networks and the nftables rules.