Friday, September 2, 2011

Prevent DoS attack in Linux using IPTABLES

A major problem facing by mail server admin is DOS (Deniel Of Service) attack. Hackers will try to mess up with the most popular ports of a UNIX/LINUX machines. We can prevent this my writing an IPTABLE rule in the server. The working is ,if some one is trying make connection continuously through a specified port the rule will block the IPADDRESS permanently. Here I am stating the securing of PORT 25 (SMTP) here you can use your own

iptables -I INPUT -p tcp --dport 25 -i eth0 -m state --state NEW -m recent --set

iptables -I INPUT -p tcp --dport 25 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP


This will Block all the IP ADDRESS which will make connection to port 25 continuously within ie 4 SMTP connection within 60 seconds. You can change PORT,INTERVALs here.

We can also log these ips as well and use for future purpose for example,if you would like to add these logged IP to TCPWRAPPERetc.
Do the following.

Firts of all Set your Log Daemon to log the IPTABLES

# vi /etc/syslog.conf

Add the following line at the end of the file

#kern.warning /var/log/iptables.log
#touch /var/log/iptables.log

Restart the System Log Service

#/etc/init.d/syslog restart (On Redhat based,Centos)

iptables -A INPUT -j LOG --log-level 4

iptables -I INPUT -p tcp --dport 25 -i eth0 -m state --state NEW -m recent --set

iptables -I INPUT -p tcp --dport 25 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP --log-prefix '** HACKERS **'--log-level 4

PERFECT. THE HACKERS ARE BEING LOGGED NOW !!!.

The next stage is to add these logged ips to TCPWRAPPER (/etc/hosts.deny).

#/bin/cat /var/log/iptables.log | awk '{print $9}' | cut -f2 -d "=" >> /root/badip.txt

The above line will grep the SOURCE ip from the log and append to badip.txt

Next Run this command as a frequent interval with the help of CRON

#vi /etc/crontab

*/1 * * * * root /bin/cat /var/log/iptables.log | awk '{print $9}' | cut -f2 -d "=" >> /root/badip.txt

Here the script will run in every minutes. The file will be grow up rapidly to heavy size if your server have heavy traffic. So CleanUP the file in a frequent intervals. Better setup another CRON for it.

Next to add these IPs in the hosts.deny file

#vi /etc/hosts.deny
SSHD:/root/badip.txt
So things are clear. The first CRON job will update the file badip.txt list, as well as it will blocked by TCPWRAPPER.