#!/bin/sh
(
#whitelist="127.0.0.1 192.168.110.1 `host test.net.com | sed -e 's/[^0-9]*//'`"
whitelist="127.0.0.1"

sed -e '/sshd\[[0-9]*\]: Failed password/!d' \
        -e 's/.*Failed password for.*from //' \
        -e 's/ port.*//' /var/log/secure.log | sort | uniq -c | \
while read info; do
    set -- $info
    count=$1
    host=$2
    whitelisted=0

    host=`echo $host | sed -e 's/::ffff://'`
    usernames=`sed -e '/sshd\[[0-9]*\]: Failed password.*from.*'$host'/!d' -e 's/.*Failed password for //' -e 's/invalid user //' -e 's/ from .*//' /var/log/secure.log | sort -u `

    for white in $whitelist ; do
            if [ "$white" = "$host" ] ; then
                    whitelisted=1
            fi
    done

    if [ "$whitelisted" = "1" ] ; then
            echo "$count attempts from WHITELISTED $host"
    elif grep -q "ALL:$host" /etc/hosts.deny ; then
            echo "$host is blacklisted $count attempts recorded"
    else
            echo "$count attempts from $host"
            if [ "$count" -gt "8" ] ; then
            ################### action for ip using ssh
                cd /tmp
                echo "Sending SSH complaint on $host"
                echo "Getting email addresses"
                emails="`host $host | awk '{print $NF}'`"
                list='admin@net.com'
                        echo "Sending email"
                        cat <<EOT |mailx -s "Escessive SSH attempts from $host" "$list"
                Received roughly $count
                attempts to login via the SSH protocol from $host
                using names: $usernames
EOT

                if grep "^ALL:$host\$" /etc/hosts.deny ; then
                        echo "Already in blocked list"
                else
                        echo "Adding $host to blocked list"
                        echo "ALL:$host" >>/etc/hosts.deny
                fi
            ################### end action
            else
                echo "     WARNING: $host is not blacklisted"
            fi
    fi
done ) > /Users/admin/logs/ssh_complaints.log