Page 1 of 1

How to Block a Suspicious IP Address.

Posted: Tue Oct 26, 2021 11:21 pm
by Rob Swan
You may have noticed suspicions repeated log entries or failed logon attempt from a certain IP address, maybe you have been the victim of a cyber-attack or you just want to ban someone.

Whatever the reason it is possible to block an IP address from accessing your server using something called iptables.

It is actually quite simple to do.

To ban the made up IP address 123.456.789.10 until the next re-boot just log into your server using you PC and Putty and issue this command.

sudo iptables -A INPUT -s 123.456.789.10 -p all -w -j DROP

That is all there is to it.

If you want a permanent ban you can put these commands into a file and then tell your server to run it when it re-boots.

This "ban list file" can be very useful if you have a list of IP addresses to ban, plus you can add to them, or take away at any time.

It is possible to install some software to permanently ban a list of IP's, however in my opinion this is the best way.

Log into your server using Putty and your PC.

Issue this command to create a new file.

sudo vi /var/www/new/ehcp/scripts/updateiptables.sh

Press I to insert and put this line at the top.

#!/bin/bash

Next press enter twice (to miss a line), and insert this version of the IP ban command.

/sbin/iptables -A INPUT -s 123.456.789.10 -p all -w -j DROP

Image

You can ban as many IP addresses as you want, so maybe your file will look something like this.

Image

Please Note:
The IP addresses in the above picture are taken from my permanent ban list, so you may want to use some of your own.

When you are happy with your list save and exit (Escape :w (Enter) :q (Enter)).

As this is a new file we have to give it permission to execute so issue this command.

sudo chmod +x /var/www/new/ehcp/scripts/updateiptables.sh

Now we just have to tell the serer to run this file on re-boot.

So issue this command.

sudo crontab -e

Press I for insert, then insert this line at the end of the file.

Code: Select all

#Process Permanent IP Address Bans
@reboot /var/www/new/ehcp/scripts/updateiptables.sh >/dev/null 2>&1
Please note, your file may look different from the following example.

Image

When you are done save and exit (Escape :w (Enter) :q (Enter)).

Then re-boot your server using.

sudo shutdown -r now

That’s it job done.

Where it is not strictly necessary, you can check the IP are banned, using this command (from Putty)

sudo iptables -L

You may have to scroll up to the start of the output to see your bans.

Sometimes, in the list you may see a web address instead of the IP, this is normal as it is just what the IP address links to (I have hidden them in this picture).

Image

To add or remove bans, just edit the file as needed using this command.

sudo vi /var/www/new/ehcp/scripts/updateiptables.sh

After editing your list, you should re-boot your server for the changes to take effect.