Block ip by IPTABLES, a simple firewall alternative

Posted under » Ubuntu » Linux » LAMP Security on 21 October 2013

In order to block an IP on your Linux server you can use iptables command. First you need to log into shell as root user. To block an IP address you type

# iptables -A INPUT -s 65.235.44.100 -j DROP

You can block subnets like so 65.235.44.0/16 65.235.44.0/24 192.168.2.0/25

If you are not sure. Then use an IP Subnet Calculator. Most of these bastards are from Russia and China.

You can block just ports too

If you are using debian/ubuntu you can make it permanent.

# apt-get install iptables-persistent
# iptables-save > /etc/iptables/rules.v4

You must save the tables again (iptables-save > /etc/iptables/rules.v4) after any change you make.
 

Deleting an entry. First you must find the line number...

iptables -L --line-numbers

Which will show something like this.

Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    DROP       all  --  216-110-74-50.static.twtelecom.net  anywhere
2    DROP       all  --  b3da8000.virtua.com.br/17  anywhere

Then delete the line

iptables -D INPUT 2

You can flush out all entry by

iptables -F INPUT

However you may be locked out from your own server via SSH. So you have to reset it by

iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS