In case you need to quickly ban a list of IP addresses from connecting to your server, iptables is perfect for the job.

iptables is a user-space firewall that can control incoming and outgoing connections with policies and filter rules.

Blocking ingress from a single IP is easily done with a single iptables rule. We can use this same command to automate the creation of many rules with a bash script that will read our list of IP addresses from a file.

iptables -I INPUT -s 1.2.3.4 -j DROP

To separate our list of IP addresses from other rules, we will create a new chain named BADACTORS and place it in the first position before the default INPUT chain.

iptables -N BADACTORS
iptables -I INPUT 1 -j BADACTORS

Next, we can confirm that the chain has been created and insert a new rule directly into the new chain.

iptables -L BADACTORS
iptables -A BADACTORS -s 1.2.3.4 -j DROP

Now we are ready to create a bash script that will read from our text file named badactors.db and automate the process. Our text file can also contain comments with # prefixed lines to separate blocks of IP addresses.

# Bad Actors
1.2.3.4
1.5.6.7
2.3.4.5

We will first need to set BADACTORSLIST to the path to the badactors.db text file. The script will remove all rules in the BADACTORS chain with iptables -F. Once the chain is flushed the script will then read all lines of the file, sort them and extract unique values before passing each IP to iptables.

#!/bin/bash

BADACTORSLIST=/path/to/badactors.db

iptables -F BADACTORS

/bin/egrep -v "^#|^$|:" $BADACTORSLIST | sort | uniq | while read IP
do
    iptables -A BADACTORS -s $IP -j DROP
done

You can save then save the script and make it executable with chmod u+x. After executing the script you can confirm that all rules have been created using iptables -L BADACTORS -n

Keep in mind that iptables rules are ephemeral and will need to be persisted across system reboots. You can save all the rules using iptables-save and pipe the output to a file for safe keeping. It would also be cool to schedule running this script automatically, and updating the list itself, but this I’ll save for another post.

Resources