Blog | G5 Cyber Security

Block Brute Force Attacks by IP Range

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

  1. 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.
  2. Create an iptables Rule: Use the following command to create a rule that drops packets from the specified IP range. Replace 192.168.1.100 and 192.168.1.150 with your actual IP addresses.
    sudo iptables -A INPUT -s 192.168.1.100/24 -j DROP

    Explanation:

    • sudo: Runs the command with administrator privileges.
    • iptables: The command-line firewall utility.
    • -A INPUT: Appends a rule to the INPUT chain (incoming traffic).
    • -s 192.168.1.100/24: Specifies the source IP address or range. The /24 indicates 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.
  3. 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
  4. Blocking on a Specific Port: To block the IP range only for a specific port (e.g., SSH port 22), add the --dport option.
    sudo iptables -A INPUT -p tcp --dport 22 -s 192.168.1.100/24 -j DROP

    Explanation:

    • -p tcp: Specifies the protocol (TCP in this case).
    • --dport 22: Specifies the destination port.
  5. Verify the Rule: Check that your rule has been added correctly.
    sudo iptables -L INPUT

    This will list all rules in the INPUT chain. Look for your newly added rule.

  6. 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-persistent
      sudo netfilter-persistent save
    • CentOS/RHEL:
      sudo yum install iptables-services
      sudo service iptables save
  7. 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-numbers and then delete it.
    sudo iptables -D INPUT <line_number>

Important Considerations

Exit mobile version