AP manageur V1.1 (Bêta)

This commit is contained in:
yoannmultigaming committed 2026-11-27 02:14:40 +01:00
1 parent 92d8cf9bd2
commit b85a7fdcfe
2 files changed
+155 -64

No files matched your search

+72 -41
View File
@@ -58,14 +58,18 @@ def remove_uptime_file():
atexit.register(remove_uptime_file) atexit.register(remove_uptime_file)
def _sig_handler(signum, frame): def _sig_handler(signum, frame):
try:
if 'shutdown_wifi' in globals():
shutdown_wifi()
except Exception: pass
try: try:
if 'disconnect_all_vpn_profiles' in globals(): if 'disconnect_all_vpn_profiles' in globals():
disconnect_all_vpn_profiles('SIGTERM') disconnect_all_vpn_profiles('SIGTERM')
except Exception: pass except Exception: pass
try:
if 'remove_bridge_if_created' in globals():
remove_bridge_if_created()
except Exception: pass
try:
if 'shutdown_wifi' in globals():
shutdown_wifi()
except Exception: pass
remove_uptime_file() remove_uptime_file()
os._exit(0) os._exit(0)
@@ -87,6 +91,22 @@ def command(*args, timeout=5):
try: return subprocess.check_output(args, text=True, stderr=subprocess.DEVNULL, timeout=timeout).strip() try: return subprocess.check_output(args, text=True, stderr=subprocess.DEVNULL, timeout=timeout).strip()
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError): return '' except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError): return ''
def is_iface_up(iface):
"""Vérifie si une interface réseau existe et est active (IFF_UP)."""
if not iface: return False
p = f'/sys/class/net/{iface}'
if not os.path.exists(p): return False
try:
with open(f'{p}/flags', 'r') as f:
flags = int(f.read().strip(), 16)
return bool(flags & 1) # IFF_UP
except Exception: pass
try:
with open(f'{p}/operstate', 'r') as f:
return f.read().strip().lower() == 'up'
except Exception: pass
return False
# Radio : 2,4 GHz ou 5 GHz. # Radio : 2,4 GHz ou 5 GHz.
AP_BAND = os.environ.get('AP_BAND', 'bg') if os.environ.get('AP_BAND', 'bg') in ('bg', 'a') else 'bg' AP_BAND = os.environ.get('AP_BAND', 'bg') if os.environ.get('AP_BAND', 'bg') in ('bg', 'a') else 'bg'
AP_CHANNEL_CONFIGURED = os.environ.get('AP_CHANNEL', '').strip() AP_CHANNEL_CONFIGURED = os.environ.get('AP_CHANNEL', '').strip()
@@ -326,12 +346,12 @@ def get_effective_ap_channel(band=None, force_rescan=False):
except (TypeError, ValueError): except (TypeError, ValueError):
return 6 return 6
# Initialisation du canal par défaut # Initialisation du canal par défaut (le scan auto est effectué au démarrage effectif de l'AP pour ne pas bloquer les imports ou le cleanup)
if not is_auto_channel(): if not is_auto_channel():
try: AP_CHANNEL = int(AP_CHANNEL_CONFIGURED) try: AP_CHANNEL = int(AP_CHANNEL_CONFIGURED)
except ValueError: AP_CHANNEL = 6 except ValueError: AP_CHANNEL = 6
else: else:
AP_CHANNEL = get_effective_ap_channel(AP_BAND) AP_CHANNEL = 6
SERVER_BOOT_TIME = time.time() SERVER_BOOT_TIME = time.time()
app_startup_done = False app_startup_done = False
@@ -7832,21 +7852,6 @@ def get_next_vpn_table_id():
return tid return tid
return 101 return 101
def is_iface_up(iface):
if not iface: return False
p = f'/sys/class/net/{iface}'
if not os.path.exists(p): return False
try:
with open(f'{p}/flags', 'r') as f:
flags = int(f.read().strip(), 16)
return bool(flags & 1) # IFF_UP
except Exception: pass
try:
with open(f'{p}/operstate', 'r') as f:
return f.read().strip().lower() == 'up'
except Exception: pass
return False
def read_iface_traffic(iface): def read_iface_traffic(iface):
rx, tx = 0, 0 rx, tx = 0, 0
if not iface: return rx, tx if not iface: return rx, tx
@@ -8476,8 +8481,8 @@ def disconnect_all_vpn_profiles(caller_ip='CONTAINER_SHUTDOWN'):
# 1. Arrêt forcé des processus OpenVPN résiduels (ovpn_ap*) # 1. Arrêt forcé des processus OpenVPN résiduels (ovpn_ap*)
try: try:
subprocess.run(['pkill', '-9', '-f', 'ovpn_ap'], capture_output=True) subprocess.run(['pkill', '-9', '-f', 'ovpn_ap'], capture_output=True, timeout=2)
subprocess.run(['pkill', '-9', '-f', 'openvpn.*ap-vpn'], capture_output=True) subprocess.run(['pkill', '-9', '-f', 'openvpn.*ap-vpn'], capture_output=True, timeout=2)
if os.path.exists(VPN_RUN_DIR): if os.path.exists(VPN_RUN_DIR):
import glob import glob
for pf in glob.glob(f"{VPN_RUN_DIR}/*.pid"): for pf in glob.glob(f"{VPN_RUN_DIR}/*.pid"):
@@ -8485,7 +8490,7 @@ def disconnect_all_vpn_profiles(caller_ip='CONTAINER_SHUTDOWN'):
with open(pf) as f: with open(pf) as f:
opid = f.read().strip() opid = f.read().strip()
if opid: if opid:
subprocess.run(['kill', '-9', opid], capture_output=True) subprocess.run(['kill', '-9', opid], capture_output=True, timeout=2)
except Exception: pass except Exception: pass
try: os.remove(pf) try: os.remove(pf)
except OSError: pass except OSError: pass
@@ -8497,19 +8502,39 @@ def disconnect_all_vpn_profiles(caller_ip='CONTAINER_SHUTDOWN'):
if os.path.exists(VPN_DIR_WG): if os.path.exists(VPN_DIR_WG):
for cf in glob.glob(f"{VPN_DIR_WG}/*.conf"): for cf in glob.glob(f"{VPN_DIR_WG}/*.conf"):
wifc = os.path.splitext(os.path.basename(cf))[0] wifc = os.path.splitext(os.path.basename(cf))[0]
subprocess.run(['wg-quick', 'down', wifc], capture_output=True) try: subprocess.run(['wg-quick', 'down', wifc], capture_output=True, timeout=2)
subprocess.run(['ip', 'link', 'set', 'dev', wifc, 'down'], capture_output=True) except Exception: pass
subprocess.run(['ip', 'link', 'delete', 'dev', wifc], capture_output=True) try: subprocess.run(['ip', 'link', 'set', 'dev', wifc, 'down'], capture_output=True, timeout=2)
except Exception: pass
try: subprocess.run(['ip', 'link', 'delete', 'dev', wifc], capture_output=True, timeout=2)
except Exception: pass
except Exception: pass except Exception: pass
# 3. Suppression directe de toute interface réseau résiduelle wg_ap* ou tun_ap* # 3. Suppression directe de toute interface réseau résiduelle wg*, wg_ap*, tun_ap*, tap_ap*
try: try:
import glob import glob
for ifpath in glob.glob('/sys/class/net/wg_ap*') + glob.glob('/sys/class/net/tun_ap*'): for ifpath in glob.glob('/sys/class/net/wg*') + glob.glob('/sys/class/net/tun_ap*') + glob.glob('/sys/class/net/tap_ap*'):
dev = os.path.basename(ifpath) dev = os.path.basename(ifpath)
subprocess.run(['wg-quick', 'down', dev], capture_output=True) try: subprocess.run(['wg-quick', 'down', dev], capture_output=True, timeout=2)
subprocess.run(['ip', 'link', 'set', 'dev', dev, 'down'], capture_output=True) except Exception: pass
subprocess.run(['ip', 'link', 'delete', 'dev', dev], capture_output=True) try: subprocess.run(['ip', 'link', 'set', 'dev', dev, 'down'], capture_output=True, timeout=2)
except Exception: pass
try: subprocess.run(['ip', 'link', 'delete', 'dev', dev], capture_output=True, timeout=2)
except Exception: pass
except Exception: pass
# Recherche directe et suppression des interfaces de type wireguard via iproute2
try:
out = command('ip', '-o', 'link', 'show', 'type', 'wireguard', timeout=2)
for line in out.splitlines():
parts = line.split(':')
if len(parts) >= 2:
dev = parts[1].strip().split('@')[0]
if dev and os.path.exists(f'/sys/class/net/{dev}'):
try: subprocess.run(['ip', 'link', 'set', 'dev', dev, 'down'], capture_output=True, timeout=2)
except Exception: pass
try: subprocess.run(['ip', 'link', 'delete', 'dev', dev], capture_output=True, timeout=2)
except Exception: pass
except Exception: pass except Exception: pass
# 4. Nettoyage des tables de routage PBR et règles de politique de routage # 4. Nettoyage des tables de routage PBR et règles de politique de routage
@@ -8519,12 +8544,16 @@ def disconnect_all_vpn_profiles(caller_ip='CONTAINER_SHUTDOWN'):
c.close() c.close()
for (tid,) in rows: for (tid,) in rows:
if tid: if tid:
subprocess.run(['ip', '-4', 'route', 'flush', 'table', str(tid)], capture_output=True) subprocess.run(['ip', '-4', 'route', 'flush', 'table', str(tid)], capture_output=True, timeout=2)
subprocess.run(['ip', '-6', 'route', 'flush', 'table', str(tid)], capture_output=True) subprocess.run(['ip', '-6', 'route', 'flush', 'table', str(tid)], capture_output=True, timeout=2)
for _ in range(5): for _ in range(3):
if subprocess.run(['ip', '-4', 'rule', 'del', 'table', str(tid)], capture_output=True).returncode != 0: break if subprocess.run(['ip', '-4', 'rule', 'del', 'table', str(tid)], capture_output=True, timeout=1).returncode != 0: break
for _ in range(5): for _ in range(3):
if subprocess.run(['ip', '-6', 'rule', 'del', 'table', str(tid)], capture_output=True).returncode != 0: break if subprocess.run(['ip', '-6', 'rule', 'del', 'table', str(tid)], capture_output=True, timeout=1).returncode != 0: break
for _ in range(3):
if subprocess.run(['ip', '-4', 'rule', 'del', 'fwmark', str(tid)], capture_output=True, timeout=1).returncode != 0: break
for _ in range(3):
if subprocess.run(['ip', '-6', 'rule', 'del', 'fwmark', str(tid)], capture_output=True, timeout=1).returncode != 0: break
except Exception: pass except Exception: pass
# 5. Nettoyage nftables et ebtables L2/L3 # 5. Nettoyage nftables et ebtables L2/L3
@@ -8532,7 +8561,7 @@ def disconnect_all_vpn_profiles(caller_ip='CONTAINER_SHUTDOWN'):
_cleanup_ebtables_vpn() _cleanup_ebtables_vpn()
nft_bin = find_bin('nft') nft_bin = find_bin('nft')
if nft_bin: if nft_bin:
subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True) subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True, timeout=2)
except Exception: pass except Exception: pass
# 6. Mise à jour de l'état dans la base de données # 6. Mise à jour de l'état dans la base de données
@@ -8545,10 +8574,12 @@ def disconnect_all_vpn_profiles(caller_ip='CONTAINER_SHUTDOWN'):
# 7. Purge conntrack # 7. Purge conntrack
try: try:
subprocess.run(['conntrack', '-F'], capture_output=True) subprocess.run(['conntrack', '-F'], capture_output=True, timeout=2)
subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True) subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True, timeout=2)
except Exception: pass except Exception: pass
atexit.register(disconnect_all_vpn_profiles)
def list_vpn_clients(): def list_vpn_clients():
all_devs = all_devices().get('devices', []) all_devs = all_devices().get('devices', [])
c = db() c = db()
+83 -23
View File
@@ -116,14 +116,33 @@ sysctl -w net.ipv4.conf.all.forwarding=1 2>/dev/null || true
sysctl -w net.ipv4.conf.all.rp_filter=0 2>/dev/null || true sysctl -w net.ipv4.conf.all.rp_filter=0 2>/dev/null || true
sysctl -w net.ipv4.conf.default.rp_filter=0 2>/dev/null || true sysctl -w net.ipv4.conf.default.rp_filter=0 2>/dev/null || true
# Nettoyage des anciennes interfaces et tables VPN résiduelles d'une précédente session # Nettoyage exhaustif des anciennes interfaces et tables VPN résiduelles d'une précédente session
for ifc in $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | grep -E '^(wg_ap|tun_ap)'); do for ifpath in /sys/class/net/wg* /sys/class/net/tun_ap* /sys/class/net/tap_ap*; do
log "Nettoyage interface VPN résiduelle : $ifc" if [[ -e "$ifpath" ]]; then
ip link delete "$ifc" 2>/dev/null || true _dev="$(basename "$ifpath")"
log "Nettoyage interface VPN résiduelle : $_dev"
timeout 2 wg-quick down "$_dev" 2>/dev/null || true
ip link set dev "$_dev" down 2>/dev/null || true
ip link delete dev "$_dev" 2>/dev/null || true
fi
done done
for tid in $(seq 101 125); do if command -v ip >/dev/null 2>&1; then
ip route flush table "$tid" 2>/dev/null || true for _wdev in $(ip -o link show type wireguard 2>/dev/null | awk -F': ' '{print $2}' | cut -d'@' -f1); do
for _i in 1 2 3; do ip rule del table "$tid" 2>/dev/null || break; done if [[ -n "$_wdev" && -d "/sys/class/net/$_wdev" ]]; then
log "Nettoyage interface WireGuard résiduelle : $_wdev"
timeout 2 wg-quick down "$_wdev" 2>/dev/null || true
ip link set dev "$_wdev" down 2>/dev/null || true
ip link delete dev "$_wdev" 2>/dev/null || true
fi
done
fi
for tid in $(seq 100 135); do
ip -4 route flush table "$tid" 2>/dev/null || true
ip -6 route flush table "$tid" 2>/dev/null || true
for _i in 1 2 3; do ip -4 rule del table "$tid" 2>/dev/null || break; done
for _i in 1 2 3; do ip -6 rule del table "$tid" 2>/dev/null || break; done
for _i in 1 2 3; do ip -4 rule del fwmark "$tid" 2>/dev/null || break; done
for _i in 1 2 3; do ip -6 rule del fwmark "$tid" 2>/dev/null || break; done
done done
purge_apmanageur_rules() { purge_apmanageur_rules() {
@@ -373,13 +392,18 @@ cleanup() {
trap - EXIT TERM INT trap - EXIT TERM INT
log "Arrêt des services et nettoyage..." log "Arrêt des services et nettoyage..."
# Arrêt et suppression propre de toutes les interfaces VPN configurées (WireGuard et OpenVPN) # 1. Notification d'arrêt aux démons internes
log "Arrêt et suppression des interfaces VPN..." if [[ -n "${API_PID:-}" ]]; then
if [[ -f /app/ap.py ]]; then kill -TERM "$API_PID" 2>/dev/null || true
python3 /app/ap.py --cleanup-vpn 2>/dev/null || true fi
if [[ -n "${WEB_PID:-}" ]]; then
kill -TERM "$WEB_PID" 2>/dev/null || true
fi
if [[ -n "${NM_PID:-}" ]]; then
kill -TERM "$NM_PID" 2>/dev/null || true
fi fi
# Filet de sécurité au niveau shell : arrêt forcé des démons OpenVPN résiduels # 2. Arrêt et suppression propre et immédiate de tous les démons OpenVPN
pkill -9 -f 'ovpn_ap' 2>/dev/null || true pkill -9 -f 'ovpn_ap' 2>/dev/null || true
pkill -9 -f 'openvpn.*ap-vpn' 2>/dev/null || true pkill -9 -f 'openvpn.*ap-vpn' 2>/dev/null || true
if [[ -d /run/ap-vpn ]]; then if [[ -d /run/ap-vpn ]]; then
@@ -392,31 +416,59 @@ cleanup() {
done done
fi fi
# Arrêt et suppression des interfaces WireGuard # 3. Arrêt et suppression de TOUTES les interfaces WireGuard et VPN
if [[ -d /etc/wireguard ]]; then log "Suppression de toutes les interfaces réseau créées (WireGuard, OpenVPN)..."
if command -v wg-quick >/dev/null 2>&1 && [[ -d /etc/wireguard ]]; then
for conf in /etc/wireguard/*.conf; do for conf in /etc/wireguard/*.conf; do
if [[ -f "$conf" ]]; then if [[ -f "$conf" ]]; then
_wifc="$(basename "$conf" .conf)" _wifc="$(basename "$conf" .conf)"
wg-quick down "$_wifc" 2>/dev/null || true timeout 2 wg-quick down "$_wifc" 2>/dev/null || true
ip link set dev "$_wifc" down 2>/dev/null || true ip link set dev "$_wifc" down 2>/dev/null || true
ip link delete dev "$_wifc" 2>/dev/null || true ip link delete dev "$_wifc" 2>/dev/null || true
fi fi
done done
fi fi
# Suppression de toutes les interfaces VPN wg_ap* et tun_ap* résiduelles sur l'hôte # Parcours exhaustif dans /sys/class/net pour wg*, tun_ap*, tap_ap*
for ifc in $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | grep -E '^(wg_ap|tun_ap)'); do for ifpath in /sys/class/net/wg* /sys/class/net/tun_ap* /sys/class/net/tap_ap*; do
log "Suppression de l'interface VPN : $ifc" if [[ -e "$ifpath" ]]; then
ip link set dev "$ifc" down 2>/dev/null || true _dev="$(basename "$ifpath")"
ip link delete "$ifc" 2>/dev/null || true log "Suppression de l'interface réseau : $_dev"
timeout 2 wg-quick down "$_dev" 2>/dev/null || true
ip link set dev "$_dev" down 2>/dev/null || true
ip link delete dev "$_dev" 2>/dev/null || true
fi
done done
# Nettoyage des tables de routage PBR et règles de politique de routage VPN # Détection par type de lien WireGuard via iproute2
for tid in $(seq 101 125); do if command -v ip >/dev/null 2>&1; then
for _wdev in $(ip -o link show type wireguard 2>/dev/null | awk -F': ' '{print $2}' | cut -d'@' -f1); do
if [[ -n "$_wdev" && -d "/sys/class/net/$_wdev" ]]; then
log "Suppression de l'interface WireGuard détectée : $_wdev"
timeout 2 wg-quick down "$_wdev" 2>/dev/null || true
ip link set dev "$_wdev" down 2>/dev/null || true
ip link delete dev "$_wdev" 2>/dev/null || true
fi
done
fi
# Recherche résiduelle dans ip link pour tout wg_ap* ou tun_ap*
for ifc in $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | cut -d'@' -f1 | grep -E '^(wg_ap|tun_ap|tap_ap)'); do
if [[ -n "$ifc" && -d "/sys/class/net/$ifc" ]]; then
log "Suppression de l'interface résiduelle : $ifc"
ip link set dev "$ifc" down 2>/dev/null || true
ip link delete dev "$ifc" 2>/dev/null || true
fi
done
# 4. Nettoyage des tables de routage PBR et règles de politique de routage VPN
for tid in $(seq 100 135); do
ip -4 route flush table "$tid" 2>/dev/null || true ip -4 route flush table "$tid" 2>/dev/null || true
ip -6 route flush table "$tid" 2>/dev/null || true ip -6 route flush table "$tid" 2>/dev/null || true
for _i in 1 2 3; do ip -4 rule del table "$tid" 2>/dev/null || break; done for _i in 1 2 3; do ip -4 rule del table "$tid" 2>/dev/null || break; done
for _i in 1 2 3; do ip -6 rule del table "$tid" 2>/dev/null || break; done for _i in 1 2 3; do ip -6 rule del table "$tid" 2>/dev/null || break; done
for _i in 1 2 3; do ip -4 rule del fwmark "$tid" 2>/dev/null || break; done
for _i in 1 2 3; do ip -6 rule del fwmark "$tid" 2>/dev/null || break; done
done done
# Arrêt complet et extinction du réseau Wi-Fi (AP/NAT et pont) # Arrêt complet et extinction du réseau Wi-Fi (AP/NAT et pont)
log "Extinction du réseau Wi-Fi et déconnexion des clients..." log "Extinction du réseau Wi-Fi et déconnexion des clients..."
@@ -442,6 +494,7 @@ cleanup() {
done done
fi fi
ip link set "$IFACE" nomaster 2>/dev/null || true ip link set "$IFACE" nomaster 2>/dev/null || true
ip addr flush dev "$IFACE" 2>/dev/null || true
ip link set "$IFACE" down 2>/dev/null || true ip link set "$IFACE" down 2>/dev/null || true
fi fi
# Suppression du fichier d'uptime lors de l'arrêt du conteneur # Suppression du fichier d'uptime lors de l'arrêt du conteneur
@@ -467,6 +520,13 @@ cleanup() {
fi fi
rm -f /run/ap-created-bridge 2>/dev/null || true rm -f /run/ap-created-bridge 2>/dev/null || true
fi fi
for _ap_br in /sys/class/net/ap-br*; do
if [[ -d "$_ap_br" ]]; then
_bname="$(basename "$_ap_br")"
ip link set dev "$_bname" down 2>/dev/null || true
ip link delete name "$_bname" type bridge 2>/dev/null || true
fi
done
# Nettoyage complet des règles iptables de redirection DNS du mode pont et VPN # Nettoyage complet des règles iptables de redirection DNS du mode pont et VPN
purge_apmanageur_rules purge_apmanageur_rules
# Nettoyage des règles ebtables et nftables VPN # Nettoyage des règles ebtables et nftables VPN
@@ -475,7 +535,7 @@ cleanup() {
for _i in 1 2; do ebtables -t nat -D PREROUTING -j AP_VPN_NAT 2>/dev/null || break; done for _i in 1 2; do ebtables -t nat -D PREROUTING -j AP_VPN_NAT 2>/dev/null || break; done
ebtables -t nat -F AP_VPN_NAT 2>/dev/null || true ebtables -t nat -F AP_VPN_NAT 2>/dev/null || true
ebtables -t nat -X AP_VPN_NAT 2>/dev/null || true ebtables -t nat -X AP_VPN_NAT 2>/dev/null || true
kill "$WEB_PID" "$API_PID" "$NM_PID" 2>/dev/null || true kill -9 "$WEB_PID" "$API_PID" "$NM_PID" 2>/dev/null || true
mountpoint -q /etc/NetworkManager/system-connections && umount /etc/NetworkManager/system-connections 2>/dev/null || true mountpoint -q /etc/NetworkManager/system-connections && umount /etc/NetworkManager/system-connections 2>/dev/null || true
mountpoint -q /var/lib/NetworkManager && umount /var/lib/NetworkManager 2>/dev/null || true mountpoint -q /var/lib/NetworkManager && umount /var/lib/NetworkManager 2>/dev/null || true
exit 0 exit 0