Blocking sender IPs in Postfix
Despite all I’ve done to filter junk mail, I recently noticed one consistent spammer who was bypassing all of my safeguards. Notably, this source has a host who’s tolerant enough that the spammer went so far as to set SPF headers, to give their messages some “credibility.”
The sender’s IPs were, fortunately, confined to a single /24
. Thanks to hosting my own email, I’m able to block their entire range until spam filters catch up.
It’s important to note that I confirmed, using IP lookup services from the appropriate regional IP registries, that the IPs and ranges I blocked were specific enough to not reject otherwise-innocuous messages. One could easily ban too-broad a subnet and lose many legitimate emails.
IP Blacklist
First, create a client_checks
file in /etc/postfix
. To it, add one or more of the following (depending on your needs) replacing the IPs or ranges with what you’ve observed in your logs, email headers, etc.:
1
2
|
123.456.789.123 REJECT Your IP is spam 123.456.789.0/24 REJECT Your IP range is spam |
Domains and subdomains could also be specified, as noted in the first tutorial linked in the References, but for my purposes, domains are rarely consistent enough to bother filtering that way.
Hash the blacklist
Next, the client_checks
file must be converted to a database that Postfix can read. This must be done every time client_checks
is updated1.
1
|
postmap /etc/postfix/client_checks |
smtpd_recipient_restrictions
After that, update smtpd_recipient_restrictions
in /etc/postfix/main.cf
so that Postfix is aware of the block list.
1
2
3
|
smtpd_recipient_restrictions = check_client_access hash:/etc/postfix/client_checks, ... |
Placing the block list at the beginning of the smtpd_recipient_restrictions
parameter ensures that the IP blocks are obeyed above all other processing, but just as importantly, prevents more-expensive operations, such as virus scanning and spam scoring, from running when the outcome is predetermined.
Wrapping up
Lastly, restart Postfix and check mail.log
to confirm that there weren’t any errors reading the new configuration. Regardless of if spam volume subsides, revisit the log to confirm that the changes had the intended effect and aren’t blocking legitimate messages.
References:
- Blacklist & Whitelist with Postfix
- Block specific sending email addresses (not covered here, but noted for reference)
- Postfix also needs to be reloaded after each subsequent rehashing of
client_checks
. ↩