IPTables Script to Fend Off DDOS Attacks

We recently have had a number of sites that have been hit by DNS amplification DDOS attacks. You can turn off recursion and do other things in NAMED to prevent you from being a target but once they target you the attack can go on for a long time after your server has been properly configured. This script is also good for thwarting SSH, IMAP, and POP3 probes. Just change the port number and tune the limits.

# IP Tables script to deny ssh, dns, flood attempts
# Alan Madill - Aug 2013 - GNU# change the port number 22 - ssh, 53 - dns, etc
# and add the exempt IP addresses and subnets to SAFEIP
MYPORT=53
SAFEIP=( "192.168.0.0/16" "216.55.111.0/24" "64.123.252.0/24" "10.10.10.0/24" "localhost" )
# set the limits
HITS=10 # number of packets received
PERIOD=60 # per timeframe until we reject them
# additional parameter ie PARAM="-i eth2"
PARAM="-i eth1"
#create the chain
iptables -N IPTARG_Brute_Force
iptables -I INPUT -p tcp -m tcp --dport $MYPORT $PARAM -m state --state NEW -j IPTARG_Brute_Force
iptables -I INPUT -p udp -m udp --dport $MYPORT $PARAM -m state --state NEW -j IPTARG_Brute_Force
for i in "${SAFEIP[@]}"
do
    iptables -A IPTARG_Brute_Force -s $i -j RETURN
done
iptables -A IPTARG_Brute_Force -m recent --set --name IPTARG --rsource
iptables -A IPTARG_Brute_Force -m recent ! --rcheck --seconds $PERIOD --hitcount $HITS --name IPTARG --rsource -j RETURN
# It really does fill up the log file - un-comment to see if it is working
#iptables -A IPTARG_Brute_Force -j LOG --log-prefix "Brute force on port $MYPORT: "
iptables -A IPTARG_Brute_Force -j REJECT