#!/bin/bash

# This script monitors SSH brute force attacks by counting failed login attempts
# within a specified time window and sends a metric to Netdata via statsd
# if the threshold is exceeded.

THRESHOLD="__THRESHOLD__"
TIME_WINDOW="__TIME_WINDOW__"
METRIC_NAME="__METRIC_NAME__"

# Get the time window start in the format 'Jul 24 11:54'
window_start=$(date -d "$TIME_WINDOW minutes ago" '+%b %d %H:%M')

# Count failed SSH login attempts in the last TIME_WINDOW minutes
count=$(awk -v start="$window_start" '
  {
    ts = $1 " " $2 " " substr($3, 1, 5)
    if (ts >= start) {
      if ($0 ~ /Failed password/) {
        c++
      } else if ($0 ~ /message repeated [0-9]+ times: \[ Failed password/) {
        match($0, /message repeated ([0-9]+) times:/, m)
        c += m[1]
      }
    }
  }
  END { print c+0 }
' /var/log/auth.log)

if [ "$count" -ge "$THRESHOLD" ]; then
  attack_flag=1
else
  attack_flag=0
fi

echo "$METRIC_NAME:$attack_flag|g" | nc -u -w 1 localhost 8125 