Linux Tutorial: Blocking IP Addresses From Your Server
Every time I need to remember how to do this I find myself looking it up so I figured it’s about time I just put my fingers to my keyboard and write it down. These commands will work on most *nix machines. If you’re not logged in as the root or have admin permissions then you’ll need to add sudo to each of the commands below. In each of these examples you’d replace xx.xx.xx.xx with the IP address in question.
How To List Your Existing IP Address Rules
If you want to know what your iptables looks like before you get started then this will list your current rules.
iptables -L
If you’re looking for the help docs on the iptables you can see the manual entries here:
iptables -h
How To Block an IP Address
To block a specific IP address you would use the following command. Then to save your changes to the iptables you’ll need to save the new rules in your config file, otherwise the rules will be lost if your server restarts. Replace xx.xx.xx.xx with the IP address you want to block.
iptables -A INPUT -s xx.xx.xx.xx -j DROP service iptables save
How to Block an IP Address for a Specific Port
Replace yy with your port number and xx.xx.xx.xx with the IP address.
iptables -A INPUT -s xx.xx.xx.xx -p tcp --destination-port yy -j DROP
How To Unblock an IP Address
Now let’s say you block the wrong IP address or you need to take one off for some reason. In order for the change to be permanent you then have to save the updated rules to the config file. Replace xx.xx.xx.xx with the IP address:
iptables -D INPUT -s xx.xxx.xx.xx -j DROP
service iptables save
How To Remove All IP Table Rules
This will only remove all of your IP table rules temporarily unless you save the changes afterwards using service iptables save. Otherwise all of your rules will return to normal when you restart.
iptables -F
How To Block A Range of IP Addresses
This is useful if you want to block specific locations (ie countries) or specific internet providers or users who are assigned an IP from a range pool. You can block 8, 16 or 24 ranges. You can find what IP block an IP is contained within by using the WHOIS lookup at ARIN. Replace xx.yy.zz with the correct portions of the IP address depending on how much you want to block.
Block 8 Range from x.y.z.0 to x.y.z.255
iptables -A INPUT -s xx.yy.zz.0/8 -j DROP
Block Range 16 from x.y.0.0 to x.y.255.255
iptables -A INPUT -s xx.yy.0.0/16 -j DROP
Block Range 24 from x.0.0.0 to x.255.255.255
iptables -A INPUT -s xx.0.0.0/24 -j DROP
References & Resources
http://www.thegeekstuff.com/2010/07/list-and-flush-iptables-rules/
http://www.techrepublic.com/article/ip-subnetting-made-easy/6089187
http://forums.serverbeach.com/showthread.php?5075-Blocking-a-ip-range
http://forum.slicehost.com/index.php?p=/discussion/4676/how-to-block-a-range-of-ip-addresses-in-iptables/p1
http://www.cyberciti.biz/faq/how-do-i-block-an-ip-on-my-linux-server/