#!/bin/bash
# =========================================================
# XBT Tracker – AutoBan DDoS (iptables)
# Détection + Ban + Expiration + Logs
# =========================================================

# -------------------------
# CONFIG
# -------------------------
PORT=8080
DURATION=10                 # secondes de capture
THRESHOLD=500              # requêtes / DURATION
BAN_TIME=3600               # durée du ban (1h)
PCAP="/tmp/ddos_8080.pcap"
LOG="/var/log/xbt_ddos.log"
BAN_DB="/var/lib/xbt_ddos_bans.db"

mkdir -p /var/lib
touch "$BAN_DB"

NOW=$(date +%s)

echo "[+] $(date) Capture trafic TCP port $PORT pendant ${DURATION}s" | tee -a "$LOG"

# -------------------------
# CAPTURE
# -------------------------
timeout "$DURATION" tcpdump -nn -i any tcp dst port "$PORT" -w "$PCAP" 2>/dev/null

# -------------------------
# DETECTION IP ABUSIVES
# Format: COUNT:IP
# -------------------------
ABUSIVE=$(tcpdump -nn -r "$PCAP" 2>/dev/null \
 | awk '{print $3}' \
 | sed -E 's/^IP6? //; s/\.[0-9]+$//' \
 | sort | uniq -c \
 | awk -v t="$THRESHOLD" '$1 >= t {print $1":"$2}')

rm -f "$PCAP"

# -------------------------
# BAN
# -------------------------
for entry in $ABUSIVE; do
    COUNT=${entry%%:*}
    ip=${entry##*:}
    RATE=$((COUNT / DURATION))

    if ! iptables -C INPUT -s "$ip" -p tcp --dport "$PORT" -j DROP 2>/dev/null; then
        iptables -I INPUT -s "$ip" -p tcp --dport "$PORT" -j DROP
        echo "$ip $NOW" >> "$BAN_DB"
        echo "[BAN] $(date) $ip ${COUNT}_req/${DURATION}s (${RATE} req/s)" | tee -a "$LOG"
    fi
done

# -------------------------
# UNBAN AUTO
# -------------------------
TMP_DB="/tmp/xbt_ddos_bans.tmp"
> "$TMP_DB"

while read -r ip ts; do
    if (( NOW - ts >= BAN_TIME )); then
        iptables -D INPUT -s "$ip" -p tcp --dport "$PORT" -j DROP 2>/dev/null
        echo "[UNBAN] $(date) $ip" | tee -a "$LOG"
    else
        echo "$ip $ts" >> "$TMP_DB"
    fi
done < "$BAN_DB"

mv "$TMP_DB" "$BAN_DB"

echo "[+] $(date) Cycle terminé" | tee -a "$LOG"

