TL;DR
This guide shows you how to use iptables on a Linux server to block SYN flood attacks. We’ll create rules that limit the rate of incoming SYN packets, dropping excess connections before they can overwhelm your system.
Blocking SYN Flood Attacks with iptables
- Understand SYN Floods: A SYN flood attack exploits the TCP handshake process. The attacker sends many SYN (synchronize) packets but never completes the connection, leaving the server waiting for a response and consuming resources.
- Check Existing Rules: Before adding new rules, see what’s already in place.
sudo iptables -LThis lists all current
iptablesrules. Note any existing rules that might affect incoming connections. - Create a New Chain (Optional but Recommended): Creating a separate chain keeps your main INPUT chain cleaner and makes it easier to manage the SYN flood protection.
sudo iptables -N synflood-protectionThis creates a new chain named
synflood-protection. - Redirect Incoming SYN Packets: Redirect incoming SYN packets to the new chain (if you created one) or directly apply rules to the INPUT chain.
If using a new chain:
sudo iptables -A INPUT -p tcp --syn -j synflood-protectionThis rule sends all incoming TCP SYN packets to the
synflood-protectionchain. - Limit Connection Rate: Use the
limitmodule to restrict the rate of incoming SYN packets. This is the core of the protection.sudo iptables -A synflood-protection -m limit --limit 10/second --limit-burst 5 -j ACCEPTThis allows up to 10 SYN packets per second, with a burst of 5. Packets exceeding this rate will fall through to the next rule.
- Drop Excess Packets: Drop any remaining SYN packets that exceed the limit.
sudo iptables -A synflood-protection -j DROPThis drops all incoming TCP SYN packets that haven’t been accepted by the previous rule.
- Save the Rules:
iptablesrules are not persistent by default. You need to save them so they survive a reboot.The method for saving rules varies depending on your Linux distribution:
- Debian/Ubuntu:
sudo apt-get install iptables-persistentThen, during installation, it will ask if you want to save current rules. Alternatively:
sudo netfilter-persistent save - CentOS/RHEL/Fedora:
sudo yum install iptables-servicesThen:
sudo service iptables saveand enable the service with
sudo systemctl enable iptables
- Debian/Ubuntu:
- Test Your Rules: After saving, reboot your server or reload
iptablesto ensure the rules are applied correctly.sudo iptables -L synflood-protectionVerify that the rules you added are present. You can also use a tool like
hping3to simulate a SYN flood and check if it’s being blocked. - Monitor Logs: Check your system logs (e.g., using
journalctlor/var/log/syslog) for dropped packets related to the SYN flood rules. This helps you fine-tune the limits.sudo journalctl -f | grep DROP

