#!/bin/bash

# This script is used to block attackers from accessing the database port

HOSTS_DENY="/etc/hosts.deny"
DB_PORT="__DB_PORT__"

blocked_ips=$(cat /var/log/ufw.log | grep "DPT=$DB_PORT" | grep "[UFW BLOCK]" | awk -F 'SRC=' '{print $2}' | awk '{print $1}' | sort | uniq)

for ip in $blocked_ips; do
    if ! grep -q "$ip" "$HOSTS_DENY"; then
        echo "ALL: $ip" | sudo tee -a "$HOSTS_DENY" > /dev/null
        echo "Denied IP: $ip has been added to $HOSTS_DENY"
    else
        echo "IP: $ip is already denied."
    fi
done
