I was monitoring the mail logs on a Postfix server and noted repeated failed connection attempts from the same IP address. The source was likely up to no good, and it was making it more difficult to monitor the logs for legitimate connections, so I decided to block it:
iptables -A INPUT -s 123.456.789.101 -j DROP
(IP address changed to protect…the innocent?)
However, the IP address was still making connections:
Dec 2 17:19:05 mercutio postfix/smtpd: connect from unknown[123.456.789.101]
Dec 2 17:19:06 mercutio postfix/smtpd: lost connection after AUTH from unknown[123.456.789.101]
Dec 2 17:19:06 mercutio postfix/smtpd: disconnect from unknown[123.456.789.101]
How is that possible? First I checked iptables to check my sanity and confirm that the rule had been added:
# iptables -L
DROP all -- 123.456.789.101 anywhere
OK, it’s there. That’s good!
The problem in this case was a different rule that had been added previously. Rules in iptables are processed in order, and no further rules are processed after a matching rule is found. Well above my newly-added rule was this rule:
ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:smtp
That rule makes sense for a mail server, but I needed my rule to be inserted before it. I determined which rule it was in the INPUT chain like this:
iptables --line-numbers -L INPUT
It was the 5th rule, so I was able to insert the new rule just above it like this:
iptables -I INPUT 4 -s 123.456.789.101 -j DROP
After that, the offending IP address stopped creating entries in the mail.log.
However, my new rule would disappear after a system restart. Since I am using iptables-persistent, I saved the rules to the config file:
iptables-save > /etc/iptables/rules.v4
To confirm everything worked, I attempted to restart iptables:
# service iptables-persistent restart
Failed to restart iptables-persistent.service: Unit iptables-persistent.service
Apparently the service name changed to
netfilter-persistent in Debian 8. The config files are still in the same location, but the service name has changed.
I restarted iptables:
# service netfilter-persistent restart
I checked the rules again and my new rule was there, above the rule allowing connections from any IP on port 25. However, I also noticed the following rule above either of those:
ACCEPT all -- anywhere anywhere
I freaked out. That rule indicates that all traffic from any source on any port should be accepted. That’s the worst firewall rule I’ve ever seen. It basically negates the entire concept of a firewall. It clearly should not be there!
However, using the verbose switch on iptables:
iptables -vL INPUT
I discovered that the rule only applied to the l0 interface (loopback). That’s a relief–that rule gets to stay.