TL;DR
This guide shows you how to block a range of IPs attempting brute force attacks on your server using iptables. It’s suitable for Linux servers and assumes basic command-line knowledge.
Blocking IP Ranges with iptables
- Identify the IP Range: First, you need to know the starting and ending IPs of the range you want to block. For example, let’s say we want to block all IPs from 192.168.1.100 to 192.168.1.150.
- Create an iptables Rule: Use the following command to create a rule that drops packets from the specified IP range. Replace
192.168.1.100and192.168.1.150with your actual IP addresses.sudo iptables -A INPUT -s 192.168.1.100/24 -j DROPExplanation:
sudo: Runs the command with administrator privileges.iptables: The command-line firewall utility.-A INPUT: Appends a rule to theINPUTchain (incoming traffic).-s 192.168.1.100/24: Specifies the source IP address or range. The/24indicates a subnet mask, meaning all IPs from 192.168.1.0 to 192.168.1.255 are included if you want to block the entire subnet. If blocking only a specific range like 192.168.1.100-192.168.1.150, use CIDR notation (see step 3).-j DROP: Specifies the target action – to drop the packets.
- Using CIDR Notation for Specific Ranges: If you need more precise control than a full subnet, calculate the CIDR notation for your range.
For example, 192.168.1.100 to 192.168.1.150 is equivalent to
192.168.1.100/26.sudo iptables -A INPUT -s 192.168.1.100/26 -j DROP - Blocking on a Specific Port: To block the IP range only for a specific port (e.g., SSH port 22), add the
--dportoption.sudo iptables -A INPUT -p tcp --dport 22 -s 192.168.1.100/24 -j DROPExplanation:
-p tcp: Specifies the protocol (TCP in this case).--dport 22: Specifies the destination port.
- Verify the Rule: Check that your rule has been added correctly.
sudo iptables -L INPUTThis will list all rules in the
INPUTchain. Look for your newly added rule. - Save the Rules: iptables rules are not permanent by default and will be lost on reboot. You need to save them.
- Debian/Ubuntu:
sudo apt-get install iptables-persistentsudo netfilter-persistent save - CentOS/RHEL:
sudo yum install iptables-servicessudo service iptables save
- Debian/Ubuntu:
- Removing a Rule: If you need to remove the rule later, use the following command. First find the line number of the rule using
iptables -L INPUT --line-numbersand then delete it.sudo iptables -D INPUT <line_number>
Important Considerations
- Test Thoroughly: Always test your rules after adding them to ensure they don’t block legitimate traffic.
- Logging: Consider enabling logging for dropped packets to help identify potential false positives.
sudo iptables -A INPUT -s 192.168.1.100/24 -j LOG --log-prefix "BruteForceBlock:" - cyber security Best Practices: Blocking IPs is a reactive measure. Implement stronger authentication methods like key-based SSH and multi-factor authentication for better cyber security.