Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Security

Spam and malware filtering on your own mail server

Layer postscreen, Rspamd and ClamAV on a self-hosted mail server, stop password guessing and open relaying, and watch the logs that reveal abuse early.

CloudSat teamNovember 18, 20267 min read
Abstract illustration of a stream of envelopes passing through three glowing filter rings
On this pageThe layers and what each one stops

Antivirus is the smallest part of mail server security. A public mail server faces three threats at once: junk and malware coming in, bots guessing passwords on the login ports, and spammers trying to send through your server, either as an open relay or with a stolen account. Each needs its own layer. This guide builds those layers on a Postfix and Dovecot server on Debian or Ubuntu, and notes where the Docker bundles already do the work.

The layers and what each one stops

Layer Stops Tool
Connection Botnets, blocklisted senders, clients that talk too early Postfix postscreen with DNS blocklists
Content Spam, phishing, spoofed senders Rspamd
Attachments Malware, risky file types ClamAV through Rspamd, extension rules
Login Password guessing on SMTP and IMAP Fail2ban, TLS-only authentication
Relay Strangers using your server to send Postfix relay restrictions
Transport TLS downgrade on the way to you MTA-STS, TLS reporting

Order matters. Every message rejected at the connection stage is a message Rspamd and ClamAV never have to parse.

Layer 1: refuse bots before they speak

Postscreen sits in front of the SMTP daemon, checks each connecting address against DNS blocklists and drops clients that send commands before the greeting, a common bot habit. Add this to /etc/postfix/main.cf:

postscreen_access_list = permit_mynetworks
postscreen_dnsbl_sites = zen.spamhaus.org=127.0.0.[2..11]*3
postscreen_dnsbl_threshold = 3
postscreen_dnsbl_action = enforce
postscreen_greet_action = enforce

The =127.0.0.[2..11] filter counts only real listings, not the error codes a blocklist returns when it refuses a query. Then switch the smtp service in /etc/postfix/master.cf from smtpd to postscreen and add its helpers. Debian and Ubuntu run these services chrooted, so keep the y in the fifth column:

smtp      inet  n       -       y       -       1       postscreen
smtpd     pass  -       -       y       -       -       smtpd
dnsblog   unix  -       -       y       -       0       dnsblog
tlsproxy  unix  -       -       y       -       0       tlsproxy

Mind how you query Spamhaus. Its public mirrors return 127.255.255.254 and no data when the query arrives through a public or open resolver, or from an address with generic reverse DNS. Run a local recursive resolver such as Unbound on the mail server, give the server attributable reverse DNS (how to set it), or register for Spamhaus's free Data Query Service and use its keyed zones instead.

Layer 2: score content with Rspamd

Rspamd scores each message on hundreds of rules: SPF, DKIM, DMARC and ARC results, URL and IP reputation, Bayes statistics, header oddities and fuzzy hashes. It talks to Postfix over the milter protocol and can also sign your outgoing mail with DKIM. The project does not support the packages in Debian's own repositories, so install from its repository:

sudo apt-get install -y lsb-release wget gpg redis-server
sudo mkdir -p /etc/apt/keyrings
wget -O- https://rspamd.com/apt-stable/gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/rspamd.gpg > /dev/null
CODENAME=$(lsb_release -c -s)
echo "deb [signed-by=/etc/apt/keyrings/rspamd.gpg] http://rspamd.com/apt-stable/ $CODENAME main" | sudo tee /etc/apt/sources.list.d/rspamd.list
sudo apt-get update && sudo apt-get --no-install-recommends install rspamd

Redis is there because Rspamd keeps its statistics, greylisting data and rate limits in it. Point Rspamd at it in /etc/rspamd/local.d/redis.conf with servers = "127.0.0.1:6379";, then connect Postfix to the proxy worker, which listens for milter traffic on port 11332:

smtpd_milters = inet:localhost:11332
non_smtpd_milters = inet:localhost:11332
milter_protocol = 6
milter_default_action = accept

milter_default_action = accept keeps mail flowing, unscanned, if Rspamd is down. Choose tempfail instead if you would rather queue mail than let anything through unfiltered.

Rspamd's default thresholds are greylist = 4, add_header = 6 and reject = 15, set in /etc/rspamd/local.d/actions.conf. Leave them alone for the first weeks, then adjust from what the history shows. The web interface on port 11334 listens on localhost only; protect it with a password hash from rspamadm pw, stored in /etc/rspamd/local.d/worker-controller.inc, and reach it through an SSH tunnel rather than opening the port. If you do expose it, allow only your own address in a cloud firewall.

Layer 3: scan attachments, and block what needs no scan

ClamAV catches known malware, but it is expensive: it loads its whole signature database into memory, and by default it loads a fresh copy beside the old one at each update, which briefly doubles its footprint. On a small server, set ConcurrentDatabaseReload no in /etc/clamav/clamd.conf; scans pause during reloads, but memory stays flat.

sudo apt-get install -y clamav-daemon clamav-freshclam
sudo systemctl enable --now clamav-freshclam clamav-daemon

Wire it into Rspamd in /etc/rspamd/local.d/antivirus.conf, using the clamd socket that the Debian and Ubuntu packages create:

clamav {
  symbol = "CLAM_VIRUS";
  type = "clamav";
  servers = "/var/run/clamav/clamd.ctl";
  action = "reject";
  scan_mime_parts = true;
}

File types are a cheaper filter than signatures. Rspamd's mime_types module already scores risky extensions such as .exe, .bat and .iso, and double extensions like .pdf.exe. If nobody you work with ever sends executables, raise those scores in local.d/mime_types.conf so they reject outright.

Layer 4: make password guessing pointless

Soon after it goes online, a mail server starts seeing login attempts on ports 465, 587 and 993. Three settings take the fun out of it:

  • Offer authentication only after TLS (smtpd_tls_auth_only = yes), and only on the submission ports 587 and 465, never on port 25.
  • Require long, unique passwords for every mailbox, and remove accounts nobody uses.
  • Ban repeat offenders with Fail2ban.

Fail2ban ships jails for both daemons. Enable them in /etc/fail2ban/jail.local:

[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5

[postfix-sasl]
enabled = true

[dovecot]
enabled = true

These jails read /var/log/mail.log, which Ubuntu writes through rsyslog. On a system that only keeps the systemd journal, install rsyslog or set backend = systemd, then confirm the jail sees failures with sudo fail2ban-client status postfix-sasl.

Layer 5: never relay for strangers

An open relay gets found by spammers and blocklisted fast. Postfix's default is safe, so check that nothing has loosened it in main.cf:

mynetworks = 127.0.0.0/8 [::1]/128
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, defer_unauth_destination

Test it from a machine outside your network, against your own server only. An unauthenticated message for a domain you do not host must be refused with Relay access denied:

swaks --to someone@example.net --from probe@example.org --server mail.example.com

Stolen accounts are the other relay risk. Rspamd's ratelimit module can cap how many messages each authenticated user sends per hour, which turns a compromised password into a small incident instead of a blocklisting.

Layer 6: protect mail on its way in

SMTP encrypts opportunistically, so an attacker in the path can strip TLS. MTA-STS tells other servers to insist on it. Publish a policy file at https://mta-sts.example.com/.well-known/mta-sts.txt, start in testing mode and switch to enforce once reports come back clean:

version: STSv1
mode: testing
mx: mail.example.com
max_age: 86400

Then add two DNS records, the second of which asks senders to email you TLS failure reports:

_mta-sts.example.com.   IN TXT "v=STSv1; id=20261118"
_smtp._tls.example.com. IN TXT "v=TLSRPTv1; rua=mailto:tlsrpt@example.com"

Watch the signals that show trouble early

  • Queue size: mailq | tail -n 1. A queue that suddenly grows usually means an account is sending spam.
  • Login failures: grep -c "SASL LOGIN authentication failed" /var/log/mail.log.
  • Rspamd history: rspamc stat and the history tab show what is being rejected and why.
  • DMARC reports: aggregate reports reveal anyone sending mail in your domain's name.
  • Your own reputation: check your IP on Spamhaus's lookup page after any incident.

If you run mailcow, Mailu or docker-mailserver, most of these layers are already in place and only need to be switched on and tuned; our comparison of self-hosted mail server software shows what each bundle includes.

FAQ

Is ClamAV still worth running on a mail server?

For mailboxes used by people who open attachments, yes. It catches known malware cheaply once loaded. Budget at least 1 GB of RAM for it, more during reloads, and pair it with extension rules for file types nobody needs.

Rspamd or SpamAssassin?

Both work. Rspamd is faster, handles DKIM signing, DMARC and rate limits in the same daemon, and includes a web interface, which is why most current bundles use it. SpamAssassin remains a fine choice if you already have years of tuned rules.

How can I tell if spam is leaving my server?

Watch the queue size and the outgoing volume per account. A sudden jump, bounces from addresses you never wrote to, or a new blocklist listing all point to a compromised mailbox. Lock the account, reset its password and clear its messages from the queue.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.