It’s annoying having scripts and bots attempting to ssh into your pbx server. If you have proper passwords they don’t stand a chance of getting in, but it’s not satisfying to ignore them while they create load and clutter up your log files with failed login messages.
There are many tools out there to monitor and block IP addresses that repeatedly attempt to connect. My needs were:
- low memory (memory is precious on a VPS)
- simple
- customizable
scan-secure.sh
#!/bin/sh # scan /var/log/secure for ssh attempts # use iptables to block the bad guys # Looking for attempts on existing and non-existing users. For example: # Nov 2 22:44:07 pbxer sshd[28318]: Failed password for root from 74.143.42.70 port 52416 ssh2 # Nov 3 00:06:57 pbxer sshd[31767]: Failed password for invalid user mat3 from 192.203.145.200 port 35841 ssh2 tail -1000 /var/log/secure | awk '/sshd/ && /Failed password for/ { if (/invalid user/) try[$13]++; else try[$11]++; } END { for (h in try) if (try[h] > 4) print h; }' | while read ip do # note: check if IP is already blocked... /sbin/iptables -L -n | grep $ip > /dev/null if [ $? -eq 0 ] ; then # echo "already denied ip: [$ip]" ; true else # echo "Subject: denying ip: $ip" | /usr/sbin/sendmail notify@email.com logger -p authpriv.notice "*** Blocking SSH attempt from: $ip" /sbin/iptables -I INPUT -s $ip -j DROP fi doneawk does all the magic. It grabs relevant lines, splits the lines into tokens, stores IP addresses in a hash and counts how many times they were seen, and finally outputs all IP addresses that were seen more than four times.
For the first few days, it’s interesting to receive an email when IP addresses are banned. Add your email and comment out that line.
Once you’re sure that the script is working how you’d like, you can add it to cron so that it runs every few minutes. I found that every two minutes works for me.
crontab -e
# scan the secure log every 2 minutes */2 * * * * /root/scan-secure.sh
After a few months you might find that the iptables are started to get cluttered.
iptables -L -n
You can clean them out by “flushing” them.
iptables -F
Now sleep tight knowing that people aren’t continually coming by to see if you locked your doors.