HOWTO: Accepting email from only a predefined whitelist of IPs for specific domains in Postfix.
USE CASE / WHY
Imagine that you have a postfix email server which is the MX record and SMTP delivery endpoint for a number of domains. This domain is getting more spam than you would like so you choose to place it behind an email filtering service. However, only this domain, not all. The MX records for those few domains may be moved to point at the spam-filter service but your server is still the end delivery point as the emails are being smtp relayed to it from the mail-fitler service. Well, if a spammer knew about this end point (which they most likely do if your moving a domain due to spam levels), then they could bypass the mailfilter and continue to deliver email directly to your server.
This solution sets postfix to only accept email from a predefined whitelist of IP addresses and only for specific domains. For the usecase above, this would mean for the domains you moved, you could set the that email should only be accepted from the IP addresses of the spam-filtering service.
1) Create the file with the IP addresses you wish to whitelist. This should be a file with one per line, in CIDR notation.
The last line of this file should have a catch all set to reject.
e.g. If you was using cloudflare's mail filtering service, this would be;
nano -w /etc/postfix/mf_ips
Contents of which are;
220.127.116.11/32 PERMIT 18.104.22.168/32 PERMIT 22.214.171.124/32 PERMIT 126.96.36.199/32 PERMIT 188.8.131.52/19 PERMIT 184.108.40.206/19 PERMIT 220.127.116.11/26 PERMIT 18.104.22.168/26 PERMIT 22.214.171.124/24 PERMIT 126.96.36.199/32 PERMIT 188.8.131.52/32 PERMIT 0.0.0.0/0 REJECT
This file does not need a hashmap
2) Create a file with the domains you wish to protect as a postfix hashmap
nano -w /etc/postfix/mf_domains
Contents of which are;
example.com mf example2.com mf example3.com mf
Create the postfix hash map of the above file
3) Update postfix main.cf
Add the following lines;
smtpd_restriction_classes = mf mf = check_client_access cidr:/etc/postfix/mf_ips, permit
Into your existing smtpd_recipient_restrictions section, add the following line;
e.g. - The resulting smtpd_recipient_restrictions section may look like this;
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, check_recipient_access hash:/etc/postfix/mf_domains, reject_invalid_hostname, .......
4) Now reload postfix --- you're all set.
Hopefully this howto has been helpful.
If you would prefer an experienced pair of hands perform this for you -- or if you just require assistance with your Linux servers, Postfix or spam filtering then Leenix are here to help.
We provide consultancy services for exactly these sorts of problems and pride ourselves on our customer focused Linux problem solving and solution specification.