Never Ending Security

It starts all here

Iptables Blacklist Script


iptables blacklist script

A small Bash shell script which uses ipset and iptables to ban a large number of IP addresses published in IP blacklists. ipset uses a hashtable to store/fetch IP addresses and thus the IP lookup is a lot faster than thousands of sequentially parsed iptables ban rules. However, the limit of an ipset list is 2^16 entries.

IP_BLACKLIST_CUSTOM=/etc/ip-blacklist-custom.conf # optional
list="chinese nigerian russian lacnic exploited-servers"
"" # Project Honey Pot Directory of Dictionary Attacker IPs
""  # TOR Exit Nodes
"" # MaxMind GeoIP Anonymous Proxies
"" # BruteForceBlocker IP List
"" # Emerging Threats - Russian Business Networks List
"" # Spamhaus Don't Route Or Peer List (DROP)
"" # C.I. Army Malicious IP List
""  # 30 day List
"" # Autoshun Shun List
"" # attackers
for i in "${BLACKLISTS[@]}"
    curl "$i" > $IP_TMP
    grep -Po '(?:\d{1,3}\.){3}\d{1,3}(?:/\d{1,2})?' $IP_TMP >> $IP_BLACKLIST_TMP
for i in `echo $list`; do
        # Download
        wget --quiet$i-iptables-blocklist.html
        # Grep out all but ip blocks
        cat $i-iptables-blocklist.html | grep -v \< | grep -v \: | grep -v \; | grep -v \# | grep [0-9] > $i.txt
        # Consolidate blocks into master list
        cat $i.txt >> $IP_BLACKLIST_TMP


ipset flush blacklist
egrep -v "^#|^$" $IP_BLACKLIST | while IFS= read -r ip
        ipset add blacklist $ip


  1. Copy into /usr/local/bin
  2. chmod +x /usr/local/bin/
  3. Modify according to your needs. Per default, the blacklisted IP addresses will be saved to /etc/ip-blacklist.conf
  4. apt-get install ipset
  5. Create the ipset blacklist and insert it into your iptables input filter
  6. Auto-update the blacklist using a cron job

iptables filter rule

ipset create blacklist hash:net
iptables -I INPUT -m set --match-set blacklist src -j DROP

Make sure to run this snippet in your firewall script. If you don’t, the ipset blacklist and the iptables rule to ban the blacklisted ip addresses will be missing!

Cron job

In order to auto-update the blacklist, copy the following code into /etc/cron.d/update-blacklist. Don’t update the list too often or some blacklist providers will ban your IP address. Once a day should be OK though.

33 23 * * *      root /usr/local/bin/

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s