So I was bored laying in bed watching movies on my Linux box and I decided to check some things while I was relaxing. I saw I had a tcp connection open on port 22 when using 'netstat -apn' so I checked the auth logs and sure enough somebody was actively brute-forcing user 'root' on my ssh server. There were other entries as well, trying silly ass usernames like 'postgres' and 'admin'.
I found this interesting, as I don't know who in the right mind would allow remote root login for their ssh daemon.
I got to thinking about /etc/hosts.deny and I thought wouldn't it be neat to write a script that audits my logs and automatically adds entries to /etc/hosts.deny?
So that's what I did. I made it so the script does not log duplicate hosts from the auth log. Works quickly, all you need is a cron job to run every 30min or something and you're good to go. Try it out, I was surprised how many entries it found.
The only problem I can think of.. What if I accidentally type a bogus username when logging into the system? My script checks for entries with the string 'Invalid user'. I will be locked out the first time that the script runs after that.
Edit: Took out search string 'Invalid user'(line 38) as it was locking me out after trying to log in with wrong username. Now the script only looks for connections made with username 'root'. I never log in as root remotely so this will work for now. My goal is to blacklist all suspicious ssh connections.
#!/bin/bash
##
### ssh-lfd.sh - ssh-l(ogin)-f(ail)-d(eny)
##
#
export DENYHOST="/etc/hosts.deny"
export AUTHLOG="/var/log/auth.log"
export LOGFILE="/var/log/ssh-lfd.log"
export TMPFILE="/tmp/ssh-lfd.tmp"
export HOSTLIST="/tmp/ssh-lfd.hosts"
banner() {
log ""
log " ssh-lfd.sh - l(ogin)-f(ail)-d(eny)"
log " Nobody enables ssh root login, right?"
log ""
}
log() {
echo $1
echo $1 >> $LOGFILE
}
cancel() {
rm -f $TMPFILE $HOSTLIST
}
trap cancel SIGINT
if [ $(whoami) != "root" ]; then
banner
log "[!] Error: login as root and try again."
exit
fi
log "[-] Parsing $AUTHLOG.."
cat $AUTHLOG | grep sshd | grep "Failed password for root" | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' >> $TMPFILE
sort -u $TMPFILE > $HOSTLIST
rm -f $TMPFILE
log "[-] Checking $DENYHOST for previous entries.."
for item in $(cat $HOSTLIST); do
if [ -z $(cat $DENYHOST | grep $item) ]; then
log "[+] Adding $item to $DENYHOST"
echo "sshd:$item" >> $DENYHOST
else
continue
fi
done
log "[-] Deleting files in /tmp.."
rm -f $TMPFILE $HOSTLIST
log "[*] Done. $(date)"