Block active ssh login attempts from unknown IP’s on linux using hosts.deny

Some hosts on the net are severely compromised or shown to be controlled by malicious  users.

imho: Never allow a root login using ssh to any machine you are setting up. Yes ~they~ are always probing. It is a storm.

The following mechanism will have the hosts that try to login as various users and various password combinations to get a time-out on your machine using hosts.deny. You should use it to throw arsholes off balance, using up their automated scanners/probes precious time.

First you need to know what hosts are attempting to use your secure shell service.
You can show that as an authoritative user, such as root, on your device by running the command:

lastb -F -i

This shows you a list of tries, with no dns lookups, just IP’s.

As such, the following command sorts the list, and creates unique entries on IP and places them in a file (~/catlastlog)

lastb -F -i| awk '{ print $3 }' |sort |uniq > ~/catlastlog

Next, the following command formats it to be used in hosts.deny.

sed -i -e 's/^/ALL:/' ~/catlastlog

Hosts.deny is the file in /etc that tells your machine to deny something from the connecting host, in essence, you can have your machine drop any connection to that host immediately.

The last two commands fill your /etc/hosts.deny file so you are one step closer to being safe from hosts that attempt to use your precious secure shell service (or any service that you publish and want to keep safe).

echo "# /etc/hosts.deny: list of hosts that are _not_ allowed to access the system." > /etc/hosts.deny
cat ~/catlastlog >> /etc/hosts.deny

The first command creates a new and clear hosts.deny file.
The second command fills it with the recent hosts that failed login attempts.

The effect is immediate. New connections are dropped instantly.
Be sure not to lock yourself out [remotely], as this mechanism locks out any failed attempts directly, if you did, you can always edit the hosts.deny file from your console.

I now usually do this manually once in a while, as the compromised hosts vary from day to day. This is a crude form of protection, but I can imagine you could run this as a cron job if you are really fed up with wasted connections on your external interface. If you do, make sure all filenames are named with full path names [such as /secure/directory/catlastlog].

In fact, I encourage any admin to block internet crap. One day you’ll regret you didn’t.
That, and, it’s best to deny evil malicious pests everything [period], even milliseconds of probing time.

Can’t be zealous enough about it.

Hopes this helps you!
Cheers!

 

This entry was posted in block, command line, hosts.deny, linux, ssh. Bookmark the permalink.