MyDeny Script

by Ramses Soto-Navarro, ramses@sotosystems.com

Overview
The Script
Cronjob
Remove IP

Overview

mydeny.sh script adds IP addresses to /etc/hosts.deny, which have too many bad SSH login attempts. It is a simple alternative to the older python denyhosts. It searches every night for IP addresses that failed to SSH more than 20 times, via cron. If so then it adds it to hosts.deny. Logging of each denied IP will be sent to /var/log/messages as mydeny.sh. Follow the parsing logic to automatically add more libwrap services to hosts.deny. This document is for experienced Linux administrators.

The Script

#!/bin/bash

MAX=20
DATE=`date +%Y-%m-%d`
MARK=$RANDOM
TMP1=~/tmp/$MARK-1.txt
TMP2=~/tmp/$MARK-2.txt

f_findbadssh () {
mkdir -p ~/tmp/
grep $DATE /var/log/messages | grep sshd | grep "error: PAM: User not known" | awk '{print $NF}' | sort | uniq > $TMP1
for a in `cat $TMP1` ; do echo -ne "$a: " && grep $a /var/log/messages | wc -l ; done > $TMP2
sed -i 's/://g' $TMP2
}

f_addtodh () {
cat $TMP2 | while read a ; do
	IP=`echo $a | awk '{print $1}'`
	COUNT=`echo $a | awk '{print $2}'`

	if [[ COUNT -gt MAX ]] ; then
		#echo "High Bad SSH Login Count = $COUNT for $IP. Adding to /etc/hosts.deny."
		CHECK1=`grep "$IP" /etc/hosts.deny`
		if [ "$CHECK1" == "" ]; then
			logger -t mydeny.sh "Adding $IP to /etc/hosts.deny."
			echo "sshd: $IP" >> /etc/hosts.deny
		fi
	fi
done
rm -f $TMP1 $TMP2
} 

f_findbadssh
f_addtodh

Cronjob

~ # crontab -l

# Add bad SSH login IPs to hosts.deny every 2 hours.
0 */2 * * * /root/bin/mydeny.sh

! # systemctl restart cron

Remove IP

To remove the IP from hosts.deny run:

# sed -i '/61.177.172.158/d' /etc/hosts.deny