diff --git a/ap.py b/ap.py index 757b56b..96e4735 100644 --- a/ap.py +++ b/ap.py @@ -5294,9 +5294,10 @@ def clients(): for m in re.finditer(r'^Station ([0-9a-f:]{17})(.*?)(?=^Station |\Z)', dump, re.I|re.M|re.S): mac = m.group(1).upper(); detail = m.group(2) # CORRECTION : « iw station dump » liste aussi les appareils qui n'ont jamais fini l'authentification - # (authorized: no, 0 octet échangé). Ce ne sont pas des clients connectés. + # (authorized: no, 4-way handshake en cours). Ne jamais traiter un appareil comme connecté ou l'éjecter + # pendant son handshake WPA sous peine de provoquer l'erreur "mot de passe incorrect" côté client. am = re.search(r'^\s*authorized:\s*(\w+)', detail, re.I|re.M) - if am and am.group(1).lower() != 'yes' and mac not in blocked_macs: continue + if am and am.group(1).lower() != 'yes': continue sig_dbm, sig_estimated, link_rate_mbps = _extract_signal_info(detail, mac) rx_m = re.search(r'^\s*rx bytes:\s*(\d+)', detail, re.I|re.M) tx_m = re.search(r'^\s*tx bytes:\s*(\d+)', detail, re.I|re.M) @@ -5480,14 +5481,55 @@ def known_device(mac): except sqlite3.Error: pass return name or device_name(ip, mac), ip +def deauth_station(mac): + """Déconnecte proprement une station Wi-Fi au niveau 802.11 (hostapd_cli + iw station del). + Permet à hostapd de réinitialiser complètement sa machine d'état WPA et d'éviter l'erreur 'mot de passe incorrect'.""" + mac = (mac or '').upper().strip() + if not mac or not INTERFACE: + return + cm = mac.lower() + try: + if is_hostapd_running(): + hostapd_bin = find_bin('hostapd_cli') + if hostapd_bin: + for ctrl_dir in ['/run/hostapd', '/var/run/hostapd']: + if os.path.exists(ctrl_dir): + subprocess.run([hostapd_bin, '-p', ctrl_dir, '-i', INTERFACE, 'deauthenticate', cm], capture_output=True, timeout=2) + subprocess.run([hostapd_bin, '-p', ctrl_dir, '-i', INTERFACE, 'disassociate', cm], capture_output=True, timeout=2) + break + except Exception: + pass + try: + iw_bin = find_bin('iw') + if iw_bin: + subprocess.run([iw_bin, 'dev', INTERFACE, 'station', 'del', cm], capture_output=True, timeout=2) + except Exception: + pass + def set_blocked(mac, blocked): + global last_applied_limits_state mac = mac.upper() if not re.fullmatch(r'[0-9A-F]{2}(:[0-9A-F]{2}){5}', mac): raise ValueError('Adresse MAC invalide') name, ip = known_device(mac) c = db() - if blocked: c.execute('INSERT OR IGNORE INTO blocked_clients VALUES(?,?)',(mac,time.strftime('%Y-%m-%d %H:%M:%S'))); command('iw','dev',INTERFACE,'station','del',mac) - else: c.execute('DELETE FROM blocked_clients WHERE mac=?',(mac,)) - c.commit(); c.close(); log('blocage' if blocked else 'déblocage', name, ip, mac) + if blocked: + c.execute('INSERT OR IGNORE INTO blocked_clients VALUES(?,?)', (mac, time.strftime('%Y-%m-%d %H:%M:%S'))) + deauth_station(mac) + else: + c.execute('DELETE FROM blocked_clients WHERE UPPER(mac)=?', (mac,)) + deauth_station(mac) + reset_station_traffic_baseline(mac) + if ip and ip not in ('Non attribuée', '', '—'): + conntrack_bin = find_bin('conntrack') + if conntrack_bin: + subprocess.run([conntrack_bin, '-D', '-s', ip], capture_output=True, timeout=2) + subprocess.run([conntrack_bin, '-D', '-d', ip], capture_output=True, timeout=2) + c.commit(); c.close() + + last_applied_limits_state = None + threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start() + + log('blocage' if blocked else 'déblocage', name, ip, mac) dispatch_notification('device_blocked', "🛑 Équipement Wi-Fi bloqué" if blocked else "✅ Équipement Wi-Fi débloqué", f"L'appareil « {name} » a été {'bloqué et éjecté du' if blocked else 'débloqué sur le'} réseau Wi-Fi.", details={"Nom": name, "IP": ip, "MAC": mac, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=5, level="warning" if blocked else "success", vars_dict={"name": name, "ip": ip, "mac": mac, "action": "bloqué et éjecté du" if blocked else "débloqué sur le"}) def blocked_list(): @@ -5656,6 +5698,9 @@ def save_client_limits(mac, data): subprocess.run([conntrack_bin, '-D', '-s', c_ip], capture_output=True, timeout=2) subprocess.run([conntrack_bin, '-D', '-d', c_ip], capture_output=True, timeout=2) + if reset_usage or not quota_enabled: + deauth_station(mac) + global last_applied_limits_state last_applied_limits_state = None threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start() @@ -5771,7 +5816,9 @@ def sync_client_bandwidth_and_quotas(force=False): "flush table bridge ap_quota_block", "add chain bridge ap_quota_block prerouting { type filter hook prerouting priority -350; policy accept; }", "add chain bridge ap_quota_block forward { type filter hook forward priority -350; policy accept; }", - # Exemptions fondamentales : ARP et DHCP (IPv4 + IPv6) + # Exemptions fondamentales : EAPOL (4-way handshake WPA), ARP et DHCP (IPv4 + IPv6) + "add rule bridge ap_quota_block prerouting ether type 0x888e accept", + "add rule bridge ap_quota_block forward ether type 0x888e accept", "add rule bridge ap_quota_block prerouting ether type arp accept", "add rule bridge ap_quota_block forward ether type arp accept", "add rule bridge ap_quota_block prerouting ether type ip udp sport 67-68 udp dport 67-68 accept", @@ -5813,6 +5860,7 @@ def sync_client_bandwidth_and_quotas(force=False): subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-I', 'FORWARD', '1', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=2) subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-D', 'INPUT', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=2) subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-I', 'INPUT', '1', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=2) + subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-p', '0x888e', '-j', 'ACCEPT'], capture_output=True, timeout=2) subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-p', 'ARP', '-j', 'ACCEPT'], capture_output=True, timeout=2) subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-dport', '67:68', '-j', 'ACCEPT'], capture_output=True, timeout=2) subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-p', 'IPv4', '--ip-proto', 'udp', '--ip-sport', '67:68', '-j', 'ACCEPT'], capture_output=True, timeout=2) @@ -9547,7 +9595,7 @@ def import_backup_data(payload, options=None): if mac: c.execute('INSERT OR IGNORE INTO blocked_clients (mac, blocked_at) VALUES (?, ?)', (mac, b_at)) stats['blocked_clients'] += 1 - try: command('iw', 'dev', INTERFACE, 'station', 'del', mac) + try: deauth_station(mac) except Exception: pass # 4. Préférences et réglages @@ -13257,6 +13305,10 @@ class Handler(BaseHTTPRequestHandler): c.execute('DELETE FROM blocked_clients WHERE UPPER(mac)=?', (mac,)) c.execute('DELETE FROM connection_logs WHERE UPPER(mac)=?', (mac,)) c.commit(); c.close() + deauth_station(mac) + global last_applied_limits_state + last_applied_limits_state = None + threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start() station_live_ips.pop(mac, None) station_live_names.pop(mac, None) _device_name_cache.pop(mac, None) @@ -13702,9 +13754,9 @@ def monitor(): items = clients() max_c = get_max_clients() - # CORRECTION : éjecter en continu les appareils bloqués qui se reconnectent. + # CORRECTION : éjecter proprement les appareils bloqués qui se reconnectent (une fois autorisés) for x in items: - if x['blocked']: command('iw','dev',INTERFACE,'station','del',x['mac']) + if x['blocked']: deauth_station(x['mac']) active_items = [x for x in items if not x['blocked']] if max_c > 0 and len(active_items) > max_c: @@ -13718,7 +13770,7 @@ def monitor(): for x in active_items: if x['mac'] not in allowed_macs: mac = x['mac'] - command('iw','dev',INTERFACE,'station','del',mac) + deauth_station(mac) log('rejet_limite', x['name'], x['ip'], mac) if mac in connected_stations_order: connected_stations_order.remove(mac)