TL;DR
Preventing spammers from using your mail server by blocking rapidly changing IP addresses on port 25 (SMTP). This guide covers firewall rules and greylisting techniques.
Solution Guide
- Understand the Problem
- Firewall Rules (iptables/ufw)
- Using iptables: (Linux systems using iptables)
- Using ufw: (Ubuntu/Debian systems using ufw)
- Greylisting
- Install greylisting software: (e.g.,
spamassassinwith thegreylistplugin) - Alternative: Use a dedicated greylisting service like
spamhaus-greylisting. - DNSBLs (DNS Blacklists)
- Configure your mail server: Most mail servers (Postfix, Sendmail, Exim) have options to integrate with DNSBLs.
- Rate Limiting per IP Address
- Using fail2ban: Create a filter to detect excessive email sending and ban offending IPs.
- Monitor Logs
Spammers often use dynamic IP addresses, frequently switching them to avoid being blocked. Blocking individual IPs is ineffective as they change quickly. We need a solution that targets this behaviour.
Configure your firewall to limit the rate of new connections on port 25. This won’t block legitimate users but will significantly hinder spammers attempting many connections from different IPs.
sudo iptables -A INPUT -p tcp --dport 25 -m conntrack --ctstate NEW -m recent --set --name SMTP --rsource
sudo iptables -A INPUT -p tcp --dport 25 -m conntrack --ctstate NEW -m recent --update seconds 60 --hitcount 4 --name SMTP --rsource -j DROP
Explanation: The first rule sets a marker for each new connection source IP. The second rule drops connections from IPs that have made more than 3 new connections in the last 60 seconds.
sudo ufw limit 25
Explanation: This limits incoming connections on port 25 to a rate defined in the /etc/default/ufw file. Adjust this setting as needed.
Greylisting temporarily rejects emails from unknown senders. Legitimate mail servers will retry, while many spammers won’t. This significantly reduces spam volume.
sudo apt update && sudo apt install spamassassin
Configure SpamAssassin to use the greylist plugin according to its documentation.
Use DNS blacklists (DNSBLs) to check incoming IP addresses against known spam sources. This is a proactive measure.
Common DNSBLs include Spamhaus ZEN and Barracuda Reputation Block List (BRBL). Add these to your mail server configuration.
Implement rate limiting based on the number of emails sent from a single IP address within a specific timeframe. This can be done using tools like fail2ban or your mail server’s configuration.
Regularly check your mail server logs for blocked connections, greylisted emails, and DNSBL hits. This helps you fine-tune your rules and identify potential issues.

