Blocking IPs with iptables

From banana_wiki
Jump to: navigation, search

If you run a Linux server and you watch your logs you may notice repeat connections from unknown IP addresses and similar situations. You may want to block this IP address for better security and to stop this waste of network resources. This tutorial assumes you have iptables already installed, most major Linux distributions have this installed already. To provide ease of use and to make this process easier we will make this a script, so that you can quickly block more IP address in the future. Create a file named block and enter this:

sudo iptables -I INPUT -s $1 -j DROP
sudo bash -c "iptables-save > /etc/network/"</code>

So next we will make this block file executable:

chmod + x block

And then copy the file to /usr/sbin so that you can run this script as a command (as root):

sudo cp block /usr/sbin

Now when you have an IP you want to block you just have to run:

sudo block

Replace the example IP above with an actual IP. This adds it to the list of IP address which iptables will simply drop any incoming packets. Since iptable rules are stored in memory we will want to make sure even after a reboot that the rule comes back on. To do this add the following to the bottom of your /etc/network/interfaces file:

post-up iptables-restore /etc/network/

Now say you want to see all of your iptable entries you will need to run:

sudo iptables -L -n

And to no longer block an IP run:

sudo iptables -D INPUT -s BAD_IP_HERE -j DROP