AP manageur V1.1 (Bêta)
This commit is contained in:
1 parent
fa73558569
commit
04c0a0c249
1 file changed
+66
-36
@@ -5101,7 +5101,12 @@ def status(force_refresh=False):
|
|||||||
return res
|
return res
|
||||||
|
|
||||||
def blocked_set():
|
def blocked_set():
|
||||||
c = db(); rows = c.execute('SELECT mac FROM blocked_clients').fetchall(); c.close(); return {r[0] for r in rows}
|
c = db()
|
||||||
|
try:
|
||||||
|
rows = c.execute('SELECT mac FROM blocked_clients').fetchall()
|
||||||
|
return {r[0].upper().strip() for r in rows if r[0]}
|
||||||
|
finally:
|
||||||
|
c.close()
|
||||||
|
|
||||||
station_live_ips = {}
|
station_live_ips = {}
|
||||||
|
|
||||||
@@ -5523,6 +5528,42 @@ def deauth_station(mac):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def _purge_conntrack_for_mac(mac):
|
||||||
|
"""Purger immédiatement les sessions conntrack bloquées et rafraîchir l'ARP pour que l'appareil reprenne aussitôt."""
|
||||||
|
mac = (mac or '').strip().upper()
|
||||||
|
if not mac: return
|
||||||
|
client_ips = set()
|
||||||
|
for m, ip in station_live_ips.items():
|
||||||
|
if m.upper() == mac and ip and ip not in ('Non attribuée', '', '—'):
|
||||||
|
client_ips.add(ip)
|
||||||
|
try:
|
||||||
|
all_m2i = get_all_mac_to_ips()
|
||||||
|
if mac in all_m2i and all_m2i[mac] not in ('Non attribuée', '', '—'):
|
||||||
|
client_ips.add(all_m2i[mac])
|
||||||
|
except Exception: pass
|
||||||
|
try:
|
||||||
|
c_tmp = db()
|
||||||
|
for row in c_tmp.execute("SELECT last_ip FROM client_names WHERE UPPER(mac)=?", (mac,)).fetchall():
|
||||||
|
if row[0] and row[0] not in ('Non attribuée', '', '—'):
|
||||||
|
client_ips.add(row[0])
|
||||||
|
for row in c_tmp.execute("SELECT ip FROM connection_logs WHERE UPPER(mac)=? AND ip NOT IN ('SYSTEM', '127.0.0.1', '::1', 'Non attribuée', '', '—') ORDER BY id DESC LIMIT 5", (mac,)).fetchall():
|
||||||
|
client_ips.add(row[0])
|
||||||
|
c_tmp.close()
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
conntrack_bin = find_bin('conntrack')
|
||||||
|
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')) if is_bridge_mode() else (INTERFACE or 'wlan0')
|
||||||
|
for ip in client_ips:
|
||||||
|
if conntrack_bin:
|
||||||
|
try:
|
||||||
|
subprocess.run([conntrack_bin, '-D', '-s', ip], capture_output=True, timeout=2)
|
||||||
|
subprocess.run([conntrack_bin, '-D', '-d', ip], capture_output=True, timeout=2)
|
||||||
|
except Exception: pass
|
||||||
|
if b_name:
|
||||||
|
try:
|
||||||
|
subprocess.run(['arping', '-c', '1', '-I', b_name, ip], capture_output=True, timeout=1)
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
def set_blocked(mac, blocked):
|
def set_blocked(mac, blocked):
|
||||||
global last_applied_limits_state
|
global last_applied_limits_state
|
||||||
mac = mac.upper().strip()
|
mac = mac.upper().strip()
|
||||||
@@ -5536,41 +5577,38 @@ def set_blocked(mac, blocked):
|
|||||||
c.execute('DELETE FROM blocked_clients WHERE UPPER(mac)=?', (mac,))
|
c.execute('DELETE FROM blocked_clients WHERE UPPER(mac)=?', (mac,))
|
||||||
# Ne pas éjecter la station lors du déblocage pour lui permettre de terminer sa ré-association WPA proprement
|
# Ne pas éjecter la station lors du déblocage pour lui permettre de terminer sa ré-association WPA proprement
|
||||||
reset_station_traffic_baseline(mac)
|
reset_station_traffic_baseline(mac)
|
||||||
if ip and ip not in ('Non attribuée', '', '—'):
|
_purge_conntrack_for_mac(mac)
|
||||||
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()
|
c.commit(); c.close()
|
||||||
|
|
||||||
last_applied_limits_state = None
|
last_applied_limits_state = None
|
||||||
threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start()
|
threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start()
|
||||||
|
threading.Thread(target=sync_vpn_client_rules, kwargs={'force': True}, daemon=True).start()
|
||||||
|
|
||||||
log('blocage' if blocked else 'déblocage', name, ip, mac)
|
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"})
|
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():
|
def blocked_list():
|
||||||
c = db(); rows = c.execute('SELECT b.mac,b.blocked_at,n.name FROM blocked_clients b LEFT JOIN client_names n ON n.mac=b.mac ORDER BY b.blocked_at DESC').fetchall(); c.close()
|
c = db(); rows = c.execute('SELECT b.mac,b.blocked_at,n.name FROM blocked_clients b LEFT JOIN client_names n ON UPPER(n.mac)=UPPER(b.mac) ORDER BY b.blocked_at DESC').fetchall(); c.close()
|
||||||
return [{'mac':r[0],'blocked_at':r[1],'name':r[2] or 'Client ' + r[0].replace(':', '')[-4:]} for r in rows]
|
return [{'mac':r[0].upper(),'blocked_at':r[1],'name':r[2] or 'Client ' + r[0].replace(':', '')[-4:]} for r in rows]
|
||||||
|
|
||||||
quota_alerted_macs = set()
|
quota_alerted_macs = set()
|
||||||
last_sync_limits_time = 0
|
last_sync_limits_time = 0
|
||||||
limits_lock = threading.RLock()
|
limits_lock = threading.RLock()
|
||||||
|
|
||||||
def get_client_traffic_usage(mac, period='total'):
|
def get_client_traffic_usage(mac, period='total'):
|
||||||
mac = (mac or '').upper()
|
mac = (mac or '').upper().strip()
|
||||||
c = db()
|
c = db()
|
||||||
try:
|
try:
|
||||||
if period == 'daily':
|
if period == 'daily':
|
||||||
today_str = time.strftime('%Y-%m-%d')
|
today_str = time.strftime('%Y-%m-%d')
|
||||||
row = c.execute("SELECT rx_bytes + tx_bytes FROM client_traffic_daily WHERE mac=? AND traffic_date=?", (mac, today_str)).fetchone()
|
row = c.execute("SELECT rx_bytes + tx_bytes FROM client_traffic_daily WHERE UPPER(mac)=? AND traffic_date=?", (mac, today_str)).fetchone()
|
||||||
return int(row[0]) if row and row[0] is not None else 0
|
return int(row[0]) if row and row[0] is not None else 0
|
||||||
elif period == 'monthly':
|
elif period == 'monthly':
|
||||||
month_prefix = time.strftime('%Y-%m-') + '%'
|
month_prefix = time.strftime('%Y-%m-') + '%'
|
||||||
row = c.execute("SELECT SUM(rx_bytes + tx_bytes) FROM client_traffic_daily WHERE mac=? AND traffic_date LIKE ?", (mac, month_prefix)).fetchone()
|
row = c.execute("SELECT SUM(rx_bytes + tx_bytes) FROM client_traffic_daily WHERE UPPER(mac)=? AND traffic_date LIKE ?", (mac, month_prefix)).fetchone()
|
||||||
return int(row[0]) if row and row[0] is not None else 0
|
return int(row[0]) if row and row[0] is not None else 0
|
||||||
else:
|
else:
|
||||||
row = c.execute("SELECT rx_bytes + tx_bytes FROM client_traffic WHERE mac=?", (mac,)).fetchone()
|
row = c.execute("SELECT rx_bytes + tx_bytes FROM client_traffic WHERE UPPER(mac)=?", (mac,)).fetchone()
|
||||||
return int(row[0]) if row and row[0] is not None else 0
|
return int(row[0]) if row and row[0] is not None else 0
|
||||||
except Exception:
|
except Exception:
|
||||||
return 0
|
return 0
|
||||||
@@ -5585,7 +5623,7 @@ def get_client_limits_dict(target_mac=None):
|
|||||||
query = "SELECT mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at FROM client_limits"
|
query = "SELECT mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at FROM client_limits"
|
||||||
params = ()
|
params = ()
|
||||||
if target_mac:
|
if target_mac:
|
||||||
query += " WHERE mac=?"
|
query += " WHERE UPPER(mac)=?"
|
||||||
params = (target_mac.upper(),)
|
params = (target_mac.upper(),)
|
||||||
rows = c.execute(query, params).fetchall()
|
rows = c.execute(query, params).fetchall()
|
||||||
res = {}
|
res = {}
|
||||||
@@ -5679,6 +5717,8 @@ def save_client_limits(mac, data):
|
|||||||
# 1. Remise à zéro totale du trafic cumulé et de l'ensemble des historiques journaliers/mensuels
|
# 1. Remise à zéro totale du trafic cumulé et de l'ensemble des historiques journaliers/mensuels
|
||||||
c.execute("UPDATE client_traffic SET rx_bytes=0, tx_bytes=0 WHERE UPPER(mac)=?", (mac,))
|
c.execute("UPDATE client_traffic SET rx_bytes=0, tx_bytes=0 WHERE UPPER(mac)=?", (mac,))
|
||||||
c.execute("UPDATE client_traffic_daily SET rx_bytes=0, tx_bytes=0 WHERE UPPER(mac)=?", (mac,))
|
c.execute("UPDATE client_traffic_daily SET rx_bytes=0, tx_bytes=0 WHERE UPPER(mac)=?", (mac,))
|
||||||
|
# 2. Supprimer tout blocage résiduel pour que l'appareil reprenne aussitôt l'accès
|
||||||
|
c.execute("DELETE FROM blocked_clients WHERE UPPER(mac)=?", (mac,))
|
||||||
quota_alerted_macs.discard(mac)
|
quota_alerted_macs.discard(mac)
|
||||||
reset_station_traffic_baseline(mac)
|
reset_station_traffic_baseline(mac)
|
||||||
|
|
||||||
@@ -5699,27 +5739,16 @@ def save_client_limits(mac, data):
|
|||||||
finally:
|
finally:
|
||||||
c.close()
|
c.close()
|
||||||
|
|
||||||
if reset_usage:
|
usage = get_client_traffic_usage(mac, quota_period)
|
||||||
# Purger immédiatement les sessions conntrack bloquées pour que l'appareil reprenne aussitôt
|
if reset_usage or (quota_enabled and quota_bytes > 0 and usage < quota_bytes):
|
||||||
conntrack_bin = find_bin('conntrack')
|
quota_alerted_macs.discard(mac)
|
||||||
if conntrack_bin:
|
_purge_conntrack_for_mac(mac)
|
||||||
c_ip = station_live_ips.get(mac, '')
|
|
||||||
if not c_ip:
|
|
||||||
try:
|
|
||||||
c_tmp = db()
|
|
||||||
row_ip = c_tmp.execute("SELECT last_ip FROM client_names WHERE UPPER(mac)=?", (mac,)).fetchone()
|
|
||||||
c_tmp.close()
|
|
||||||
if row_ip and row_ip[0] and row_ip[0] not in ('Non attribuée', '', '—'):
|
|
||||||
c_ip = row_ip[0]
|
|
||||||
except Exception: pass
|
|
||||||
if c_ip:
|
|
||||||
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)
|
|
||||||
|
|
||||||
# Ne pas déconnecter le client lors de la remise à zéro ou de la modification pour lui éviter l'erreur WPA 'mot de passe incorrect'
|
# Ne pas déconnecter le client lors de la remise à zéro ou de la modification pour lui éviter l'erreur WPA 'mot de passe incorrect'
|
||||||
global last_applied_limits_state
|
global last_applied_limits_state
|
||||||
last_applied_limits_state = None
|
last_applied_limits_state = None
|
||||||
threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start()
|
threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start()
|
||||||
|
threading.Thread(target=sync_vpn_client_rules, kwargs={'force': True}, daemon=True).start()
|
||||||
return get_client_limits_dict(mac)
|
return get_client_limits_dict(mac)
|
||||||
|
|
||||||
last_applied_limits_state = None
|
last_applied_limits_state = None
|
||||||
@@ -5853,18 +5882,17 @@ def sync_client_bandwidth_and_quotas(force=False):
|
|||||||
nft_cmds.append(f"add rule bridge ap_quota_block forward ether daddr {cm} drop")
|
nft_cmds.append(f"add rule bridge ap_quota_block forward ether daddr {cm} drop")
|
||||||
subprocess.run([nft_bin, '-f', '-'], input="\n".join(nft_cmds), text=True, capture_output=True, timeout=5)
|
subprocess.run([nft_bin, '-f', '-'], input="\n".join(nft_cmds), text=True, capture_output=True, timeout=5)
|
||||||
else:
|
else:
|
||||||
|
subprocess.run([nft_bin, 'flush', 'table', 'bridge', 'ap_quota_block'], capture_output=True, timeout=3)
|
||||||
subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_quota_block'], capture_output=True, timeout=3)
|
subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_quota_block'], capture_output=True, timeout=3)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[ap-limits] Erreur nftables bridge : {e}", flush=True)
|
print(f"[ap-limits] Erreur nftables bridge : {e}", flush=True)
|
||||||
|
|
||||||
# 3. Couche 2 Pont Ethernet (L2 Bridge) : ebtables (uniquement si blocage actif ou module déjà chargé)
|
# 3. Couche 2 Pont Ethernet (L2 Bridge) : ebtables
|
||||||
ebtables_bin = find_bin('ebtables')
|
ebtables_bin = find_bin('ebtables')
|
||||||
if ebtables_bin and (all_blocked_macs or os.path.exists('/sys/module/ebtable_filter')):
|
if ebtables_bin:
|
||||||
try:
|
try:
|
||||||
if not all_blocked_macs:
|
if not all_blocked_macs:
|
||||||
# Si aucun équipement n'est bloqué, nettoyer seulement si la chaîne existe
|
# Si aucun équipement n'est bloqué, nettoyer impérativement ebtables
|
||||||
r_eb = subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-L', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=2)
|
|
||||||
if r_eb.returncode == 0:
|
|
||||||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-D', 'FORWARD', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=2)
|
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-D', 'FORWARD', '-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', '-D', 'INPUT', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=2)
|
||||||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-F', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=2)
|
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-F', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=2)
|
||||||
@@ -5896,13 +5924,13 @@ def sync_client_bandwidth_and_quotas(force=False):
|
|||||||
try:
|
try:
|
||||||
target_chains = [('filter', 'FORWARD'), ('filter', 'INPUT'), ('mangle', 'PREROUTING')]
|
target_chains = [('filter', 'FORWARD'), ('filter', 'INPUT'), ('mangle', 'PREROUTING')]
|
||||||
if not all_blocked_macs:
|
if not all_blocked_macs:
|
||||||
# Si aucun équipement n'est bloqué : ne toucher aux tables que si AP_QUOTA_BLOCK existe
|
# Si aucun équipement n'est bloqué : vider d'abord (-F) pour stopper tout DROP immédiatement !
|
||||||
for tbl in ('filter', 'mangle'):
|
for tbl in ('filter', 'mangle'):
|
||||||
if _ipt_has_chain(bin_cmd, tbl, 'AP_QUOTA_BLOCK'):
|
if _ipt_has_chain(bin_cmd, tbl, 'AP_QUOTA_BLOCK'):
|
||||||
|
subprocess.run([bin_cmd, '-w', '2', '-t', tbl, '-F', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||||||
for t_tbl, chain in target_chains:
|
for t_tbl, chain in target_chains:
|
||||||
if t_tbl == tbl:
|
if t_tbl == tbl:
|
||||||
_ipt_del_jump(bin_cmd, tbl, chain, 'AP_QUOTA_BLOCK')
|
_ipt_del_jump(bin_cmd, tbl, chain, 'AP_QUOTA_BLOCK')
|
||||||
subprocess.run([bin_cmd, '-w', '2', '-t', tbl, '-F', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
|
||||||
subprocess.run([bin_cmd, '-w', '2', '-t', tbl, '-X', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
subprocess.run([bin_cmd, '-w', '2', '-t', tbl, '-X', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||||||
else:
|
else:
|
||||||
for tbl, chain in target_chains:
|
for tbl, chain in target_chains:
|
||||||
@@ -13338,6 +13366,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
global last_applied_limits_state
|
global last_applied_limits_state
|
||||||
last_applied_limits_state = None
|
last_applied_limits_state = None
|
||||||
threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start()
|
threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start()
|
||||||
|
threading.Thread(target=sync_vpn_client_rules, kwargs={'force': True}, daemon=True).start()
|
||||||
|
_purge_conntrack_for_mac(mac)
|
||||||
station_live_ips.pop(mac, None)
|
station_live_ips.pop(mac, None)
|
||||||
station_live_names.pop(mac, None)
|
station_live_names.pop(mac, None)
|
||||||
_device_name_cache.pop(mac, None)
|
_device_name_cache.pop(mac, None)
|
||||||
|
|||||||
Reference in new issue
Block a user