Limiting Connections Using IPTables

Just recently I have been experiencing a DoS-like attack on one of my systems. The system has been receiving several requests from a single ip, say, 6000+requests from a single client every 1~2 minutes. So, this was the culprit of a system crash for over a day.

client request flood

I have implemented several options of blocking this. One strategy would be to add the ip-address to the deny-list in .htaccess.

memory free after blocking with .htaccess

But what if it is just an uncontrolled influx of requests that are, in turn also relevant to us but we just want to limit it? I tried another approach which is to create a built-in limiter via script using php. By adding a new table in the database which tracks how many requests the client has already sent and by restricting all succeeding requests once the limit has been reached. This strategy did not solve the problem, it still added to the hog of server-resources.

The last strategy I tried was to resort to IPTables. Using IPTables lets you utilize the operating system firewall, in my case, Linux’s. I have added some restrictions to the client’s IP address by only limiting it to a few concurrent requests only, but before this, the client is sending at around 100+ requests and this is incremental.

This is how I did it:
Execute this script via ssh:
[cc lang=”dos” tab_size=”2″ lines=”-1″]
iptables -A INPUT -p tcp –syn –dport 80 -m connlimit –connlimit-above 9 -j REJECT -s “127.0.0.1”
[/cc]
where: 127.0.0.1 or any ip is the client that you need to limit.
where: 80 or any port that you need to limit
where: –connlimit-above x (x is the number of connections you want to limit to)

You may also list down all IPTables’ current rules using this command:
[cc lang=”dos” tab_size=”2″ lines=”-1″]
iptables -L
[/cc]

And then finally, you may also flush all current rules of IPTables using this command:
[cc lang=”dos” tab_size=”2″ lines=”-1″]
iptables -F
[/cc]

I have learned about IPTables when I was searching for a way to limit client / host connections into my servers.

Check any of these links for more information on setting up IPTables
http://www.linuxhelp.in/2011/04/how-to-limit-connections-from-one-ip.html
http://www.cyberciti.biz/faq/iptables-connection-limits-howto
http://www.thegeekstuff.com/2011/01/iptables-fundamentals
http://www.thegeekstuff.com/2010/07/list-and-flush-iptables-rules
http://www.thegeekstuff.com/2011/01/redhat-iptables-flush