Top

Using BTMP Log to Automate Firewall Rules

Using firewalld and want to drop traffic from numerous bad logins? Check out this article.

Use your BTMP to drop bad actors making bad SSH login attempts

We all see it - our SSH ports get spammed by bots trying to password crack our server, even with keys enabled. All of this gets logged thankfully and we can leverage this information to our advantage. Here’s the starting point:

lastb | tr -s ' ' | cut -d' ' -f1 | uniq | sort | uniq -c | sort -rn

Running this command will yield you a treasure trove of information that looks a little like the following:

236 ubuntu
218 admin
117 test
 82 user
 61 oracle
 36 testuser
 36 ali
 28 git
 25 administ
 24 postgres

These are the usernames used to try and access your server grouped by the number of attempts. Using this, we can pivot and use a similar command to get IP Addresses for these kinds of “people:”

lastb | cut -f3 | grep -P "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" -o | sort | uniq -c | sort -rn

This will output a list of similar results that likely look like the following:

296 170.64.173.229
 56 185.225.74.193
 39 161.35.108.241
 38 89.117.88.253
 35 95.181.230.228
 35 60.173.229.129
 33 62.122.184.124
 32 62.122.184.125
 31 46.148.41.185
 31 143.198.196.195

This is real data by the way. So, how can we use this information to prevent such actors from even being able to talk to our server? Well, it’s not that hard, actually. Using the above command, you can redirect the output to a file of your choosing like so:

lastb | cut -f3 | grep -P "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" -o | sort | uniq -c | sort -rn > badguys.txt

This will put it in the file for us and now we can use the following script to read this file, and add the IP addresses to our drop list:

#!/usr/bin/bash
#Check for bad login file
data=$(cat /path/to/badguys.txt | awk '{$1=$1;print}' | cut -d" " -f 2);
for IP in $data;
do
echo "Adding $IP to shit list...";
iptables -I INPUT -s $IP -j DROP;
done;

Watch all of them bad login requests start falling! This can also have the unintended consequence of blocking good traffic, so you could always limit this to people with a high number by putting the “head” command somewhere in your pipeline to only block those at the top of the list. After all, why do they have so many bad logins when your SSH “should” be keyed….hope this has helped you!

Think I might be a good fit for your project?

Let's get the conversation started!