Samstag, 22. November 2014

Ban assholes trying to hack SSH passwords.

Normally I do not care much about those assholes trying to hack my system by probing SSH passwords. But today a probing attack took so much resources, that my own session starts lagging. So I had to take a fly swap to smash the gadfly. Here is the swap.

#! /bin/bash
##
## Ban SSH password cracking attempts.
##
## Time-stamp: <2014-11-22 19:26:44 szi>
##

set -eu

FILE="$1"; shift

IP='[0-9]\+\.[0-9]\+\.[0-9]\+.[0-9]\+'
TZ=$(date '+%Y-%m-%d %H:%M:%S %z')

# Search failed SSH logins.
sed -n 's/.* sshd\[[0-9]*\]: Failed password .* \('"$IP"'\).*/\1/p' "$FILE" |
# Count the number of failures.
sort | uniq -c |
# Select all addresses with more than 3 failures.
awk '$1>3 {print $2}' |
# Remove the already banned.
grep -v -f <(iptables -n -L INPUT | awk '$1=="DROP" {print $4}') |
# Report
tee >(read LINE < <(xargs echo); echo "Banning: ${LINE:-none}" >&2) |
# And ban the new assholes.
xargs -i iptables -A INPUT -s '{}' -m comment --comment "$TZ" -j DROP

The script needs the file containing the SSH auth log as an argument and can be run in a cron job every five minutes. Each drop rule gets a time stamp. This makes it possible to remove old entries, if the INPUT chain gets too big.

Here is an example. Flush the INPUT chain:

# iptables -F INPUT

Run the script:

# banip /var/log/auth.log
Banning: 103.41.124.12 122.225.109.211 122.225.97.75 122.225.97.97 222.186.34.119 61.136.171.198 62.210.141.172 62.210.172.143 62.210.172.206 82.165.128.189

Control the new input chain:

# iptables -n -L INPUT
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
DROP       all  --  103.41.124.12        0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */
DROP       all  --  122.225.109.211      0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */
DROP       all  --  122.225.97.75        0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */
DROP       all  --  122.225.97.97        0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */
DROP       all  --  222.186.34.119       0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */
DROP       all  --  61.136.171.198       0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */
DROP       all  --  62.210.141.172       0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */
DROP       all  --  62.210.172.143       0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */
DROP       all  --  62.210.172.206       0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */
DROP       all  --  82.165.128.189       0.0.0.0/0            /* 2014-11-22 19:27:44 +0100 */

Of course it is also possible to install fail2ban but my small Geode has only 256MB RAM and therefor I have to minimize my services. The above script is enough for me.

The code can be found on Github.

Keine Kommentare: