Created
September 17, 2016 10:30
-
-
Save Sunnyztj/99f109fd5ab6b18121f2888d35f43a08 to your computer and use it in GitHub Desktop.
Blocking IP addresses in Linux with iptables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Block IP addresses | |
Using iptables | |
Most system administrators will already be familiar with iptables. It is around for quite a while, and by default enabled within the Linux kernel. Within this article we are going to configure iptables to block one or multiple IP addresses. This may come in handy when you get repeating port scans, or see failed login attempts in your log files. | |
Check existing iptables configuration | |
First step is to validate existing rules. | |
iptables -L | |
Manually blocking a single IP address | |
The first option to permanently block an IP address is by creating a rule in the INPUT chain. This way traffic is no longer allowed from that particular IP address. | |
iptables -I INPUT -s 192.168.1.100 -j DROP | |
Using blacklists with iptables | |
Another option is creating a blacklist. This way we can add multiple systems we no longer want to connect to our systems. | |
Install ipset utility | |
Most Linux systems do not have the ipset utility installed by default. So first step is installing that. | |
CentOS | |
yum install ipset | |
You may need to install the epel-release package first. | |
Debian and Ubuntu | |
apt-get install ipset | |
Creating a blacklist | |
With the newly installed ipset utility we create a new list. We name it “blacklist” to show its purpose. | |
# Create blacklist with ipset utility (once) | |
ipset create blacklist hash:ip hashsize 4096 | |
After the blacklist is created, we can use the set in iptables. It is related to the –match-set option. | |
# Set up iptables rules. Match with blacklist and drop traffic | |
iptables -I INPUT -m set --match-set blacklist src -j DROP | |
iptables -I FORWARD -m set --match-set blacklist src -j DROP | |
These commands will add link the blacklist (or set) to the INPUT and FORWARD chains. As this is a blacklist, the related policy is to drop traffic. | |
Next step is adding actual IP address to the list: | |
# Add a specific IP address to your newly created blacklist | |
ipset add blacklist 192.168.1.100 | |
To confirm the blacklist contains the IP address, use the ipset list command. | |
Output of ipset command showing blacklist | |
Member on blacklist | |
In this screenshot we can see the IP address is listed as a member of the set. Now traffic should be blocked. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
apt-get install ipset
ipset create blacklist hash:ip hashsize 4096
iptables -I INPUT -m set --match-set blacklist src -j DROP
ipset add blacklist 192.168.1.100