Squelching SIP attacks

Since I run an Asterisk server, it seems every third-world slime crawler wants to see if they can get free phone calls.  So far none have succeeded, but if you let a million monkeys keep pounding on keyboards, eventually they’ll guess something right.

Unfortunately Asterisk doesn’t have any facility for doing anything with SIP attacks other than logging them.  I finally got tired of seeing thousands of connection attempts from various places and blocking them individually, so I came up with a script to add the offending IP addresses to my iptables filter.  When an invalid connection attempt comes in, I block their entire /24 net just for good measure.

#!/bin/bash
/bin/grep "No matching peer found" /var/log/asterisk/messages|cut -d "'" -f 4 | \\
  cut -d "." -f 1-3 |sort -n |/usr/bin/uniq >> /root/anti-sip-attack.tmp
for d in `cat /root/anti-sip-attack.tmp`; do
  c=`grep -c $d /root/anti-sip-attack.lst`
  if [ "$c" = "0" ]; then
    /sbin/iptables -I INPUT -s $d.0/24 -j DROP 
    echo $d >> /root/anti-sip-attack.lst
  fi
done
rm /root/anti-sip-attack.tmp

This script gets run from cron every few minutes…  so far it’s worked quite well.  The next step is to tee the Asterisk log file and do it in real time, so they only get one shot and they’re blocked.  As it is now they have up to five minutes to try to brute-force their way in.