Search code examples
bashshellscriptingshiptables

IPTables Script to block Concurrent Connections


We are using Suse Linux Enterprise Server 12. We need to block concurrent IP Addresses which is hitting our web server for more thatn 50 times per second and block that ip address for 10 minutes. Also it should distinguish attacker and genuine traffic and block attacker's IP forever. We have currently blocked using iptables , below is the rule.

iptables -I INPUT -p tcp --dport 443 -i eth0 -m state --state NEW -m recent --set   
iptables -I INPUT -p tcp --dport 443 -i eth0 -m state --state NEW -m recent --update --seconds 1 --hitcount 50 -j DROP

It will just block the IPAddress which exceeds 50 connections but wont blacklist the IPAddress. Please let us know if we have a script that will match all the scenarios which is metioned above. Please Help.


Solution

  • I tested this and it works really nice. If the behavior is detected, the IP is put into hold-down for 10 minutes and logged. You can verify it's operation by watching these files. /proc/net/xt_recent/NICE, /proc/net/xt_recent/NAUGHTY. You need to build a script to parse the log for bad IP's and commit them to a file that is loaded into iptables on startup if you want to blacklist permanently. That concept is already clear so no need for me to include it.

    #flush and clear
    iptables -F -t nat
    iptables -F 
    iptables -X
    
    #this is where naughty kids go
    iptables -N GETCAUGHT
    
    #you got added to the naughty list 
    iptables -A GETCAUGHT -m recent --name NAUGHTY --set                   #everyone here is bad
    iptables -A GETCAUGHT -j LOG --log-prefix "iwasbad: " --log-level 4    #and it goes on your permanent record
    
    #if you are on the NAUGHTY list you get a lump of coal                                
    iptables -A INPUT -i eth0 -m recent --name NAUGHTY --rcheck --seconds 600 -j DROP       #check everyone at the door
    
    #though everyone starts out on the NICE list
    iptables -A INPUT -i eth0 -p tcp --dport 443 -m conntrack --ctstate NEW -m recent --name NICE --set     #you seem nice
    
    #but if you GETCAUGHT doing this you are naughty 
    iptables -A INPUT -i eth0 -p tcp --dport 443 -m conntrack --ctstate NEW -m recent --name NICE --seconds 1 --hitcount 50 --update -j GETCAUGHT    #that wasn't nice