Tag: hosts.deny
Update hosts.deny to block ssh brute force attemps
by Felipe 'chronos' Prenholato on 02:14 PM, under Linux, Servers
Here I show a sinple script to block IPs that try brute force at your host, preventing you from use a alternative ssh port, as example.
The script runs over /var/log/messages and detect via regex brute force attemps, and add IPs to /etc/hosts.deny
Code:
#!/bin/bash</code> cp /etc/hosts.deny /var/tmp/hosts.deny # Jun 8 00:39:43 mintaka sshd[23332]: User root from 222.77.183.51 not allowed because not listed in AllowUsers egrep "$(date +%b) ($(date +%d)|$(date +%e)).*User .* from [a-z0-9\.]* not allowed because not listed in AllowUsers" /var/log/messages | sed -e 's/.* from \([a-z0-9\.]*\) .*/\1/' | sort | uniq | sed -e 's/^/ALL:/' > /etc/hosts.deny ; #Jun 8 11:54:33 mintaka sshd[31221]: Invalid user bob from 62.204.145.224 egrep "$(date +%b) ($(date +%d)|$(date +%e)).*Invalid user .* from [a-z0-9\.]*$" /var/log/messages | sed -e 's/.*Invalid user .* from//' | sort | uniq | sed -e 's/^/ALL:/' >> /etc/hosts.deny ; diff -u /etc/hosts.deny /var/tmp/hosts.deny &>/dev/null || (echo "** hosts.deny updated **" ; cat /etc/hosts.deny)
Script working:
Sep 2 16:55:02 mintaka -- MARK --
Sep 2 13:58:10 mintaka sshd[20790]: Did not receive identification string from 189.2.118.72
Sep 2 13:58:34 mintaka sshd[20795]: Invalid user suporte from 189.2.118.72
# Brute force attemp
Sep 2 13:58:41 mintaka sshd[20798]: Invalid user suporte from 189.2.118.72
Sep 2 13:58:43 mintaka sshd[20800]: Invalid user suporte from 189.2.118.72
Sep 2 13:58:46 mintaka sshd[20802]: Invalid user suporte from 189.2.118.72
Sep 2 13:58:49 mintaka sshd[20804]: Invalid user suporte from 189.2.118.72
Sep 2 13:58:51 mintaka sshd[20806]: Invalid user suporte from 189.2.118.72
Sep 2 13:59:24 mintaka sshd[20817]: Did not receive identification string from 189.2.118.72
# Script running
** hosts.deny updated **
ALL:74.221.239.100
ALL: 189.2.118.72
ALL: 200.27.79.101
ALL: 74.221.239.100
# and now IPs are blocked
Sep 2 14:00:09 mintaka sshd[20826]: Invalid user teste2008 from 189.2.118.72
Sep 2 14:00:10 mintaka sshd[20864]: refused connect from 189.2.118.72 (189.2.118.72)
I run in my machine every two minutes