#!/bin/bash
# vte.ego.it — Hardening LAMP (fail2ban + Apache) — Ubuntu 24.04
# Riferimento: https://usermanual.vtenext.com/books/corso-installerconfigurator/page/hardening
# Uso: sudo bash /var/www/html/server-ops/ego/hardening-lamp-vtenext.sh

set -euo pipefail

if [[ "${EUID:-0}" -ne 0 ]]; then
	echo "Esegui come root: sudo bash $0" >&2
	exit 1
fi

. /etc/os-release
echo "[INFO] OS: ${PRETTY_NAME:-unknown}"
echo "[INFO] Hardening: fail2ban + Apache (MySQL escluso)"

export DEBIAN_FRONTEND=noninteractive

# --- Fase 1: fail2ban ---
echo "[INFO] Installazione fail2ban..."
apt-get update -qq
apt-get install -y fail2ban
systemctl enable --now fail2ban

echo "[INFO] Creazione filtro /etc/fail2ban/filter.d/apache-404.conf"
cat > /etc/fail2ban/filter.d/apache-404.conf <<'EOF'
[Definition]

failregex = ^<HOST> .* "(GET|POST|HEAD|PUT).*" 404
ignoreregex =.*(robots.txt|favicon.ico|jpg|png|gif)
EOF

echo "[INFO] Creazione jail /etc/fail2ban/jail.local"
cat > /etc/fail2ban/jail.local <<'EOF'
[DEFAULT]

ignoreip = 127.0.0.1/8 ::1 10.0.0.0/24

[apache-404]

enabled = true
port = http,https
filter = apache-404
action = iptables-allports[protocol=all, blocktype=DROP]

logpath = /var/log/apache2/access.log

bantime  = 3600
findtime = 120
maxretry = 100
EOF

systemctl reload fail2ban

# --- Fase 2: Apache security.conf ---
SECURITY_CONF="/etc/apache2/conf-enabled/security.conf"
if [[ ! -f "$SECURITY_CONF" ]]; then
	echo "[ERR] File non trovato: $SECURITY_CONF" >&2
	exit 1
fi

echo "[INFO] Aggiornamento $SECURITY_CONF"
sed -i 's/^ServerTokens.*/ServerTokens Prod/' "$SECURITY_CONF"
sed -i 's/^ServerSignature.*/ServerSignature Off/' "$SECURITY_CONF"
# TraceEnable Off dovrebbe già essere impostato; forza se commentato o assente
if grep -q '^TraceEnable' "$SECURITY_CONF"; then
	sed -i 's/^TraceEnable.*/TraceEnable Off/' "$SECURITY_CONF"
else
	echo "TraceEnable Off" >> "$SECURITY_CONF"
fi

echo "[INFO] Direttive Apache attive:"
grep -E '^(ServerTokens|ServerSignature|TraceEnable)' "$SECURITY_CONF" || true

systemctl restart apache2

# --- Fase 3: Verifica ---
echo ""
echo "========== VERIFICA =========="

echo "[CHECK] fail2ban:"
systemctl is-active fail2ban
fail2ban-client status
fail2ban-client status apache-404

echo ""
echo "[CHECK] Header Apache (atteso: solo 'Server: Apache'):"
curl -sI http://localhost/ | grep -i '^server:' || true

echo ""
echo "[CHECK] VTEnext HTTPS:"
curl -sI https://vte.ego.it/ | head -5 || true

echo ""
echo "[OK] Hardening completato."
