A script to automatically blacklist illegal ssh attempts

Sep 14, '04 10:01:00AM

Contributed by: Anonymous

With increasingly-automated ssh break-in attempts, I created an automated blocking script (which must be run by root) to put into /etc/crontab.

This script auto-blocks IPs that attempt to ssh into your mac illegally (background info). Hope this is useful to someone.

[robg adds: Enter the following in your favorite pure text editor, and make sure it's executable (chmod 755 scriptname). Adding it to cron is left as an exercise for the reader. I have not tested this one yet, and I'm not sure how you create exceptions for allowed IP addresses, such as a Mac at your office.]

#!/bin/sh
#
IPFW=/sbin/ipfw
MYIPS=`ifconfig | fgrep inet | fgrep netmask | awk '{print $2}'`
if [ "$MYIPS" = "" ]
then
  exit 1
fi
#
#if [ "$1" = "" ]
#then
#  LOG=/var/log/system.log
#else
#  LOG="$@"
#fi

zgrep -i Illegal /var/log/system.log*gz | fgrep sshd | awk '{print $NF}' | sort | uniq > /tmp/iplist

touch /etc/blacklist
cat /tmp/iplist /etc/blacklist | sort | uniq > /etc/blacklist.new
if [ -s /etc/blacklist.new ]
then
  mv /etc/blacklist.new /etc/blacklist
else
  rm -f /etc/blacklist.new
fi
rm -f /tmp/iplist
chmod og-rwx /etc/blacklist

IPS=`cat /etc/blacklist`

for ip in $IPS
do
  if [ "echo $MYIPS | fgrep $ip" != "" ]
  then
    rules=`/sbin/ipfw show | fgrep $ip | awk '{print $1}'`
    if [ "$rules" != "" ]
    then
      for rul in $rules
      do
        /sbin/ipfw delete $rul
        echo "/sbin/ipfw delete $rul"
      done
    fi
    /sbin/ipfw add deny log ip from $ip to any
  fi
done

Comments (14)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20040913102948373