#!/bin/bash # ============================================================ # VPN WATCHDOG — WireGuard # Vérifie que le trafic sort bien par wg0 # Si fuite détectée : redémarre WireGuard # ============================================================ WG_INTERFACE="wg0" LOG_FILE="/var/log/vpn_watchdog.log" MAX_HANDSHAKE_AGE=180 # secondes log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE" } # ============================================================ # ÉTAPE 1 : Vérifier que l'interface wg0 existe # ============================================================ if ! wg show "$WG_INTERFACE" &>/dev/null; then log "ALERTE : Interface $WG_INTERFACE absente. Tentative de démarrage..." systemctl restart wg-quick@$WG_INTERFACE.service sleep 10 if ! wg show "$WG_INTERFACE" &>/dev/null; then log "ECHEC : Impossible de démarrer $WG_INTERFACE. Intervention manuelle requise." exit 1 fi log "OK : $WG_INTERFACE démarré." fi # ============================================================ # ÉTAPE 2 : Vérifier l'âge du dernier handshake # ============================================================ LAST_HANDSHAKE=$(wg show "$WG_INTERFACE" latest-handshakes | awk '{print $2}') NOW=$(date +%s) DIFF=$((NOW - LAST_HANDSHAKE)) if [[ $DIFF -gt $MAX_HANDSHAKE_AGE ]]; then log "ALERTE : Handshake trop ancien (${DIFF}s). Redémarrage de WireGuard..." systemctl restart wg-quick@$WG_INTERFACE.service sleep 10 fi # ============================================================ # ÉTAPE 3 : Vérifier que le trafic sort bien par wg0 # ============================================================ ROUTE_DEV=$(ip route get 8.8.8.8 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="dev") print $(i+1)}') if [[ "$ROUTE_DEV" != "$WG_INTERFACE" ]]; then log "ALERTE : Fuite détectée — trafic sur '$ROUTE_DEV' au lieu de '$WG_INTERFACE'. Redémarrage..." systemctl restart wg-quick@$WG_INTERFACE.service sleep 10 # Revérifier après redémarrage ROUTE_DEV_AFTER=$(ip route get 8.8.8.8 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="dev") print $(i+1)}') if [[ "$ROUTE_DEV_AFTER" == "$WG_INTERFACE" ]]; then log "OK : Trafic rétabli sur $WG_INTERFACE après redémarrage." else log "ECHEC : Trafic toujours sur '$ROUTE_DEV_AFTER'. Intervention manuelle requise." exit 1 fi else log "OK : Trafic sur $WG_INTERFACE — VPN actif." fi exit 0