iptables: Read a List of IP Address From File And Block

How do I read a list of ip address (subnets) using a text file and block all of them using Linux iptables command?

You can create a file which contains the list of all blocked ip address or subnets per line. You can read a file line by line using while loop.

Example: iptables Read IPs / Subnets From The Text File

Create a text file – /root/firewall/badips.db as follows:

# Block db
# Added on Aug/19/2009
# Spammers

The basic logic as follows to read a text file:

$IPT -N droplist
egrep -v "^#|^$" x | while IFS= read -r ip
	$IPT -A droplist -i eth1 -s $ip -j LOG --log-prefix " myBad IP BlockList  "
	$IPT -A droplist -i eth1 -s $ip -j DROP
done < "$_input"
# Drop it 
$IPT -I INPUT -j droplist
$IPT -I OUTPUT -j droplist
$IPT -I FORWARD -j droplist

Here is a sample shell script:

# Modify script as per your setup
# Usage: Sample firewall script
# ---------------------------
# Die if file not found
[ ! -f "$_input" ] && { echo "$0: File $_input not found."; exit 1; }
# DROP and close everything
# Unlimited lo access
# Allow all outgoing connection but no incoming stuff by default
$IPT -A OUTPUT -o ${_pub_if} -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -i ${_pub_if} -m state --state ESTABLISHED,RELATED -j ACCEPT
### Setup our black list ###
# Create a new chain 
$IPT -N droplist
# Filter out comments and blank lines
# store each ip or subnet in $ip
egrep -v "^#|^$" x | while IFS= read -r ip
        # Append everything to droplist
	$IPT -A droplist -i ${_pub_if} -s $ip -j LOG --log-prefix " Drop Bad IP List "
	$IPT -A droplist -i ${_pub_if} -s $ip -j DROP
done <"${_input}"
# Finally, insert or append our black list 
$IPT -I INPUT -j droplist
$IPT -I OUTPUT -j droplist
$IPT -I FORWARD -j droplist
# Okay add your rest of $IPT commands here 
# Example: open port 53
#$IPT -A INPUT -i ${_pub_if} -s 0/0 -d -p udp --dport 53 -j ACCEPT
#$IPT -A INPUT -i ${_pub_if} -s 0/0 -d -p tcp --dport 53 -j ACCEPT
# Open port 80
# $IPT -A INPUT -i ${_pub_if} -s 0/0 -d -p tcp --destination-port 80  -j ACCEPT
# Allow incoming ICMP ping pong stuff
# $IPT -A INPUT -i ${_pub_if} -p icmp --icmp-type 8 -m state --state NEW,ESTABLISHED,RELATED -m limit --limit 30/sec  -j ACCEPT
# $IPT -A INPUT -i ${_pub_if}  -p icmp -m icmp --icmp-type 3 -m limit --limit 30/sec -j ACCEPT
# $IPT -A INPUT -i ${_pub_if}  -p icmp -m icmp --icmp-type 5 -m limit --limit 30/sec -j ACCEPT
# $IPT -A INPUT -i ${_pub_if}  -p icmp -m icmp --icmp-type 11 -m limit --limit 30/sec -j ACCEPT
# drop and log everything else
$IPT -A INPUT -m limit --limit 5/m --limit-burst 7 -j LOG

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.