Spam is a constant problem for me as a sys admin. Even after greylisting and denyhosts and fail2banning I still find myself wanting to deny access to the occasional ip address. The netfilter.org project iptables provides a pretty nice firewall for the Linux kernel. I often forget the syntax and I often try to ban an IP that I’ve already banned elsewhere. This is a script that I use to ban IPs on the GNU/Linux machines that I admin.
Banning an IP address with iptables is as simple as typing
$ sudo iptables -v -A INPUT -s 192.168.0.99 -j DROPThat command would drop any packets received from 192.168.0.99 – replace with the IP you want to block and you're away. But you can end up creating duplicate rules when doing this. No big deal but a script tidies things up a little. It also saves me having to remember to sudo, which for a lazy person like me us a plus!
$ cat `which spamblock.sh`
if [ $# = 1 ]; then
LOOKUP=`sudo iptables -nL | grep $1`
if [ -z "$LOOKUP" ]; then
echo Blocking $1
sudo iptables -v -A INPUT -s $1 -j DROP
echo ALREADY BLOCKED
echo Must get exactly 1 IP address to spam block
We first check that exactly one IP was received (the IP to block). If not we give a warning and exit. If we did get an IP we check it isn't blocked and if not block it. Simple as that.
And you use it thus (note that I am already root in this session).
# spamblock.sh 220.127.116.11
DROP all opt -- in * out * 18.104.22.168 -> 0.0.0.0/0
# spamblock.sh 22.214.171.124
DROP all -- 126.96.36.199 0.0.0.0/0
Even a Bash script as seemingly trivial as this can save typing, forgetting to sudo and duplicate iptables rules. Enjoy.