What is iptables?
The iptables utility is the traditional, immensely powerful command-line firewall interface for Linux. It interacts directly with the netfilter hooks in the Linux kernel to inspect, modify, drop, or accept network packets based on administrator-defined rules. When your server is under a brute-force attack or a simple Denial of Service (DoS), iptables is the fastest way to drop the malicious traffic instantly at the kernel level.
Step 1: Check Current iptables Rules
Before adding new rules, you should check if any rules currently exist. Open your terminal and run:
sudo iptables -L -n -v
The -L flag lists the rules, -n forces numeric output (preventing slow DNS lookups), and -v makes the output verbose. You will see three default chains: INPUT (incoming traffic), FORWARD (routed traffic), and OUTPUT (outgoing traffic).
Step 2: Block a Specific IP Address
To block all incoming traffic from a specific malicious IP address (e.g., 203.0.113.50), you must append a rule to the INPUT chain instructing the firewall to DROP the packets.
sudo iptables -A INPUT -s 203.0.113.50 -j DROP
-A INPUT: Appends the rule to the end of the INPUT chain.-s: Specifies the source IP address.-j DROP: Tells the firewall to jump to the DROP action (silently discarding the packet).
Step 3: Block an Entire Subnet
If an attack is originating from multiple IPs within the same network block, you can drop the entire subnet using CIDR notation. For example, to drop all traffic from the 192.168.2.x subnet:
sudo iptables -A INPUT -s 192.168.2.0/24 -j DROP
Step 4: Block an IP on a Specific Port
Sometimes you want to block an IP from accessing a specific service (like SSH on port 22) but still allow them to access your public web server (port 80). To drop traffic from an IP only when it attempts to reach port 22, use the -p (protocol) and --dport (destination port) flags:
sudo iptables -A INPUT -p tcp -s 203.0.113.50 --dport 22 -j DROP
Step 5: Make the Rules Persistent
The iptables rules you apply via the command line are stored entirely in RAM. If the server reboots, all your blocks will be erased. You must save them to a file.
On Ubuntu/Debian systems, install the persistent package:
sudo apt install iptables-persistent -y
Then save the rules:
sudo netfilter-persistent save
On RHEL/CentOS systems, save the rules using:
sudo service iptables save
Your server is now actively dropping the malicious IP addresses at the kernel level, drastically reducing the load on your applications.