#!/bin/sh
# Sharpener.sh
# Simple SSH brute force blocker and reporter tool running from cron
# (c) 2006 J. Oquendo
# sil @ infiltrated dot net
# 
# I got tired of seeing questions posted on blocking brute force attempts. This was started as a small
# project and was a clean 7 line script... However, I thought it would come in handy to give admins
# the option of sharing information on brute force attempts. This information will be shared weekly
# for others to use. Something akin to a "RBL" for brute force addresses. 
#
# The theory behind this is, if enough addresses are accumulated, perhaps network engineers can
# take a peek from time to time and see who if anyone on their network is attacking another
# machine.
#
# On the backend side of this, should you uncomment the "mail to" portion of this script, addresses
# will be taken, sorted, posted to a page, and an auto generated email will be sent to the attackers
# provider and upstream.
#
# I made this for a Linux machine I administer and was tired of sifting through logs and having to
# block out attackers... I post the data that is sent to my account to a specific webserver, then
# on all machines I come in contact with, ,they all wget this file and add the offenders to their
# lists too. Think of it as an all inclusive oddly managed "attacker repository"
#
# Tested on FC5, Scientific Linux, SuSE 10.1, FC3
# Also tested on NetBSD 3.0 and FreeBSD 6.1 using IPF ... Feel free to uncomment that portion of
# the script. I just didn't feel like doing if [ -e /path/to/ipfw ] || [ -e /path/to/pf ]..
#

if [ -e /tmp/hosts.deny ]
 then
 rm /tmp/hosts.deny
fi

awk '/error retrieving/{getline;print $13}' /var/log/secure|sort -ru >> /tmp/hosts.deny
diff /etc/hosts.deny /tmp/hosts.deny|awk '/>/{print $2}'

OS=$( uname|sed -n '1p')

# IPTables function...
ifaddr=`ifconfig -a|awk '/inet/ && !/inet6/ && !/127.0/ && !/192.168/{print $2}'|sed 's/addr\://g'`

function IPT {

awk '!/#/ && /\./ && !a[$0]++
{print "iptables -A INPUT -s "$1" -i eth0 -d '$ifaddr' -p TCP --dport 22 -j REJECT"}' /etc/hosts.deny |\
awk '/iptables/ && !/#/ && !/-s  -i/'|sh

}


if [ $OS = Linux ]

	then
		IPT
	else

case "$OS" in
*BSD)		

		echo "Sorry... Didn't feel like doing a BSD script..."
		echo "Too many variables... ipf, pf, ipfw..."

# IPF (tested on NetBSD)
# cat /etc/hosts.deny|\
# awk '!/#/ &&
# /./ &&
# ! a[$0]++
# {print "echo \"block in quick from "$1" to any\" |ipf -f -"}'|\
# awk '!/#/ && !/from  to/'|awk '/block/'|sh

	esac

fi


# The purpose of the following will be to maintain a list of known brute
# forcer's IP addresses. This list will be summarized and posted weekly so that
# others can add the offenders to their firewall rules and a report be generated
# for the provider of the attacker


awk '{print $1" has been blocked via SSH"}' /etc/hosts.deny |\
mail -s "Sharpener" sharpener@infiltrated.net