msgbartop
MAC OS X, Linux, Windows and other IT Tips and Tricks
msgbarbottom

21 Dec 17 Blocking hosts blacklist and iptables

Intro:
I happen to have sone attacks coming from specific hosts which I decided to block access to the server. Here is how I did it using a script which deletes and reload a full iptables CHAIN based on a file containing a list of IPs/Ranges.

STEPS:
Create a file called blacklist.txt with one IP/Range per line in the same directory as the script.
eg.
14.141.107.206
23.180.0.0/14
37.59.34.120
46.140.157.157
46.218.35.59
47.74.0.40
51.15.56.170
59.62.0.0/15
59.63.188.3
61.177.172.60

Script to run at boot time
#!/bin/bash
# Tiny firewall protecting rpcbind (port 111)
scriptdir=$(dirname $(readlink -f $0))
blacklist="$scriptdir/blacklist.txt"
# Load the blacklists
HOSTS="$(cat $blacklist | egrep -v '^$|#')"
# Delete the existing custom chain
/sbin/iptables --flush BLACKLIST
/sbin/iptables -X BLACKLIST
/sbin/iptables -t filter -D INPUT -j BLACKLIST
# Create the BLACKLIST Chain and jump
/sbin/iptables -N BLACKLIST
/sbin/iptables -t filter -I INPUT -j BLACKLIST
# Fill-in the BLACKLIST Chain with rejected hosts list
for host in $HOSTS ; do
/sbin/iptables -A BLACKLIST -s $host -p tcp -j DROP
done
# Return from Blacklist
/sbin/iptables -A BLACKLIST -j RETURN
#eof

Note: iptables will complain with the following errors. Not to worry, it will still do the proper job.
iptables: Too many links.
iptables: Chain already exists.

Leave a Reply

%d bloggers like this: