Table of Contents
Blocking suspicious traffic protects your VPS from brute-force attacks, port scans, and unwanted access attempts.
Step 1: Check Current Firewall Rules
Before making changes, review existing iptables rules.
sudo iptables -L -n -v
This shows active rules, packet counts, and blocked traffic.
Step 2: Block a Suspicious IP Address
Immediately drop traffic from a known malicious IP.
sudo iptables -A INPUT -s 203.0.113.45 -j DROP
Replace 203.0.113.45 with the IP you want to block.
Step 3: Block Traffic from an IP Range
Useful when repeated attacks come from the same subnet.
sudo iptables -A INPUT -s 203.0.113.0/24 -j DROP
Apply carefully to avoid blocking legitimate users.
Step 4: Block Port Scanning Attempts
Limit repeated connection attempts to common ports.
sudo iptables -A INPUT -p tcp --syn -m recent --name portscan --set
sudo iptables -A INPUT -p tcp --syn -m recent --name portscan --update --seconds 60 --hitcount 10 -j DROP
This drops IPs making excessive connection attempts.
Step 5: Block Invalid or Malformed Packets
Drop packets that do not match valid connection states.
sudo iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
This reduces noise and suspicious traffic.
Step 6: Allow Established Connections
Always allow established and related traffic to avoid disconnecting yourself.
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
Step 7: Save iptables Rules
iptables rules are not persistent by default.
sudo apt install iptables-persistent -y
sudo netfilter-persistent save
This ensures blocked traffic stays blocked after reboot.
You may also want to review this related article: Limit Bandwidth Per Port or IP on Ubuntu 25.04
Check rule counters to see how often traffic is blocked.
sudo iptables -L -n -v --line-numbers