#!/bin/sh ############################################## # Read Asterisk logs and ban bruteforces # # # # Author: Subnets.ru # # URL: http://subnets.ru/blog/?p=1552 # # Version: 0.1 # # Date: 03.09.2010 # ############################################## ###################################################################################################### # INSTALL # # # # 1. mv protect_aster.txt protect_aster.sh # # 2. chmod a+x protect_aster.sh # # 3. add rule to firewall (ipfw), where XXX is rule number: # # ipfw add XXX reject ip from "table(56)" to me # # 4. add to /etc/crontab: # # */5 * * * * root /full/path/to/script/protect_aster.sh # # # ###################################################################################################### time=$(expr `/bin/date +%H%M` / 1) if [ $time -eq 1015 ]; then echo "Table 56 contents IP:" echo "=====================" /sbin/ipfw table 56 list echo "=====================" /sbin/ipfw table 56 flush echo "Table 56 flushed" fi if [ $time -eq 0 ]; then rm -rf `/bin/date -v-180d +'/var/log/asterisk/%Y/%m/'` # echo "Deleted dir " `/bin/date -v-180d +'/var/log/asterisk/%Y/%m/'` mkdir -p `/bin/date +'/var/log/asterisk/%Y/%m/'` # echo "Created dir " `/bin/date +'/var/log/asterisk/%Y/%m/'` fi /usr/local/sbin/asterisk -rx 'logger rotate' /bin/sleep 2 /usr/bin/grep -E ' chan_sip.c: Registration from .* No matching peer found$' /var/log/asterisk/messages.0 | \ awk -F "'" '{ ips[$4]++ } END { for (a in ips){ if (ips[a]> 10 ){ cmd=sprintf("/sbin/ipfw table 56 add %s/32 5060 >/dev/null 2>&1",a); system(cmd); printf ("asterisk: Wrong peers repeated [%d] times: IP [%s] blocked\n",ips[a],a); } } }' /usr/bin/grep -E ' chan_sip.c: Registration from .* Wrong password$' /var/log/asterisk/messages.0 | \ awk -F "'" '{ ips[$4]++ } END { for (a in ips){ if (ips[a]> 20 ){ cmd=sprintf("/sbin/ipfw table 56 add %s/32 5061 >/dev/null 2>&1",a); system(cmd); printf ("asterisk: Wrong passwords repeated [%d] times: IP [%s] blocked\n",ips[a],a); } } }' mesdst=`/bin/date +'/var/log/asterisk/%Y/%m/mes_%Y%m%d.log'` evtdst=`/bin/date +'/var/log/asterisk/%Y/%m/evt_%Y%m%d.log'` quedst=`/bin/date +'/var/log/asterisk/%Y/%m/que_%Y%m%d.log'` cat /var/log/asterisk/messages.0 >> $mesdst rm /var/log/asterisk/messages.0 cat /var/log/asterisk/event_log.0 >> $evtdst rm /var/log/asterisk/event_log.0 cat /var/log/asterisk/queue_log.0 >> $quedst rm /var/log/asterisk/queue_log.0