APmanageur Wi-Fi V1.0

This commit is contained in:
yoannmultigaming committed 2026-11-18 03:32:39 +01:00
1 parent eb6659dad2
commit f291ef2df8
1 file changed
+134 -56
+134 -56
View File
@@ -6712,33 +6712,25 @@ def get_all_mac_to_ips():
return mac_to_ip return mac_to_ip
_last_broute_log_sig = None
def setup_nftables_broute(assigned_macs, local_subnets=None): def setup_nftables_broute(assigned_macs, local_subnets=None):
"""Active le brouting matériel via nftables (Linux 6.4+, Debian 13) pour détourner les trames du pont L2 vers la couche L3.""" """Active le brouting L2 (mode Pont uniquement) via nftables (meta broute) avec repli automatique sur ebtables si le noyau n'inclut pas nft_meta_bridge."""
global _last_broute_log_sig
nft_bin = find_bin('nft') nft_bin = find_bin('nft')
if not assigned_macs: if not assigned_macs or not is_bridge_mode():
# Aucun client assigné à un VPN : supprimer la table pour ne jamais interférer avec le pont hôte # Aucun client assigné à un VPN ou mode AP (pas de pont) : supprimer les tables broute pour ne jamais interférer avec l'hôte
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)
return for eb in [b for b in (find_bin('ebtables'), find_bin('ebtables-legacy')) if b]:
if os.path.exists('/sys/module/ebtable_broute') or eb.endswith('ebtables'):
subprocess.run([eb, '-t', 'broute', '-F', 'BROUTING'], capture_output=True)
_last_broute_log_sig = None
return True
for mod in ['br_netfilter', 'nf_tables', 'nft_compat']: for mod in ['nf_tables', 'nft_meta_bridge', 'nft_compat']:
subprocess.run(['modprobe', mod], capture_output=True) subprocess.run(['modprobe', mod], capture_output=True)
if not nft_bin:
return
subprocess.run([nft_bin, 'add', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
subprocess.run([nft_bin, 'flush', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
subprocess.run([nft_bin, 'add', 'chain', 'bridge', 'ap_vpn_broute', 'prerouting', '{ type filter hook prerouting priority -300; policy accept; }'], capture_output=True)
# 1. Exemptions ABSOLUES du brouting :
# DHCP (ports 67/68 UDP) et Broadcast (ff:ff:ff:ff:ff:ff et 255.255.255.255).
# Ces paquets DOIVENT être bridgés en L2 pour que les clients reçoivent leur IP locale de la box !
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'daddr', 'ff:ff:ff:ff:ff:ff', 'accept'], capture_output=True)
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'udp', 'dport', '67-68', 'accept'], capture_output=True)
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'udp', 'sport', '67-68', 'accept'], capture_output=True)
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'ip', 'daddr', '255.255.255.255', 'accept'], capture_output=True)
# Obtenir la liste des MACs bloquées (quota dépassé ou blocage manuel) pour ne JAMAIS les router # Obtenir la liste des MACs bloquées (quota dépassé ou blocage manuel) pour ne JAMAIS les router
blocked_macs = set() blocked_macs = set()
try: try:
@@ -6749,31 +6741,128 @@ def setup_nftables_broute(assigned_macs, local_subnets=None):
blocked_macs.add(m.upper()) blocked_macs.add(m.upper())
except Exception: pass except Exception: pass
for mac in assigned_macs: b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) or 'br0'
clean_mac = mac.strip().lower() br_mac = ''
if not clean_mac: continue try:
br_mac_path = f'/sys/class/net/{b_name}/address'
if os.path.exists(br_mac_path):
br_mac = open(br_mac_path).read().strip().lower()
except OSError:
pass
if mac.strip().upper() in blocked_macs: nft_ok = False
# Client bloqué : DROP absolu, pas de broute VPN ! nft_mode = ''
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', if nft_bin:
'ether', 'saddr', clean_mac, 'drop'], capture_output=True) subprocess.run([nft_bin, 'add', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
subprocess.run([nft_bin, 'flush', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
r_ch = subprocess.run([nft_bin, 'add', 'chain', 'bridge', 'ap_vpn_broute', 'prerouting', '{ type filter hook prerouting priority -300; policy accept; }'], capture_output=True, text=True)
if r_ch.returncode == 0:
# 1. Exemptions ABSOLUES du brouting :
# DHCP (ports 67/68 UDP) et Broadcast (ff:ff:ff:ff:ff:ff et 255.255.255.255).
# Ces paquets DOIVENT être bridgés en L2 pour que les clients reçoivent leur IP locale de la box !
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'daddr', 'ff:ff:ff:ff:ff:ff', 'accept'], capture_output=True)
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'udp', 'dport', '67-68', 'accept'], capture_output=True)
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'udp', 'sport', '67-68', 'accept'], capture_output=True)
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'ip', 'daddr', '255.255.255.255', 'accept'], capture_output=True)
nft_ok = True
for mac in assigned_macs:
clean_mac = mac.strip().lower()
if not clean_mac: continue
if mac.strip().upper() in blocked_macs:
# Client bloqué : DROP absolu, pas de broute VPN !
subprocess.run([nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting',
'ether', 'saddr', clean_mac, 'drop'], capture_output=True)
continue
# Essai 1 : meta broute set 1 + meta pkttype set host
cmd_v4_a = [nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting',
'ether', 'saddr', clean_mac, 'ether', 'type', 'ip',
'meta', 'broute', 'set', '1', 'meta', 'pkttype', 'set', 'host', 'accept']
res = subprocess.run(cmd_v4_a, capture_output=True, text=True)
if res.returncode == 0:
nft_mode = 'nftables (meta broute + pkttype host)'
else:
# Essai 2 : réécriture ether daddr vers MAC du pont + meta broute set 1 (noyaux où meta pkttype set host n'est pas supporté en bridge)
res2 = None
if br_mac:
cmd_v4_b = [nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting',
'ether', 'saddr', clean_mac, 'ether', 'type', 'ip',
'ether', 'daddr', 'set', br_mac, 'meta', 'broute', 'set', '1', 'accept']
res2 = subprocess.run(cmd_v4_b, capture_output=True, text=True)
if res2 is not None and res2.returncode == 0:
nft_mode = f'nftables (ether daddr {br_mac} + meta broute)'
else:
nft_ok = False
break
# Bloquer les fuites IPv6 pour forcer la bascule complète en IPv4 via le VPN
cmd_v6 = [nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting',
'ether', 'saddr', clean_mac, 'ether', 'type', 'ip6', 'drop']
subprocess.run(cmd_v6, capture_output=True)
if not nft_ok:
# Noyau sans support nft_meta_bridge : supprimer la table ap_vpn_broute et basculer proprement sur ebtables
subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
if nft_ok:
# Nettoyer ebtables pour éviter les doublons si nftables fonctionne
for eb in [b for b in (find_bin('ebtables'), find_bin('ebtables-legacy')) if b]:
if os.path.exists('/sys/module/ebtable_broute') or eb.endswith('ebtables'):
subprocess.run([eb, '-t', 'broute', '-F', 'BROUTING'], capture_output=True)
sig = ('nft', nft_mode, tuple(sorted(m.strip().lower() for m in assigned_macs if m.strip())), tuple(sorted(blocked_macs)))
if sig != _last_broute_log_sig:
_last_broute_log_sig = sig
print(f"[ap-vpn] [NFTABLES] Broute actif via {nft_mode} pour {len(assigned_macs)} client(s).", flush=True)
return True
# Repli natif ebtables (-t broute -j redirect --redirect-target DROP) : fonctionne sur Raspberry Pi OS même sans CONFIG_NFT_BRIDGE_META
for mod in ['ebtable_broute', 'ebt_redirect']:
subprocess.run(['modprobe', mod], capture_output=True)
eb_candidates = []
for name in ('ebtables', 'ebtables-legacy'):
b = find_bin(name)
if b and b not in eb_candidates:
eb_candidates.append(b)
for eb in eb_candidates:
r_fl = subprocess.run([eb, '-t', 'broute', '-F', 'BROUTING'], capture_output=True, text=True)
if r_fl.returncode != 0:
continue continue
subprocess.run([eb, '-t', 'broute', '-A', 'BROUTING', '-d', 'Broadcast', '-j', 'ACCEPT'], capture_output=True)
# meta broute set 1 : détourne la trame du pont Ethernet directement dans la pile IP locale (L3) subprocess.run([eb, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-dport', '67:68', '-j', 'ACCEPT'], capture_output=True)
# meta pkttype set host : force le noyau (ip_forward) à accepter le paquet au lieu de le jeter comme PACKET_OTHERHOST subprocess.run([eb, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-sport', '67:68', '-j', 'ACCEPT'], capture_output=True)
cmd_v4 = [nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', subprocess.run([eb, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '--ip-dst', '255.255.255.255', '-j', 'ACCEPT'], capture_output=True)
'ether', 'saddr', clean_mac, 'ether', 'type', 'ip', eb_ok = True
'meta', 'broute', 'set', '1', 'meta', 'pkttype', 'set', 'host', 'accept'] eb_err = ''
res = subprocess.run(cmd_v4, capture_output=True, text=True) for mac in assigned_macs:
if res.returncode != 0: clean_mac = mac.strip().lower()
print(f"[ap-vpn] Erreur nftables broute {clean_mac} : {res.stderr.strip()}", flush=True) if not clean_mac: continue
if mac.strip().upper() in blocked_macs:
subprocess.run([eb, '-t', 'broute', '-A', 'BROUTING', '-s', clean_mac, '-j', 'DROP'], capture_output=True)
continue
r_v4 = subprocess.run([eb, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '-s', clean_mac, '-j', 'redirect', '--redirect-target', 'DROP'], capture_output=True, text=True)
if r_v4.returncode != 0:
eb_ok = False
eb_err = (r_v4.stderr or '').strip()
break
subprocess.run([eb, '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv6', '-s', clean_mac, '-j', 'DROP'], capture_output=True)
if eb_ok:
sig = ('ebtables', os.path.basename(eb), tuple(sorted(m.strip().lower() for m in assigned_macs if m.strip())), tuple(sorted(blocked_macs)))
if sig != _last_broute_log_sig:
_last_broute_log_sig = sig
print(f"[ap-vpn] [EBTABLES] Broute actif ({os.path.basename(eb)} redirect->host) pour {len(assigned_macs)} client(s).", flush=True)
return True
else: else:
print(f"[ap-vpn] [NFTABLES] Broute actif pour {clean_mac} (meta broute set 1, pkttype host)", flush=True) subprocess.run([eb, '-t', 'broute', '-F', 'BROUTING'], capture_output=True)
sig = ('err', os.path.basename(eb), eb_err)
# Bloquer les fuites IPv6 pour forcer la bascule complète du smartphone en IPv4 via WireGuard if sig != _last_broute_log_sig:
cmd_v6 = [nft_bin, 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', _last_broute_log_sig = sig
'ether', 'saddr', clean_mac, 'ether', 'type', 'ip6', 'drop'] print(f"[ap-vpn] Avertissement broute ({os.path.basename(eb)}) : {eb_err}", flush=True)
subprocess.run(cmd_v6, capture_output=True) return False
def sync_vpn_client_rules(): def sync_vpn_client_rules():
with vpn_lock: with vpn_lock:
@@ -6824,8 +6913,8 @@ def sync_vpn_client_rules():
# Exemptions indispensables : broadcast et DHCP (maintien du bail IP) # Exemptions indispensables : broadcast et DHCP (maintien du bail IP)
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-d', '255.255.255.255', '-j', 'RETURN'], capture_output=True) subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-d', '255.255.255.255', '-j', 'RETURN'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-p', 'udp', '--dport', '67:68', '-j', 'RETURN'], capture_output=True) subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-p', 'udp', '--dport', '67:68', '-j', 'RETURN'], capture_output=True)
subprocess.run(['iptables', '-t', 'mangle', '-p', 'udp', '--sport', '67:68', '-j', 'RETURN'], capture_output=True) subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-p', 'udp', '--sport', '67:68', '-j', 'RETURN'], capture_output=True)
# 3. Réinitialisation de la chaîne NAT DNS pour rediriger les requêtes DNS des clients VPN vers un DNS public (Cloudflare 1.1.1.1) # 3. Réinitialisation de la chaîne NAT DNS pour rediriger les requêtes DNS des clients VPN vers un DNS public (Cloudflare 1.1.1.1)
# afin d'éviter les fuites DNS locales (box) et de garantir la résolution sans toucher au LAN. # afin d'éviter les fuites DNS locales (box) et de garantir la résolution sans toucher au LAN.
@@ -6865,21 +6954,10 @@ def sync_vpn_client_rules():
dns_target = dns_list[0] dns_target = dns_list[0]
except Exception: pass except Exception: pass
# 6. Application du brouting natif nftables pour tous les clients assignés (sans exemption LAN) # 6. Application du brouting L2 (uniquement en mode Pont) : nftables avec repli automatique sur ebtables
assigned_macs = [mac for mac, rinfo in client_routes.items() if rinfo.get('profile_id', 0) > 0] assigned_macs = [mac for mac, rinfo in client_routes.items() if rinfo.get('profile_id', 0) > 0]
setup_nftables_broute(assigned_macs) setup_nftables_broute(assigned_macs)
# 7. Fallback legacy ebtables avec redirect vers host (sans exemption LAN)
subprocess.run(['ebtables', '-t', 'broute', '-F', 'BROUTING'], capture_output=True)
if assigned_macs:
subprocess.run(['ebtables', '-t', 'broute', '-A', 'BROUTING', '-d', 'Broadcast', '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['ebtables', '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-dport', '67:68', '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['ebtables', '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-sport', '67:68', '-j', 'ACCEPT'], capture_output=True)
subprocess.run(['ebtables', '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '--ip-dst', '255.255.255.255', '-j', 'ACCEPT'], capture_output=True)
for mac in assigned_macs:
subprocess.run(['ebtables', '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv4', '-s', mac, '-j', 'redirect', '--redirect-target', 'DROP'], capture_output=True)
subprocess.run(['ebtables', '-t', 'broute', '-A', 'BROUTING', '-p', 'IPv6', '-s', mac, '-j', 'DROP'], capture_output=True)
prio_base = 10000 prio_base = 10000
active_tables = set() active_tables = set()
lan_ifaces = list(dict.fromkeys(['br0', 'eth0', 'eth1', 'enp0s3', 'enp1s0'] + ([INTERFACE] if INTERFACE else []))) lan_ifaces = list(dict.fromkeys(['br0', 'eth0', 'eth1', 'enp0s3', 'enp1s0'] + ([INTERFACE] if INTERFACE else [])))