8286 lines
418 KiB
Python
8286 lines
418 KiB
Python
#!/usr/bin/env python3
|
||
import base64, hashlib, hmac, json, os, re, secrets, socket, sqlite3, subprocess, threading, time, urllib.parse, urllib.request, urllib.error, socketserver, shutil, datetime, atexit, signal, struct, smtplib, ssl, ipaddress, queue, http.client, io, zipfile, tempfile
|
||
from email.mime.text import MIMEText
|
||
from email.mime.multipart import MIMEMultipart
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
|
||
for p in ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin']:
|
||
if p not in os.environ.get('PATH', '').split(':'):
|
||
os.environ['PATH'] = p + ':' + os.environ.get('PATH', '')
|
||
|
||
INTERFACE = os.environ.get('AP_INTERFACE', 'wls16b1')
|
||
SOCKET_PATH = os.environ.get('AP_SOCKET', '/run/ap-api.sock')
|
||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||
DB_FILE = os.environ.get('AP_DB_FILE', os.path.join(BASE_DIR, 'ap-dashboard.sqlite3'))
|
||
CONNECTION_FILE = os.environ.get('AP_CONNECTION_FILE', os.path.join(BASE_DIR, 'ap-dashboard-connection'))
|
||
UPTIME_FILE = os.environ.get('AP_UPTIME_FILE', os.path.join(BASE_DIR, 'ap-dashboard-uptime'))
|
||
|
||
def remove_uptime_file():
|
||
try:
|
||
if os.path.exists(UPTIME_FILE):
|
||
os.remove(UPTIME_FILE)
|
||
except OSError: pass
|
||
|
||
atexit.register(remove_uptime_file)
|
||
|
||
def _sig_handler(signum, frame):
|
||
remove_uptime_file()
|
||
os._exit(0)
|
||
|
||
try:
|
||
signal.signal(signal.SIGTERM, _sig_handler)
|
||
signal.signal(signal.SIGINT, _sig_handler)
|
||
except Exception: pass
|
||
|
||
# Auto-migration de l'ancienne DB si présente
|
||
OLD_DB_FILE = '/var/lib/ap-dashboard.sqlite3'
|
||
if not os.path.exists(DB_FILE) and os.path.exists(OLD_DB_FILE):
|
||
try:
|
||
import shutil
|
||
shutil.copy2(OLD_DB_FILE, DB_FILE)
|
||
except Exception: pass
|
||
|
||
# Radio : 2,4 GHz canal 6 par défaut (le plus compatible en mode point d'accès). Modifiable via docker-compose.
|
||
AP_BAND = os.environ.get('AP_BAND', 'bg') if os.environ.get('AP_BAND', 'bg') in ('bg', 'a') else 'bg'
|
||
try: AP_CHANNEL = int(os.environ.get('AP_CHANNEL', '6'))
|
||
except ValueError: AP_CHANNEL = 6
|
||
|
||
APP_VERSION = 'V5.5'
|
||
SERVER_BOOT_TIME = time.time()
|
||
app_startup_done = False
|
||
SESSION_TTL = 30 * 86400 # 30 jours (1 mois)
|
||
sessions = {}
|
||
last_macs = set()
|
||
|
||
def uptime_start():
|
||
try: return float(open(UPTIME_FILE, encoding='utf8').read().strip())
|
||
except (OSError, ValueError): return None
|
||
|
||
def mark_ap_started():
|
||
try:
|
||
folder = os.path.dirname(UPTIME_FILE)
|
||
if folder: os.makedirs(folder, exist_ok=True)
|
||
open(UPTIME_FILE, 'w', encoding='utf8').write(str(time.time()))
|
||
except OSError: pass
|
||
|
||
def ap_uptime():
|
||
started = uptime_start()
|
||
return max(0, int(time.time() - started)) if started else 0
|
||
|
||
def lease_entries():
|
||
"""Baux dnsmasq (mac, ip, hostname) de TOUS les fichiers existants.
|
||
En mode pont, dnsmasq est inactif : les baux résiduels 10.42.x.x sont ignorés."""
|
||
try:
|
||
if is_bridge_mode(): return []
|
||
except Exception: pass
|
||
import glob
|
||
files = ['/var/lib/misc/dnsmasq.leases', '/var/lib/NetworkManager/dnsmasq.leases']
|
||
files += sorted(glob.glob('/var/lib/NetworkManager/dnsmasq-*.leases'))
|
||
entries = []
|
||
for path in files:
|
||
try:
|
||
with open(path, encoding='utf8') as f:
|
||
for line in f:
|
||
fields = line.split()
|
||
if len(fields) >= 4: entries.append((fields[1].upper(), fields[2], fields[3]))
|
||
except (OSError, UnicodeError): continue
|
||
return entries
|
||
|
||
_device_name_cache = {} # mac -> (name, timestamp)
|
||
_journal_dhcp_cache = {'time': 0, 'entries': {}}
|
||
|
||
def get_journal_dhcp_entries():
|
||
now = time.time()
|
||
if now - _journal_dhcp_cache['time'] < 15:
|
||
return _journal_dhcp_cache['entries']
|
||
entries = {}
|
||
try:
|
||
journal = command('journalctl', '-u', 'NetworkManager', '--no-pager', '-n', '200', timeout=1)
|
||
pattern = r'DHCPACK\([^)]*\)\s+(\S+)\s+([0-9a-f:]{17})\s+(\S+)'
|
||
for line in reversed(journal.splitlines()):
|
||
m = re.search(pattern, line, re.I)
|
||
if m:
|
||
j_mac = m.group(2).upper()
|
||
j_host = m.group(3).strip()
|
||
if j_host and j_host != '*' and j_mac not in entries:
|
||
entries[j_mac] = j_host
|
||
except Exception:
|
||
pass
|
||
_journal_dhcp_cache['time'] = now
|
||
_journal_dhcp_cache['entries'] = entries
|
||
return entries
|
||
|
||
def device_name(ip, mac):
|
||
mac = (mac or '').upper()
|
||
now = time.time()
|
||
if mac and mac in _device_name_cache:
|
||
c_name, c_time = _device_name_cache[mac]
|
||
if now - c_time < 30:
|
||
return c_name
|
||
|
||
# 1. Base de données client_names (nom personnalisé ou précédemment appris)
|
||
if mac:
|
||
try:
|
||
c = db(); row = c.execute('SELECT name FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
|
||
if row and row[0] and not row[0].startswith('Client ') and row[0] != 'Nom non communiqué':
|
||
_device_name_cache[mac] = (row[0], now)
|
||
return row[0]
|
||
except sqlite3.Error: pass
|
||
|
||
# 2. Baux DHCP dnsmasq
|
||
try: is_bridge = is_bridge_mode()
|
||
except Exception: is_bridge = False
|
||
if not is_bridge:
|
||
for l_mac, l_ip, l_host in reversed(lease_entries()):
|
||
if l_mac == mac or (ip and l_ip == ip):
|
||
if l_host and l_host != '*':
|
||
name = l_host.strip()
|
||
_device_name_cache[mac] = (name, now)
|
||
return name
|
||
# 3. Journal DHCP NetworkManager (avec cache et timeout 1s)
|
||
dhcp_entries = get_journal_dhcp_entries()
|
||
if mac in dhcp_entries:
|
||
name = dhcp_entries[mac]
|
||
_device_name_cache[mac] = (name, now)
|
||
return name
|
||
|
||
# 4. Table des voisins ARP (ip neigh)
|
||
if ip and ip not in ('Non attribuée', '—') and not (is_bridge and ip.startswith('10.42.')):
|
||
host_line = command('ip', 'neigh', 'show', ip, timeout=1)
|
||
match = re.search(r'\(([^)]+)\)', host_line)
|
||
if match and match.group(1) != ip:
|
||
name = match.group(1)
|
||
_device_name_cache[mac] = (name, now)
|
||
return name
|
||
|
||
# 5. Nom en base même si générique
|
||
if mac:
|
||
try:
|
||
c = db(); row = c.execute('SELECT name FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
|
||
if row and row[0]:
|
||
_device_name_cache[mac] = (row[0], now)
|
||
return row[0]
|
||
except sqlite3.Error: pass
|
||
|
||
fallback = 'Client ' + mac.replace(':', '')[-4:] if mac else 'Nom non communiqué'
|
||
if mac:
|
||
_device_name_cache[mac] = (fallback, now)
|
||
return fallback
|
||
|
||
# __AUTHENTICATION_IMPLEMENTATION__
|
||
_db_initialized = False
|
||
_db_init_lock = threading.Lock()
|
||
|
||
def init_db():
|
||
global _db_initialized
|
||
with _db_init_lock:
|
||
if _db_initialized:
|
||
return
|
||
folder = os.path.dirname(DB_FILE)
|
||
if folder: os.makedirs(folder, exist_ok=True)
|
||
c = sqlite3.connect(DB_FILE, timeout=30.0)
|
||
try:
|
||
c.execute('PRAGMA journal_mode = WAL')
|
||
c.execute('PRAGMA synchronous = NORMAL')
|
||
c.execute('PRAGMA busy_timeout = 30000')
|
||
c.execute('CREATE TABLE IF NOT EXISTS auth_users (username TEXT PRIMARY KEY, password_hash TEXT NOT NULL)')
|
||
columns = {row[1] for row in c.execute('PRAGMA table_info(auth_users)').fetchall()}
|
||
if 'totp_secret' not in columns:
|
||
c.execute('ALTER TABLE auth_users ADD COLUMN totp_secret TEXT DEFAULT NULL')
|
||
c.commit()
|
||
recovery_table(c)
|
||
c.execute('CREATE TABLE IF NOT EXISTS connection_logs(id INTEGER PRIMARY KEY,event_time TEXT,event TEXT,name TEXT,ip TEXT,mac TEXT)')
|
||
c.execute('CREATE TABLE IF NOT EXISTS blocked_clients(mac TEXT PRIMARY KEY,blocked_at TEXT)')
|
||
c.execute('CREATE TABLE IF NOT EXISTS client_names(mac TEXT PRIMARY KEY,name TEXT NOT NULL,last_ip TEXT,last_seen TEXT,device_type TEXT DEFAULT "")')
|
||
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
|
||
if 'device_type' not in cn_cols:
|
||
try:
|
||
c.execute('ALTER TABLE client_names ADD COLUMN device_type TEXT DEFAULT ""')
|
||
c.commit()
|
||
except Exception: pass
|
||
c.execute('CREATE TABLE IF NOT EXISTS client_traffic(mac TEXT PRIMARY KEY, rx_bytes INTEGER DEFAULT 0, tx_bytes INTEGER DEFAULT 0, last_updated TEXT)')
|
||
c.execute('CREATE TABLE IF NOT EXISTS client_traffic_daily(mac TEXT, traffic_date TEXT, rx_bytes INTEGER DEFAULT 0, tx_bytes INTEGER DEFAULT 0, PRIMARY KEY(mac, traffic_date))')
|
||
c.execute('CREATE INDEX IF NOT EXISTS idx_client_traffic_daily_date ON client_traffic_daily(traffic_date)')
|
||
try:
|
||
cnt_daily = c.execute("SELECT COUNT(*) FROM client_traffic_daily").fetchone()[0]
|
||
if cnt_daily == 0:
|
||
today_str = time.strftime('%Y-%m-%d')
|
||
c.execute('''
|
||
INSERT OR IGNORE INTO client_traffic_daily(mac, traffic_date, rx_bytes, tx_bytes)
|
||
SELECT mac, COALESCE(SUBSTR(last_updated, 1, 10), ?), rx_bytes, tx_bytes
|
||
FROM client_traffic
|
||
WHERE rx_bytes > 0 OR tx_bytes > 0
|
||
''', (today_str,))
|
||
c.commit()
|
||
except Exception: pass
|
||
c.execute('CREATE TABLE IF NOT EXISTS preferences(key TEXT PRIMARY KEY, value TEXT NOT NULL)')
|
||
c.execute('CREATE TABLE IF NOT EXISTS geoip_cache (ip TEXT PRIMARY KEY, code TEXT, country TEXT, flag TEXT, created_at REAL)')
|
||
c.execute('CREATE TABLE IF NOT EXISTS vpn_profiles (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, type TEXT NOT NULL, config_content TEXT NOT NULL, auth_user TEXT DEFAULT "", auth_pass TEXT DEFAULT "", table_id INTEGER DEFAULT 101, iface TEXT DEFAULT "", auto_connect INTEGER DEFAULT 0, status TEXT DEFAULT "disconnected", last_error TEXT DEFAULT "", created_at TEXT DEFAULT "", updated_at TEXT DEFAULT "")')
|
||
c.execute('CREATE TABLE IF NOT EXISTS client_vpn_routes (mac TEXT PRIMARY KEY, profile_id INTEGER DEFAULT 0, kill_switch INTEGER DEFAULT 0, updated_at TEXT DEFAULT "")')
|
||
c.execute('CREATE TABLE IF NOT EXISTS auth_sessions(token TEXT PRIMARY KEY, username TEXT, expires REAL, ip TEXT DEFAULT "", ua TEXT DEFAULT "", device_name TEXT DEFAULT "", os_name TEXT DEFAULT "", created_at TEXT DEFAULT "", last_seen TEXT DEFAULT "")')
|
||
session_cols = {row[1] for row in c.execute('PRAGMA table_info(auth_sessions)').fetchall()}
|
||
for col in ('ip', 'ua', 'device_name', 'os_name', 'browser_name', 'created_at', 'last_seen'):
|
||
if col not in session_cols:
|
||
try: c.execute(f'ALTER TABLE auth_sessions ADD COLUMN {col} TEXT DEFAULT ""')
|
||
except Exception: pass
|
||
c.execute('CREATE TABLE IF NOT EXISTS auth_passkeys(id TEXT PRIMARY KEY, username TEXT NOT NULL, public_key TEXT NOT NULL, name TEXT NOT NULL, device_type TEXT DEFAULT "security_key", sign_count INTEGER DEFAULT 0, created_at TEXT DEFAULT "", last_used_at TEXT DEFAULT "")')
|
||
c.execute('''
|
||
CREATE TABLE IF NOT EXISTS client_limits (
|
||
mac TEXT PRIMARY KEY,
|
||
quota_enabled INTEGER DEFAULT 0,
|
||
quota_bytes INTEGER DEFAULT 0,
|
||
quota_period TEXT DEFAULT 'total',
|
||
bandwidth_enabled INTEGER DEFAULT 0,
|
||
rate_down_kbps INTEGER DEFAULT 0,
|
||
rate_up_kbps INTEGER DEFAULT 0,
|
||
quota_action TEXT DEFAULT 'block',
|
||
updated_at TEXT DEFAULT ''
|
||
)
|
||
''')
|
||
init_device_types_table(c)
|
||
c.commit()
|
||
_db_initialized = True
|
||
finally:
|
||
c.close()
|
||
|
||
def db():
|
||
if not _db_initialized:
|
||
init_db()
|
||
c = sqlite3.connect(DB_FILE, timeout=30.0)
|
||
c.execute('PRAGMA busy_timeout = 30000')
|
||
return c
|
||
|
||
def init_device_types_table(c):
|
||
c.execute('''
|
||
CREATE TABLE IF NOT EXISTS custom_device_types(
|
||
id TEXT PRIMARY KEY,
|
||
label TEXT NOT NULL,
|
||
icon TEXT NOT NULL,
|
||
desc TEXT DEFAULT "",
|
||
sort_order INTEGER DEFAULT 0
|
||
)
|
||
''')
|
||
try:
|
||
count = c.execute('SELECT COUNT(*) FROM custom_device_types').fetchone()[0]
|
||
if count == 0:
|
||
defaults = [
|
||
('phone', 'Smartphone', '📱', 'iPhone, Android, Galaxy...', 1),
|
||
('tablet', 'Tablette', 'tablet_svg', 'iPad, Galaxy Tab, Kindle...', 2),
|
||
('laptop', 'PC Portable', '💻', 'MacBook, ThinkPad, Laptop...', 3),
|
||
('desktop', 'Ordinateur fixe', '🖥️', 'PC Bureau, Mac Pro, Tour...', 4),
|
||
('tv', 'Smart TV / Box', '📺', 'Apple TV, Chromecast, Box...', 5),
|
||
('console', 'Console de jeux', '🎮', 'PlayStation, Switch, Xbox...', 6),
|
||
('iot', 'Objet connecté', '📟', 'IoT, Caméra, Domotique, RPi...', 7),
|
||
('generic', 'Standard / Autre', '💻', 'Appareil générique / inconnu', 8)
|
||
]
|
||
c.executemany('INSERT INTO custom_device_types(id, label, icon, desc, sort_order) VALUES(?,?,?,?,?)', defaults)
|
||
c.commit()
|
||
except Exception as e:
|
||
print(f"[ap-error] Erreur init_device_types_table: {e}", flush=True)
|
||
|
||
|
||
def password_hash(value, salt=None):
|
||
salt = salt or secrets.token_bytes(16)
|
||
digest = hashlib.pbkdf2_hmac('sha256', value.encode(), salt, 240000)
|
||
return salt.hex() + ':' + digest.hex()
|
||
|
||
def password_ok(value, stored):
|
||
try:
|
||
salt, digest = stored.split(':', 1)
|
||
actual = hashlib.pbkdf2_hmac('sha256', value.encode(), bytes.fromhex(salt), 240000).hex()
|
||
return hmac.compare_digest(actual, digest)
|
||
except (ValueError, TypeError): return False
|
||
|
||
def totp_code(secret, counter=None):
|
||
counter = int(time.time() // 30) if counter is None else counter
|
||
key = base64.b32decode(secret + '=' * (-len(secret) % 8), casefold=True)
|
||
raw = hmac.new(key, counter.to_bytes(8, 'big'), hashlib.sha1).digest()
|
||
offset = raw[-1] & 15
|
||
number = int.from_bytes(raw[offset:offset + 4], 'big') & 0x7fffffff
|
||
return f'{number % 1000000:06d}'
|
||
|
||
def totp_ok(secret, code):
|
||
code = str(code or '').strip()
|
||
if not re.fullmatch(r'\d{6}', code): return False
|
||
counter = int(time.time() // 30)
|
||
return any(hmac.compare_digest(totp_code(secret, counter + drift), code) for drift in (-1, 0, 1))
|
||
|
||
def auth_state():
|
||
c = db(); row = c.execute('SELECT username,totp_secret FROM auth_users LIMIT 1').fetchone()
|
||
has_pk = bool(c.execute('SELECT 1 FROM auth_passkeys LIMIT 1').fetchone())
|
||
rows = dict(c.execute("SELECT key,value FROM preferences").fetchall()); c.close()
|
||
conn = connection_name() if callable(globals().get('connection_name')) else ''
|
||
eth_list = detect_ethernet_interfaces() if callable(globals().get('detect_ethernet_interfaces')) else []
|
||
admin_ok = bool(row)
|
||
wifi_ok = bool(conn)
|
||
return {
|
||
'configured': admin_ok,
|
||
'admin_configured': admin_ok,
|
||
'wifi_configured': wifi_ok,
|
||
'setup_completed': admin_ok and wifi_ok,
|
||
'two_factor': bool(row and row[1]),
|
||
'has_passkeys': has_pk,
|
||
'ethernet_interfaces': eth_list,
|
||
'app_name': rows.get('app_name', 'Administration de l’AP Wi‑Fi'),
|
||
'app_short_name': rows.get('app_short_name', 'AP Manageur'),
|
||
'language': rows.get('language', 'fr'),
|
||
'is_starting': not app_startup_done,
|
||
'boot_time': SERVER_BOOT_TIME,
|
||
'username': row[0] if row else 'admin'
|
||
}
|
||
|
||
RECOVERY_COUNT = 8
|
||
|
||
def recovery_table(c):
|
||
c.execute('CREATE TABLE IF NOT EXISTS recovery_codes(code_hash TEXT PRIMARY KEY, used INTEGER NOT NULL DEFAULT 0)')
|
||
|
||
def recovery_hash(code):
|
||
return hashlib.sha256(re.sub(r'[^A-Z0-9]', '', str(code or '').upper()).encode()).hexdigest()
|
||
|
||
def recovery_generate():
|
||
alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
|
||
codes = []
|
||
for _ in range(RECOVERY_COUNT):
|
||
raw = ''.join(secrets.choice(alphabet) for _ in range(10))
|
||
codes.append(raw[:5] + '-' + raw[5:])
|
||
c = db(); recovery_table(c); c.execute('DELETE FROM recovery_codes')
|
||
c.executemany('INSERT INTO recovery_codes(code_hash) VALUES(?)', [(recovery_hash(x),) for x in codes]); c.commit(); c.close()
|
||
return codes
|
||
|
||
def recovery_use(code):
|
||
cleaned = re.sub(r'[^A-Za-z0-9]', '', str(code or ''))
|
||
if len(cleaned) != 10: return False
|
||
c = db(); recovery_table(c)
|
||
cur = c.execute('UPDATE recovery_codes SET used=1 WHERE code_hash=? AND used=0', (recovery_hash(cleaned),))
|
||
c.commit(); ok = cur.rowcount == 1; c.close(); return ok
|
||
|
||
def recovery_remaining():
|
||
c = db(); recovery_table(c); n = c.execute('SELECT COUNT(*) FROM recovery_codes WHERE used=0').fetchone()[0]; c.close(); return n
|
||
|
||
def recovery_clear():
|
||
c = db(); recovery_table(c); c.execute('DELETE FROM recovery_codes'); c.commit(); c.close()
|
||
|
||
def second_factor_ok(secret, code):
|
||
return totp_ok(secret, code) or recovery_use(code)
|
||
|
||
|
||
# ==============================================================================
|
||
# WEBAUTHN / PASSKEYS HELPER FUNCTIONS
|
||
# ==============================================================================
|
||
passkey_pending_challenges = {}
|
||
|
||
P256_P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
|
||
P256_A = P256_P - 3
|
||
P256_B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
|
||
P256_GX = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
|
||
P256_GY = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5
|
||
P256_N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
|
||
|
||
def _ec_inv(k, m): return pow(k, m - 2, m)
|
||
def _ec_point_add(p1, p2):
|
||
if p1 is None: return p2
|
||
if p2 is None: return p1
|
||
x1, y1 = p1; x2, y2 = p2
|
||
if x1 == x2:
|
||
if (y1 + y2) % P256_P == 0: return None
|
||
l = (3 * x1 * x1 + P256_A) * _ec_inv(2 * y1, P256_P) % P256_P
|
||
else:
|
||
l = (y2 - y1) * _ec_inv(x2 - x1, P256_P) % P256_P
|
||
x3 = (l * l - x1 - x2) % P256_P
|
||
y3 = (l * (x1 - x3) - y1) % P256_P
|
||
return x3, y3
|
||
|
||
def _ec_point_mul(k, p):
|
||
res = None; cur = p
|
||
while k > 0:
|
||
if k & 1: res = _ec_point_add(res, cur)
|
||
cur = _ec_point_add(cur, cur)
|
||
k >>= 1
|
||
return res
|
||
|
||
def b64url_decode(s):
|
||
if isinstance(s, bytes): s = s.decode('ascii')
|
||
s = str(s).replace('-', '+').replace('_', '/')
|
||
while len(s) % 4: s += '='
|
||
return base64.b64decode(s)
|
||
|
||
def b64url_encode(b):
|
||
if isinstance(b, str): b = b.encode('utf-8')
|
||
return base64.b64encode(b).decode('ascii').replace('+', '-').replace('/', '_').rstrip('=')
|
||
|
||
def decode_cbor(data, offset=0):
|
||
if offset >= len(data): raise ValueError('Fin de données CBOR inattendue')
|
||
b = data[offset]; major = b >> 5; info = b & 0x1f; offset += 1
|
||
if info < 24: val = info
|
||
elif info == 24: val = data[offset]; offset += 1
|
||
elif info == 25: val = int.from_bytes(data[offset:offset+2], 'big'); offset += 2
|
||
elif info == 26: val = int.from_bytes(data[offset:offset+4], 'big'); offset += 4
|
||
elif info == 27: val = int.from_bytes(data[offset:offset+8], 'big'); offset += 8
|
||
else: raise ValueError(f'Info CBOR non supportée : {info}')
|
||
if major == 0: return val, offset
|
||
elif major == 1: return -1 - val, offset
|
||
elif major == 2: return data[offset:offset+val], offset+val
|
||
elif major == 3: return data[offset:offset+val].decode('utf-8', errors='replace'), offset+val
|
||
elif major == 4:
|
||
arr = []
|
||
for _ in range(val): item, offset = decode_cbor(data, offset); arr.append(item)
|
||
return arr, offset
|
||
elif major == 5:
|
||
m = {}
|
||
for _ in range(val):
|
||
k, offset = decode_cbor(data, offset); v, offset = decode_cbor(data, offset); m[k] = v
|
||
return m, offset
|
||
elif major == 7:
|
||
if info == 20: return False, offset
|
||
if info == 21: return True, offset
|
||
if info == 22: return None, offset
|
||
return val, offset
|
||
else: raise ValueError(f'Type majeur CBOR non supporté : {major}')
|
||
|
||
def parse_der_signature(sig_bytes):
|
||
if not sig_bytes or sig_bytes[0] != 0x30:
|
||
raise ValueError('Signature DER invalide')
|
||
idx = 2
|
||
if sig_bytes[1] & 0x80:
|
||
idx += (sig_bytes[1] & 0x7f)
|
||
if sig_bytes[idx] != 0x02:
|
||
raise ValueError('Entier r invalide dans la signature DER')
|
||
r_len = sig_bytes[idx+1]
|
||
r = int.from_bytes(sig_bytes[idx+2 : idx+2+r_len], 'big')
|
||
idx = idx + 2 + r_len
|
||
if sig_bytes[idx] != 0x02:
|
||
raise ValueError('Entier s invalide dans la signature DER')
|
||
s_len = sig_bytes[idx+1]
|
||
s = int.from_bytes(sig_bytes[idx+2 : idx+2+s_len], 'big')
|
||
return r, s
|
||
|
||
def verify_es256_signature(pub_x_bytes, pub_y_bytes, sig_bytes, signed_data):
|
||
try:
|
||
from cryptography.hazmat.primitives.asymmetric import ec
|
||
from cryptography.hazmat.primitives import hashes
|
||
pub_num = ec.EllipticCurvePublicNumbers(
|
||
int.from_bytes(pub_x_bytes, 'big'),
|
||
int.from_bytes(pub_y_bytes, 'big'),
|
||
ec.SECP256R1()
|
||
)
|
||
pub_num.public_key().verify(sig_bytes, signed_data, ec.ECDSA(hashes.SHA256()))
|
||
return True
|
||
except Exception:
|
||
pass
|
||
try:
|
||
r, s = parse_der_signature(sig_bytes)
|
||
if not (1 <= r < P256_N and 1 <= s < P256_N):
|
||
return False
|
||
z = int.from_bytes(hashlib.sha256(signed_data).digest(), 'big')
|
||
w = _ec_inv(s, P256_N)
|
||
u1 = (z * w) % P256_N
|
||
u2 = (r * w) % P256_N
|
||
pub_pt = (int.from_bytes(pub_x_bytes, 'big'), int.from_bytes(pub_y_bytes, 'big'))
|
||
pt = _ec_point_add(_ec_point_mul(u1, (P256_GX, P256_GY)), _ec_point_mul(u2, pub_pt))
|
||
return pt is not None and (pt[0] % P256_N) == (r % P256_N)
|
||
except Exception:
|
||
return False
|
||
|
||
def verify_rs256_signature(n_bytes, e_bytes, sig_bytes, signed_data):
|
||
try:
|
||
from cryptography.hazmat.primitives.asymmetric import rsa, padding
|
||
from cryptography.hazmat.primitives import hashes
|
||
pub_num = rsa.RSAPublicNumbers(int.from_bytes(e_bytes, 'big'), int.from_bytes(n_bytes, 'big'))
|
||
pub_num.public_key().verify(sig_bytes, signed_data, padding.PKCS1v15(), hashes.SHA256())
|
||
return True
|
||
except Exception:
|
||
pass
|
||
try:
|
||
sig_int = int.from_bytes(sig_bytes, 'big')
|
||
e_int = int.from_bytes(e_bytes, 'big')
|
||
n_int = int.from_bytes(n_bytes, 'big')
|
||
m = pow(sig_int, e_int, n_int)
|
||
em = m.to_bytes((n_int.bit_length() + 7) // 8, 'big')
|
||
sha = hashlib.sha256(signed_data).digest()
|
||
oid = bytes.fromhex('3031300d060960864801650304020105000420')
|
||
return em.endswith(oid + sha)
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def create_user(username, password, secret=None):
|
||
if not re.fullmatch(r'[A-Za-z0-9_.-]{3,32}', username or ''): raise ValueError('Nom utilisateur invalide')
|
||
if not 8 <= len(password) <= 128: raise ValueError('Le mot de passe doit contenir entre 8 et 128 caractères')
|
||
c = db(); c.execute('DELETE FROM auth_users'); c.execute('INSERT INTO auth_users VALUES(?,?,?)', (username, password_hash(password), secret)); c.commit(); c.close()
|
||
|
||
def verify_user(username, password):
|
||
c = db(); row = c.execute('SELECT username,password_hash,totp_secret FROM auth_users WHERE username=?', (username.strip(),)).fetchone(); c.close()
|
||
return row if row and password_ok(password, row[1]) else None
|
||
|
||
def parse_os(user_agent):
|
||
if not user_agent: return 'Inconnu'
|
||
ua = user_agent.lower()
|
||
if 'windows nt 10.0' in ua or 'windows nt 11.0' in ua: return 'Windows 10/11'
|
||
elif 'windows nt 6.3' in ua: return 'Windows 8.1'
|
||
elif 'windows nt 6.2' in ua: return 'Windows 8'
|
||
elif 'windows nt 6.1' in ua: return 'Windows 7'
|
||
elif 'windows' in ua: return 'Windows'
|
||
elif 'iphone' in ua:
|
||
m = re.search(r'cpu iphone os ([0-9_]+)', ua)
|
||
return 'iOS ' + m.group(1).replace('_', '.') if m else 'iOS'
|
||
elif 'ipad' in ua: return 'iPadOS'
|
||
elif 'macintosh' in ua or 'mac os x' in ua:
|
||
m = re.search(r'mac os x ([0-9_]+)', ua)
|
||
return 'macOS ' + m.group(1).replace('_', '.') if m else 'macOS'
|
||
elif 'android' in ua:
|
||
m = re.search(r'android ([0-9.]+)', ua)
|
||
return 'Android ' + m.group(1) if m else 'Android'
|
||
elif 'cros' in ua: return 'ChromeOS'
|
||
elif 'linux' in ua: return 'Linux'
|
||
return 'Autre'
|
||
|
||
def parse_browser(user_agent):
|
||
if not user_agent: return 'Inconnu'
|
||
ua = user_agent.lower()
|
||
if 'edg/' in ua or 'edge/' in ua:
|
||
m = re.search(r'edg[e]?/([0-9.]+)', ua)
|
||
return 'Microsoft Edge' + (' ' + m.group(1).split('.')[0] if m else '')
|
||
elif 'opr/' in ua or 'opera/' in ua:
|
||
m = re.search(r'(?:opr|opera)/([0-9.]+)', ua)
|
||
return 'Opera' + (' ' + m.group(1).split('.')[0] if m else '')
|
||
elif 'samsungbrowser/' in ua:
|
||
m = re.search(r'samsungbrowser/([0-9.]+)', ua)
|
||
return 'Samsung Internet' + (' ' + m.group(1).split('.')[0] if m else '')
|
||
elif 'firefox/' in ua or 'fxios/' in ua:
|
||
m = re.search(r'(?:firefox|fxios)/([0-9.]+)', ua)
|
||
return 'Firefox' + (' ' + m.group(1).split('.')[0] if m else '')
|
||
elif 'chrome/' in ua or 'crios/' in ua:
|
||
m = re.search(r'(?:chrome|crios)/([0-9.]+)', ua)
|
||
return 'Chrome' + (' ' + m.group(1).split('.')[0] if m else '')
|
||
elif 'safari/' in ua and 'version/' in ua:
|
||
m = re.search(r'version/([0-9.]+)', ua)
|
||
return 'Safari' + (' ' + m.group(1).split('.')[0] if m else '')
|
||
return 'Navigateur Web'
|
||
|
||
def resolve_device_name(ip):
|
||
if not ip or ip in ('127.0.0.1', '::1', 'localhost', 'Non attribuée', '—'):
|
||
return 'Serveur local'
|
||
try:
|
||
c = db()
|
||
row = c.execute('SELECT name FROM client_names WHERE last_ip=?', (ip,)).fetchone()
|
||
c.close()
|
||
if row and row[0]: return row[0]
|
||
except Exception: pass
|
||
for lease_file in ['/var/lib/misc/dnsmasq.leases', '/tmp/dnsmasq.leases']:
|
||
try:
|
||
if os.path.exists(lease_file):
|
||
with open(lease_file, 'r', encoding='utf-8', errors='ignore') as f:
|
||
for line in f:
|
||
parts = line.strip().split()
|
||
if len(parts) >= 4 and parts[2] == ip and parts[3] != '*':
|
||
return parts[3]
|
||
except Exception: pass
|
||
try:
|
||
name = socket.gethostbyaddr(ip)[0]
|
||
if name and name != ip: return name.split('.')[0]
|
||
except Exception: pass
|
||
try:
|
||
host_line = command('ip', 'neigh', 'show', ip)
|
||
m = re.search(r'\(([^)]+)\)', host_line)
|
||
if m and m.group(1) != ip: return m.group(1)
|
||
except Exception: pass
|
||
return f"Machine ({ip})"
|
||
|
||
def new_session(username, ip='', ua='', custom_name=''):
|
||
token = secrets.token_urlsafe(32)
|
||
now = time.time()
|
||
expires = now + SESSION_TTL
|
||
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
os_name = parse_os(ua)
|
||
browser_name = parse_browser(ua)
|
||
dev_name = (custom_name or '').strip() or resolve_device_name(ip)
|
||
sess_data = {
|
||
'username': username,
|
||
'expires': expires,
|
||
'ip': ip,
|
||
'ua': ua,
|
||
'device_name': dev_name,
|
||
'os_name': os_name,
|
||
'browser_name': browser_name,
|
||
'created_at': now_str,
|
||
'last_seen': now_str,
|
||
'_last_updated': now
|
||
}
|
||
sessions[token] = sess_data
|
||
try:
|
||
c = db()
|
||
c.execute('''
|
||
INSERT OR REPLACE INTO auth_sessions
|
||
(token, username, expires, ip, ua, device_name, os_name, browser_name, created_at, last_seen)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||
''', (token, username, expires, ip, ua, dev_name, os_name, browser_name, now_str, now_str))
|
||
c.commit(); c.close()
|
||
except Exception as e:
|
||
print(f"[ap-error] Erreur enregistrement session SQLite: {e}", flush=True)
|
||
return token
|
||
|
||
def delete_session(token):
|
||
if not token: return
|
||
sessions.pop(token, None)
|
||
try:
|
||
c = db()
|
||
c.execute('DELETE FROM auth_sessions WHERE token=?', (token,))
|
||
c.commit(); c.close()
|
||
except Exception: pass
|
||
|
||
def get_session(token):
|
||
if not token: return None
|
||
now = time.time()
|
||
s = sessions.get(token)
|
||
if isinstance(s, dict):
|
||
if s.get('expires', 0) > now:
|
||
return s
|
||
else:
|
||
delete_session(token)
|
||
return None
|
||
try:
|
||
c = db()
|
||
row = c.execute('''
|
||
SELECT username, expires, ip, ua, device_name, os_name, browser_name, created_at, last_seen
|
||
FROM auth_sessions WHERE token=?
|
||
''', (token,)).fetchone()
|
||
c.close()
|
||
if row:
|
||
if row[1] > now:
|
||
s = {
|
||
'username': row[0],
|
||
'expires': row[1],
|
||
'ip': row[2] or '',
|
||
'ua': row[3] or '',
|
||
'device_name': row[4] or '',
|
||
'os_name': row[5] or '',
|
||
'browser_name': row[6] or '',
|
||
'created_at': row[7] or '',
|
||
'last_seen': row[8] or '',
|
||
'_last_updated': now
|
||
}
|
||
sessions[token] = s
|
||
return s
|
||
else:
|
||
delete_session(token)
|
||
except Exception: pass
|
||
return None
|
||
|
||
def update_session_activity(token, ip, ua, custom_name=''):
|
||
if not token: return
|
||
now = time.time()
|
||
s = sessions.get(token)
|
||
if isinstance(s, dict):
|
||
last_t = s.get('_last_updated', 0)
|
||
need_info = not s.get('ip') or not s.get('os_name') or not s.get('browser_name') or (custom_name and s.get('device_name') != custom_name)
|
||
if (now - last_t >= 30) or need_info:
|
||
s['_last_updated'] = now
|
||
s['last_seen'] = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
if custom_name:
|
||
s['device_name'] = custom_name
|
||
elif ip and not s.get('ip'):
|
||
s['ip'] = ip
|
||
s['device_name'] = resolve_device_name(ip)
|
||
elif not s.get('device_name') and s.get('ip'):
|
||
s['device_name'] = resolve_device_name(s['ip'])
|
||
if ua and not s.get('ua'):
|
||
s['ua'] = ua
|
||
s['os_name'] = parse_os(ua)
|
||
s['browser_name'] = parse_browser(ua)
|
||
elif not s.get('browser_name') and s.get('ua'):
|
||
s['browser_name'] = parse_browser(s['ua'])
|
||
try:
|
||
c = db()
|
||
c.execute('''
|
||
UPDATE auth_sessions
|
||
SET last_seen=?,
|
||
ip=CASE WHEN (ip IS NULL OR ip='') THEN ? ELSE ip END,
|
||
ua=CASE WHEN (ua IS NULL OR ua='') THEN ? ELSE ua END,
|
||
device_name=CASE WHEN ? != '' THEN ? ELSE (CASE WHEN (device_name IS NULL OR device_name='') THEN ? ELSE device_name END) END,
|
||
os_name=CASE WHEN (os_name IS NULL OR os_name='') THEN ? ELSE os_name END,
|
||
browser_name=CASE WHEN (browser_name IS NULL OR browser_name='') THEN ? ELSE browser_name END
|
||
WHERE token=?
|
||
''', (s['last_seen'], ip or '', ua or '', custom_name, custom_name, s.get('device_name',''), s.get('os_name',''), s.get('browser_name',''), token))
|
||
c.commit(); c.close()
|
||
except Exception: pass
|
||
|
||
def list_sessions(current_token='', lang='fr'):
|
||
now = time.time()
|
||
is_en = str(lang or '').lower().startswith('en')
|
||
unknown_machine = 'Unknown machine' if is_en else 'Machine inconnue'
|
||
unknown_os = 'Unknown' if is_en else 'Inconnu'
|
||
default_browser = 'Web Browser' if is_en else 'Navigateur Web'
|
||
try:
|
||
c = db()
|
||
c.execute('DELETE FROM auth_sessions WHERE expires < ?', (now,))
|
||
c.commit()
|
||
rows = c.execute('''
|
||
SELECT token, username, expires, ip, ua, device_name, os_name, browser_name, created_at, last_seen
|
||
FROM auth_sessions
|
||
ORDER BY last_seen DESC, created_at DESC
|
||
''').fetchall()
|
||
c.close()
|
||
except Exception as e:
|
||
print(f"[ap-error] Erreur récupération auth_sessions: {e}", flush=True)
|
||
rows = []
|
||
|
||
res = []
|
||
for r in rows:
|
||
token, uname, expires, ip, ua, dev_name, os_name, browser_name, created_at, last_seen = r
|
||
if not os_name or os_name == 'Autre':
|
||
os_name = parse_os(ua)
|
||
if not browser_name or browser_name == 'Navigateur Web':
|
||
browser_name = parse_browser(ua)
|
||
if not dev_name or dev_name.startswith('Machine ('):
|
||
resolved = resolve_device_name(ip)
|
||
if resolved: dev_name = resolved
|
||
is_current = bool(current_token and token == current_token)
|
||
res.append({
|
||
'token': token,
|
||
'is_current': is_current,
|
||
'username': uname or 'admin',
|
||
'ip': ip or '127.0.0.1',
|
||
'device_name': dev_name or unknown_machine,
|
||
'os_name': os_name or unknown_os,
|
||
'browser_name': browser_name or default_browser,
|
||
'created_at': created_at or '—',
|
||
'last_seen': last_seen or created_at or '—'
|
||
})
|
||
return res
|
||
|
||
def extract_token(h):
|
||
token = h.headers.get('X-Session-Token', '') if hasattr(h, 'headers') else ''
|
||
if not token and hasattr(h, 'headers') and 'Cookie' in h.headers:
|
||
for part in h.headers.get('Cookie', '').split(';'):
|
||
part = part.strip()
|
||
if part.startswith('apAuthToken='):
|
||
token = urllib.parse.unquote(part.split('=', 1)[1])
|
||
break
|
||
if not token and hasattr(h, 'path') and 'token=' in h.path:
|
||
try:
|
||
parsed = urllib.parse.urlparse(h.path)
|
||
token = urllib.parse.parse_qs(parsed.query).get('token', [''])[0]
|
||
except Exception: pass
|
||
return token
|
||
|
||
def valid_session(h):
|
||
token = extract_token(h)
|
||
s = get_session(token)
|
||
if s is not None:
|
||
try:
|
||
custom_name = urllib.parse.unquote(h.headers.get('X-Device-Name', '')) if hasattr(h, 'headers') else ''
|
||
update_session_activity(token, request_ip(h), h.headers.get('User-Agent', ''), custom_name)
|
||
except Exception: pass
|
||
return True
|
||
return False
|
||
|
||
def username(h):
|
||
token = extract_token(h)
|
||
s = get_session(token)
|
||
return s.get('username', '') if s else ''
|
||
|
||
def command(*args, timeout=5):
|
||
try: return subprocess.check_output(args, text=True, stderr=subprocess.DEVNULL, timeout=timeout).strip()
|
||
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError): return ''
|
||
|
||
def read_json(h):
|
||
return json.loads(h.rfile.read(int(h.headers.get('Content-Length', '0'))) or b'{}')
|
||
|
||
def clean_ip_str(ip_str):
|
||
if not ip_str: return ''
|
||
s = ip_str.strip()
|
||
if s.startswith('[') and ']' in s:
|
||
s = s[1:s.index(']')]
|
||
elif ':' in s and s.count(':') == 1:
|
||
s = s.split(':')[0]
|
||
return s.strip()
|
||
|
||
def is_ip_trusted_proxy(ip_str, trusted_list_str, trust_all_private=True):
|
||
ip_clean = clean_ip_str(ip_str)
|
||
if not ip_clean: return False
|
||
try:
|
||
ip = ipaddress.ip_address(ip_clean)
|
||
except ValueError:
|
||
return False
|
||
if trust_all_private and (ip.is_private or ip.is_loopback or ip.is_link_local):
|
||
return True
|
||
for item in (trusted_list_str or '').split(','):
|
||
item = item.strip()
|
||
if not item: continue
|
||
if item == '*': return True
|
||
try:
|
||
if '/' in item:
|
||
if ip in ipaddress.ip_network(item, strict=False): return True
|
||
else:
|
||
item_clean = clean_ip_str(item)
|
||
if ip == ipaddress.ip_address(item_clean): return True
|
||
except ValueError:
|
||
pass
|
||
return False
|
||
|
||
def get_reverse_proxy_config():
|
||
try:
|
||
c = db()
|
||
rows = dict(c.execute("SELECT key, value FROM preferences WHERE key LIKE 'reverse_proxy_%'").fetchall())
|
||
c.close()
|
||
except Exception:
|
||
rows = {}
|
||
return {
|
||
'enabled': rows.get('reverse_proxy_enabled', '1') == '1',
|
||
'header': rows.get('reverse_proxy_header', 'auto').lower(),
|
||
'trusted_proxies': rows.get('reverse_proxy_trusted_proxies', '127.0.0.1, ::1, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16'),
|
||
'trust_all_private': rows.get('reverse_proxy_trust_all_private', '1') == '1'
|
||
}
|
||
|
||
def request_ip(h):
|
||
socket_ip = h.client_address[0] if hasattr(h, 'client_address') and h.client_address else '127.0.0.1'
|
||
raw_direct = clean_ip_str(h.headers.get('X-Client-Raw-IP', '').strip()) or socket_ip
|
||
cfg = get_reverse_proxy_config()
|
||
if not cfg['enabled']:
|
||
return raw_direct
|
||
if not is_ip_trusted_proxy(raw_direct, cfg['trusted_proxies'], cfg['trust_all_private']):
|
||
return raw_direct
|
||
hdr_pref = cfg['header']
|
||
def get_list(hdr):
|
||
val = h.headers.get(hdr, '').strip()
|
||
if not val: return []
|
||
return [p.strip() for p in val.split(',') if p.strip()]
|
||
if hdr_pref == 'cf-connecting-ip':
|
||
candidates = get_list('CF-Connecting-IP')
|
||
elif hdr_pref == 'true-client-ip':
|
||
candidates = get_list('True-Client-IP')
|
||
elif hdr_pref == 'x-real-ip':
|
||
candidates = get_list('X-Real-IP')
|
||
elif hdr_pref == 'x-forwarded-for':
|
||
candidates = get_list('X-Forwarded-For')
|
||
else:
|
||
candidates = (get_list('CF-Connecting-IP') or
|
||
get_list('True-Client-IP') or
|
||
get_list('X-Forwarded-For') or
|
||
get_list('X-Real-IP'))
|
||
for cand in candidates:
|
||
cand_clean = clean_ip_str(cand)
|
||
try:
|
||
val_ip = ipaddress.ip_address(cand_clean)
|
||
return str(val_ip)
|
||
except ValueError:
|
||
continue
|
||
return raw_direct
|
||
|
||
def log(event, name='Nom non communiqué', ip='Non attribuée', mac='—'):
|
||
ts = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
print(f"[ap-event] [{ts}] {event} | client='{name}' ({mac}) | ip={ip}", flush=True)
|
||
try:
|
||
c = db(); c.execute('INSERT INTO connection_logs(event_time,event,name,ip,mac) VALUES(?,?,?,?,?)', (ts, event, name, ip, mac)); c.commit(); c.close()
|
||
except sqlite3.Error as e:
|
||
print(f"[ap-error] Erreur base SQLite: {e}", flush=True)
|
||
|
||
def logs():
|
||
c = db()
|
||
rows = c.execute('SELECT event_time,event,name,ip,mac FROM connection_logs ORDER BY id DESC LIMIT 200').fetchall()
|
||
vpn_routes = dict(c.execute('SELECT mac, profile_id FROM client_vpn_routes WHERE profile_id > 0').fetchall())
|
||
vpn_profiles = {r[0]: {'name': r[1], 'status': r[2], 'iface': r[3]} for r in c.execute('SELECT id, name, status, iface FROM vpn_profiles').fetchall()}
|
||
c.close()
|
||
result = []
|
||
for r in rows:
|
||
mac = (r[4] or '').upper()
|
||
pid = vpn_routes.get(mac, 0)
|
||
prof = vpn_profiles.get(pid) if pid > 0 else None
|
||
vname = prof['name'] if prof else ''
|
||
vrouted = bool(prof and prof['status'] == 'connected' and is_iface_up(prof['iface']))
|
||
result.append({
|
||
'time': r[0],
|
||
'event': r[1],
|
||
'name': r[2],
|
||
'ip': r[3],
|
||
'mac': r[4],
|
||
'vpn_profile_name': vname,
|
||
'vpn_routed': vrouted
|
||
})
|
||
return result
|
||
|
||
MONTHS_FR = ['', 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre']
|
||
MONTHS_SHORT_FR = ['', 'Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sep', 'Oct', 'Nov', 'Déc']
|
||
DAYS_FR = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
|
||
DAYS_SHORT_FR = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim']
|
||
|
||
MONTHS_EN = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
|
||
MONTHS_SHORT_EN = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
||
DAYS_EN = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
|
||
DAYS_SHORT_EN = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
|
||
|
||
station_traffic = {}
|
||
traffic_lock = threading.Lock()
|
||
|
||
def format_speed(bps):
|
||
if not bps or bps <= 0: return "0 o/s"
|
||
if bps < 1024: return f"{int(bps)} o/s"
|
||
if bps < 1048576: return f"{bps/1024:.1f} Ko/s"
|
||
if bps < 1073741824: return f"{bps/1048576:.2f} Mo/s"
|
||
if bps < 1099511627776: return f"{bps/1073741824:.2f} Go/s"
|
||
return f"{bps/1099511627776:.2f} To/s"
|
||
|
||
def format_bytes(b):
|
||
if not b or b <= 0: return "0 o"
|
||
if b < 1024: return f"{int(b)} o"
|
||
if b < 1048576: return f"{b/1024:.1f} Ko"
|
||
if b < 1073741824: return f"{b/1048576:.2f} Mo"
|
||
if b < 1099511627776: return f"{b/1073741824:.2f} Go"
|
||
return f"{b/1099511627776:.2f} To"
|
||
|
||
def get_top_clients(active_items=None, range_type='day'):
|
||
active_map = {}
|
||
if active_items is not None:
|
||
active_map = {x['mac']: x for x in active_items}
|
||
else:
|
||
try: active_map = {x['mac']: x for x in clients()}
|
||
except Exception: pass
|
||
|
||
now = datetime.datetime.now()
|
||
today_str = now.strftime('%Y-%m-%d')
|
||
|
||
if range_type == 'day':
|
||
start_date = today_str
|
||
end_date = today_str
|
||
elif range_type == 'week':
|
||
mon = now.date() - datetime.timedelta(days=now.weekday())
|
||
sun = mon + datetime.timedelta(days=6)
|
||
start_date = mon.strftime('%Y-%m-%d')
|
||
end_date = sun.strftime('%Y-%m-%d')
|
||
elif range_type == 'month':
|
||
start_date = now.strftime('%Y-%m-01')
|
||
end_date = now.strftime('%Y-%m-31')
|
||
elif range_type == 'year':
|
||
start_date = now.strftime('%Y-01-01')
|
||
end_date = now.strftime('%Y-12-31')
|
||
else:
|
||
start_date = '1970-01-01'
|
||
end_date = '2099-12-31'
|
||
|
||
try:
|
||
c = db()
|
||
rows = c.execute('''
|
||
SELECT
|
||
m.mac AS mac,
|
||
COALESCE(NULLIF(n.name, ''), 'Client ' || REPLACE(SUBSTR(m.mac, -5), ':', '')) AS display_name,
|
||
COALESCE(n.last_ip, 'Non attribuée') AS last_ip,
|
||
COALESCE(n.last_seen, '—') AS last_seen,
|
||
COALESCE(t.sum_tx, 0) AS download_bytes,
|
||
COALESCE(t.sum_rx, 0) AS upload_bytes,
|
||
(COALESCE(t.sum_tx, 0) + COALESCE(t.sum_rx, 0)) AS total_bytes
|
||
FROM (
|
||
SELECT mac FROM client_traffic_daily WHERE traffic_date >= ? AND traffic_date <= ?
|
||
UNION
|
||
SELECT mac FROM client_names
|
||
) m
|
||
LEFT JOIN (
|
||
SELECT mac, SUM(tx_bytes) as sum_tx, SUM(rx_bytes) as sum_rx
|
||
FROM client_traffic_daily
|
||
WHERE traffic_date >= ? AND traffic_date <= ?
|
||
GROUP BY mac
|
||
) t ON t.mac = m.mac
|
||
LEFT JOIN client_names n ON n.mac = m.mac
|
||
ORDER BY total_bytes DESC
|
||
LIMIT 50
|
||
''', (start_date, end_date, start_date, end_date)).fetchall()
|
||
c.close()
|
||
except Exception as e:
|
||
print(f"[ap-error] Erreur récupération top_clients ({range_type}): {e}", flush=True)
|
||
rows = []
|
||
|
||
res = []
|
||
for mac, name, ip, last_seen, dl_b, ul_b, tot_b in rows:
|
||
is_online = mac in active_map
|
||
live_client = active_map.get(mac, {})
|
||
res.append({
|
||
'mac': mac,
|
||
'name': name,
|
||
'ip': live_client.get('ip', ip),
|
||
'last_seen': last_seen,
|
||
'download_bytes': dl_b,
|
||
'upload_bytes': ul_b,
|
||
'total_bytes': tot_b,
|
||
'download_str': format_bytes(dl_b),
|
||
'upload_str': format_bytes(ul_b),
|
||
'total_str': format_bytes(tot_b),
|
||
'connected': is_online,
|
||
'download_speed_str': live_client.get('download_speed_str', '—') if is_online else '—',
|
||
'upload_speed_str': live_client.get('upload_speed_str', '—') if is_online else '—'
|
||
})
|
||
return res
|
||
|
||
_cached_stats = None
|
||
_cached_topology = None
|
||
_metrics_lock = threading.Lock()
|
||
_metrics_count = 0
|
||
_metrics_last_duration_ms = 0
|
||
_metrics_last_time = 0
|
||
|
||
def compute_stats_internal(active_items=None):
|
||
now = datetime.datetime.now()
|
||
today_str = now.strftime('%Y-%m-%d')
|
||
cur_year = now.strftime('%Y')
|
||
cur_month = now.strftime('%Y-%m')
|
||
|
||
cur_monday = now.date() - datetime.timedelta(days=now.weekday())
|
||
cur_week_start = cur_monday.strftime('%Y-%m-%d 00:00:00')
|
||
|
||
# 0. Heures de la journée (Aujourd'hui : 00h à 23h)
|
||
hours = []
|
||
hours_map = {}
|
||
hour_macs = {h: set() for h in range(24)}
|
||
hour_devs = {h: {} for h in range(24)}
|
||
for h in range(24):
|
||
key = f"{today_str} {h:02d}:00"
|
||
label = f"{h:02d}h"
|
||
label_en = f"{h:02d}:00"
|
||
full_label = f"Aujourd’hui de {h:02d}h00 à {h:02d}h59"
|
||
full_label_en = f"Today from {h:02d}:00 to {h:02d}:59"
|
||
item = {'period': key, 'hour': h, 'label': label, 'label_en': label_en, 'full_label': full_label, 'full_label_en': full_label_en, 'unique_clients': 0, 'total_connections': 0, 'devices': []}
|
||
hours.append(item)
|
||
hours_map[h] = item
|
||
|
||
# 1. Jours (30 derniers jours)
|
||
days = []
|
||
days_map = {}
|
||
for i in range(29, -1, -1):
|
||
d = now - datetime.timedelta(days=i)
|
||
key = d.strftime('%Y-%m-%d')
|
||
label = f"{DAYS_SHORT_FR[d.weekday()]} {d.day:02d}/{d.month:02d}"
|
||
label_en = f"{DAYS_SHORT_EN[d.weekday()]} {d.month:02d}/{d.day:02d}"
|
||
full_label = f"{DAYS_FR[d.weekday()]} {d.day:02d} {MONTHS_FR[d.month].lower()} {d.year}"
|
||
full_label_en = f"{DAYS_EN[d.weekday()]}, {MONTHS_EN[d.month]} {d.day:02d}, {d.year}"
|
||
item = {'period': key, 'label': label, 'label_en': label_en, 'full_label': full_label, 'full_label_en': full_label_en, 'unique_clients': 0, 'total_connections': 0, 'devices': []}
|
||
days.append(item)
|
||
days_map[key] = item
|
||
|
||
# 2. Semaines (12 dernières semaines)
|
||
weeks = []
|
||
weeks_map = {}
|
||
for i in range(11, -1, -1):
|
||
mon = cur_monday - datetime.timedelta(weeks=i)
|
||
sun = mon + datetime.timedelta(days=6)
|
||
key = mon.strftime('%Y-W%W')
|
||
week_num = mon.isocalendar()[1]
|
||
label = f"Sem {week_num}"
|
||
label_en = f"Wk {week_num}"
|
||
full_label = f"Semaine {week_num} (du {mon.day:02d}/{mon.month:02d} au {sun.day:02d}/{sun.month:02d}/{sun.year})"
|
||
full_label_en = f"Week {week_num} (from {mon.month:02d}/{mon.day:02d} to {sun.month:02d}/{sun.day:02d}/{sun.year})"
|
||
item = {'period': key, 'start': mon.strftime('%Y-%m-%d'), 'end': sun.strftime('%Y-%m-%d'), 'label': label, 'label_en': label_en, 'full_label': full_label, 'full_label_en': full_label_en, 'unique_clients': 0, 'total_connections': 0, 'devices': []}
|
||
weeks.append(item)
|
||
weeks_map[key] = item
|
||
|
||
# 3. Mois (12 derniers mois)
|
||
months = []
|
||
months_map = {}
|
||
for i in range(11, -1, -1):
|
||
y = now.year
|
||
m = now.month - i
|
||
while m <= 0:
|
||
m += 12
|
||
y -= 1
|
||
key = f"{y:04d}-{m:02d}"
|
||
label = f"{MONTHS_SHORT_FR[m]} {y}"
|
||
label_en = f"{MONTHS_SHORT_EN[m]} {y}"
|
||
full_label = f"{MONTHS_FR[m]} {y}"
|
||
full_label_en = f"{MONTHS_EN[m]} {y}"
|
||
item = {'period': key, 'label': label, 'label_en': label_en, 'full_label': full_label, 'full_label_en': full_label_en, 'unique_clients': 0, 'total_connections': 0, 'devices': []}
|
||
months.append(item)
|
||
months_map[key] = item
|
||
|
||
# 4. Années (5 dernières années ou depuis la plus ancienne connexion)
|
||
min_year = now.year - 4
|
||
try:
|
||
c = db()
|
||
min_row = c.execute("SELECT MIN(event_time) FROM connection_logs WHERE event='connexion' AND mac LIKE '%:%'").fetchone()
|
||
c.close()
|
||
if min_row and min_row[0]:
|
||
log_min_year = int(min_row[0][:4])
|
||
if log_min_year < min_year: min_year = log_min_year
|
||
except Exception: pass
|
||
|
||
years = []
|
||
years_map = {}
|
||
for y in range(min_year, now.year + 1):
|
||
key = str(y)
|
||
item = {'period': key, 'label': key, 'label_en': key, 'full_label': f"Année {key}", 'full_label_en': f"Year {key}", 'unique_clients': 0, 'total_connections': 0, 'devices': []}
|
||
years.append(item)
|
||
years_map[key] = item
|
||
|
||
day_macs = {k: set() for k in days_map}
|
||
week_macs = {k: set() for k in weeks_map}
|
||
month_macs = {k: set() for k in months_map}
|
||
year_macs = {k: set() for k in years_map}
|
||
|
||
day_devs = {k: {} for k in days_map}
|
||
week_devs = {k: {} for k in weeks_map}
|
||
month_devs = {k: {} for k in months_map}
|
||
year_devs = {k: {} for k in years_map}
|
||
|
||
today_macs = set()
|
||
week_macs_cur = set()
|
||
month_macs_cur = set()
|
||
year_macs_cur = set()
|
||
today_total = 0
|
||
week_total = 0
|
||
month_total = 0
|
||
year_total = 0
|
||
|
||
try:
|
||
c = db()
|
||
rows = c.execute('''
|
||
SELECT
|
||
l.event_time,
|
||
l.event,
|
||
l.mac,
|
||
COALESCE(NULLIF(n.name, ''), NULLIF(l.name, ''), 'Client ' || REPLACE(SUBSTR(l.mac, -5), ':', '')) AS display_name
|
||
FROM connection_logs l
|
||
LEFT JOIN client_names n ON n.mac = l.mac
|
||
WHERE l.event IN ('connexion', 'déconnexion') AND l.mac LIKE '%:%'
|
||
ORDER BY l.id ASC
|
||
''').fetchall()
|
||
|
||
# Également récupérer l'historique du trafic journalier stocké en base
|
||
try:
|
||
traffic_rows = c.execute('''
|
||
SELECT
|
||
t.mac,
|
||
t.traffic_date,
|
||
COALESCE(NULLIF(n.name, ''), 'Client ' || REPLACE(SUBSTR(t.mac, -5), ':', '')) AS display_name,
|
||
(COALESCE(t.rx_bytes, 0) + COALESCE(t.tx_bytes, 0)) AS total_bytes
|
||
FROM client_traffic_daily t
|
||
LEFT JOIN client_names n ON n.mac = t.mac
|
||
WHERE (t.rx_bytes > 0 OR t.tx_bytes > 0)
|
||
''').fetchall()
|
||
except Exception:
|
||
traffic_rows = []
|
||
|
||
# Également récupérer les derniers accès connus dans client_names
|
||
try:
|
||
cn_rows = c.execute('''
|
||
SELECT mac, name, last_seen FROM client_names
|
||
WHERE last_seen IS NOT NULL AND last_seen != '' AND last_seen != '—'
|
||
''').fetchall()
|
||
except Exception:
|
||
cn_rows = []
|
||
|
||
c.close()
|
||
except Exception as e:
|
||
rows = []
|
||
traffic_rows = []
|
||
cn_rows = []
|
||
print(f"[ap-error] Erreur récupération statistiques: {e}", flush=True)
|
||
|
||
# 1. Événements de journaux de connexion
|
||
today_sessions = {} # mac -> [(dt, event, name)]
|
||
for et, ev, mac, name in rows:
|
||
try:
|
||
dt = datetime.datetime.strptime(et[:19], '%Y-%m-%d %H:%M:%S')
|
||
except Exception:
|
||
continue
|
||
|
||
d_key = dt.strftime('%Y-%m-%d')
|
||
dt_monday = dt.date() - datetime.timedelta(days=dt.weekday())
|
||
w_key = dt_monday.strftime('%Y-W%W')
|
||
m_key = dt.strftime('%Y-%m')
|
||
y_key = dt.strftime('%Y')
|
||
|
||
if ev == 'connexion':
|
||
if et.startswith(today_str):
|
||
today_macs.add(mac)
|
||
today_total += 1
|
||
h = dt.hour
|
||
if h in hours_map:
|
||
hours_map[h]['total_connections'] += 1
|
||
hour_macs[h].add(mac)
|
||
hour_devs[h][mac] = name
|
||
if et >= cur_week_start:
|
||
week_macs_cur.add(mac)
|
||
week_total += 1
|
||
if et.startswith(cur_month):
|
||
month_macs_cur.add(mac)
|
||
month_total += 1
|
||
if et.startswith(cur_year):
|
||
year_macs_cur.add(mac)
|
||
year_total += 1
|
||
|
||
if d_key in days_map:
|
||
days_map[d_key]['total_connections'] += 1
|
||
day_macs[d_key].add(mac)
|
||
day_devs[d_key][mac] = name
|
||
if w_key in weeks_map:
|
||
weeks_map[w_key]['total_connections'] += 1
|
||
week_macs[w_key].add(mac)
|
||
week_devs[w_key][mac] = name
|
||
if m_key in months_map:
|
||
months_map[m_key]['total_connections'] += 1
|
||
month_macs[m_key].add(mac)
|
||
month_devs[m_key][mac] = name
|
||
if y_key in years_map:
|
||
years_map[y_key]['total_connections'] += 1
|
||
year_macs[y_key].add(mac)
|
||
year_devs[y_key][mac] = name
|
||
|
||
if et.startswith(today_str):
|
||
today_sessions.setdefault(mac, []).append((dt, ev, name))
|
||
|
||
# Reconstitution des tranches horaires pour aujourd'hui selon la durée de présence
|
||
for mac, ev_list in today_sessions.items():
|
||
last_conn_dt = None
|
||
dev_name = None
|
||
for dt, ev, name in ev_list:
|
||
dev_name = name or dev_name
|
||
if ev == 'connexion':
|
||
if last_conn_dt is not None:
|
||
for h in range(last_conn_dt.hour, dt.hour + 1):
|
||
if h in hours_map:
|
||
hour_macs[h].add(mac)
|
||
hour_devs[h][mac] = dev_name
|
||
last_conn_dt = dt
|
||
elif ev == 'déconnexion':
|
||
if last_conn_dt is not None:
|
||
for h in range(last_conn_dt.hour, dt.hour + 1):
|
||
if h in hours_map:
|
||
hour_macs[h].add(mac)
|
||
hour_devs[h][mac] = dev_name
|
||
last_conn_dt = None
|
||
else:
|
||
for h in range(0, dt.hour + 1):
|
||
if h in hours_map:
|
||
hour_macs[h].add(mac)
|
||
hour_devs[h][mac] = dev_name
|
||
if last_conn_dt is not None:
|
||
for h in range(last_conn_dt.hour, min(23, now.hour) + 1):
|
||
if h in hours_map:
|
||
hour_macs[h].add(mac)
|
||
hour_devs[h][mac] = dev_name
|
||
|
||
# 2. Intégration du trafic journalier (client_traffic_daily) enregistré en base SQLite
|
||
for mac, t_date, name, tot_b in traffic_rows:
|
||
try:
|
||
dt = datetime.datetime.strptime(t_date[:10], '%Y-%m-%d')
|
||
except Exception:
|
||
continue
|
||
d_key = t_date[:10]
|
||
dt_monday = dt.date() - datetime.timedelta(days=dt.weekday())
|
||
w_key = dt_monday.strftime('%Y-W%W')
|
||
m_key = dt.strftime('%Y-%m')
|
||
y_key = dt.strftime('%Y')
|
||
|
||
if d_key == today_str:
|
||
today_macs.add(mac)
|
||
if d_key >= cur_week_start[:10]:
|
||
week_macs_cur.add(mac)
|
||
if d_key.startswith(cur_month):
|
||
month_macs_cur.add(mac)
|
||
if d_key.startswith(cur_year):
|
||
year_macs_cur.add(mac)
|
||
|
||
if d_key in days_map:
|
||
day_macs[d_key].add(mac)
|
||
day_devs[d_key][mac] = name
|
||
if w_key in weeks_map:
|
||
week_macs[w_key].add(mac)
|
||
week_devs[w_key][mac] = name
|
||
if m_key in months_map:
|
||
month_macs[m_key].add(mac)
|
||
month_devs[m_key][mac] = name
|
||
if y_key in years_map:
|
||
year_macs[y_key].add(mac)
|
||
year_devs[y_key][mac] = name
|
||
|
||
# 3. Intégration des derniers accès enregistrés en base SQLite (client_names.last_seen)
|
||
for mac, name, last_seen in cn_rows:
|
||
ls = str(last_seen).strip()
|
||
if len(ls) >= 10:
|
||
ls_date = ls[:10]
|
||
if ls_date == today_str:
|
||
today_macs.add(mac)
|
||
try:
|
||
ls_h = int(ls[11:13])
|
||
if ls_h in hours_map:
|
||
hour_macs[ls_h].add(mac)
|
||
hour_devs[ls_h][mac] = name
|
||
except Exception:
|
||
pass
|
||
if ls_date >= cur_week_start[:10]:
|
||
week_macs_cur.add(mac)
|
||
if ls_date.startswith(cur_month):
|
||
month_macs_cur.add(mac)
|
||
if ls_date.startswith(cur_year):
|
||
year_macs_cur.add(mac)
|
||
if ls_date in days_map:
|
||
day_macs[ls_date].add(mac)
|
||
day_devs[ls_date][mac] = name
|
||
|
||
if active_items is None:
|
||
try: active_items = clients()
|
||
except Exception: active_items = []
|
||
active_count = len(active_items)
|
||
|
||
cur_h = now.hour
|
||
if active_items:
|
||
for x in active_items:
|
||
m = x.get('mac')
|
||
n = x.get('name') or m
|
||
if m:
|
||
today_macs.add(m)
|
||
week_macs_cur.add(m)
|
||
month_macs_cur.add(m)
|
||
year_macs_cur.add(m)
|
||
if cur_h in hours_map:
|
||
hour_macs[cur_h].add(m)
|
||
hour_devs[cur_h][m] = n
|
||
if today_str in days_map:
|
||
day_macs[today_str].add(m)
|
||
day_devs[today_str][m] = n
|
||
|
||
for h, item in hours_map.items():
|
||
item['unique_clients'] = len(hour_macs[h])
|
||
if item['total_connections'] < item['unique_clients']:
|
||
item['total_connections'] = item['unique_clients']
|
||
item['devices'] = sorted(list(hour_devs[h].values()))
|
||
|
||
for k, item in days_map.items():
|
||
item['unique_clients'] = len(day_macs[k])
|
||
if item['total_connections'] < item['unique_clients']:
|
||
item['total_connections'] = item['unique_clients']
|
||
item['devices'] = sorted(list(day_devs[k].values()))
|
||
|
||
for k, item in weeks_map.items():
|
||
item['unique_clients'] = len(week_macs[k])
|
||
if item['total_connections'] < item['unique_clients']:
|
||
item['total_connections'] = item['unique_clients']
|
||
item['devices'] = sorted(list(week_devs[k].values()))
|
||
|
||
for k, item in months_map.items():
|
||
item['unique_clients'] = len(month_macs[k])
|
||
if item['total_connections'] < item['unique_clients']:
|
||
item['total_connections'] = item['unique_clients']
|
||
item['devices'] = sorted(list(month_devs[k].values()))
|
||
|
||
for k, item in years_map.items():
|
||
item['unique_clients'] = len(year_macs[k])
|
||
if item['total_connections'] < item['unique_clients']:
|
||
item['total_connections'] = item['unique_clients']
|
||
item['devices'] = sorted(list(year_devs[k].values()))
|
||
|
||
today_total = max(today_total, len(today_macs))
|
||
week_total = max(week_total, len(week_macs_cur))
|
||
month_total = max(month_total, len(month_macs_cur))
|
||
year_total = max(year_total, len(year_macs_cur))
|
||
|
||
top_clients_by_range = {
|
||
'day': get_top_clients(active_items, 'day'),
|
||
'week': get_top_clients(active_items, 'week'),
|
||
'month': get_top_clients(active_items, 'month'),
|
||
'year': get_top_clients(active_items, 'year')
|
||
}
|
||
top_clients = top_clients_by_range['day']
|
||
now_str = time.strftime('%H:%M:%S')
|
||
|
||
return {
|
||
'summary': {
|
||
'current': active_count,
|
||
'today': {'unique': len(today_macs), 'total': today_total},
|
||
'week': {'unique': len(week_macs_cur), 'total': week_total},
|
||
'month': {'unique': len(month_macs_cur), 'total': month_total},
|
||
'year': {'unique': len(year_macs_cur), 'total': year_total}
|
||
},
|
||
'hours': hours,
|
||
'days': days,
|
||
'weeks': weeks,
|
||
'months': months,
|
||
'years': years,
|
||
'top_clients': top_clients,
|
||
'top_clients_by_range': top_clients_by_range,
|
||
'updated_at': now_str,
|
||
'analyzed_at': now_str,
|
||
'background_analyzed': True,
|
||
'analysis_count': _metrics_count,
|
||
'analysis_duration_ms': _metrics_last_duration_ms
|
||
}
|
||
|
||
def stats():
|
||
with _metrics_lock:
|
||
if _cached_stats is not None:
|
||
return _cached_stats
|
||
return compute_stats_internal()
|
||
|
||
def connection_name():
|
||
active = command('nmcli','-t','-g','GENERAL.CONNECTION','device','show',INTERFACE)
|
||
if active and active != '--': return active
|
||
try: return open(CONNECTION_FILE, encoding='utf8').read().strip()
|
||
except OSError: return os.environ.get('AP_CONNECTION', '')
|
||
|
||
def save_connection(name):
|
||
try: open(CONNECTION_FILE, 'w', encoding='utf8').write(name)
|
||
except OSError: pass
|
||
|
||
def apply_radio_defaults():
|
||
"""Applique bande/canal/CCMP à la connexion AP déjà créée (sans avoir à ré-enregistrer les réglages)."""
|
||
name = connection_name()
|
||
if not name: return
|
||
band = command('nmcli','-t','-g','802-11-wireless.band','connection','show',name)
|
||
chan = command('nmcli','-t','-g','802-11-wireless.channel','connection','show',name)
|
||
key = command('nmcli','-t','-g','802-11-wireless-security.key-mgmt','connection','show',name)
|
||
if band == AP_BAND and chan == str(AP_CHANNEL): return
|
||
args = ['nmcli','connection','modify',name,'802-11-wireless.band',AP_BAND,'802-11-wireless.channel',str(AP_CHANNEL)]
|
||
if key in ('wpa-psk','sae'): args += ['802-11-wireless-security.pairwise','ccmp','802-11-wireless-security.group','ccmp']
|
||
r = subprocess.run(args, text=True, capture_output=True)
|
||
print(f"[ap-api] Radio {name} : bande={AP_BAND} canal={AP_CHANNEL} -> {'OK' if not r.returncode else r.stderr.strip()}", flush=True)
|
||
if not r.returncode and command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE).startswith('100'):
|
||
subprocess.run(['nmcli','connection','up',name], text=True, capture_output=True)
|
||
|
||
def security(value):
|
||
values = {'wpa1':('wpa-psk','wpa','optional'), 'wpa2':('wpa-psk','rsn','optional'), 'wpa3':('sae',None,'required')}
|
||
value = str(value or 'wpa2').lower()
|
||
if value not in values: raise ValueError('Sécurité Wi-Fi invalide')
|
||
key, proto, pmf = values[value]; return value, key, proto, pmf
|
||
|
||
def get_pref(key, default=None):
|
||
try:
|
||
c = db(); row = c.execute("SELECT value FROM preferences WHERE key=?", (key,)).fetchone(); c.close()
|
||
if row and row[0] is not None: return row[0]
|
||
except Exception: pass
|
||
return default
|
||
|
||
def set_pref(key, value):
|
||
try:
|
||
c = db(); c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES(?,?)", (key, str(value))); c.commit(); c.close()
|
||
except Exception: pass
|
||
|
||
def current_mode():
|
||
try:
|
||
# Pendant l'assistant de configuration initial (setup non terminé), forcer le mode de l'environnement (ap par défaut)
|
||
if callable(globals().get('auth_state')):
|
||
st = auth_state()
|
||
if not st.get('setup_completed'):
|
||
return os.environ.get('AP_MODE', 'ap').lower()
|
||
except Exception: pass
|
||
|
||
# Si l'environnement impose expressément le mode AP
|
||
if os.environ.get('AP_MODE', '').lower() == 'ap':
|
||
return 'ap'
|
||
|
||
name = connection_name()
|
||
if name:
|
||
slave_type = (command('nmcli','-t','-g','connection.slave-type','connection','show',name) or command('nmcli','-t','-g','connection.port-type','connection','show',name)).lower()
|
||
if slave_type == 'bridge':
|
||
return 'bridge'
|
||
master = (command('nmcli','-t','-g','connection.master','connection','show',name) or command('nmcli','-t','-g','connection.controller','connection','show',name))
|
||
if master:
|
||
return 'bridge'
|
||
if os.path.exists(f'/sys/class/net/{INTERFACE}/master'):
|
||
return 'bridge'
|
||
try:
|
||
pref = get_pref('mode', os.environ.get('AP_MODE', 'ap'))
|
||
return str(pref).lower() if pref else 'ap'
|
||
except Exception:
|
||
return 'ap'
|
||
|
||
def is_bridge_mode():
|
||
return current_mode() == 'bridge'
|
||
|
||
def get_max_clients():
|
||
try: return int(get_pref('max_clients', os.environ.get('AP_MAX_CLIENTS', 0)) or 0)
|
||
except (ValueError, TypeError): return 0
|
||
|
||
def set_max_clients(val):
|
||
try: n = max(0, int(val if val is not None else 0))
|
||
except (ValueError, TypeError): n = 0
|
||
set_pref('max_clients', n)
|
||
try:
|
||
conf_dir = '/etc/NetworkManager/dnsmasq-shared.d'
|
||
conf = os.path.join(conf_dir, '20-max-clients.conf')
|
||
if n > 0:
|
||
os.makedirs(conf_dir, exist_ok=True)
|
||
with open(conf, 'w', encoding='utf8') as f: f.write(f"# Limite dynamique de baux DHCP\ndhcp-lease-max={n}\n")
|
||
else:
|
||
if os.path.exists(conf): os.remove(conf)
|
||
except OSError: pass
|
||
return n
|
||
|
||
def ensure_dnsmasq_dns():
|
||
"""Garantit que dnsmasq fournit toujours les serveurs AP_DNS aux clients Wi-Fi."""
|
||
dns_env = os.environ.get('AP_DNS', '1.1.1.1,9.9.9.9').strip()
|
||
if not dns_env:
|
||
return
|
||
parts = [p.strip() for p in re.split(r'[,;\s]+', dns_env) if p.strip()]
|
||
if not parts:
|
||
return
|
||
clean_dns = ','.join(parts)
|
||
try:
|
||
conf_dir = '/etc/NetworkManager/dnsmasq-shared.d'
|
||
os.makedirs(conf_dir, exist_ok=True)
|
||
conf_file = os.path.join(conf_dir, '15-ap-dns.conf')
|
||
lines = [
|
||
"# Configuration DNS distribuée aux clients Wi-Fi (AP_DNS)",
|
||
f"dhcp-option=6,{clean_dns}",
|
||
"no-resolv"
|
||
]
|
||
for s in parts:
|
||
lines.append(f"server={s}")
|
||
with open(conf_file, 'w', encoding='utf-8') as f:
|
||
f.write('\n'.join(lines) + '\n')
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
# =====================================================================
|
||
# Système de notifications multi-canaux (Email SMTP, Gotify, Discord)
|
||
# =====================================================================
|
||
|
||
DEFAULT_NOTIFICATION_TEMPLATES = {
|
||
"new_device": {
|
||
"title": "📱 Nouvel appareil détecté",
|
||
"message": "L'appareil « {name} » vient de se connecter pour la première fois au réseau Wi-Fi."
|
||
},
|
||
"device_connected": {
|
||
"title": "📶 Appareil connecté",
|
||
"message": "L'appareil « {name} » s'est connecté au réseau Wi-Fi."
|
||
},
|
||
"device_disconnected": {
|
||
"title": "📴 Appareil déconnecté",
|
||
"message": "L'appareil « {name} » s'est déconnecté du réseau Wi-Fi."
|
||
},
|
||
"admin_login": {
|
||
"title": "🔒 Connexion au compte administrateur",
|
||
"message": "Connexion réussie au compte administrateur « {user} »."
|
||
},
|
||
"admin_login_failed": {
|
||
"title": "⚠️ Échec de connexion administrateur",
|
||
"message": "Une tentative de connexion au compte administrateur a échoué (mot de passe invalide)."
|
||
},
|
||
"device_blocked": {
|
||
"title": "🛑 Équipement Wi-Fi bloqué / débloqué",
|
||
"message": "L'appareil « {name} » a été {action} le réseau Wi-Fi."
|
||
},
|
||
"settings_changed": {
|
||
"title": "⚙️ Modification réglages Wi-Fi / AP",
|
||
"message": "Les réglages du point d'accès Wi-Fi ont été modifiés (SSID : {ssid})."
|
||
},
|
||
"vpn_client_connected": {
|
||
"title": "🛡️ Client routé via VPN",
|
||
"message": "L'appareil « {name} » ({ip}) est désormais connecté et routé via le VPN « {vpn} »."
|
||
},
|
||
"vpn_client_disconnected": {
|
||
"title": "🌐 Client déconnecté du VPN",
|
||
"message": "L'appareil « {name} » ({ip}) n'est plus routé via le VPN « {vpn} »."
|
||
},
|
||
"vpn_profile_connected": {
|
||
"title": "🛡️ Tunnel VPN connecté",
|
||
"message": "Le profil VPN « {name} » ({type}) est désormais connecté avec succès (interface {iface})."
|
||
},
|
||
"vpn_profile_disconnected": {
|
||
"title": "⚠️ Tunnel VPN déconnecté",
|
||
"message": "Le profil VPN « {name} » ({type}) a été déconnecté (interface {iface})."
|
||
},
|
||
"quota_exceeded": {
|
||
"title": "⚠️ Quota de données dépassé",
|
||
"message": "L'appareil « {name} » ({ip}) a dépassé son quota de {quota} (consommé : {consumption}). L'accès Internet a été coupé."
|
||
},
|
||
"stats_report": {
|
||
"title": "📊 Rapport statistiques & métriques Wi‑Fi",
|
||
"message": "📊 Rapport Wi‑Fi ({date}) :\n• {clients_count} appareil(s) connecté(s) (↓ {traffic_down} • ↑ {traffic_up})\n• Aujourd'hui : {today_unique} visiteur(s) unique(s) ({today_total} sessions)\n• Cette semaine : {week_unique} unique(s) | Ce mois : {month_unique} unique(s)\n• VPN : {active_vpns} tunnel(s) actif(s) ({vpn_routed_clients} appareil(s) routé(s))\n• Passerelle WAN : {gateway_status} ({gateway_ip})\n• Top clients (Consommation de données) :\n{top_clients}"
|
||
}
|
||
}
|
||
|
||
DEFAULT_NOTIFICATIONS_CONFIG = {
|
||
"email": {
|
||
"enabled": False,
|
||
"smtp_host": "",
|
||
"smtp_port": 587,
|
||
"smtp_secure": "starttls",
|
||
"smtp_user": "",
|
||
"smtp_pass": "",
|
||
"from_addr": "",
|
||
"to_addr": ""
|
||
},
|
||
"gotify": {
|
||
"enabled": False,
|
||
"server_url": "",
|
||
"token": "",
|
||
"priority": 5
|
||
},
|
||
"discord": {
|
||
"enabled": False,
|
||
"webhook_url": "",
|
||
"bot_name": "AP Manageur"
|
||
},
|
||
"ntfy": {
|
||
"enabled": False,
|
||
"server_url": "https://ntfy.sh",
|
||
"topic": "",
|
||
"token": "",
|
||
"priority": 3
|
||
},
|
||
"pushbullet": {
|
||
"enabled": False,
|
||
"api_token": "",
|
||
"device_iden": ""
|
||
},
|
||
"pushover": {
|
||
"enabled": False,
|
||
"user_key": "",
|
||
"api_token": "",
|
||
"priority": 0
|
||
},
|
||
"slack": {
|
||
"enabled": False,
|
||
"webhook_url": "",
|
||
"bot_name": "AP Manageur"
|
||
},
|
||
"telegram": {
|
||
"enabled": False,
|
||
"bot_token": "",
|
||
"chat_id": "",
|
||
"thread_id": ""
|
||
},
|
||
"webhook": {
|
||
"enabled": False,
|
||
"url": "",
|
||
"method": "POST",
|
||
"headers": ""
|
||
},
|
||
"events": {
|
||
"new_device": True, # Nouvel équipement Wi-Fi (première connexion)
|
||
"device_connected": False, # Reconnexion d'un équipement Wi-Fi connu
|
||
"device_disconnected": False, # Déconnexion d'un équipement Wi-Fi
|
||
"admin_login": True, # Connexion réussie au compte admin
|
||
"admin_login_failed": True, # Tentative de connexion admin échouée
|
||
"device_blocked": True, # Appareil bloqué ou débloqué
|
||
"settings_changed": True, # Modification des réglages Wi-Fi / AP
|
||
"vpn_client_connected": True, # Connexion / Assignation d'un client au VPN
|
||
"vpn_client_disconnected": True, # Déconnexion / Retrait d'un client du VPN
|
||
"vpn_profile_connected": True, # Connexion d'un profil VPN (tunnel actif)
|
||
"vpn_profile_disconnected": True, # Déconnexion d'un profil VPN (tunnel coupé)
|
||
"quota_exceeded": True, # Quota de données dépassé par un équipement Wi-Fi
|
||
"stats_report": False # Rapport planifié des statistiques et métriques (Tâche Cron)
|
||
},
|
||
"stats_report_schedule": {
|
||
"enabled": False,
|
||
"mode": "daily",
|
||
"day": "*",
|
||
"hour": 8,
|
||
"minute": 0,
|
||
"cron_expr": "0 8 * * *",
|
||
"top_range": "day"
|
||
},
|
||
"templates": DEFAULT_NOTIFICATION_TEMPLATES
|
||
}
|
||
|
||
def get_notifications_config():
|
||
raw = get_pref('notifications_config')
|
||
if not raw:
|
||
return json.loads(json.dumps(DEFAULT_NOTIFICATIONS_CONFIG))
|
||
try:
|
||
cfg = json.loads(raw)
|
||
res = json.loads(json.dumps(DEFAULT_NOTIFICATIONS_CONFIG))
|
||
for section in ('email', 'gotify', 'discord', 'ntfy', 'pushbullet', 'pushover', 'slack', 'telegram', 'webhook', 'events', 'templates', 'stats_report_schedule'):
|
||
if section in cfg and isinstance(cfg[section], dict):
|
||
if section == 'templates':
|
||
for ev, tmpl in cfg['templates'].items():
|
||
if isinstance(tmpl, dict) and ev in res['templates']:
|
||
res['templates'][ev].update(tmpl)
|
||
else:
|
||
res[section].update(cfg[section])
|
||
return res
|
||
except Exception:
|
||
return json.loads(json.dumps(DEFAULT_NOTIFICATIONS_CONFIG))
|
||
|
||
def get_notifications_settings_public():
|
||
cfg = get_notifications_config()
|
||
email_cfg = cfg.get('email', {})
|
||
has_pass = bool(email_cfg.get('smtp_pass'))
|
||
email_cfg['smtp_pass_set'] = has_pass
|
||
email_cfg['smtp_pass'] = ''
|
||
return cfg
|
||
|
||
def save_notifications_settings(data):
|
||
if not isinstance(data, dict):
|
||
raise ValueError("Données de configuration invalides")
|
||
current = get_notifications_config()
|
||
|
||
if 'email' in data and isinstance(data['email'], dict):
|
||
ne = data['email']
|
||
current['email']['enabled'] = bool(ne.get('enabled', False))
|
||
current['email']['smtp_host'] = str(ne.get('smtp_host', '')).strip()
|
||
try: current['email']['smtp_port'] = int(ne.get('smtp_port') or 587)
|
||
except (ValueError, TypeError): current['email']['smtp_port'] = 587
|
||
current['email']['smtp_secure'] = str(ne.get('smtp_secure', 'starttls')).strip().lower()
|
||
current['email']['smtp_user'] = str(ne.get('smtp_user', '')).strip()
|
||
new_pass = str(ne.get('smtp_pass', ''))
|
||
if new_pass:
|
||
current['email']['smtp_pass'] = new_pass
|
||
current['email']['from_addr'] = str(ne.get('from_addr', '')).strip()
|
||
current['email']['to_addr'] = str(ne.get('to_addr', '')).strip()
|
||
|
||
if 'gotify' in data and isinstance(data['gotify'], dict):
|
||
ng = data['gotify']
|
||
current['gotify']['enabled'] = bool(ng.get('enabled', False))
|
||
current['gotify']['server_url'] = str(ng.get('server_url', '')).strip().rstrip('/')
|
||
current['gotify']['token'] = str(ng.get('token', '')).strip()
|
||
try: current['gotify']['priority'] = min(10, max(1, int(ng.get('priority') or 5)))
|
||
except (ValueError, TypeError): current['gotify']['priority'] = 5
|
||
|
||
if 'discord' in data and isinstance(data['discord'], dict):
|
||
nd = data['discord']
|
||
current['discord']['enabled'] = bool(nd.get('enabled', False))
|
||
current['discord']['webhook_url'] = str(nd.get('webhook_url', '')).strip()
|
||
current['discord']['bot_name'] = str(nd.get('bot_name', '')).strip() or "AP Manageur"
|
||
|
||
if 'ntfy' in data and isinstance(data['ntfy'], dict):
|
||
nn = data['ntfy']
|
||
current['ntfy']['enabled'] = bool(nn.get('enabled', False))
|
||
current['ntfy']['server_url'] = str(nn.get('server_url', 'https://ntfy.sh')).strip().rstrip('/')
|
||
current['ntfy']['topic'] = str(nn.get('topic', '')).strip()
|
||
current['ntfy']['token'] = str(nn.get('token', '')).strip()
|
||
try: current['ntfy']['priority'] = min(5, max(1, int(nn.get('priority') or 3)))
|
||
except (ValueError, TypeError): current['ntfy']['priority'] = 3
|
||
|
||
if 'pushbullet' in data and isinstance(data['pushbullet'], dict):
|
||
np = data['pushbullet']
|
||
current['pushbullet']['enabled'] = bool(np.get('enabled', False))
|
||
current['pushbullet']['api_token'] = str(np.get('api_token', '')).strip()
|
||
current['pushbullet']['device_iden'] = str(np.get('device_iden', '')).strip()
|
||
|
||
if 'pushover' in data and isinstance(data['pushover'], dict):
|
||
npo = data['pushover']
|
||
current['pushover']['enabled'] = bool(npo.get('enabled', False))
|
||
current['pushover']['user_key'] = str(npo.get('user_key', '')).strip()
|
||
current['pushover']['api_token'] = str(npo.get('api_token', '')).strip()
|
||
try: current['pushover']['priority'] = min(2, max(-2, int(npo.get('priority') or 0)))
|
||
except (ValueError, TypeError): current['pushover']['priority'] = 0
|
||
|
||
if 'slack' in data and isinstance(data['slack'], dict):
|
||
nsl = data['slack']
|
||
current['slack']['enabled'] = bool(nsl.get('enabled', False))
|
||
current['slack']['webhook_url'] = str(nsl.get('webhook_url', '')).strip()
|
||
current['slack']['bot_name'] = str(nsl.get('bot_name', '')).strip() or "AP Manageur"
|
||
|
||
if 'telegram' in data and isinstance(data['telegram'], dict):
|
||
ntg = data['telegram']
|
||
current['telegram']['enabled'] = bool(ntg.get('enabled', False))
|
||
current['telegram']['bot_token'] = str(ntg.get('bot_token', '')).strip()
|
||
current['telegram']['chat_id'] = str(ntg.get('chat_id', '')).strip()
|
||
current['telegram']['thread_id'] = str(ntg.get('thread_id', '')).strip()
|
||
|
||
if 'webhook' in data and isinstance(data['webhook'], dict):
|
||
nwh = data['webhook']
|
||
current['webhook']['enabled'] = bool(nwh.get('enabled', False))
|
||
current['webhook']['url'] = str(nwh.get('url', '')).strip()
|
||
current['webhook']['method'] = str(nwh.get('method', 'POST')).strip().upper()
|
||
if current['webhook']['method'] not in ('POST', 'PUT', 'GET'): current['webhook']['method'] = 'POST'
|
||
current['webhook']['headers'] = str(nwh.get('headers', '')).strip()
|
||
|
||
if 'events' in data and isinstance(data['events'], dict):
|
||
for k in current['events']:
|
||
if k in data['events']:
|
||
current['events'][k] = bool(data['events'][k])
|
||
|
||
if 'templates' in data and isinstance(data['templates'], dict):
|
||
if 'templates' not in current or not isinstance(current['templates'], dict):
|
||
current['templates'] = json.loads(json.dumps(DEFAULT_NOTIFICATION_TEMPLATES))
|
||
for ev, tmpl in data['templates'].items():
|
||
if isinstance(tmpl, dict) and ev in DEFAULT_NOTIFICATION_TEMPLATES:
|
||
current['templates'][ev] = {
|
||
'title': str(tmpl.get('title', '')).strip(),
|
||
'message': str(tmpl.get('message', '')).strip()
|
||
}
|
||
|
||
if 'stats_report_schedule' in data and isinstance(data['stats_report_schedule'], dict):
|
||
ss = data['stats_report_schedule']
|
||
cur_s = current.setdefault('stats_report_schedule', {})
|
||
cur_s['enabled'] = bool(ss.get('enabled', False))
|
||
cur_s['mode'] = str(ss.get('mode', 'daily')).strip()
|
||
cur_s['day'] = str(ss.get('day', '*')).strip()
|
||
try: cur_s['hour'] = min(23, max(0, int(ss.get('hour', 8))))
|
||
except (ValueError, TypeError): cur_s['hour'] = 8
|
||
try: cur_s['minute'] = min(59, max(0, int(ss.get('minute', 0))))
|
||
except (ValueError, TypeError): cur_s['minute'] = 0
|
||
cron_raw = str(ss.get('cron_expr', '')).strip()
|
||
if not cron_raw or len(cron_raw.split()) != 5:
|
||
cron_raw = f"{cur_s['minute']} {cur_s['hour']} * * {cur_s['day']}"
|
||
cur_s['cron_expr'] = cron_raw
|
||
top_r = str(ss.get('top_range', 'day')).strip().lower()
|
||
if top_r not in ('day', 'week', 'month', 'year', 'all_ranges'):
|
||
top_r = 'day'
|
||
cur_s['top_range'] = top_r
|
||
if 'events' in current and isinstance(current['events'], dict):
|
||
current['events']['stats_report'] = cur_s['enabled']
|
||
|
||
set_pref('notifications_config', json.dumps(current))
|
||
return True
|
||
|
||
def send_email_notification(cfg, title, message, details=None, level="info"):
|
||
host = cfg.get('smtp_host', '').strip()
|
||
port = int(cfg.get('smtp_port') or 587)
|
||
secure = cfg.get('smtp_secure', 'starttls').lower()
|
||
user = cfg.get('smtp_user', '').strip()
|
||
password = cfg.get('smtp_pass', '')
|
||
from_addr = cfg.get('from_addr', '').strip() or user
|
||
to_addr = cfg.get('to_addr', '').strip()
|
||
|
||
if not host:
|
||
raise ValueError("Hôte SMTP manquant")
|
||
if not to_addr:
|
||
raise ValueError("Adresse email de destination manquante")
|
||
if not from_addr:
|
||
raise ValueError("Adresse email d'expédition manquante")
|
||
|
||
recipients = [a.strip() for a in re.split(r'[,;]+', to_addr) if a.strip()]
|
||
if not recipients:
|
||
raise ValueError("Aucun destinataire valide")
|
||
|
||
msg = MIMEMultipart('alternative')
|
||
msg['Subject'] = f"[AP Manageur] {title}"
|
||
msg['From'] = from_addr
|
||
msg['To'] = ', '.join(recipients)
|
||
msg['Date'] = time.strftime('%a, %d %b %Y %H:%M:%S +0000', time.gmtime())
|
||
|
||
lines = [f"{title}", "=" * len(title), message, ""]
|
||
if details:
|
||
for k, v in details.items():
|
||
lines.append(f"• {k} : {v}")
|
||
lines += ["", "--", "Notification automatique envoyée par AP Manageur"]
|
||
msg.attach(MIMEText('\n'.join(lines), 'plain', 'utf-8'))
|
||
|
||
color_map = {
|
||
"info": "#1e6ef0",
|
||
"success": "#13a06a",
|
||
"warning": "#f6ad55",
|
||
"danger": "#e53935"
|
||
}
|
||
badge_color = color_map.get(level, "#1e6ef0")
|
||
|
||
rows_html = ""
|
||
if details:
|
||
for k, v in details.items():
|
||
rows_html += f"<tr><td style='padding:8px 12px;color:#8898aa;font-size:13px;border-bottom:1px solid #edf2f7;width:35%'><strong>{k}</strong></td><td style='padding:8px 12px;color:#1a202c;font-size:13px;border-bottom:1px solid #edf2f7;font-family:monospace'>{v}</td></tr>"
|
||
|
||
html = f"""<!DOCTYPE html>
|
||
<html>
|
||
<body style="margin:0;padding:24px;background:#f7fafc;font-family:system-ui,-apple-system,sans-serif">
|
||
<div style="max-width:560px;margin:auto;background:#ffffff;border-radius:12px;border:1px solid #e2e8f0;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,0.05)">
|
||
<div style="background:#0d1d36;padding:20px;color:#ffffff;border-bottom:3px solid {badge_color}">
|
||
<div style="font-size:12px;letter-spacing:1px;text-transform:uppercase;color:#5ca7ff;font-weight:700">AP Manageur • Alerte</div>
|
||
<h2 style="margin:6px 0 0;font-size:18px">{title}</h2>
|
||
</div>
|
||
<div style="padding:24px">
|
||
<p style="margin:0 0 16px;font-size:15px;color:#2d3748;line-height:1.5">{message}</p>
|
||
{"<table style='width:100%;border-collapse:collapse;margin:16px 0;background:#f8fafc;border-radius:8px;overflow:hidden'>" + rows_html + "</table>" if rows_html else ""}
|
||
<p style="font-size:12px;color:#a0aec0;margin:20px 0 0;border-top:1px solid #edf2f7;padding-top:12px">
|
||
Notification générée automatiquement par le point d'accès Wi-Fi <strong>AP Manageur</strong> à {time.strftime('%H:%M:%S le %d/%m/%Y')}.
|
||
</p>
|
||
</div>
|
||
</div>
|
||
</body>
|
||
</html>"""
|
||
msg.attach(MIMEText(html, 'html', 'utf-8'))
|
||
|
||
if secure == 'ssl' or port == 465:
|
||
server = smtplib.SMTP_SSL(host, port, timeout=12)
|
||
else:
|
||
server = smtplib.SMTP(host, port, timeout=12)
|
||
if secure == 'starttls':
|
||
server.starttls()
|
||
if user and password:
|
||
server.login(user, password)
|
||
server.sendmail(from_addr, recipients, msg.as_string())
|
||
server.quit()
|
||
return True
|
||
|
||
def send_gotify_notification(cfg, title, message, details=None, priority=5):
|
||
server_url = (cfg.get('server_url') or '').strip()
|
||
token = (cfg.get('token') or '').strip()
|
||
if not server_url:
|
||
raise ValueError("URL du serveur Gotify manquante")
|
||
if not token:
|
||
raise ValueError("Token d'application Gotify manquant")
|
||
|
||
# Normalisation du protocole et de l'URL
|
||
if not (server_url.startswith('http://') or server_url.startswith('https://')):
|
||
server_url = 'http://' + server_url
|
||
server_url = server_url.rstrip('/')
|
||
if server_url.endswith('/message'):
|
||
server_url = server_url[:-len('/message')].rstrip('/')
|
||
|
||
# Détection des erreurs courantes de token (jeton Client au lieu d'Application)
|
||
# Dans Gotify v3+, les tokens d'app commencent par 'gtfya.' et les clients par 'gtfyc.'
|
||
# Dans Gotify v2, les tokens d'app commencent par 'A' et les clients par 'C'
|
||
if token.startswith('gtfyc.') or (token.startswith('C') and not token.startswith('gtfya.') and len(token) >= 10):
|
||
raise ValueError(
|
||
"Le token fourni commence par 'gtfyc.' ou 'C' (jeton Client Gotify). "
|
||
"Gotify exige un jeton d'Application créé dans l'onglet 'APPS' "
|
||
"(commençant par 'gtfya.' en v3 ou 'A' en v2) pour publier des alertes."
|
||
)
|
||
|
||
try:
|
||
p = int(cfg.get('priority') or priority or 5)
|
||
except (ValueError, TypeError):
|
||
p = 5
|
||
p = max(0, min(10, p))
|
||
|
||
msg_body = message
|
||
if details and isinstance(details, dict):
|
||
msg_body += '\n\n' + '\n'.join(f'• **{k}** : `{v}`' for k, v in details.items())
|
||
|
||
payload = {
|
||
"title": f"AP Manageur - {title}",
|
||
"message": msg_body,
|
||
"priority": p,
|
||
"extras": {
|
||
"client::display": {
|
||
"contentType": "text/markdown"
|
||
}
|
||
}
|
||
}
|
||
|
||
# Authentification triple : URL param (?token=...) + headers X-Gotify-Key et Authorization: Bearer
|
||
# Assure une compatibilité totale avec Gotify v2 et v3.1.1 et tous reverse-proxies
|
||
post_url = f"{server_url}/message?token={urllib.parse.quote(token)}"
|
||
headers = {
|
||
'Content-Type': 'application/json',
|
||
'X-Gotify-Key': token,
|
||
'Authorization': f'Bearer {token}',
|
||
'User-Agent': 'AP-Manageur/1.0'
|
||
}
|
||
|
||
ctx = None
|
||
if server_url.startswith('https://'):
|
||
ctx = ssl.create_default_context()
|
||
ctx.check_hostname = False
|
||
ctx.verify_mode = ssl.CERT_NONE
|
||
|
||
def _post_payload(p_dict):
|
||
data = json.dumps(p_dict).encode('utf-8')
|
||
req = urllib.request.Request(
|
||
post_url,
|
||
data=data,
|
||
headers=headers,
|
||
method='POST'
|
||
)
|
||
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
|
||
if resp.status not in (200, 201, 202, 204):
|
||
raise RuntimeError(f"Code HTTP Gotify inattendu : {resp.status}")
|
||
return True
|
||
|
||
try:
|
||
return _post_payload(payload)
|
||
except urllib.error.HTTPError as e:
|
||
body = ""
|
||
try:
|
||
body = e.read().decode('utf-8', errors='ignore')
|
||
except Exception:
|
||
pass
|
||
|
||
err_desc = ""
|
||
try:
|
||
err_json = json.loads(body)
|
||
err_desc = err_json.get('errorDescription') or err_json.get('error') or ""
|
||
except Exception:
|
||
err_desc = body[:200] if body else ""
|
||
|
||
# En cas d'erreur 400 (Bad Request), retenter sans extras si un plugin strict le rejette
|
||
if e.code == 400 and 'extras' in payload:
|
||
try:
|
||
simple_payload = {
|
||
"title": f"AP Manageur - {title}",
|
||
"message": msg_body,
|
||
"priority": p
|
||
}
|
||
return _post_payload(simple_payload)
|
||
except Exception:
|
||
pass
|
||
|
||
if e.code == 401:
|
||
raise RuntimeError(
|
||
f"Erreur Gotify 401 (Non autorisé) : {err_desc or 'Jeton non reconnu'}. "
|
||
"Assurez-vous d'utiliser un token créé dans l'onglet 'APPS' de Gotify 3.1.1 (et non dans 'CLIENTS')."
|
||
)
|
||
elif e.code == 403:
|
||
raise RuntimeError(f"Erreur Gotify 403 (Interdit) : {err_desc or 'Accès refusé'}.")
|
||
elif e.code == 404:
|
||
raise RuntimeError(f"Erreur Gotify 404 (Introuvable) : L'adresse '{server_url}/message' est introuvable. Vérifiez l'URL de votre serveur Gotify.")
|
||
elif e.code == 400:
|
||
raise RuntimeError(f"Erreur Gotify 400 (Requête invalide) : {err_desc or 'Message ou titre rejeté'}.")
|
||
else:
|
||
raise RuntimeError(f"Erreur serveur Gotify HTTP {e.code} : {err_desc or e.reason}")
|
||
except urllib.error.URLError as e:
|
||
reason_str = str(e.reason)
|
||
if "Connection refused" in reason_str:
|
||
raise RuntimeError(f"Connexion refusée vers {server_url}. Vérifiez que Gotify est bien démarré et que le port/IP est correct.")
|
||
elif "Name or service not known" in reason_str or "getaddrinfo failed" in reason_str:
|
||
raise RuntimeError(f"Hôte introuvable : Impossible de résoudre '{server_url}'. Vérifiez le nom de domaine.")
|
||
elif "timed out" in reason_str.lower():
|
||
raise RuntimeError(f"Délai d'attente dépassé (10s) en joignant Gotify sur {server_url}.")
|
||
elif "CERTIFICATE_VERIFY_FAILED" in reason_str:
|
||
raise RuntimeError(f"Erreur certificat SSL vers {server_url} : {reason_str}")
|
||
else:
|
||
raise RuntimeError(f"Impossible de joindre Gotify ({server_url}) : {reason_str}")
|
||
|
||
def send_discord_notification(cfg, title, message, details=None, level="info"):
|
||
webhook_url = (cfg.get('webhook_url') or '').strip()
|
||
if not webhook_url or not webhook_url.startswith('http'):
|
||
raise ValueError("URL du Webhook Discord invalide")
|
||
|
||
color_map = {
|
||
"info": 0x38BDF8, # Bleu clair
|
||
"success": 0x32D583, # Vert
|
||
"warning": 0xF6AD55, # Orange
|
||
"danger": 0xFF6B6B # Rouge
|
||
}
|
||
color = color_map.get(level, 0x38BDF8)
|
||
bot_name = (cfg.get('bot_name') or '').strip() or "AP Manageur"
|
||
|
||
fields = []
|
||
if details and isinstance(details, dict):
|
||
for k, v in details.items():
|
||
fields.append({"name": str(k), "value": f"`{v}`" if any(c in str(v) for c in (':', '.')) else str(v), "inline": True})
|
||
|
||
embed = {
|
||
"title": title,
|
||
"description": message,
|
||
"color": color,
|
||
"fields": fields,
|
||
"footer": {
|
||
"text": "AP Manageur • Système de notifications"
|
||
},
|
||
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||
}
|
||
|
||
payload = {
|
||
"username": bot_name,
|
||
"embeds": [embed]
|
||
}
|
||
data = json.dumps(payload).encode('utf-8')
|
||
req = urllib.request.Request(
|
||
webhook_url,
|
||
data=data,
|
||
headers={
|
||
'Content-Type': 'application/json',
|
||
'User-Agent': 'AP-Manageur/1.0'
|
||
},
|
||
method='POST'
|
||
)
|
||
|
||
ctx = None
|
||
if webhook_url.startswith('https://'):
|
||
ctx = ssl.create_default_context()
|
||
ctx.check_hostname = False
|
||
ctx.verify_mode = ssl.CERT_NONE
|
||
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
|
||
if resp.status not in (200, 204):
|
||
raise RuntimeError(f"Code HTTP Discord inattendu : {resp.status}")
|
||
return True
|
||
except urllib.error.HTTPError as e:
|
||
body = ""
|
||
try:
|
||
body = e.read().decode('utf-8', errors='ignore')
|
||
except Exception:
|
||
pass
|
||
err_desc = ""
|
||
try:
|
||
err_json = json.loads(body)
|
||
err_desc = err_json.get('message') or ""
|
||
except Exception:
|
||
err_desc = body[:200] if body else ""
|
||
raise RuntimeError(f"Erreur HTTP Discord {e.code} : {err_desc or e.reason}")
|
||
except urllib.error.URLError as e:
|
||
raise RuntimeError(f"Impossible de joindre Discord : {e.reason}")
|
||
|
||
def send_ntfy_notification(cfg, title, message, details=None, priority=3):
|
||
server_url = (cfg.get('server_url') or '').strip() or 'https://ntfy.sh'
|
||
topic = (cfg.get('topic') or '').strip()
|
||
token = (cfg.get('token') or '').strip()
|
||
if not topic:
|
||
raise ValueError("Topic ntfy manquant")
|
||
|
||
if not (server_url.startswith('http://') or server_url.startswith('https://')):
|
||
server_url = 'https://' + server_url
|
||
server_url = server_url.rstrip('/')
|
||
|
||
post_url = f"{server_url}/{urllib.parse.quote(topic)}"
|
||
|
||
try:
|
||
p = int(cfg.get('priority') or priority or 3)
|
||
except (ValueError, TypeError):
|
||
p = 3
|
||
p = max(1, min(5, p))
|
||
|
||
msg_body = message
|
||
if details and isinstance(details, dict):
|
||
msg_body += "\n\n" + "\n".join(f"• {k} : {v}" for k, v in details.items())
|
||
|
||
payload = {
|
||
"topic": topic,
|
||
"title": f"AP Manageur - {title}",
|
||
"message": msg_body,
|
||
"priority": p,
|
||
"tags": ["warning" if p >= 4 else "bell"]
|
||
}
|
||
|
||
headers = {
|
||
'Content-Type': 'application/json',
|
||
'User-Agent': 'AP-Manageur/1.0'
|
||
}
|
||
if token:
|
||
headers['Authorization'] = f"Bearer {token}"
|
||
|
||
ctx = None
|
||
if server_url.startswith('https://'):
|
||
ctx = ssl.create_default_context()
|
||
ctx.check_hostname = False
|
||
ctx.verify_mode = ssl.CERT_NONE
|
||
|
||
data = json.dumps(payload).encode('utf-8')
|
||
req = urllib.request.Request(post_url, data=data, headers=headers, method='POST')
|
||
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
|
||
if resp.status not in (200, 201, 202, 204):
|
||
raise RuntimeError(f"Code HTTP ntfy inattendu : {resp.status}")
|
||
return True
|
||
except urllib.error.HTTPError as e:
|
||
body = ""
|
||
try: body = e.read().decode('utf-8', errors='ignore')
|
||
except Exception: pass
|
||
raise RuntimeError(f"Erreur HTTP ntfy {e.code} : {body[:200] or e.reason}")
|
||
except urllib.error.URLError as e:
|
||
raise RuntimeError(f"Impossible de joindre ntfy ({server_url}) : {e.reason}")
|
||
|
||
def send_pushbullet_notification(cfg, title, message, details=None):
|
||
token = (cfg.get('api_token') or '').strip()
|
||
if not token:
|
||
raise ValueError("Jeton d'accès (Access Token) Pushbullet manquant")
|
||
|
||
post_url = "https://api.pushbullet.com/v2/pushes"
|
||
body_text = message
|
||
if details and isinstance(details, dict):
|
||
body_text += "\n\n" + "\n".join(f"• {k} : {v}" for k, v in details.items())
|
||
|
||
payload = {
|
||
"type": "note",
|
||
"title": f"AP Manageur - {title}",
|
||
"body": body_text
|
||
}
|
||
device_iden = (cfg.get('device_iden') or '').strip()
|
||
if device_iden:
|
||
payload["device_iden"] = device_iden
|
||
|
||
data = json.dumps(payload).encode('utf-8')
|
||
headers = {
|
||
'Access-Token': token,
|
||
'Content-Type': 'application/json',
|
||
'User-Agent': 'AP-Manageur/1.0'
|
||
}
|
||
|
||
ctx = ssl.create_default_context()
|
||
ctx.check_hostname = False
|
||
ctx.verify_mode = ssl.CERT_NONE
|
||
|
||
req = urllib.request.Request(post_url, data=data, headers=headers, method='POST')
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
|
||
if resp.status not in (200, 201, 204):
|
||
raise RuntimeError(f"Code HTTP Pushbullet inattendu : {resp.status}")
|
||
return True
|
||
except urllib.error.HTTPError as e:
|
||
body = ""
|
||
try: body = e.read().decode('utf-8', errors='ignore')
|
||
except Exception: pass
|
||
raise RuntimeError(f"Erreur HTTP Pushbullet {e.code} : {body[:200] or e.reason}")
|
||
except urllib.error.URLError as e:
|
||
raise RuntimeError(f"Impossible de joindre Pushbullet : {e.reason}")
|
||
|
||
def send_pushover_notification(cfg, title, message, details=None, priority=0):
|
||
user_key = (cfg.get('user_key') or '').strip()
|
||
api_token = (cfg.get('api_token') or '').strip()
|
||
if not user_key:
|
||
raise ValueError("Clé utilisateur (User Key) Pushover manquante")
|
||
if not api_token:
|
||
raise ValueError("Jeton d'application (API Token) Pushover manquant")
|
||
|
||
post_url = "https://api.pushover.net/1/messages.json"
|
||
msg_body = message
|
||
if details and isinstance(details, dict):
|
||
msg_body += "\n\n" + "\n".join(f"• {k} : {v}" for k, v in details.items())
|
||
|
||
try:
|
||
p = int(cfg.get('priority') or priority or 0)
|
||
except (ValueError, TypeError):
|
||
p = 0
|
||
p = max(-2, min(2, p))
|
||
|
||
payload = {
|
||
"token": api_token,
|
||
"user": user_key,
|
||
"title": f"AP Manageur - {title}",
|
||
"message": msg_body,
|
||
"priority": p
|
||
}
|
||
|
||
data = urllib.parse.urlencode(payload).encode('utf-8')
|
||
headers = {
|
||
'Content-Type': 'application/x-www-form-urlencoded',
|
||
'User-Agent': 'AP-Manageur/1.0'
|
||
}
|
||
|
||
ctx = ssl.create_default_context()
|
||
ctx.check_hostname = False
|
||
ctx.verify_mode = ssl.CERT_NONE
|
||
|
||
req = urllib.request.Request(post_url, data=data, headers=headers, method='POST')
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
|
||
if resp.status not in (200, 201):
|
||
raise RuntimeError(f"Code HTTP Pushover inattendu : {resp.status}")
|
||
return True
|
||
except urllib.error.HTTPError as e:
|
||
body = ""
|
||
try: body = e.read().decode('utf-8', errors='ignore')
|
||
except Exception: pass
|
||
raise RuntimeError(f"Erreur HTTP Pushover {e.code} : {body[:200] or e.reason}")
|
||
except urllib.error.URLError as e:
|
||
raise RuntimeError(f"Impossible de joindre Pushover : {e.reason}")
|
||
|
||
def send_slack_notification(cfg, title, message, details=None, level="info"):
|
||
webhook_url = (cfg.get('webhook_url') or '').strip()
|
||
if not webhook_url or not webhook_url.startswith('http'):
|
||
raise ValueError("URL du Webhook entrant Slack invalide")
|
||
|
||
bot_name = (cfg.get('bot_name') or '').strip() or "AP Manageur"
|
||
|
||
color_map = {
|
||
"info": "#38BDF8",
|
||
"success": "#32D583",
|
||
"warning": "#F6AD55",
|
||
"danger": "#FF6B6B"
|
||
}
|
||
color = color_map.get(level, "#38BDF8")
|
||
|
||
fields = []
|
||
if details and isinstance(details, dict):
|
||
for k, v in details.items():
|
||
fields.append({"title": str(k), "value": str(v), "short": True})
|
||
|
||
attachment = {
|
||
"color": color,
|
||
"title": f"AP Manageur - {title}",
|
||
"text": message,
|
||
"fields": fields,
|
||
"footer": "AP Manageur",
|
||
"ts": int(time.time())
|
||
}
|
||
|
||
payload = {
|
||
"username": bot_name,
|
||
"attachments": [attachment]
|
||
}
|
||
|
||
data = json.dumps(payload).encode('utf-8')
|
||
headers = {
|
||
'Content-Type': 'application/json',
|
||
'User-Agent': 'AP-Manageur/1.0'
|
||
}
|
||
|
||
ctx = ssl.create_default_context()
|
||
ctx.check_hostname = False
|
||
ctx.verify_mode = ssl.CERT_NONE
|
||
|
||
req = urllib.request.Request(webhook_url, data=data, headers=headers, method='POST')
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
|
||
if resp.status not in (200, 204):
|
||
raise RuntimeError(f"Code HTTP Slack inattendu : {resp.status}")
|
||
return True
|
||
except urllib.error.HTTPError as e:
|
||
body = ""
|
||
try: body = e.read().decode('utf-8', errors='ignore')
|
||
except Exception: pass
|
||
raise RuntimeError(f"Erreur HTTP Slack {e.code} : {body[:200] or e.reason}")
|
||
except urllib.error.URLError as e:
|
||
raise RuntimeError(f"Impossible de joindre Slack : {e.reason}")
|
||
|
||
def send_telegram_notification(cfg, title, message, details=None):
|
||
bot_token = (cfg.get('bot_token') or '').strip()
|
||
chat_id = (cfg.get('chat_id') or '').strip()
|
||
if not bot_token:
|
||
raise ValueError("Jeton de bot Telegram (Bot Token) manquant")
|
||
if not chat_id:
|
||
raise ValueError("Identifiant de discussion (Chat ID) Telegram manquant")
|
||
|
||
post_url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
|
||
|
||
def escape_html(s):
|
||
return str(s).replace('&', '&').replace('<', '<').replace('>', '>')
|
||
|
||
text = f"<b>{escape_html(title)}</b>\n\n{escape_html(message)}"
|
||
if details and isinstance(details, dict):
|
||
text += "\n\n" + "\n".join(f"• <b>{escape_html(k)}</b> : <code>{escape_html(v)}</code>" for k, v in details.items())
|
||
|
||
payload = {
|
||
"chat_id": chat_id,
|
||
"text": text,
|
||
"parse_mode": "HTML",
|
||
"disable_web_page_preview": True
|
||
}
|
||
thread_id = (cfg.get('thread_id') or '').strip()
|
||
if thread_id:
|
||
try: payload["message_thread_id"] = int(thread_id)
|
||
except (ValueError, TypeError): pass
|
||
|
||
data = json.dumps(payload).encode('utf-8')
|
||
headers = {
|
||
'Content-Type': 'application/json',
|
||
'User-Agent': 'AP-Manageur/1.0'
|
||
}
|
||
|
||
ctx = ssl.create_default_context()
|
||
ctx.check_hostname = False
|
||
ctx.verify_mode = ssl.CERT_NONE
|
||
|
||
req = urllib.request.Request(post_url, data=data, headers=headers, method='POST')
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
|
||
if resp.status not in (200, 201):
|
||
raise RuntimeError(f"Code HTTP Telegram inattendu : {resp.status}")
|
||
return True
|
||
except urllib.error.HTTPError as e:
|
||
body = ""
|
||
try: body = e.read().decode('utf-8', errors='ignore')
|
||
except Exception: pass
|
||
err_msg = ""
|
||
try:
|
||
j = json.loads(body)
|
||
err_msg = j.get('description') or ""
|
||
except Exception:
|
||
err_msg = body[:200]
|
||
raise RuntimeError(f"Erreur HTTP Telegram {e.code} : {err_msg or e.reason}")
|
||
except urllib.error.URLError as e:
|
||
raise RuntimeError(f"Impossible de joindre Telegram : {e.reason}")
|
||
|
||
def send_custom_webhook_notification(cfg, title, message, details=None, level="info"):
|
||
url = (cfg.get('url') or '').strip()
|
||
if not url or not url.startswith('http'):
|
||
raise ValueError("URL du Webhook personnalisé invalide")
|
||
|
||
method = (cfg.get('method') or 'POST').strip().upper()
|
||
if method not in ('POST', 'PUT', 'GET'):
|
||
method = 'POST'
|
||
|
||
headers_str = (cfg.get('headers') or '').strip()
|
||
headers = {
|
||
'User-Agent': 'AP-Manageur/1.0'
|
||
}
|
||
if headers_str:
|
||
try:
|
||
custom_h = json.loads(headers_str)
|
||
if isinstance(custom_h, dict):
|
||
for hk, hv in custom_h.items():
|
||
headers[str(hk)] = str(hv)
|
||
except Exception:
|
||
for line in headers_str.splitlines():
|
||
if ':' in line:
|
||
hk, hv = line.split(':', 1)
|
||
headers[hk.strip()] = hv.strip()
|
||
|
||
payload = {
|
||
"service": "AP Manageur",
|
||
"title": title,
|
||
"message": message,
|
||
"level": level,
|
||
"details": details or {},
|
||
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||
}
|
||
|
||
ctx = None
|
||
if url.startswith('https://'):
|
||
ctx = ssl.create_default_context()
|
||
ctx.check_hostname = False
|
||
ctx.verify_mode = ssl.CERT_NONE
|
||
|
||
if method == 'GET':
|
||
query = urllib.parse.urlencode({"title": title, "message": message})
|
||
final_url = f"{url}{'&' if '?' in url else '?'}{query}"
|
||
req = urllib.request.Request(final_url, headers=headers, method='GET')
|
||
else:
|
||
if 'Content-Type' not in headers:
|
||
headers['Content-Type'] = 'application/json'
|
||
data = json.dumps(payload).encode('utf-8')
|
||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
|
||
if resp.status not in (200, 201, 202, 204):
|
||
raise RuntimeError(f"Code HTTP Webhook inattendu : {resp.status}")
|
||
return True
|
||
except urllib.error.HTTPError as e:
|
||
body = ""
|
||
try: body = e.read().decode('utf-8', errors='ignore')
|
||
except Exception: pass
|
||
raise RuntimeError(f"Erreur HTTP Webhook {e.code} : {body[:200] or e.reason}")
|
||
except urllib.error.URLError as e:
|
||
raise RuntimeError(f"Impossible de joindre le Webhook ({url}) : {e.reason}")
|
||
def test_notifications(channel='all', test_config=None):
|
||
cfg = get_notifications_config()
|
||
all_channels = ('email', 'gotify', 'discord', 'ntfy', 'pushbullet', 'pushover', 'slack', 'telegram', 'webhook')
|
||
if isinstance(test_config, dict):
|
||
for sec in all_channels:
|
||
if sec in test_config and isinstance(test_config[sec], dict):
|
||
if sec == 'email' and not test_config['email'].get('smtp_pass') and cfg.get('email', {}).get('smtp_pass'):
|
||
test_config['email']['smtp_pass'] = cfg['email']['smtp_pass']
|
||
cfg[sec].update(test_config[sec])
|
||
|
||
channel = (channel or 'all').lower()
|
||
results = {}
|
||
|
||
title = "🧪 Notification de test"
|
||
message = "Ceci est un test envoyé depuis le tableau de bord AP Manageur pour vérifier le bon acheminement de vos alertes."
|
||
details = {
|
||
"Statut": "Opérationnel",
|
||
"Horodatage": time.strftime('%d/%m/%Y %H:%M:%S'),
|
||
"Service": f"AP Manageur {APP_VERSION}"
|
||
}
|
||
|
||
if channel in ('all', 'email'):
|
||
if channel == 'email' or cfg.get('email', {}).get('enabled'):
|
||
try:
|
||
send_email_notification(cfg.get('email', {}), title, message, details, level="success")
|
||
results['email'] = {'ok': True, 'message': f"Email envoyé avec succès à {cfg.get('email', {}).get('to_addr')}"}
|
||
except Exception as e:
|
||
results['email'] = {'ok': False, 'error': str(e)}
|
||
|
||
if channel in ('all', 'gotify'):
|
||
if channel == 'gotify' or cfg.get('gotify', {}).get('enabled'):
|
||
try:
|
||
send_gotify_notification(cfg.get('gotify', {}), title, message, details, priority=5)
|
||
results['gotify'] = {'ok': True, 'message': "Message de test Gotify envoyé avec succès"}
|
||
except Exception as e:
|
||
results['gotify'] = {'ok': False, 'error': str(e)}
|
||
|
||
if channel in ('all', 'discord'):
|
||
if channel == 'discord' or cfg.get('discord', {}).get('enabled'):
|
||
try:
|
||
send_discord_notification(cfg.get('discord', {}), title, message, details, level="success")
|
||
results['discord'] = {'ok': True, 'message': "Webhook Discord exécuté avec succès"}
|
||
except Exception as e:
|
||
results['discord'] = {'ok': False, 'error': str(e)}
|
||
|
||
if channel in ('all', 'ntfy'):
|
||
if channel == 'ntfy' or cfg.get('ntfy', {}).get('enabled'):
|
||
try:
|
||
send_ntfy_notification(cfg.get('ntfy', {}), title, message, details, priority=3)
|
||
results['ntfy'] = {'ok': True, 'message': f"Message ntfy envoyé avec succès sur le topic « {cfg.get('ntfy', {}).get('topic')} »"}
|
||
except Exception as e:
|
||
results['ntfy'] = {'ok': False, 'error': str(e)}
|
||
|
||
if channel in ('all', 'pushbullet'):
|
||
if channel == 'pushbullet' or cfg.get('pushbullet', {}).get('enabled'):
|
||
try:
|
||
send_pushbullet_notification(cfg.get('pushbullet', {}), title, message, details)
|
||
results['pushbullet'] = {'ok': True, 'message': "Push Pushbullet envoyé avec succès"}
|
||
except Exception as e:
|
||
results['pushbullet'] = {'ok': False, 'error': str(e)}
|
||
|
||
if channel in ('all', 'pushover'):
|
||
if channel == 'pushover' or cfg.get('pushover', {}).get('enabled'):
|
||
try:
|
||
send_pushover_notification(cfg.get('pushover', {}), title, message, details, priority=0)
|
||
results['pushover'] = {'ok': True, 'message': "Notification Pushover délivrée avec succès"}
|
||
except Exception as e:
|
||
results['pushover'] = {'ok': False, 'error': str(e)}
|
||
|
||
if channel in ('all', 'slack'):
|
||
if channel == 'slack' or cfg.get('slack', {}).get('enabled'):
|
||
try:
|
||
send_slack_notification(cfg.get('slack', {}), title, message, details, level="success")
|
||
results['slack'] = {'ok': True, 'message': "Notification envoyée sur Slack avec succès"}
|
||
except Exception as e:
|
||
results['slack'] = {'ok': False, 'error': str(e)}
|
||
|
||
if channel in ('all', 'telegram'):
|
||
if channel == 'telegram' or cfg.get('telegram', {}).get('enabled'):
|
||
try:
|
||
send_telegram_notification(cfg.get('telegram', {}), title, message, details)
|
||
results['telegram'] = {'ok': True, 'message': f"Message Telegram envoyé avec succès au chat {cfg.get('telegram', {}).get('chat_id')}"}
|
||
except Exception as e:
|
||
results['telegram'] = {'ok': False, 'error': str(e)}
|
||
|
||
if channel in ('all', 'webhook'):
|
||
if channel == 'webhook' or cfg.get('webhook', {}).get('enabled'):
|
||
try:
|
||
send_custom_webhook_notification(cfg.get('webhook', {}), title, message, details, level="success")
|
||
results['webhook'] = {'ok': True, 'message': f"Requête Webhook exécutée avec succès vers {cfg.get('webhook', {}).get('url')}"}
|
||
except Exception as e:
|
||
results['webhook'] = {'ok': False, 'error': str(e)}
|
||
|
||
if not results:
|
||
results['general'] = {'ok': False, 'error': "Aucun canal de notification n'est activé à tester"}
|
||
|
||
return results
|
||
|
||
def dispatch_notification(event_type, title, message, details=None, priority=5, level="info", vars_dict=None, force=False):
|
||
"""Envoie de façon asynchrone la notification aux canaux configurés si l'événement est actif."""
|
||
cfg = get_notifications_config()
|
||
events = cfg.get('events', {})
|
||
|
||
if not force and event_type != 'test' and not events.get(event_type, False):
|
||
return
|
||
|
||
# Préparation des variables de substitution
|
||
safe_vars = {
|
||
'date': time.strftime('%d/%m/%Y %H:%M:%S'),
|
||
'heure': time.strftime('%H:%M:%S'),
|
||
'time': time.strftime('%d/%m/%Y %H:%M:%S')
|
||
}
|
||
if details and isinstance(details, dict):
|
||
for k, v in details.items():
|
||
val_str = str(v)
|
||
safe_vars[str(k).lower()] = val_str
|
||
clean_k = re.sub(r'[^a-zA-Z0-9_]', '', str(k).lower())
|
||
if clean_k:
|
||
safe_vars[clean_k] = val_str
|
||
|
||
if vars_dict and isinstance(vars_dict, dict):
|
||
for k, v in vars_dict.items():
|
||
val_str = str(v)
|
||
safe_vars[str(k).lower()] = val_str
|
||
|
||
# Alias fréquents
|
||
if 'nom' in safe_vars and 'name' not in safe_vars:
|
||
safe_vars['name'] = safe_vars['nom']
|
||
if 'name' in safe_vars and 'nom' not in safe_vars:
|
||
safe_vars['nom'] = safe_vars['name']
|
||
if 'compte' in safe_vars and 'user' not in safe_vars:
|
||
safe_vars['user'] = safe_vars['compte']
|
||
if 'identifiant' in safe_vars and 'user' not in safe_vars:
|
||
safe_vars['user'] = safe_vars['identifiant']
|
||
if 'identifianttente' in safe_vars and 'user' not in safe_vars:
|
||
safe_vars['user'] = safe_vars['identifianttente']
|
||
if 'machine' in safe_vars and 'device' not in safe_vars:
|
||
safe_vars['device'] = safe_vars['machine']
|
||
if 'navigateur' in safe_vars and 'browser' not in safe_vars:
|
||
safe_vars['browser'] = safe_vars['navigateur']
|
||
if 'securite' in safe_vars and 'security' not in safe_vars:
|
||
safe_vars['security'] = safe_vars['securite']
|
||
if 'profilvpn' in safe_vars and 'vpn' not in safe_vars:
|
||
safe_vars['vpn'] = safe_vars['profilvpn']
|
||
if 'profil_vpn' in safe_vars and 'vpn' not in safe_vars:
|
||
safe_vars['vpn'] = safe_vars['profil_vpn']
|
||
if 'vpn_name' in safe_vars and 'vpn' not in safe_vars:
|
||
safe_vars['vpn'] = safe_vars['vpn_name']
|
||
if 'profil' in safe_vars and 'name' not in safe_vars:
|
||
safe_vars['name'] = safe_vars['profil']
|
||
if 'profile' in safe_vars and 'name' not in safe_vars:
|
||
safe_vars['name'] = safe_vars['profile']
|
||
if 'interface' in safe_vars and 'iface' not in safe_vars:
|
||
safe_vars['iface'] = safe_vars['interface']
|
||
if 'consumption' in safe_vars and 'consommation' not in safe_vars:
|
||
safe_vars['consommation'] = safe_vars['consumption']
|
||
if 'consommation' in safe_vars and 'consumption' not in safe_vars:
|
||
safe_vars['consumption'] = safe_vars['consommation']
|
||
if 'usage' in safe_vars and 'consommation' not in safe_vars:
|
||
safe_vars['consommation'] = safe_vars['usage']
|
||
if 'usage' in safe_vars and 'consumption' not in safe_vars:
|
||
safe_vars['consumption'] = safe_vars['usage']
|
||
if 'quota' in safe_vars and 'limite' not in safe_vars:
|
||
safe_vars['limite'] = safe_vars['quota']
|
||
if 'limite' in safe_vars and 'quota' not in safe_vars:
|
||
safe_vars['quota'] = safe_vars['limite']
|
||
|
||
def render_tmpl(text):
|
||
if not text:
|
||
return ""
|
||
return re.sub(r'\{([a-zA-Z0-9_]+)\}', lambda m: safe_vars.get(m.group(1).lower(), '{' + m.group(1) + '}'), text)
|
||
|
||
pref_lang = 'fr'
|
||
try: pref_lang = get_pref('language', 'fr')
|
||
except Exception: pass
|
||
final_title = title
|
||
final_message = message
|
||
if pref_lang and pref_lang.startswith('en'):
|
||
final_title = translate_api_text(final_title, pref_lang)
|
||
final_message = translate_api_text(final_message, pref_lang)
|
||
|
||
templates = cfg.get('templates', {})
|
||
tmpl = templates.get(event_type) if isinstance(templates, dict) else None
|
||
if tmpl and isinstance(tmpl, dict):
|
||
custom_t = (tmpl.get('title') or '').strip()
|
||
custom_m = (tmpl.get('message') or '').strip()
|
||
if custom_t:
|
||
final_title = render_tmpl(custom_t)
|
||
if custom_m:
|
||
final_message = render_tmpl(custom_m)
|
||
|
||
def _worker():
|
||
if cfg.get('email', {}).get('enabled'):
|
||
try:
|
||
send_email_notification(cfg['email'], final_title, final_message, details, level=level)
|
||
print(f"[ap-notif] Email envoyé pour {event_type}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur envoi Email ({event_type}) : {e}", flush=True)
|
||
|
||
if cfg.get('gotify', {}).get('enabled'):
|
||
try:
|
||
send_gotify_notification(cfg['gotify'], final_title, final_message, details, priority=priority)
|
||
print(f"[ap-notif] Gotify envoyé pour {event_type}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur envoi Gotify ({event_type}) : {e}", flush=True)
|
||
|
||
if cfg.get('discord', {}).get('enabled'):
|
||
try:
|
||
send_discord_notification(cfg['discord'], final_title, final_message, details, level=level)
|
||
print(f"[ap-notif] Discord envoyé pour {event_type}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur envoi Discord ({event_type}) : {e}", flush=True)
|
||
|
||
if cfg.get('ntfy', {}).get('enabled'):
|
||
try:
|
||
send_ntfy_notification(cfg['ntfy'], final_title, final_message, details, priority=3)
|
||
print(f"[ap-notif] ntfy envoyé pour {event_type}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur envoi ntfy ({event_type}) : {e}", flush=True)
|
||
|
||
if cfg.get('pushbullet', {}).get('enabled'):
|
||
try:
|
||
send_pushbullet_notification(cfg['pushbullet'], final_title, final_message, details)
|
||
print(f"[ap-notif] Pushbullet envoyé pour {event_type}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur envoi Pushbullet ({event_type}) : {e}", flush=True)
|
||
|
||
if cfg.get('pushover', {}).get('enabled'):
|
||
try:
|
||
send_pushover_notification(cfg['pushover'], final_title, final_message, details, priority=0)
|
||
print(f"[ap-notif] Pushover envoyé pour {event_type}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur envoi Pushover ({event_type}) : {e}", flush=True)
|
||
|
||
if cfg.get('slack', {}).get('enabled'):
|
||
try:
|
||
send_slack_notification(cfg['slack'], final_title, final_message, details, level=level)
|
||
print(f"[ap-notif] Slack envoyé pour {event_type}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur envoi Slack ({event_type}) : {e}", flush=True)
|
||
|
||
if cfg.get('telegram', {}).get('enabled'):
|
||
try:
|
||
send_telegram_notification(cfg['telegram'], final_title, final_message, details)
|
||
print(f"[ap-notif] Telegram envoyé pour {event_type}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur envoi Telegram ({event_type}) : {e}", flush=True)
|
||
|
||
if cfg.get('webhook', {}).get('enabled'):
|
||
try:
|
||
send_custom_webhook_notification(cfg['webhook'], final_title, final_message, details, level=level)
|
||
print(f"[ap-notif] Webhook envoyé pour {event_type}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur envoi Webhook ({event_type}) : {e}", flush=True)
|
||
|
||
threading.Thread(target=_worker, daemon=True).start()
|
||
|
||
def detect_ethernet_interfaces():
|
||
eths = []
|
||
try:
|
||
import glob
|
||
for path in sorted(glob.glob('/sys/class/net/*')):
|
||
iface = os.path.basename(path)
|
||
if iface in ('lo', INTERFACE) or iface.startswith(('docker', 'veth', 'br', 'virbr')):
|
||
continue
|
||
type_file = os.path.join(path, 'type')
|
||
if os.path.exists(type_file):
|
||
try:
|
||
if open(type_file).read().strip() == '1':
|
||
if not os.path.exists(os.path.join(path, 'wireless')) and not os.path.exists(os.path.join(path, 'phy80211')):
|
||
eths.append(iface)
|
||
except OSError: pass
|
||
except Exception: pass
|
||
return eths
|
||
|
||
CREATED_BRIDGE_FILE = '/run/ap-created-bridge'
|
||
|
||
def get_iface_ip_info(iface):
|
||
"""Récupère l'IP CIDR, la passerelle par défaut et la MAC d'une interface."""
|
||
ip_cidr = None
|
||
gw = None
|
||
mac = None
|
||
try:
|
||
out = command('ip', '-4', '-o', 'addr', 'show', 'dev', iface)
|
||
m = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+/\d+)', out)
|
||
if m: ip_cidr = m.group(1)
|
||
except Exception: pass
|
||
try:
|
||
out = command('ip', 'route', 'show', 'default')
|
||
m = re.search(rf'default via (\d+\.\d+\.\d+\.\d+)\s+dev\s+{re.escape(iface)}', out)
|
||
if m: gw = m.group(1)
|
||
except Exception: pass
|
||
try:
|
||
mac_file = f'/sys/class/net/{iface}/address'
|
||
if os.path.exists(mac_file):
|
||
mac = open(mac_file).read().strip()
|
||
except Exception: pass
|
||
return ip_cidr, gw, mac
|
||
|
||
def clean_stale_router_leases():
|
||
"""Supprime les baux dnsmasq obsolètes et nettoie les IP 10.42.x.x en mode pont."""
|
||
global station_live_ips
|
||
try:
|
||
station_live_ips = {k: v for k, v in station_live_ips.items() if not v.startswith('10.42.')}
|
||
except Exception: pass
|
||
import glob
|
||
for lf in glob.glob('/var/lib/NetworkManager/dnsmasq*.leases') + ['/var/lib/misc/dnsmasq.leases']:
|
||
try: open(lf, 'w').close()
|
||
except OSError: pass
|
||
try:
|
||
c = db()
|
||
c.execute("UPDATE client_names SET last_ip='Non attribuée' WHERE last_ip LIKE '10.42.%'")
|
||
c.commit(); c.close()
|
||
except Exception: pass
|
||
try:
|
||
subprocess.run(['ip', 'neigh', 'flush', 'to', '10.42.0.0/16'], capture_output=True)
|
||
subprocess.run(['ip', 'neigh', 'flush', 'dev', INTERFACE], capture_output=True)
|
||
except Exception: pass
|
||
|
||
def find_bin(name):
|
||
if not name: return None
|
||
for candidate in [name, f'/usr/sbin/{name}', f'/sbin/{name}', f'/usr/local/sbin/{name}', f'/usr/bin/{name}', f'/bin/{name}']:
|
||
p = shutil.which(candidate)
|
||
if p and os.path.isfile(p) and os.access(p, os.X_OK):
|
||
return p
|
||
return shutil.which(name) or name
|
||
|
||
def run_cmd(*args):
|
||
if not args: return None
|
||
cmd = list(args)
|
||
cmd[0] = find_bin(cmd[0])
|
||
try:
|
||
return subprocess.run(cmd, capture_output=True)
|
||
except Exception:
|
||
return None
|
||
|
||
def setup_bridge_dns_redirection(bridge_name='br0', iface=None):
|
||
"""Intercepte les requêtes DNS (port 53 UDP/TCP) des clients Wi-Fi en mode pont pour les rediriger vers AP_DNS."""
|
||
iface = iface or INTERFACE
|
||
dns_servers = get_dns_servers()
|
||
if not dns_servers or not iface:
|
||
return
|
||
|
||
# Si l'interface Wi-Fi n'est pas active ou pas encore en mode AP, ne rien faire pour préserver l'hôte
|
||
if not is_iface_up(iface):
|
||
return
|
||
st = command('iw', 'dev', iface, 'info') or ''
|
||
if 'type AP' not in st:
|
||
return
|
||
|
||
try:
|
||
# Redirection DNS propre ciblée UNIQUEMENT sur l'interface Wi-Fi via ebtables broute
|
||
# Cela détourne uniquement le port 53 des clients Wi-Fi vers la couche IP locale
|
||
for proto in ('udp', 'tcp'):
|
||
run_cmd('ebtables', '-t', 'broute', '-D', 'BROUTING', '-i', iface, '-p', 'IPv4', '--ip-proto', proto, '--ip-dport', '53', '-j', 'redirect', '--redirect-target', 'DROP')
|
||
run_cmd('ebtables', '-t', 'broute', '-A', 'BROUTING', '-i', iface, '-p', 'IPv4', '--ip-proto', proto, '--ip-dport', '53', '-j', 'redirect', '--redirect-target', 'DROP')
|
||
|
||
# Chaîne personnalisée de redirection PREROUTING (DNAT) pour l'interface Wi-Fi uniquement
|
||
run_cmd('iptables', '-t', 'nat', '-N', 'AP_BRIDGE_DNS')
|
||
run_cmd('iptables', '-t', 'nat', '-F', 'AP_BRIDGE_DNS')
|
||
|
||
for proto in ('udp', 'tcp'):
|
||
run_cmd('iptables', '-t', 'nat', '-D', 'PREROUTING', '-i', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS')
|
||
run_cmd('iptables', '-t', 'nat', '-I', 'PREROUTING', '1', '-i', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS')
|
||
|
||
# Rediriger vers AP_DNS (avec répartition équitable si plusieurs serveurs)
|
||
n = len(dns_servers)
|
||
for idx, s in enumerate(dns_servers):
|
||
prob = round(1.0 / (n - idx), 4) if idx < n - 1 else None
|
||
for proto in ('udp', 'tcp'):
|
||
cmd = ['iptables', '-t', 'nat', '-A', 'AP_BRIDGE_DNS', '-p', proto, '--dport', '53']
|
||
if prob is not None:
|
||
cmd += ['-m', 'statistic', '--mode', 'random', '--probability', str(prob)]
|
||
cmd += ['-j', 'DNAT', '--to-destination', f"{s}:53"]
|
||
run_cmd(*cmd)
|
||
|
||
print(f"[ap-bridge] Redirection DNS active en mode Pont pour les clients Wi-Fi ({iface}) vers {', '.join(dns_servers)}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-bridge] Erreur configuration redirection DNS : {e}", flush=True)
|
||
|
||
def teardown_bridge_dns_redirection(bridge_name='br0', iface=None):
|
||
"""Nettoie les règles de redirection DNS du mode pont."""
|
||
iface = iface or INTERFACE
|
||
try:
|
||
run_cmd('iptables', '-t', 'nat', '-F', 'AP_BRIDGE_DNS')
|
||
run_cmd('iptables', '-t', 'nat', '-F', 'AP_BRIDGE_DNS_POST')
|
||
for proto in ('udp', 'tcp'):
|
||
if iface:
|
||
run_cmd('iptables', '-t', 'nat', '-D', 'PREROUTING', '-i', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS')
|
||
run_cmd('iptables', '-t', 'nat', '-D', 'PREROUTING', '-m', 'physdev', '--physdev-in', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS')
|
||
run_cmd('iptables', '-t', 'nat', '-D', 'POSTROUTING', '-m', 'physdev', '--physdev-in', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST')
|
||
run_cmd('ebtables', '-t', 'broute', '-D', 'BROUTING', '-i', iface, '-p', 'IPv4', '--ip-proto', proto, '--ip-dport', '53', '-j', 'redirect', '--redirect-target', 'DROP')
|
||
run_cmd('iptables', '-t', 'nat', '-D', 'POSTROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST')
|
||
except Exception:
|
||
pass
|
||
|
||
def setup_bridge(bridge_name='br0', bridge_eth=None):
|
||
bridge_name = bridge_name or 'br0'
|
||
bridge_path = f'/sys/class/net/{bridge_name}'
|
||
|
||
if not bridge_eth:
|
||
bridge_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
|
||
if not bridge_eth:
|
||
candidates = detect_ethernet_interfaces()
|
||
if candidates: bridge_eth = candidates[0]
|
||
|
||
# Vérifier si l'interface Ethernet est déjà asservie à ce pont
|
||
eth_master = None
|
||
if bridge_eth and os.path.exists(f'/sys/class/net/{bridge_eth}/master'):
|
||
try: eth_master = os.path.basename(os.readlink(f'/sys/class/net/{bridge_eth}/master'))
|
||
except OSError: pass
|
||
|
||
bridge_already_existed = os.path.exists(bridge_path)
|
||
|
||
# Si le pont n'existe pas encore au niveau noyau, le créer directement via iproute2 (sans profil NetworkManager)
|
||
if not bridge_already_existed:
|
||
print(f"[ap-bridge] Création sécurisée du pont noyau {bridge_name}...", flush=True)
|
||
subprocess.run(['ip', 'link', 'add', 'name', bridge_name, 'type', 'bridge'], capture_output=True)
|
||
try: open(CREATED_BRIDGE_FILE, 'w').write(f"{bridge_name}:{bridge_eth or ''}")
|
||
except OSError: pass
|
||
|
||
# Asservir l'Ethernet physique s'il n'est pas déjà dans le pont et que le pont n'existait pas déjà avec IP
|
||
has_bridge_ip = bool(get_iface_ip_info(bridge_name)[0])
|
||
if bridge_eth and os.path.exists(f'/sys/class/net/{bridge_eth}') and eth_master != bridge_name and not has_bridge_ip and not bridge_already_existed:
|
||
ip_cidr, gw, mac = get_iface_ip_info(bridge_eth)
|
||
if mac:
|
||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'address', mac], capture_output=True)
|
||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True)
|
||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_eth, 'master', bridge_name], capture_output=True)
|
||
# Transférer l'adresse IP et la passerelle au pont pour ne JAMAIS perdre le ping et l'accès à l'hôte
|
||
if ip_cidr:
|
||
subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_eth], capture_output=True)
|
||
subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', bridge_name], capture_output=True)
|
||
if gw:
|
||
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', bridge_name], capture_output=True)
|
||
print(f"[ap-bridge] Ethernet {bridge_eth} asservi à {bridge_name}. IP {ip_cidr} et passerelle {gw} migrées sur {bridge_name} (Ping préservé).", flush=True)
|
||
else:
|
||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'up'], capture_output=True)
|
||
|
||
try:
|
||
subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True)
|
||
except Exception: pass
|
||
clean_stale_router_leases()
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True)
|
||
setup_bridge_dns_redirection(bridge_name, INTERFACE)
|
||
|
||
def teardown_bridge(bridge_name='br0', bridge_eth=None):
|
||
teardown_bridge_dns_redirection(bridge_name, INTERFACE)
|
||
bridge_name = bridge_name or 'br0'
|
||
bridge_path = f'/sys/class/net/{bridge_name}'
|
||
|
||
was_created_by_us = False
|
||
saved_eth = bridge_eth
|
||
if os.path.exists(CREATED_BRIDGE_FILE):
|
||
try:
|
||
content = open(CREATED_BRIDGE_FILE).read().strip().split(':')
|
||
if content and content[0] == bridge_name:
|
||
was_created_by_us = True
|
||
if len(content) > 1 and content[1]: saved_eth = content[1]
|
||
except Exception: pass
|
||
|
||
conns = command('nmcli', '-t', '-g', 'NAME', 'connection', 'show').splitlines()
|
||
for c in conns:
|
||
if c.startswith(('ap-bridge-eth-', f"ap-bridge-{bridge_name}")):
|
||
subprocess.run(['nmcli', 'connection', 'down', c], capture_output=True)
|
||
subprocess.run(['nmcli', 'connection', 'delete', c], capture_output=True)
|
||
|
||
# Détecter si une interface Ethernet physique de l'hôte est asservie à ce pont
|
||
slaved_eth = None
|
||
eth_candidates = [saved_eth, bridge_eth] + detect_ethernet_interfaces()
|
||
for cand in eth_candidates:
|
||
if cand and os.path.exists(f'/sys/class/net/{cand}/master'):
|
||
try:
|
||
master = os.path.basename(os.readlink(f'/sys/class/net/{cand}/master'))
|
||
if master == bridge_name:
|
||
slaved_eth = cand
|
||
break
|
||
except OSError: pass
|
||
|
||
# Ne restaurer et ne détruire le pont QUE si nous l'avons créé nous-mêmes (préserver impérativement la configuration hôte)
|
||
if was_created_by_us and os.path.exists(bridge_path):
|
||
if slaved_eth:
|
||
ip_cidr, gw, _ = get_iface_ip_info(bridge_name)
|
||
subprocess.run(['ip', 'link', 'set', 'dev', slaved_eth, 'nomaster'], capture_output=True)
|
||
if ip_cidr:
|
||
subprocess.run(['ip', 'addr', 'flush', 'dev', bridge_name], capture_output=True)
|
||
subprocess.run(['ip', 'addr', 'add', ip_cidr, 'dev', slaved_eth], capture_output=True)
|
||
if gw:
|
||
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', slaved_eth], capture_output=True)
|
||
print(f"[ap-bridge] IP {ip_cidr} et passerelle {gw} restaurées sur {slaved_eth}.", flush=True)
|
||
|
||
subprocess.run(['ip', 'link', 'set', 'dev', bridge_name, 'down'], capture_output=True)
|
||
subprocess.run(['ip', 'link', 'delete', 'name', bridge_name, 'type', 'bridge'], capture_output=True)
|
||
print(f"[ap-bridge] Pont créé {bridge_name} nettoyé et supprimé.", flush=True)
|
||
|
||
try:
|
||
if os.path.exists(CREATED_BRIDGE_FILE): os.remove(CREATED_BRIDGE_FILE)
|
||
except OSError: pass
|
||
|
||
_status_cache = {'time': 0, 'data': None}
|
||
_status_cache_lock = threading.Lock()
|
||
|
||
def invalidate_status_cache():
|
||
with _status_cache_lock:
|
||
_status_cache['time'] = 0
|
||
_status_cache['data'] = None
|
||
|
||
def status(force_refresh=False):
|
||
now = time.time()
|
||
with _status_cache_lock:
|
||
if not force_refresh and _status_cache['data'] is not None and (now - _status_cache['time'] < 2.0):
|
||
cached = dict(_status_cache['data'])
|
||
if cached.get('active'):
|
||
cached['uptime_seconds'] = ap_uptime()
|
||
return cached
|
||
|
||
name = connection_name(); ssid = command('nmcli','-t','-g','802-11-wireless.ssid','connection','show',name) if name else ''
|
||
password = command('nmcli','--show-secrets','-t','-g','802-11-wireless-security.psk','connection','show',name) if name else ''
|
||
key = command('nmcli','-t','-g','802-11-wireless-security.key-mgmt','connection','show',name).lower() if name else ''
|
||
proto = command('nmcli','-t','-g','802-11-wireless-security.proto','connection','show',name).lower() if name else ''
|
||
sec = 'wpa3' if key == 'sae' else 'wpa1' if proto == 'wpa' else 'wpa2'
|
||
state = command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE)
|
||
# CORRECTION : "30 (disconnected)" contient "connected" ; seul le code 100 signifie connecté.
|
||
active = state.startswith('100')
|
||
auto = command('nmcli','-t','-g','connection.autoconnect','connection','show',name).lower() == 'yes' if name else False
|
||
if active and uptime_start() is None:
|
||
mark_ap_started()
|
||
slave_type = (command('nmcli','-t','-g','connection.slave-type','connection','show',name) or command('nmcli','-t','-g','connection.port-type','connection','show',name)).lower() if name else ''
|
||
master = (command('nmcli','-t','-g','connection.master','connection','show',name) or command('nmcli','-t','-g','connection.controller','connection','show',name)) if name else ''
|
||
mode = current_mode()
|
||
b_name = master or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
|
||
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
|
||
res = {'ssid':ssid or 'SSID inconnu','password':password,'security':sec,'autoconnect':auto,'mode':mode,'bridge_name':b_name,'bridge_eth':b_eth,'ethernet_interfaces':detect_ethernet_interfaces(),'interface':INTERFACE,'connection':name,'active':active,'configured':bool(name),'uptime_seconds':ap_uptime() if active else 0,'max_clients':get_max_clients(),'dns':get_dns_servers(),'is_starting':not app_startup_done,'boot_time':SERVER_BOOT_TIME}
|
||
with _status_cache_lock:
|
||
_status_cache['time'] = now
|
||
_status_cache['data'] = res
|
||
return res
|
||
|
||
def blocked_set():
|
||
c = db(); rows = c.execute('SELECT mac FROM blocked_clients').fetchall(); c.close(); return {r[0] for r in rows}
|
||
|
||
station_live_ips = {}
|
||
|
||
def arp_listener():
|
||
"""Écoute passivement les trames réseau (IPv4 et ARP) pour capturer en temps réel l'IP réelle des clients."""
|
||
try:
|
||
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
|
||
except Exception as e:
|
||
print(f"[ap-arp] Écouteur réseau passif indisponible : {e}", flush=True)
|
||
return
|
||
while True:
|
||
try:
|
||
raw = s.recv(2048)
|
||
if len(raw) < 14: continue
|
||
eth_type = raw[12:14]
|
||
is_bridge = is_bridge_mode()
|
||
|
||
# 1. Trame IPv4 (0x0800)
|
||
if eth_type == b'\x08\x00' and len(raw) >= 34:
|
||
smac = ':'.join(f'{b:02x}' for b in raw[6:12]).upper()
|
||
sip = socket.inet_ntoa(raw[26:30])
|
||
if sip and not sip.startswith(('0.', '127.', '169.254.', '255.')):
|
||
if is_bridge and sip.startswith('10.42.'):
|
||
continue
|
||
if not is_bridge and not sip.startswith('10.42.'):
|
||
continue
|
||
station_live_ips[smac] = sip
|
||
|
||
# 2. Trame ARP (0x0806)
|
||
elif eth_type == b'\x08\x06' and len(raw) >= 42:
|
||
smac = ':'.join(f'{b:02x}' for b in raw[22:28]).upper()
|
||
sip = socket.inet_ntoa(raw[28:32])
|
||
if sip and not sip.startswith(('0.', '127.', '169.254.', '255.')):
|
||
if is_bridge and sip.startswith('10.42.'):
|
||
continue
|
||
if not is_bridge and not sip.startswith('10.42.'):
|
||
continue
|
||
station_live_ips[smac] = sip
|
||
except Exception:
|
||
time.sleep(0.2)
|
||
|
||
def lease_ip(mac):
|
||
mac = (mac or '').upper()
|
||
if is_bridge_mode(): return ''
|
||
for l_mac, l_ip, _ in reversed(lease_entries()):
|
||
if l_mac == mac and re.fullmatch(r'\d{1,3}(?:\.\d{1,3}){3}', l_ip): return l_ip
|
||
return ''
|
||
|
||
def clients():
|
||
is_bridge = is_bridge_mode()
|
||
if is_bridge:
|
||
for k in list(station_live_ips.keys()):
|
||
if station_live_ips[k].startswith('10.42.'):
|
||
del station_live_ips[k]
|
||
|
||
vpn_routes = {}
|
||
vpn_profiles = {}
|
||
custom_types = {}
|
||
try:
|
||
c_vpn = db()
|
||
for row in c_vpn.execute('SELECT mac, profile_id, kill_switch FROM client_vpn_routes').fetchall():
|
||
vpn_routes[row[0].upper()] = {'profile_id': row[1], 'kill_switch': row[2]}
|
||
for row in c_vpn.execute('SELECT id, name, type, status, iface FROM vpn_profiles').fetchall():
|
||
vpn_profiles[row[0]] = {'name': row[1], 'type': row[2], 'status': row[3], 'iface': row[4]}
|
||
cn_cols = {r[1] for r in c_vpn.execute('PRAGMA table_info(client_names)').fetchall()}
|
||
if 'device_type' in cn_cols:
|
||
for row in c_vpn.execute('SELECT mac, COALESCE(device_type, "") FROM client_names').fetchall():
|
||
if row[0] and row[1]:
|
||
custom_types[row[0].upper()] = row[1]
|
||
c_vpn.close()
|
||
except Exception: pass
|
||
|
||
neigh = command('ip','neigh','show'); ipmac = {}
|
||
for line in neigh.splitlines():
|
||
m = re.search(r'^(\S+).*?lladdr ([0-9a-f:]{17})', line, re.I)
|
||
if m:
|
||
nip = m.group(1)
|
||
nmac = m.group(2).upper()
|
||
if is_bridge and nip.startswith('10.42.'):
|
||
continue
|
||
if not is_bridge and not nip.startswith('10.42.'):
|
||
continue
|
||
if 'FAILED' in line:
|
||
continue
|
||
ipmac[nmac] = nip
|
||
|
||
output = []; dump = command('iw','dev',INTERFACE,'station','dump'); blocked_macs = blocked_set()
|
||
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.
|
||
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
|
||
sm = re.search(r'^\s*signal:\s*(-?\d+)', detail, re.I|re.M)
|
||
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)
|
||
raw_rx = int(rx_m.group(1)) if rx_m else 0
|
||
raw_tx = int(tx_m.group(1)) if tx_m else 0
|
||
now_ts = time.time()
|
||
|
||
rx_rate = 0.0
|
||
tx_rate = 0.0
|
||
delta_rx = 0
|
||
delta_tx = 0
|
||
|
||
with traffic_lock:
|
||
prev = station_traffic.get(mac)
|
||
if prev:
|
||
dt = now_ts - prev['last_time']
|
||
if dt >= 0.8:
|
||
delta_rx = raw_rx - prev['last_rx'] if raw_rx >= prev['last_rx'] else raw_rx
|
||
delta_tx = raw_tx - prev['last_tx'] if raw_tx >= prev['last_tx'] else raw_tx
|
||
rx_rate = delta_rx / dt
|
||
tx_rate = delta_tx / dt
|
||
station_traffic[mac] = {
|
||
'last_rx': raw_rx,
|
||
'last_tx': raw_tx,
|
||
'last_time': now_ts,
|
||
'rx_rate': rx_rate,
|
||
'tx_rate': tx_rate
|
||
}
|
||
else:
|
||
rx_rate = prev['rx_rate']
|
||
tx_rate = prev['tx_rate']
|
||
else:
|
||
delta_rx = raw_rx
|
||
delta_tx = raw_tx
|
||
station_traffic[mac] = {
|
||
'last_rx': raw_rx,
|
||
'last_tx': raw_tx,
|
||
'last_time': now_ts,
|
||
'rx_rate': 0.0,
|
||
'tx_rate': 0.0
|
||
}
|
||
|
||
if delta_rx > 0 or delta_tx > 0:
|
||
try:
|
||
c = db()
|
||
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
today_str = time.strftime('%Y-%m-%d')
|
||
c.execute('''
|
||
INSERT INTO client_traffic(mac, rx_bytes, tx_bytes, last_updated)
|
||
VALUES(?, ?, ?, ?)
|
||
ON CONFLICT(mac) DO UPDATE SET
|
||
rx_bytes = client_traffic.rx_bytes + excluded.rx_bytes,
|
||
tx_bytes = client_traffic.tx_bytes + excluded.tx_bytes,
|
||
last_updated = excluded.last_updated
|
||
''', (mac, delta_rx, delta_tx, now_str))
|
||
c.execute('''
|
||
INSERT INTO client_traffic_daily(mac, traffic_date, rx_bytes, tx_bytes)
|
||
VALUES(?, ?, ?, ?)
|
||
ON CONFLICT(mac, traffic_date) DO UPDATE SET
|
||
rx_bytes = client_traffic_daily.rx_bytes + excluded.rx_bytes,
|
||
tx_bytes = client_traffic_daily.tx_bytes + excluded.tx_bytes
|
||
''', (mac, today_str, delta_rx, delta_tx))
|
||
c.commit()
|
||
c.close()
|
||
except Exception as e:
|
||
print(f"[ap-error] Erreur sauvegarde client_traffic: {e}", flush=True)
|
||
|
||
# 1. IP capturée en direct par l'écouteur réseau ou par la table des voisins
|
||
ip = station_live_ips.get(mac, '') or ipmac.get(mac, '')
|
||
if not ip and not is_bridge:
|
||
ip = lease_ip(mac)
|
||
|
||
# 2. Historique base de données (si non obsolète)
|
||
if not ip:
|
||
try:
|
||
c = db(); row = c.execute('SELECT last_ip FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
|
||
if row and row[0] and row[0] != 'Non attribuée':
|
||
saved_ip = row[0]
|
||
if is_bridge and not saved_ip.startswith('10.42.'):
|
||
ip = saved_ip
|
||
elif not is_bridge and saved_ip.startswith('10.42.'):
|
||
ip = saved_ip
|
||
except sqlite3.Error: pass
|
||
|
||
if not ip or (is_bridge and ip.startswith('10.42.')):
|
||
ip = 'Non attribuée'
|
||
|
||
blocked = mac in blocked_macs; name = device_name(ip if ip != 'Non attribuée' else '', mac)
|
||
if not name.startswith('Client ') and name != 'Nom non communiqué':
|
||
try:
|
||
c = db(); c.execute('INSERT INTO client_names(mac,name,last_ip,last_seen) VALUES(?,?,?,?) ON CONFLICT(mac) DO UPDATE SET name=excluded.name,last_ip=CASE WHEN excluded.last_ip != \'Non attribuée\' THEN excluded.last_ip ELSE client_names.last_ip END,last_seen=excluded.last_seen', (mac,name,ip,time.strftime('%Y-%m-%d %H:%M:%S'))); c.commit(); c.close()
|
||
except sqlite3.Error: pass
|
||
elif ip != 'Non attribuée':
|
||
try:
|
||
c = db(); c.execute('UPDATE client_names SET last_ip=?,last_seen=? WHERE mac=?', (ip,time.strftime('%Y-%m-%d %H:%M:%S'),mac)); c.commit(); c.close()
|
||
except sqlite3.Error: pass
|
||
|
||
vroute = vpn_routes.get(mac)
|
||
vpid = vroute['profile_id'] if vroute else 0
|
||
vprof = vpn_profiles.get(vpid) if vpid > 0 else None
|
||
v_is_up = bool(vprof and vprof['status'] == 'connected' and is_iface_up(vprof['iface']))
|
||
v_pub_ip = vpn_public_ip_cache.get(vprof['iface'], {}).get('ip', '') if (vprof and v_is_up) else ''
|
||
v_pub_geo = get_ip_geo(v_pub_ip) if v_pub_ip else None
|
||
|
||
output.append({
|
||
'name': name,
|
||
'ip': ip,
|
||
'mac': mac,
|
||
'device_type': custom_types.get(mac) or guess_device_type(name, mac),
|
||
'signal_dbm': int(sm.group(1)) if sm else None,
|
||
'blocked': blocked,
|
||
'connected': not blocked,
|
||
'download_speed': round(tx_rate),
|
||
'upload_speed': round(rx_rate),
|
||
'download_speed_str': format_speed(tx_rate),
|
||
'upload_speed_str': format_speed(rx_rate),
|
||
'raw_rx': raw_rx,
|
||
'raw_tx': raw_tx,
|
||
'vpn_profile_id': vpid,
|
||
'vpn_profile_name': vprof['name'] if vprof else '',
|
||
'vpn_profile_type': vprof['type'] if vprof else '',
|
||
'vpn_profile_status': vprof['status'] if vprof else '',
|
||
'vpn_routed': v_is_up,
|
||
'lan_isolated': v_is_up,
|
||
'vpn_public_ip': v_pub_ip,
|
||
'vpn_public_ip_geo': v_pub_geo,
|
||
'kill_switch': vroute['kill_switch'] if vroute else 0,
|
||
'limits': get_client_limits_dict(mac)
|
||
})
|
||
return output
|
||
|
||
def known_device(mac):
|
||
name, ip = '', 'Non attribuée'
|
||
is_bridge = is_bridge_mode()
|
||
try:
|
||
c = db(); row = c.execute('SELECT name,last_ip FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
|
||
if row:
|
||
name = row[0] or ''
|
||
saved_ip = row[1] or ''
|
||
if is_bridge and saved_ip.startswith('10.42.'):
|
||
saved_ip = ''
|
||
elif not is_bridge and not saved_ip.startswith('10.42.'):
|
||
saved_ip = ''
|
||
ip = saved_ip or ip
|
||
except sqlite3.Error: pass
|
||
return name or device_name(ip, mac), ip
|
||
|
||
def set_blocked(mac, blocked):
|
||
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)
|
||
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():
|
||
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()
|
||
return [{'mac':r[0],'blocked_at':r[1],'name':r[2] or 'Client ' + r[0].replace(':', '')[-4:]} for r in rows]
|
||
|
||
quota_alerted_macs = set()
|
||
last_sync_limits_time = 0
|
||
limits_lock = threading.RLock()
|
||
|
||
def get_client_traffic_usage(mac, period='total'):
|
||
mac = (mac or '').upper()
|
||
c = db()
|
||
try:
|
||
if period == 'daily':
|
||
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()
|
||
return int(row[0]) if row and row[0] is not None else 0
|
||
elif period == 'monthly':
|
||
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()
|
||
return int(row[0]) if row and row[0] is not None else 0
|
||
else:
|
||
row = c.execute("SELECT rx_bytes + tx_bytes FROM client_traffic WHERE mac=?", (mac,)).fetchone()
|
||
return int(row[0]) if row and row[0] is not None else 0
|
||
except Exception:
|
||
return 0
|
||
finally:
|
||
c.close()
|
||
|
||
def get_client_limits_dict(target_mac=None):
|
||
c = db()
|
||
try:
|
||
has_table = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='client_limits'").fetchone())
|
||
if not has_table: return None if target_mac else {}
|
||
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 = ()
|
||
if target_mac:
|
||
query += " WHERE mac=?"
|
||
params = (target_mac.upper(),)
|
||
rows = c.execute(query, params).fetchall()
|
||
res = {}
|
||
for r in rows:
|
||
m = (r[0] or '').upper()
|
||
q_en = bool(r[1])
|
||
q_bytes = int(r[2] or 0)
|
||
q_period = r[3] or 'total'
|
||
bw_en = bool(r[4])
|
||
r_down = int(r[5] or 0)
|
||
r_up = int(r[6] or 0)
|
||
usage = get_client_traffic_usage(m, q_period)
|
||
exceeded = q_en and q_bytes > 0 and usage >= q_bytes
|
||
pct = min(100.0, round((usage / q_bytes) * 100.0, 1)) if (q_bytes > 0) else 0.0
|
||
remaining = max(0, q_bytes - usage) if q_bytes > 0 else 0
|
||
res[m] = {
|
||
'mac': m,
|
||
'quota_enabled': q_en,
|
||
'quota_bytes': q_bytes,
|
||
'quota_bytes_str': format_bytes(q_bytes) if q_bytes > 0 else 'Illimité',
|
||
'quota_period': q_period,
|
||
'quota_period_label': 'Total cumulé' if q_period == 'total' else ('Par mois' if q_period == 'monthly' else 'Par jour'),
|
||
'bandwidth_enabled': bw_en,
|
||
'rate_down_kbps': r_down,
|
||
'rate_up_kbps': r_up,
|
||
'rate_down_str': f"{r_down // 1000} Mbps" if r_down >= 1000 else (f"{r_down} Kbps" if r_down > 0 else 'Illimité'),
|
||
'rate_up_str': f"{r_up // 1000} Mbps" if r_up >= 1000 else (f"{r_up} Kbps" if r_up > 0 else 'Illimité'),
|
||
'usage_bytes': usage,
|
||
'usage_bytes_str': format_bytes(usage),
|
||
'usage_percent': pct,
|
||
'remaining_bytes': remaining,
|
||
'remaining_bytes_str': format_bytes(remaining),
|
||
'quota_exceeded': exceeded,
|
||
'quota_action': r[7] or 'block',
|
||
'updated_at': r[8] or ''
|
||
}
|
||
return res.get(target_mac.upper()) if target_mac else res
|
||
except Exception as e:
|
||
print(f"[ap-limits] Erreur get_client_limits_dict: {e}", flush=True)
|
||
return None if target_mac else {}
|
||
finally:
|
||
c.close()
|
||
|
||
def save_client_limits(mac, data):
|
||
mac = (mac or '').strip().upper()
|
||
if not re.fullmatch(r'[0-9A-F]{2}(:[0-9A-F]{2}){5}', mac):
|
||
raise ValueError('Adresse MAC invalide')
|
||
|
||
quota_enabled = 1 if data.get('quota_enabled') else 0
|
||
try: quota_bytes = max(0, int(data.get('quota_bytes', 0)))
|
||
except (ValueError, TypeError): quota_bytes = 0
|
||
quota_period = str(data.get('quota_period', 'total')).strip().lower()
|
||
if quota_period not in ('total', 'daily', 'monthly'): quota_period = 'total'
|
||
|
||
bandwidth_enabled = 1 if data.get('bandwidth_enabled') else 0
|
||
try: rate_down_kbps = max(0, int(data.get('rate_down_kbps', 0)))
|
||
except (ValueError, TypeError): rate_down_kbps = 0
|
||
try: rate_up_kbps = max(0, int(data.get('rate_up_kbps', 0)))
|
||
except (ValueError, TypeError): rate_up_kbps = 0
|
||
quota_action = str(data.get('quota_action', 'block')).strip().lower()
|
||
|
||
reset_usage = bool(data.get('reset_usage', False))
|
||
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
|
||
c = db()
|
||
try:
|
||
if reset_usage:
|
||
c.execute("UPDATE client_traffic SET rx_bytes=0, tx_bytes=0 WHERE mac=?", (mac,))
|
||
today_str = time.strftime('%Y-%m-%d')
|
||
c.execute("UPDATE client_traffic_daily SET rx_bytes=0, tx_bytes=0 WHERE mac=? AND traffic_date=?", (mac, today_str))
|
||
if mac in quota_alerted_macs:
|
||
quota_alerted_macs.discard(mac)
|
||
|
||
c.execute('''
|
||
INSERT INTO client_limits (mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||
ON CONFLICT(mac) DO UPDATE SET
|
||
quota_enabled=excluded.quota_enabled,
|
||
quota_bytes=excluded.quota_bytes,
|
||
quota_period=excluded.quota_period,
|
||
bandwidth_enabled=excluded.bandwidth_enabled,
|
||
rate_down_kbps=excluded.rate_down_kbps,
|
||
rate_up_kbps=excluded.rate_up_kbps,
|
||
quota_action=excluded.quota_action,
|
||
updated_at=excluded.updated_at
|
||
''', (mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, now_str))
|
||
c.commit()
|
||
finally:
|
||
c.close()
|
||
|
||
threading.Thread(target=sync_client_bandwidth_and_quotas, kwargs={'force': True}, daemon=True).start()
|
||
return get_client_limits_dict(mac)
|
||
|
||
last_applied_limits_state = None
|
||
|
||
def sync_client_bandwidth_and_quotas(force=False):
|
||
global last_sync_limits_time, last_applied_limits_state
|
||
now_ts = time.time()
|
||
if not force and now_ts - last_sync_limits_time < 3:
|
||
return
|
||
last_sync_limits_time = now_ts
|
||
|
||
with limits_lock:
|
||
try:
|
||
c = db()
|
||
has_table = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='client_limits'").fetchone())
|
||
if not has_table:
|
||
c.close()
|
||
return
|
||
|
||
rows = c.execute("SELECT mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action FROM client_limits").fetchall()
|
||
c.close()
|
||
|
||
limits = {}
|
||
for r in rows:
|
||
limits[r[0].upper()] = {
|
||
'quota_enabled': bool(r[1]),
|
||
'quota_bytes': int(r[2] or 0),
|
||
'quota_period': r[3] or 'total',
|
||
'bandwidth_enabled': bool(r[4]),
|
||
'rate_down_kbps': int(r[5] or 0),
|
||
'rate_up_kbps': int(r[6] or 0),
|
||
'quota_action': r[7] or 'block'
|
||
}
|
||
|
||
# 1. Vérifier les quotas dépassés et appareils bloqués
|
||
quota_blocked_macs = set()
|
||
mac_to_ip = get_all_mac_to_ips()
|
||
|
||
for mac, lim in limits.items():
|
||
if lim['quota_enabled'] and lim['quota_bytes'] > 0:
|
||
usage = get_client_traffic_usage(mac, lim['quota_period'])
|
||
if usage >= lim['quota_bytes']:
|
||
quota_blocked_macs.add(mac)
|
||
if mac not in quota_alerted_macs:
|
||
quota_alerted_macs.add(mac)
|
||
name, ip = known_device(mac)
|
||
q_str = format_bytes(lim['quota_bytes'])
|
||
u_str = format_bytes(usage)
|
||
msg = f"L'appareil « {name} » ({ip or mac}) a dépassé son quota de {q_str} (consommé : {u_str}). L'accès Internet a été coupé."
|
||
log('quota_depasse', name, ip, mac)
|
||
dispatch_notification(
|
||
'quota_exceeded',
|
||
"⚠️ Quota de données dépassé",
|
||
msg,
|
||
details={
|
||
"Nom": name,
|
||
"IP": ip or "—",
|
||
"MAC": mac,
|
||
"Quota": q_str,
|
||
"Consommation": u_str,
|
||
"Action": "Accès Internet coupé"
|
||
},
|
||
priority=5,
|
||
level="warning",
|
||
vars_dict={
|
||
"name": name,
|
||
"nom": name,
|
||
"ip": ip or "—",
|
||
"mac": mac,
|
||
"quota": q_str,
|
||
"consumption": u_str,
|
||
"consommation": u_str,
|
||
"usage": u_str,
|
||
"action": "L'accès Internet a été coupé"
|
||
}
|
||
)
|
||
else:
|
||
if mac in quota_alerted_macs:
|
||
quota_alerted_macs.discard(mac)
|
||
|
||
try:
|
||
manually_blocked = blocked_set()
|
||
except Exception:
|
||
manually_blocked = set()
|
||
|
||
all_blocked_macs = set(quota_blocked_macs) | set(manually_blocked)
|
||
|
||
active_rate_limits = {
|
||
mac: lim for mac, lim in limits.items()
|
||
if lim['bandwidth_enabled'] and (lim['rate_down_kbps'] > 0 or lim['rate_up_kbps'] > 0)
|
||
}
|
||
|
||
# Optimisation majeure : si l'état des blocages et débits n'a pas changé, éviter de relancer les sous-processus système
|
||
current_state = (
|
||
frozenset(all_blocked_macs),
|
||
frozenset((m, lim['rate_down_kbps'], lim['rate_up_kbps']) for m, lim in active_rate_limits.items()),
|
||
tuple(sorted((m, mac_to_ip.get(m, '')) for m in all_blocked_macs | set(active_rate_limits.keys())))
|
||
)
|
||
if not force and last_applied_limits_state == current_state:
|
||
return
|
||
last_applied_limits_state = current_state
|
||
|
||
# 2. Couche 2 Pont Ethernet (L2 Bridge) : nftables family bridge (Priorité -350, avant le broute VPN -300)
|
||
nft_bin = find_bin('nft')
|
||
if nft_bin:
|
||
try:
|
||
if all_blocked_macs:
|
||
nft_cmds = [
|
||
"add table bridge ap_quota_block",
|
||
"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)
|
||
"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",
|
||
"add rule bridge ap_quota_block forward ether type ip udp sport 67-68 udp dport 67-68 accept",
|
||
"add rule bridge ap_quota_block prerouting ether type ip6 udp sport 546-547 udp dport 546-547 accept",
|
||
"add rule bridge ap_quota_block forward ether type ip6 udp sport 546-547 udp dport 546-547 accept",
|
||
"add rule bridge ap_quota_block prerouting ether type ip6 icmpv6 type { 133, 134, 135, 136 } accept",
|
||
"add rule bridge ap_quota_block forward ether type ip6 icmpv6 type { 133, 134, 135, 136 } accept",
|
||
]
|
||
for b_mac in all_blocked_macs:
|
||
cm = b_mac.strip().lower()
|
||
if cm:
|
||
nft_cmds.append(f"add rule bridge ap_quota_block prerouting ether saddr {cm} drop")
|
||
nft_cmds.append(f"add rule bridge ap_quota_block prerouting ether daddr {cm} drop")
|
||
nft_cmds.append(f"add rule bridge ap_quota_block forward ether saddr {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)
|
||
else:
|
||
subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_quota_block'], capture_output=True, timeout=3)
|
||
except Exception as e:
|
||
print(f"[ap-limits] Erreur nftables bridge : {e}", flush=True)
|
||
|
||
# 3. Couche 2 Pont Ethernet (L2 Bridge) : ebtables (avec --concurrent)
|
||
ebtables_bin = find_bin('ebtables')
|
||
if ebtables_bin:
|
||
try:
|
||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-N', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-F', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-D', 'FORWARD', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-D', 'INPUT', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
if all_blocked_macs:
|
||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-I', 'FORWARD', '1', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-I', 'INPUT', '1', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-p', 'ARP', '-j', 'ACCEPT'], capture_output=True, timeout=5)
|
||
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=5)
|
||
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=5)
|
||
for b_mac in all_blocked_macs:
|
||
cm = b_mac.strip().lower()
|
||
if cm:
|
||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-s', cm, '-j', 'DROP'], capture_output=True, timeout=5)
|
||
subprocess.run([ebtables_bin, '--concurrent', '-t', 'filter', '-A', 'AP_QUOTA_BLOCK', '-d', cm, '-j', 'DROP'], capture_output=True, timeout=5)
|
||
except Exception as e:
|
||
print(f"[ap-limits] Erreur ebtables : {e}", flush=True)
|
||
|
||
# 4. Couche 3 (IPv4 & IPv6) : iptables et ip6tables (filter & mangle avec verrou -w 5 et test -C)
|
||
iptables_bin = find_bin('iptables')
|
||
ip6tables_bin = find_bin('ip6tables')
|
||
for bin_cmd, is_v6 in [(iptables_bin, False), (ip6tables_bin, True)]:
|
||
if not bin_cmd: continue
|
||
try:
|
||
for tbl, chain in [('filter', 'FORWARD'), ('filter', 'INPUT'), ('mangle', 'PREROUTING')]:
|
||
# Créer et vider la chaîne
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-N', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-F', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
|
||
# Vérifier si la règle de saut existe
|
||
check_r = subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-C', chain, '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
has_jump = (check_r.returncode == 0)
|
||
|
||
if all_blocked_macs:
|
||
if not has_jump:
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-I', chain, '1', '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
else:
|
||
if has_jump:
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-D', chain, '-j', 'AP_QUOTA_BLOCK'], capture_output=True, timeout=5)
|
||
|
||
if all_blocked_macs:
|
||
if not is_v6:
|
||
for tbl in ['filter', 'mangle']:
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'udp', '--dport', '67:68', '-j', 'RETURN'], capture_output=True, timeout=5)
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'udp', '--sport', '67:68', '-j', 'RETURN'], capture_output=True, timeout=5)
|
||
else:
|
||
for tbl in ['filter', 'mangle']:
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'udp', '--dport', '546:547', '-j', 'RETURN'], capture_output=True, timeout=5)
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'udp', '--sport', '546:547', '-j', 'RETURN'], capture_output=True, timeout=5)
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-p', 'ipv6-icmp', '-j', 'RETURN'], capture_output=True, timeout=5)
|
||
|
||
for b_mac in all_blocked_macs:
|
||
cm = b_mac.strip().lower()
|
||
if cm:
|
||
for tbl in ['filter', 'mangle']:
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-m', 'mac', '--mac-source', cm, '-j', 'DROP'], capture_output=True, timeout=5)
|
||
if not is_v6:
|
||
ip = mac_to_ip.get(b_mac)
|
||
if ip and ip not in ('Non attribuée', '—'):
|
||
for tbl in ['filter', 'mangle']:
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-s', ip, '-j', 'DROP'], capture_output=True, timeout=5)
|
||
subprocess.run([bin_cmd, '-w', '5', '-t', tbl, '-A', 'AP_QUOTA_BLOCK', '-d', ip, '-j', 'DROP'], capture_output=True, timeout=5)
|
||
except Exception as e:
|
||
print(f"[ap-limits] Erreur iptables/ip6tables ({bin_cmd}) : {e}", flush=True)
|
||
|
||
# 5. Maintenir le filtrage isolé pour ne pas impacter la résolution de l'hôte
|
||
if all_blocked_macs:
|
||
try:
|
||
subprocess.run(['sysctl', '-w', 'net.bridge.bridge-nf-call-iptables=0'], capture_output=True, timeout=3)
|
||
subprocess.run(['sysctl', '-w', 'net.bridge.bridge-nf-call-ip6tables=0'], capture_output=True, timeout=3)
|
||
except Exception: pass
|
||
|
||
# 6. Limitation de bande passante & Drop direct avec Traffic Control (tc)
|
||
tc_bin = find_bin('tc')
|
||
target_iface = INTERFACE
|
||
if tc_bin and target_iface:
|
||
try:
|
||
subprocess.run([tc_bin, 'qdisc', 'del', 'dev', target_iface, 'root'], capture_output=True, timeout=3)
|
||
subprocess.run([tc_bin, 'qdisc', 'del', 'dev', target_iface, 'ingress'], capture_output=True, timeout=3)
|
||
except Exception: pass
|
||
|
||
if active_rate_limits or all_blocked_macs:
|
||
subprocess.run([tc_bin, 'qdisc', 'add', 'dev', target_iface, 'root', 'handle', '1:', 'htb', 'default', '999'], capture_output=True, timeout=3)
|
||
subprocess.run([tc_bin, 'class', 'add', 'dev', target_iface, 'parent', '1:', 'classid', '1:999', 'htb', 'rate', '1000mbit', 'ceil', '1000mbit'], capture_output=True, timeout=3)
|
||
subprocess.run([tc_bin, 'qdisc', 'add', 'dev', target_iface, 'handle', 'ffff:', 'ingress'], capture_output=True, timeout=3)
|
||
|
||
# Pour chaque client bloqué : drop immédiat en TC (ingress et egress)
|
||
for b_mac in all_blocked_macs:
|
||
b_ip = mac_to_ip.get(b_mac)
|
||
if b_ip and b_ip not in ('Non attribuée', '—'):
|
||
subprocess.run([
|
||
tc_bin, 'filter', 'add', 'dev', target_iface, 'parent', 'ffff:', 'protocol', 'ip', 'prio', '1',
|
||
'u32', 'match', 'ip', 'src', b_ip, 'action', 'drop'
|
||
], capture_output=True, timeout=3)
|
||
subprocess.run([
|
||
tc_bin, 'filter', 'add', 'dev', target_iface, 'parent', '1:', 'protocol', 'ip', 'prio', '1',
|
||
'u32', 'match', 'ip', 'dst', b_ip, 'action', 'drop'
|
||
], capture_output=True, timeout=3)
|
||
|
||
cls_idx = 10
|
||
for mac, lim in active_rate_limits.items():
|
||
if mac in all_blocked_macs:
|
||
continue
|
||
ip = mac_to_ip.get(mac)
|
||
if not ip or ip in ('Non attribuée', '—'):
|
||
continue
|
||
|
||
if lim['rate_down_kbps'] > 0:
|
||
rate_str = f"{lim['rate_down_kbps']}kbit"
|
||
class_id = f"1:{cls_idx}"
|
||
subprocess.run([tc_bin, 'class', 'add', 'dev', target_iface, 'parent', '1:', 'classid', class_id, 'htb', 'rate', rate_str, 'ceil', rate_str], capture_output=True, timeout=3)
|
||
subprocess.run([tc_bin, 'filter', 'add', 'dev', target_iface, 'protocol', 'ip', 'parent', '1:', 'prio', '2', 'u32', 'match', 'ip', 'dst', ip, 'flowid', class_id], capture_output=True, timeout=3)
|
||
cls_idx += 1
|
||
|
||
if lim['rate_up_kbps'] > 0:
|
||
rate_str = f"{lim['rate_up_kbps']}kbit"
|
||
burst_str = f"{max(32, lim['rate_up_kbps'] // 8)}k"
|
||
subprocess.run([
|
||
tc_bin, 'filter', 'add', 'dev', target_iface, 'parent', 'ffff:', 'protocol', 'ip', 'prio', '2',
|
||
'u32', 'match', 'ip', 'src', ip,
|
||
'police', 'rate', rate_str, 'burst', burst_str, 'drop', 'flowid', ':1'
|
||
], capture_output=True, timeout=3)
|
||
|
||
# 7. Conntrack flush : coupe immédiatement les flux et téléchargements en cours
|
||
conntrack_bin = find_bin('conntrack')
|
||
if conntrack_bin and all_blocked_macs:
|
||
for b_mac in all_blocked_macs:
|
||
b_ip = mac_to_ip.get(b_mac)
|
||
if b_ip and b_ip not in ('Non attribuée', '—'):
|
||
subprocess.run([conntrack_bin, '-D', '-s', b_ip], capture_output=True, timeout=3)
|
||
subprocess.run([conntrack_bin, '-D', '-d', b_ip], capture_output=True, timeout=3)
|
||
except Exception as e:
|
||
print(f"[ap-limits] Erreur synchronisation quotas & débits : {e}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-limits] Erreur synchronisation quotas & débits : {e}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-limits] Erreur synchronisation quotas & débits : {e}", flush=True)
|
||
|
||
def all_devices(lang='fr'):
|
||
"""Récupère l'ensemble des équipements qui se sont déjà connectés au réseau depuis la base de données SQLite."""
|
||
is_en = str(lang or '').lower().startswith('en')
|
||
c = db()
|
||
names_dict = {}
|
||
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
|
||
has_dev_type = 'device_type' in cn_cols
|
||
query = 'SELECT mac, name, last_ip, last_seen, COALESCE(device_type, "") FROM client_names' if has_dev_type else 'SELECT mac, name, last_ip, last_seen, "" FROM client_names'
|
||
for r in c.execute(query).fetchall():
|
||
m = (r[0] or '').upper()
|
||
if m:
|
||
names_dict[m] = {
|
||
'name': r[1] or '',
|
||
'last_ip': r[2] or '',
|
||
'last_seen': r[3] or '',
|
||
'device_type': r[4] or ''
|
||
}
|
||
|
||
logs_dict = {}
|
||
try:
|
||
rows = c.execute('''
|
||
SELECT mac, MIN(event_time), MAX(event_time),
|
||
(SELECT name FROM connection_logs WHERE mac = l.mac AND name != '' AND name != 'Nom non communiqué' ORDER BY id DESC LIMIT 1),
|
||
(SELECT ip FROM connection_logs WHERE mac = l.mac AND ip != '' AND ip != 'Non attribuée' ORDER BY id DESC LIMIT 1)
|
||
FROM connection_logs l
|
||
WHERE mac LIKE '%:%'
|
||
GROUP BY mac
|
||
''').fetchall()
|
||
for r in rows:
|
||
m = (r[0] or '').upper()
|
||
if m:
|
||
logs_dict[m] = {
|
||
'first_seen': r[1] or '',
|
||
'last_seen': r[2] or '',
|
||
'name': r[3] or '',
|
||
'last_ip': r[4] or ''
|
||
}
|
||
except Exception: pass
|
||
|
||
blocked_dict = {}
|
||
try:
|
||
for r in c.execute('SELECT mac, blocked_at FROM blocked_clients').fetchall():
|
||
m = (r[0] or '').upper()
|
||
if m: blocked_dict[m] = r[1] or ''
|
||
except Exception: pass
|
||
|
||
vpn_routes = {}
|
||
try:
|
||
p_dict = dict(c.execute('SELECT id, name FROM vpn_profiles').fetchall())
|
||
for r in c.execute('SELECT mac, profile_id FROM client_vpn_routes WHERE profile_id > 0').fetchall():
|
||
m = (r[0] or '').upper()
|
||
if m: vpn_routes[m] = {'profile_id': r[1], 'profile_name': p_dict.get(r[1], 'VPN')}
|
||
except Exception: pass
|
||
|
||
traffic_dict = {}
|
||
try:
|
||
for r in c.execute('SELECT mac, rx_bytes, tx_bytes FROM client_traffic').fetchall():
|
||
m = (r[0] or '').upper()
|
||
if m:
|
||
rx = r[1] or 0
|
||
tx = r[2] or 0
|
||
traffic_dict[m] = {'rx': rx, 'tx': tx, 'total': rx + tx}
|
||
except Exception: pass
|
||
|
||
c.close()
|
||
limits_dict = get_client_limits_dict() or {}
|
||
|
||
live_clients = {}
|
||
try:
|
||
for cl in clients():
|
||
m = (cl.get('mac') or '').upper()
|
||
if m: live_clients[m] = cl
|
||
except Exception: pass
|
||
|
||
all_macs = sorted(set(names_dict.keys()) | set(logs_dict.keys()) | set(blocked_dict.keys()) | set(live_clients.keys()) | set(limits_dict.keys()))
|
||
|
||
devices = []
|
||
for mac in all_macs:
|
||
live = live_clients.get(mac)
|
||
is_conn = live is not None
|
||
is_block = mac in blocked_dict
|
||
|
||
nd = names_dict.get(mac, {})
|
||
ld = logs_dict.get(mac, {})
|
||
td = traffic_dict.get(mac, {'rx': 0, 'tx': 0, 'total': 0})
|
||
vd = vpn_routes.get(mac)
|
||
|
||
name = ''
|
||
if live and live.get('name') and live['name'] not in ('Nom non communiqué', 'Inconnu'):
|
||
name = live['name']
|
||
if not name and nd.get('name') and nd['name'] not in ('Nom non communiqué', 'Inconnu'):
|
||
name = nd['name']
|
||
if not name and ld.get('name'):
|
||
name = ld['name']
|
||
if not name:
|
||
name = 'Client ' + mac.replace(':', '')[-4:]
|
||
|
||
ip = ''
|
||
if live and live.get('ip') and live['ip'] not in ('Non attribuée', '—'):
|
||
ip = live['ip']
|
||
if not ip and nd.get('last_ip') and nd['last_ip'] not in ('Non attribuée', '—'):
|
||
ip = nd['last_ip']
|
||
if not ip and ld.get('last_ip') and ld['last_ip'] not in ('Non attribuée', '—'):
|
||
ip = ld['last_ip']
|
||
if not ip:
|
||
ip = 'Non attribuée'
|
||
|
||
first_seen = ld.get('first_seen') or nd.get('last_seen') or '—'
|
||
last_seen = nd.get('last_seen') or ld.get('last_seen') or '—'
|
||
online_label = 'Currently online' if is_en else 'Actuellement en ligne'
|
||
unknown_label = 'Unknown' if is_en else 'Inconnue'
|
||
last_seen_str = online_label if is_conn else (last_seen if last_seen != '—' else unknown_label)
|
||
|
||
custom_type = nd.get('device_type') or (live.get('device_type') if live else '')
|
||
dev_type = custom_type if custom_type else guess_device_type(name, mac)
|
||
|
||
devices.append({
|
||
'mac': mac,
|
||
'name': name,
|
||
'ip': ip,
|
||
'connected': is_conn,
|
||
'status': 'connected' if is_conn else 'offline',
|
||
'blocked': is_block,
|
||
'blocked_at': blocked_dict.get(mac, ''),
|
||
'first_seen': first_seen,
|
||
'last_seen': last_seen,
|
||
'last_seen_display': last_seen_str,
|
||
'device_type': dev_type,
|
||
'signal_dbm': live.get('signal_dbm') if live else None,
|
||
'download_speed_str': live.get('download_speed_str', '') if live else '',
|
||
'upload_speed_str': live.get('upload_speed_str', '') if live else '',
|
||
'traffic_total_str': format_bytes(td['total']) if td['total'] > 0 else '0 o',
|
||
'traffic_total_bytes': td['total'],
|
||
'vpn_profile_name': vd['profile_name'] if vd else '',
|
||
'limits': limits_dict.get(mac, None)
|
||
})
|
||
|
||
def _dev_sort(d):
|
||
conn_rank = 0 if d['connected'] else 1
|
||
ts = 0
|
||
ls = d.get('last_seen') or ''
|
||
if re.match(r'^\d{4}-\d{2}-\d{2}', ls):
|
||
try: ts = time.mktime(time.strptime(ls, '%Y-%m-%d %H:%M:%S'))
|
||
except Exception: pass
|
||
return (conn_rank, -ts, d['name'].lower())
|
||
|
||
devices.sort(key=_dev_sort)
|
||
|
||
return {
|
||
'devices': devices,
|
||
'total': len(devices),
|
||
'connected_count': sum(1 for d in devices if d['connected']),
|
||
'offline_count': sum(1 for d in devices if not d['connected']),
|
||
'blocked_count': sum(1 for d in devices if d['blocked'])
|
||
}
|
||
|
||
def get_default_gateway():
|
||
try:
|
||
res = command('ip', 'route', 'show', 'default')
|
||
m = re.search(r'default via (\S+)(?: dev (\S+))?', res)
|
||
if m:
|
||
return {'gateway_ip': m.group(1), 'interface': m.group(2) or ''}
|
||
except Exception: pass
|
||
try:
|
||
with open('/proc/net/route') as f:
|
||
for line in f:
|
||
fields = line.strip().split()
|
||
if len(fields) >= 3 and fields[1] == '00000000':
|
||
gw_hex = fields[2]
|
||
gw_ip = socket.inet_ntoa(struct.pack('<L', int(gw_hex, 16)))
|
||
return {'gateway_ip': gw_ip, 'interface': fields[0]}
|
||
except Exception: pass
|
||
return {'gateway_ip': '', 'interface': ''}
|
||
|
||
def get_ap_ip(interface):
|
||
try:
|
||
res = command('ip', '-4', 'addr', 'show', 'dev', interface)
|
||
m = re.search(r'inet (\d+\.\d+\.\d+\.\d+)/(\d+)', res)
|
||
if m:
|
||
return {'ip': m.group(1), 'cidr': m.group(2)}
|
||
except Exception: pass
|
||
return {'ip': '', 'cidr': ''}
|
||
|
||
def get_wifi_channel_freq(interface):
|
||
try:
|
||
res = command('iw', 'dev', interface, 'info')
|
||
m = re.search(r'channel\s+(\d+)\s*\(([\d\.]+)\s*MHz\)', res)
|
||
if m:
|
||
return {'channel': int(m.group(1)), 'freq_mhz': float(m.group(2))}
|
||
m_freq = re.search(r'frequency\s+(\d+)', res)
|
||
if m_freq:
|
||
f = int(m_freq.group(1))
|
||
ch = (f - 2407) // 5 if f < 2500 else (f - 5000) // 5
|
||
return {'channel': ch, 'freq_mhz': f}
|
||
except Exception: pass
|
||
return {'channel': 6, 'freq_mhz': 2437}
|
||
|
||
def get_dns_servers():
|
||
env_dns = os.environ.get('AP_DNS', '').strip()
|
||
if env_dns:
|
||
parts = [p.strip() for p in re.split(r'[,;\s]+', env_dns) if p.strip()]
|
||
if parts:
|
||
return parts
|
||
dns = []
|
||
try:
|
||
with open('/etc/resolv.conf') as f:
|
||
for line in f:
|
||
if line.startswith('nameserver'):
|
||
parts = line.split()
|
||
if len(parts) >= 2 and parts[1] not in ('127.0.0.1', '127.0.0.53'):
|
||
dns.append(parts[1])
|
||
except Exception: pass
|
||
return dns or ['1.1.1.1', '8.8.8.8']
|
||
|
||
def guess_device_type(name, mac=''):
|
||
n = (name or '').lower()
|
||
if any(k in n for k in ('iphone', 'android', 'galaxy', 'pixel', 'xiaomi', 'redmi', 'huawei', 'oneplus', 'oppo', 'mobile', 'smartphone', 'sm-')):
|
||
return 'phone'
|
||
if any(k in n for k in ('ipad', 'tablet', 'tab', 'kindle')):
|
||
return 'tablet'
|
||
if any(k in n for k in ('macbook', 'laptop', 'portable', 'thinkpad', 'zenbook', 'notebook', 'dell-xps', 'hp-envy', 'surface')):
|
||
return 'laptop'
|
||
if any(k in n for k in ('pc', 'desktop', 'bureau', 'workstation', 'imac', 'mac-pro', 'tower')):
|
||
return 'desktop'
|
||
if any(k in n for k in ('tv', 'chromecast', 'roku', 'firestick', 'apple-tv', 'bravia', 'smarttv', 'shield')):
|
||
return 'tv'
|
||
if any(k in n for k in ('playstation', 'ps4', 'ps5', 'xbox', 'switch', 'nintendo')):
|
||
return 'console'
|
||
if any(k in n for k in ('esp_', 'esp32', 'esp8266', 'tasmota', 'shelly', 'camera', 'cam', 'printer', 'imprimante', 'nas', 'synology', 'raspberry', 'rpi')):
|
||
return 'iot'
|
||
return 'generic'
|
||
|
||
def compute_topology_internal(active_items=None, active_status=None):
|
||
st = active_status if active_status is not None else status()
|
||
cl = active_items if active_items is not None else clients()
|
||
bl = blocked_list()
|
||
gw = get_default_gateway()
|
||
iface = st.get('interface') or INTERFACE
|
||
ap_net = get_ap_ip(iface)
|
||
wifi_radio = get_wifi_channel_freq(iface)
|
||
dns = get_dns_servers()
|
||
|
||
total_rx_rate = 0
|
||
total_tx_rate = 0
|
||
|
||
for c in cl:
|
||
c['device_type'] = c.get('device_type') or guess_device_type(c.get('name', ''), c.get('mac', ''))
|
||
sig = c.get('signal_dbm')
|
||
if sig is None:
|
||
c['signal_rating'] = 'Inconnu'
|
||
c['signal_level'] = 0
|
||
elif sig >= -50:
|
||
c['signal_rating'] = 'Excellent'
|
||
c['signal_level'] = 4
|
||
elif sig >= -60:
|
||
c['signal_rating'] = 'Bon'
|
||
c['signal_level'] = 3
|
||
elif sig >= -70:
|
||
c['signal_rating'] = 'Moyen'
|
||
c['signal_level'] = 2
|
||
else:
|
||
c['signal_rating'] = 'Faible'
|
||
c['signal_level'] = 1
|
||
total_rx_rate += c.get('upload_speed', 0)
|
||
total_tx_rate += c.get('download_speed', 0)
|
||
|
||
wan_ip = gw.get('gateway_ip') or ('192.168.1.1' if not is_bridge_mode() else 'Passerelle LAN')
|
||
wan_if = gw.get('interface') or ('eth0' if os.path.exists('/sys/class/net/eth0') else 'WAN')
|
||
|
||
vpn_profiles_list = []
|
||
try:
|
||
c_topo = db()
|
||
p_rows = c_topo.execute('SELECT id, name, type, status, iface, table_id FROM vpn_profiles').fetchall()
|
||
c_topo.close()
|
||
for pid, pname, ptype, pstatus, piface, ptable in p_rows:
|
||
piface = piface or (f"wg_ap{pid}" if ptype == "wireguard" else f"tun_ap{pid}")
|
||
is_up = bool(pstatus == 'connected' and is_iface_up(piface))
|
||
client_macs = [c['mac'] for c in cl if c.get('vpn_profile_id') == pid and c.get('vpn_routed')]
|
||
pub_ip = vpn_public_ip_cache.get(piface, {}).get('ip', '') if is_up else ''
|
||
pub_geo = get_ip_geo(pub_ip) if pub_ip else None
|
||
vpn_profiles_list.append({
|
||
'id': pid,
|
||
'name': pname,
|
||
'type': ptype,
|
||
'status': 'connected' if is_up else 'disconnected',
|
||
'iface': piface,
|
||
'table_id': ptable,
|
||
'public_ip': pub_ip,
|
||
'public_ip_geo': pub_geo,
|
||
'connected': is_up,
|
||
'client_count': len(client_macs),
|
||
'client_macs': client_macs
|
||
})
|
||
except Exception as e:
|
||
print(f"[ap-error] Erreur récupération vpn_profiles topologie: {e}", flush=True)
|
||
|
||
now_str = time.strftime('%H:%M:%S')
|
||
return {
|
||
'internet': {
|
||
'status': 'online' if st.get('active') else 'standby',
|
||
'gateway_ip': wan_ip,
|
||
'interface': wan_if,
|
||
'dns': dns,
|
||
},
|
||
'vpn_profiles': vpn_profiles_list,
|
||
'active_vpn_count': sum(1 for p in vpn_profiles_list if p.get('connected')),
|
||
'ap': {
|
||
'ssid': st.get('ssid') or 'AP Wi-Fi',
|
||
'active': st.get('active', False),
|
||
'interface': iface,
|
||
'ip': ap_net.get('ip') or ('10.42.0.1' if st.get('mode') == 'nat' else 'IP Pont LAN'),
|
||
'cidr': ap_net.get('cidr') or '24',
|
||
'mode': 'NAT (Routeur Wi-Fi)' if st.get('mode') == 'nat' else 'Pont réseau (Bridge)',
|
||
'mode_key': 'nat' if st.get('mode') == 'nat' else 'bridge',
|
||
'channel': wifi_radio.get('channel') or 6,
|
||
'frequency_mhz': wifi_radio.get('freq_mhz') or 2437,
|
||
'band': '5 GHz' if (wifi_radio.get('freq_mhz') or 0) > 4000 else '2.4 GHz',
|
||
'uptime_seconds': st.get('uptime_seconds', 0),
|
||
'security': st.get('security', 'wpa2').upper(),
|
||
'max_clients': st.get('max_clients', 30)
|
||
},
|
||
'clients': cl,
|
||
'blocked': bl,
|
||
'blocked_count': len(bl),
|
||
'total_clients_count': len(cl),
|
||
'total_download_rate': total_tx_rate,
|
||
'total_upload_rate': total_rx_rate,
|
||
'total_download_str': format_speed(total_tx_rate),
|
||
'total_upload_str': format_speed(total_rx_rate),
|
||
'updated_at': now_str,
|
||
'analyzed_at': now_str,
|
||
'background_analyzed': True,
|
||
'analysis_count': _metrics_count,
|
||
'analysis_duration_ms': _metrics_last_duration_ms
|
||
}
|
||
|
||
def network_topology():
|
||
with _metrics_lock:
|
||
if _cached_topology is not None:
|
||
return _cached_topology
|
||
return compute_topology_internal()
|
||
|
||
def update_background_metrics(items=None, st=None):
|
||
global _cached_stats, _cached_topology, _metrics_count, _metrics_last_duration_ms, _metrics_last_time
|
||
t0 = time.time()
|
||
try:
|
||
active_items = items if items is not None else clients()
|
||
active_status = st if st is not None else status()
|
||
|
||
new_stats = compute_stats_internal(active_items)
|
||
new_topo = compute_topology_internal(active_items, active_status)
|
||
|
||
_metrics_count += 1
|
||
_metrics_last_duration_ms = max(1, int((time.time() - t0) * 1000))
|
||
_metrics_last_time = time.time()
|
||
|
||
new_stats['analysis_count'] = _metrics_count
|
||
new_stats['analysis_duration_ms'] = _metrics_last_duration_ms
|
||
new_topo['analysis_count'] = _metrics_count
|
||
new_topo['analysis_duration_ms'] = _metrics_last_duration_ms
|
||
|
||
with _metrics_lock:
|
||
_cached_stats = new_stats
|
||
_cached_topology = new_topo
|
||
except Exception as e:
|
||
print(f"[ap-metrics] Erreur analyse métriques arrière-plan : {e}", flush=True)
|
||
|
||
def match_cron_field(pattern, value):
|
||
pattern = pattern.strip()
|
||
if pattern == '*':
|
||
return True
|
||
for part in pattern.split(','):
|
||
part = part.strip()
|
||
if not part:
|
||
continue
|
||
if '/' in part:
|
||
sub, step_str = part.split('/', 1)
|
||
try: step = int(step_str)
|
||
except ValueError: continue
|
||
if step <= 0: continue
|
||
if sub == '*':
|
||
if value % step == 0:
|
||
return True
|
||
elif '-' in sub:
|
||
try:
|
||
s_str, e_str = sub.split('-', 1)
|
||
start, end = int(s_str), int(e_str)
|
||
if start <= value <= end and (value - start) % step == 0:
|
||
return True
|
||
except ValueError: pass
|
||
elif '-' in part:
|
||
try:
|
||
s_str, e_str = part.split('-', 1)
|
||
start, end = int(s_str), int(e_str)
|
||
if start <= value <= end:
|
||
return True
|
||
except ValueError: pass
|
||
else:
|
||
try:
|
||
if int(part) == value:
|
||
return True
|
||
except ValueError: pass
|
||
return False
|
||
|
||
def match_cron(expr, dt):
|
||
"""Vérifie si un objet datetime correspond à l'expression cron (min heure dom mois dow)."""
|
||
parts = expr.strip().split()
|
||
if len(parts) != 5:
|
||
return False
|
||
min_pat, hour_pat, dom_pat, month_pat, dow_pat = parts
|
||
if not match_cron_field(min_pat, dt.minute):
|
||
return False
|
||
if not match_cron_field(hour_pat, dt.hour):
|
||
return False
|
||
if not match_cron_field(dom_pat, dt.day):
|
||
return False
|
||
if not match_cron_field(month_pat, dt.month):
|
||
return False
|
||
cron_dow = (dt.weekday() + 1) % 7 # Sunday=0, Monday=1..Saturday=6
|
||
if not match_cron_field(dow_pat, cron_dow):
|
||
if cron_dow == 0 and match_cron_field(dow_pat, 7):
|
||
return True
|
||
return False
|
||
return True
|
||
|
||
def format_top_clients_text(c_list, limit=5):
|
||
items = []
|
||
compact_items = []
|
||
valid = [c for c in c_list if c.get('total_bytes', 0) > 0]
|
||
to_show = valid[:limit] if valid else c_list[:limit]
|
||
for idx, c in enumerate(to_show, 1):
|
||
c_name = c.get('name') or c.get('mac', 'Inconnu')
|
||
tot = c.get('total_str', '0 o')
|
||
dl = c.get('download_str', '0 o')
|
||
ul = c.get('upload_str', '0 o')
|
||
status_dot = "🟢 " if c.get('connected') else "⚪ "
|
||
items.append(f" {idx}. {status_dot}{c_name} : {tot} (↓ {dl} • ↑ {ul})")
|
||
compact_items.append(f"{idx}. {c_name} ({tot})")
|
||
text_out = "\n".join(items) if items else " Aucun transfert enregistré"
|
||
compact = ", ".join(compact_items) if compact_items else "Aucun transfert enregistré"
|
||
return text_out, compact
|
||
|
||
def generate_stats_report_vars(top_range=None):
|
||
"""Rassemble toutes les variables dynamiques pour le message de rapport de statistiques et métriques."""
|
||
cfg = get_notifications_config()
|
||
sched = cfg.get('stats_report_schedule', {})
|
||
if not top_range:
|
||
top_range = sched.get('top_range', 'day')
|
||
top_range = str(top_range).strip().lower()
|
||
if top_range not in ('day', 'week', 'month', 'year', 'all_ranges'):
|
||
top_range = 'day'
|
||
|
||
st_data = stats()
|
||
topo_data = network_topology()
|
||
st = status()
|
||
|
||
summary = st_data.get('summary', {})
|
||
today_info = summary.get('today', {})
|
||
week_info = summary.get('week', {})
|
||
month_info = summary.get('month', {})
|
||
year_info = summary.get('year', {})
|
||
|
||
clients_list = clients()
|
||
clients_cnt = len(clients_list)
|
||
|
||
vpn_profs = topo_data.get('vpn_profiles', [])
|
||
active_vpn_cnt = sum(1 for p in vpn_profs if p.get('connected'))
|
||
vpn_clients_cnt = sum(1 for c in clients_list if c.get('vpn_active') or c.get('profile_id'))
|
||
|
||
inet = topo_data.get('internet', {})
|
||
gw_online = inet.get('status') == 'online'
|
||
gw_status_str = "En ligne" if gw_online else "En veille / Hors ligne"
|
||
gw_ip = inet.get('gateway_ip') or '192.168.1.1'
|
||
|
||
ap_info = topo_data.get('ap', {})
|
||
ssid = ap_info.get('ssid', 'AP Wi-Fi')
|
||
chan = ap_info.get('channel', 6)
|
||
band = ap_info.get('band', '2.4 GHz')
|
||
mode = ap_info.get('mode', 'NAT')
|
||
|
||
now_dt = datetime.datetime.now()
|
||
date_str = now_dt.strftime('%d/%m/%Y %H:%M:%S')
|
||
heure_str = now_dt.strftime('%H:%M:%S')
|
||
|
||
down_str = topo_data.get('total_download_str', '0 o/s')
|
||
up_str = topo_data.get('total_upload_str', '0 o/s')
|
||
|
||
# Calcul des top clients pour chaque période (Jour, Semaine, Mois, Année)
|
||
tc_day = get_top_clients(clients_list, 'day')
|
||
tc_week = get_top_clients(clients_list, 'week')
|
||
tc_month = get_top_clients(clients_list, 'month')
|
||
tc_year = get_top_clients(clients_list, 'year')
|
||
|
||
top_day_str, top_day_compact = format_top_clients_text(tc_day)
|
||
top_week_str, top_week_compact = format_top_clients_text(tc_week)
|
||
top_month_str, top_month_compact = format_top_clients_text(tc_month)
|
||
top_year_str, top_year_compact = format_top_clients_text(tc_year)
|
||
|
||
top_all_ranges_str = (
|
||
"• Top Aujourd'hui :\n" + top_day_str + "\n"
|
||
"• Top Cette semaine :\n" + top_week_str + "\n"
|
||
"• Top Ce mois-ci :\n" + top_month_str + "\n"
|
||
"• Top Cette année :\n" + top_year_str
|
||
)
|
||
top_all_ranges_compact = (
|
||
f"Jour: {top_day_compact} | Sem.: {top_week_compact} | Mois: {top_month_compact} | An: {top_year_compact}"
|
||
)
|
||
|
||
range_map = {
|
||
'day': (top_day_str, top_day_compact, "Aujourd'hui"),
|
||
'week': (top_week_str, top_week_compact, "Cette semaine"),
|
||
'month': (top_month_str, top_month_compact, "Ce mois-ci"),
|
||
'year': (top_year_str, top_year_compact, "Cette année"),
|
||
'all_ranges': (top_all_ranges_str, top_all_ranges_compact, "Toutes périodes")
|
||
}
|
||
|
||
selected_top_str, selected_top_compact, selected_label = range_map.get(top_range, (top_day_str, top_day_compact, "Aujourd'hui"))
|
||
|
||
return {
|
||
'clients_count': str(clients_cnt),
|
||
'clients': str(clients_cnt),
|
||
'today_unique': str(today_info.get('unique', 0)),
|
||
'today_total': str(today_info.get('total', 0)),
|
||
'week_unique': str(week_info.get('unique', 0)),
|
||
'week_total': str(week_info.get('total', 0)),
|
||
'month_unique': str(month_info.get('unique', 0)),
|
||
'month_total': str(month_info.get('total', 0)),
|
||
'year_unique': str(year_info.get('unique', 0)),
|
||
'year_total': str(year_info.get('total', 0)),
|
||
'traffic_down': down_str,
|
||
'traffic_up': up_str,
|
||
'download_rate': down_str,
|
||
'upload_rate': up_str,
|
||
'active_vpns': str(active_vpn_cnt),
|
||
'vpn_count': str(active_vpn_cnt),
|
||
'vpn_routed_clients': str(vpn_clients_cnt),
|
||
'gateway_status': gw_status_str,
|
||
'gateway_ip': str(gw_ip),
|
||
'ssid': str(ssid),
|
||
'channel': str(chan),
|
||
'band': str(band),
|
||
'mode': str(mode),
|
||
# Période active / sélectionnée
|
||
'top_clients': selected_top_str,
|
||
'top_clients_compact': selected_top_compact,
|
||
'top_conso': selected_top_str,
|
||
'top_consommation': selected_top_str,
|
||
'top_range_label': selected_label,
|
||
# Spécifique Jour
|
||
'top_clients_day': top_day_str,
|
||
'top_clients_day_compact': top_day_compact,
|
||
'top_jour': top_day_str,
|
||
'top_day': top_day_str,
|
||
# Spécifique Semaine
|
||
'top_clients_week': top_week_str,
|
||
'top_clients_week_compact': top_week_compact,
|
||
'top_semaine': top_week_str,
|
||
'top_week': top_week_str,
|
||
# Spécifique Mois
|
||
'top_clients_month': top_month_str,
|
||
'top_clients_month_compact': top_month_compact,
|
||
'top_mois': top_month_str,
|
||
'top_month': top_month_str,
|
||
# Spécifique Année
|
||
'top_clients_year': top_year_str,
|
||
'top_clients_year_compact': top_year_compact,
|
||
'top_annee': top_year_str,
|
||
'top_year': top_year_str,
|
||
# Toutes périodes réunies
|
||
'top_clients_all': top_all_ranges_str,
|
||
'top_clients_all_compact': top_all_ranges_compact,
|
||
'top_tous': top_all_ranges_str,
|
||
'date': date_str,
|
||
'heure': heure_str,
|
||
'time': heure_str
|
||
}
|
||
|
||
def trigger_manual_stats_report():
|
||
"""Déclenche immédiatement l'envoi d'un rapport de statistiques de test vers tous les canaux configurés."""
|
||
cfg = get_notifications_config()
|
||
sched = cfg.get('stats_report_schedule', {})
|
||
top_range = sched.get('top_range', 'day')
|
||
vars_dict = generate_stats_report_vars(top_range=top_range)
|
||
|
||
top_lbl = vars_dict.get('top_range_label', "Aujourd'hui")
|
||
title = "📊 Rapport statistiques & métriques Wi‑Fi"
|
||
message = (
|
||
"📊 Rapport Wi‑Fi ({date}) :\n"
|
||
"• {clients_count} appareil(s) connecté(s) (↓ {traffic_down} • ↑ {traffic_up})\n"
|
||
"• Aujourd'hui : {today_unique} visiteur(s) unique(s) ({today_total} sessions)\n"
|
||
"• Cette semaine : {week_unique} unique(s) | Ce mois : {month_unique} unique(s)\n"
|
||
"• VPN : {active_vpns} tunnel(s) actif(s) ({vpn_routed_clients} appareil(s) routé(s))\n"
|
||
"• Passerelle WAN : {gateway_status} ({gateway_ip})\n"
|
||
f"• Top clients ({top_lbl}) :\n{{top_clients}}"
|
||
)
|
||
|
||
details = {
|
||
"Clients actifs": f"{vars_dict.get('clients_count', 0)} appareil(s)",
|
||
"Visiteurs aujourd'hui": f"{vars_dict.get('today_unique', 0)} uniques ({vars_dict.get('today_total', 0)} sessions)",
|
||
"Débits réseau": f"↓ {vars_dict.get('traffic_down', '0 o/s')} • ↑ {vars_dict.get('traffic_up', '0 o/s')}",
|
||
"Tunnels VPN": f"{vars_dict.get('active_vpns', 0)} actif(s) ({vars_dict.get('vpn_routed_clients', 0)} client(s) routé(s))",
|
||
"Passerelle WAN": f"{vars_dict.get('gateway_status')} ({vars_dict.get('gateway_ip')})",
|
||
"Point d'accès": f"SSID: {vars_dict.get('ssid')} • Ch.{vars_dict.get('channel')} ({vars_dict.get('band')})",
|
||
f"Top clients ({top_lbl})": vars_dict.get('top_clients_compact', 'Aucun transfert')
|
||
}
|
||
|
||
dispatch_notification(
|
||
event_type='stats_report',
|
||
title=title,
|
||
message=message,
|
||
details=details,
|
||
priority=4,
|
||
level="info",
|
||
vars_dict=vars_dict,
|
||
force=True
|
||
)
|
||
return True, "Rapport de statistiques et métriques envoyé avec succès à tous les canaux actifs"
|
||
|
||
_last_stats_report_minute = None
|
||
|
||
def stats_report_scheduler_loop():
|
||
"""Boucle d'arrière-plan vérifiant les expressions Cron et déclenchant les rapports statistiques."""
|
||
global _last_stats_report_minute
|
||
while True:
|
||
try:
|
||
now = datetime.datetime.now()
|
||
cur_key = f"{now.year}-{now.month:02d}-{now.day:02d} {now.hour:02d}:{now.minute:02d}"
|
||
|
||
if cur_key != _last_stats_report_minute:
|
||
cfg = get_notifications_config()
|
||
events = cfg.get('events', {})
|
||
sched = cfg.get('stats_report_schedule', {})
|
||
|
||
is_active = events.get('stats_report', False) or sched.get('enabled', False)
|
||
if is_active:
|
||
cron_expr = sched.get('cron_expr', '').strip()
|
||
if not cron_expr:
|
||
m = sched.get('minute', 0)
|
||
h = sched.get('hour', 8)
|
||
d = sched.get('day', '*')
|
||
cron_expr = f"{m} {h} * * {d}"
|
||
|
||
if match_cron(cron_expr, now):
|
||
_last_stats_report_minute = cur_key
|
||
print(f"[ap-notif] Déclenchement tâche cron rapport statistiques ({cron_expr}) à {cur_key}", flush=True)
|
||
try:
|
||
top_range = sched.get('top_range', 'day')
|
||
vars_dict = generate_stats_report_vars(top_range=top_range)
|
||
top_lbl = vars_dict.get('top_range_label', "Aujourd'hui")
|
||
title = "📊 Rapport statistiques & métriques Wi‑Fi"
|
||
message = (
|
||
"📊 Rapport Wi‑Fi ({date}) :\n"
|
||
"• {clients_count} appareil(s) connecté(s) (↓ {traffic_down} • ↑ {traffic_up})\n"
|
||
"• Aujourd'hui : {today_unique} visiteur(s) unique(s) ({today_total} sessions)\n"
|
||
"• Cette semaine : {week_unique} unique(s) | Ce mois : {month_unique} unique(s)\n"
|
||
"• VPN : {active_vpns} tunnel(s) actif(s) ({vpn_routed_clients} appareil(s) routé(s))\n"
|
||
"• Passerelle WAN : {gateway_status} ({gateway_ip})\n"
|
||
f"• Top clients ({top_lbl}) :\n{{top_clients}}"
|
||
)
|
||
details = {
|
||
"Clients actifs": f"{vars_dict.get('clients_count', 0)} appareil(s)",
|
||
"Visiteurs aujourd'hui": f"{vars_dict.get('today_unique', 0)} uniques ({vars_dict.get('today_total', 0)} sessions)",
|
||
"Débits réseau": f"↓ {vars_dict.get('traffic_down', '0 o/s')} • ↑ {vars_dict.get('traffic_up', '0 o/s')}",
|
||
"Tunnels VPN": f"{vars_dict.get('active_vpns', 0)} actif(s) ({vars_dict.get('vpn_routed_clients', 0)} client(s) routé(s))",
|
||
"Passerelle WAN": f"{vars_dict.get('gateway_status')} ({vars_dict.get('gateway_ip')})",
|
||
"Point d'accès": f"SSID: {vars_dict.get('ssid')} • Ch.{vars_dict.get('channel')} ({vars_dict.get('band')})",
|
||
f"Top clients ({top_lbl})": vars_dict.get('top_clients_compact', 'Aucun transfert')
|
||
}
|
||
dispatch_notification(
|
||
event_type='stats_report',
|
||
title=title,
|
||
message=message,
|
||
details=details,
|
||
priority=4,
|
||
level="info",
|
||
vars_dict=vars_dict
|
||
)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur lors de l'envoi planifié du rapport statistiques : {e}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-notif] Erreur boucle scheduler stats : {e}", flush=True)
|
||
|
||
time.sleep(20)
|
||
|
||
IP_WAIT = 15 # secondes d'attente de l'IP avant de journaliser une connexion sans IP
|
||
pending = {}
|
||
|
||
def update_logs(items):
|
||
global last_macs
|
||
now = time.time(); current = {x['mac']:x for x in items}; announced = set()
|
||
for mac,x in current.items():
|
||
if mac in last_macs: announced.add(mac); continue
|
||
# Le client apparaît dans « iw station dump » dès l'association Wi-Fi, avant le DHCP :
|
||
# on attend son IP (ou IP_WAIT s) pour ne plus journaliser « Non attribuée » à tort.
|
||
first = pending.setdefault(mac, now)
|
||
if x['ip'] not in ('', 'Non attribuée') or now - first >= IP_WAIT:
|
||
v_badge = f" [🛡️ {x['vpn_profile_name']}]" if x.get('vpn_routed') and x.get('vpn_profile_name') else ""
|
||
log('connexion', f"{x['name']}{v_badge}", x['ip'], mac); pending.pop(mac, None); announced.add(mac)
|
||
try:
|
||
c_cnt = db()
|
||
cnt = c_cnt.execute("SELECT COUNT(*) FROM connection_logs WHERE mac=? AND event='connexion'", (mac,)).fetchone()[0]
|
||
c_cnt.close()
|
||
except Exception: cnt = 1
|
||
if cnt <= 1:
|
||
dispatch_notification('new_device', "📱 Nouvel appareil détecté", f"L'appareil « {x['name']} » vient de se connecter pour la première fois au réseau Wi-Fi.", details={"Nom": x['name'], "IP": x['ip'], "MAC": mac, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=6, level="warning")
|
||
else:
|
||
dispatch_notification('device_connected', "📶 Appareil connecté", f"L'appareil « {x['name']} » s'est connecté au réseau Wi-Fi.", details={"Nom": x['name'], "IP": x['ip'], "MAC": mac, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=3, level="info")
|
||
if x.get('vpn_routed') and x.get('vpn_profile_name'):
|
||
dispatch_notification('vpn_client_connected', "🛡️ Client routé via VPN", f"L'appareil « {x['name']} » ({x['ip']}) s'est connecté au réseau Wi-Fi sous le tunnel VPN « {x['vpn_profile_name']} ».", details={"Nom": x['name'], "IP": x['ip'], "MAC": mac, "Profil VPN": x['vpn_profile_name'], "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=4, level="success", vars_dict={"name": x['name'], "ip": x['ip'], "mac": mac, "vpn": x['vpn_profile_name'], "date": time.strftime('%d/%m/%Y %H:%M:%S')})
|
||
for mac in [m for m in pending if m not in current]: pending.pop(mac, None)
|
||
for mac in last_macs - set(current):
|
||
name, ip = 'Nom non communiqué', 'Non attribuée'
|
||
try:
|
||
c = db(); row = c.execute('SELECT name,last_ip FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
|
||
if row:
|
||
name = row[0] or name
|
||
saved_ip = row[1] or ''
|
||
if is_bridge_mode() and saved_ip.startswith('10.42.'):
|
||
saved_ip = ''
|
||
ip = saved_ip or ip
|
||
except sqlite3.Error: pass
|
||
log('déconnexion', name, ip, mac)
|
||
dispatch_notification('device_disconnected', "📴 Appareil déconnecté", f"L'appareil « {name} » s'est déconnecté du réseau Wi-Fi.", details={"Nom": name, "IP": ip, "MAC": mac, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=2, level="info")
|
||
try:
|
||
c_v = db()
|
||
row_v = c_v.execute('SELECT p.name FROM client_vpn_routes r JOIN vpn_profiles p ON p.id = r.profile_id WHERE r.mac=? AND r.profile_id > 0', (mac,)).fetchone()
|
||
c_v.close()
|
||
if row_v and row_v[0]:
|
||
vpn_pname = row_v[0]
|
||
dispatch_notification('vpn_client_disconnected', "🌐 Client VPN déconnecté", f"L'appareil « {name} » ({ip}) routé via le VPN « {vpn_pname} » s'est déconnecté du réseau Wi-Fi.", details={"Nom": name, "IP": ip, "MAC": mac, "Profil VPN": vpn_pname, "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=3, level="info", vars_dict={"name": name, "ip": ip, "mac": mac, "vpn": vpn_pname, "date": time.strftime('%d/%m/%Y %H:%M:%S')})
|
||
except Exception: pass
|
||
last_macs = announced
|
||
|
||
def configure_ap(data, initial=False, caller_ip=None):
|
||
ssid, password = str(data.get('ssid','')).strip(), str(data.get('password',''))
|
||
sec, key, proto, pmf = security(data.get('security','wpa2'))
|
||
if not ssid or len(ssid)>32 or not 8<=len(password)<=63: raise ValueError('SSID ou mot de passe Wi-Fi invalide')
|
||
if 'max_clients' in data:
|
||
set_max_clients(data.get('max_clients'))
|
||
|
||
mode = str(data.get('mode', '')).lower()
|
||
if mode not in ('ap', 'bridge'):
|
||
mode = get_pref('mode', os.environ.get('AP_MODE', 'ap')).lower()
|
||
if mode not in ('ap', 'bridge'): mode = 'ap'
|
||
set_pref('mode', mode)
|
||
|
||
bridge_name = str(data.get('bridge_name', '')).strip() or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
|
||
set_pref('bridge_name', bridge_name)
|
||
|
||
bridge_eth = str(data.get('bridge_eth', '')).strip()
|
||
if not bridge_eth:
|
||
bridge_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
|
||
if mode == 'bridge' and not bridge_eth:
|
||
candidates = detect_ethernet_interfaces()
|
||
if candidates: bridge_eth = candidates[0]
|
||
if bridge_eth: set_pref('bridge_eth', bridge_eth)
|
||
|
||
print(f"[ap-wifi] Configuration AP: SSID='{ssid}', Sécurité={sec}, Mode={mode}, Autoconnect={'oui' if data.get('autoconnect',True) else 'non'}", flush=True)
|
||
old_name = connection_name()
|
||
target_name = 'AP-' + ssid
|
||
name = target_name
|
||
|
||
# Arrêter et supprimer proprement toute ancienne connexion pour éviter les conflits d'options slave/master/ipv4
|
||
to_delete = {n for n in (old_name, target_name) if n}
|
||
for c in to_delete:
|
||
subprocess.run(['nmcli', 'connection', 'down', c], capture_output=True, text=True)
|
||
subprocess.run(['nmcli', 'connection', 'delete', c], capture_output=True, text=True)
|
||
|
||
if mode == 'bridge':
|
||
setup_bridge(bridge_name, bridge_eth)
|
||
# Arrêter le dnsmasq interne pour que les clients reçoivent l'IP de la box et non 10.42.0.x
|
||
subprocess.run(['pkill', '-f', 'dnsmasq.*shared'], text=True, capture_output=True)
|
||
for lf in ['/var/lib/misc/dnsmasq.leases', '/var/lib/NetworkManager/dnsmasq.leases']:
|
||
try:
|
||
if os.path.exists(lf): open(lf, 'w').close()
|
||
except OSError: pass
|
||
|
||
add_args = [
|
||
'nmcli', 'connection', 'add',
|
||
'type', 'wifi',
|
||
'ifname', INTERFACE,
|
||
'con-name', name,
|
||
'ssid', ssid,
|
||
'slave-type', 'bridge',
|
||
'master', bridge_name
|
||
]
|
||
r = subprocess.run(add_args, text=True, capture_output=True)
|
||
if r.returncode:
|
||
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé de créer la connexion en mode pont')
|
||
|
||
modify_args = [
|
||
'nmcli', 'connection', 'modify', name,
|
||
'802-11-wireless.mode', 'ap',
|
||
'802-11-wireless-security.key-mgmt', key,
|
||
'802-11-wireless-security.psk', password,
|
||
'802-11-wireless-security.pmf', pmf,
|
||
'802-11-wireless.band', AP_BAND,
|
||
'802-11-wireless.channel', str(AP_CHANNEL),
|
||
'connection.autoconnect', 'yes' if data.get('autoconnect', True) else 'no'
|
||
]
|
||
if proto: modify_args += ['802-11-wireless-security.proto', proto]
|
||
if sec in ('wpa2', 'wpa3'):
|
||
modify_args += ['802-11-wireless-security.pairwise', 'ccmp', '802-11-wireless-security.group', 'ccmp']
|
||
r = subprocess.run(modify_args, text=True, capture_output=True)
|
||
if r.returncode:
|
||
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé la configuration AP en mode pont')
|
||
else:
|
||
teardown_bridge(bridge_name, bridge_eth)
|
||
add_args = [
|
||
'nmcli', 'connection', 'add',
|
||
'type', 'wifi',
|
||
'ifname', INTERFACE,
|
||
'con-name', name,
|
||
'ssid', ssid
|
||
]
|
||
r = subprocess.run(add_args, text=True, capture_output=True)
|
||
if r.returncode:
|
||
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé de créer la connexion Wi-Fi')
|
||
|
||
modify_args = [
|
||
'nmcli', 'connection', 'modify', name,
|
||
'802-11-wireless.mode', 'ap',
|
||
'802-11-wireless-security.key-mgmt', key,
|
||
'802-11-wireless-security.psk', password,
|
||
'802-11-wireless-security.pmf', pmf,
|
||
'ipv4.method', 'shared',
|
||
'ipv6.method', 'ignore',
|
||
'802-11-wireless.band', AP_BAND,
|
||
'802-11-wireless.channel', str(AP_CHANNEL),
|
||
'connection.autoconnect', 'yes' if data.get('autoconnect', True) else 'no'
|
||
]
|
||
if proto: modify_args += ['802-11-wireless-security.proto', proto]
|
||
if sec in ('wpa2', 'wpa3'):
|
||
modify_args += ['802-11-wireless-security.pairwise', 'ccmp', '802-11-wireless-security.group', 'ccmp']
|
||
# Note : ipv4.dns est interdit par NetworkManager lorsque ipv4.method=shared.
|
||
# Les serveurs DNS (AP_DNS) sont distribués aux clients Wi-Fi via dnsmasq (ensure_dnsmasq_dns / dhcp-option=6).
|
||
r = subprocess.run(modify_args, text=True, capture_output=True)
|
||
if r.returncode:
|
||
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé la configuration AP')
|
||
|
||
ensure_dnsmasq_dns()
|
||
save_connection(name)
|
||
r = subprocess.run(['nmcli', 'connection', 'up', name], text=True, capture_output=True)
|
||
if r.returncode:
|
||
raise RuntimeError(r.stderr.strip() or 'Impossible de démarrer le point d’accès')
|
||
mark_ap_started()
|
||
invalidate_status_cache()
|
||
log('création' if initial else 'enregistrement_modifie', f"Réseau Wi-Fi {ssid} ({'Mode Pont' if mode == 'bridge' else 'Mode AP'})", ip=caller_ip or 'Non attribuée', mac='AP')
|
||
dispatch_notification('settings_changed', "⚙️ Modification réglages Wi-Fi / AP", f"Les réglages du point d'accès Wi-Fi ont été modifiés.", details={"SSID": ssid, "Mode": "Mode Pont" if mode == 'bridge' else "Mode AP", "Sécurité": sec.upper(), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=5, level="warning")
|
||
return name
|
||
|
||
# =====================================================================
|
||
# Module d'analyse réseau avancé & Capture Wireshark (PCAP)
|
||
# =====================================================================
|
||
capture_running = False
|
||
capture_thread = None
|
||
capture_lock = threading.Lock()
|
||
capture_packets = []
|
||
capture_pcap_bytes = bytearray(struct.pack('<IHHiIII', 0xa1b2c3d4, 2, 4, 0, 0, 65535, 1))
|
||
capture_id_counter = 0
|
||
capture_stats = {'dns': 0, 'icmp': 0, 'tcp': 0, 'udp': 0, 'arp': 0, 'dhcp': 0, 'tls': 0, 'http': 0, 'other': 0}
|
||
captured_domains = {} # domain -> {'domain', 'count', 'first_seen', 'last_seen', 'last_seen_str', 'last_client_ip', 'last_client_name', 'proto'}
|
||
capture_iface_used = ''
|
||
capture_started_at = 0.0
|
||
|
||
# =====================================================================
|
||
# Moteur GeoIP & Détection Pays pour adresses IP (Wireshark / Capture)
|
||
# =====================================================================
|
||
geoip_lock = threading.Lock()
|
||
GEOIP_CACHE = {} # ip -> {'is_ip': True, 'is_local': bool, 'code': str, 'country': str, 'flag': str}
|
||
geoip_queue = queue.Queue(maxsize=2000)
|
||
geoip_pending = set()
|
||
|
||
def country_code_to_flag(code):
|
||
if not code or len(code) != 2:
|
||
return '🌐'
|
||
c = code.upper()
|
||
try:
|
||
return chr(0x1F1E6 + ord(c[0]) - ord('A')) + chr(0x1F1E6 + ord(c[1]) - ord('A'))
|
||
except Exception:
|
||
return '🌐'
|
||
|
||
# Plages IP publiques courantes pré-renseignées pour détection instantanée (0ms)
|
||
KNOWN_NETWORKS = [
|
||
# Cloudflare
|
||
(ipaddress.ip_network('1.0.0.0/8'), 'US', 'Cloudflare', '🇺🇸'),
|
||
(ipaddress.ip_network('104.16.0.0/12'), 'US', 'Cloudflare', '🇺🇸'),
|
||
(ipaddress.ip_network('172.64.0.0/13'), 'US', 'Cloudflare', '🇺🇸'),
|
||
# Google
|
||
(ipaddress.ip_network('8.8.8.0/24'), 'US', 'Google DNS', '🇺🇸'),
|
||
(ipaddress.ip_network('8.8.4.0/24'), 'US', 'Google DNS', '🇺🇸'),
|
||
(ipaddress.ip_network('142.250.0.0/15'), 'US', 'Google', '🇺🇸'),
|
||
(ipaddress.ip_network('172.217.0.0/16'), 'US', 'Google', '🇺🇸'),
|
||
(ipaddress.ip_network('216.58.192.0/19'), 'US', 'Google', '🇺🇸'),
|
||
(ipaddress.ip_network('173.194.0.0/16'), 'US', 'Google', '🇺🇸'),
|
||
# Quad9
|
||
(ipaddress.ip_network('9.9.9.0/24'), 'CH', 'Quad9 DNS', '🇨🇭'),
|
||
(ipaddress.ip_network('149.112.112.0/24'), 'CH', 'Quad9 DNS', '🇨🇭'),
|
||
# Cisco OpenDNS
|
||
(ipaddress.ip_network('208.67.220.0/22'), 'US', 'Cisco OpenDNS', '🇺🇸'),
|
||
# Microsoft & Azure
|
||
(ipaddress.ip_network('13.64.0.0/11'), 'US', 'Microsoft Azure', '🇺🇸'),
|
||
(ipaddress.ip_network('20.0.0.0/8'), 'US', 'Microsoft', '🇺🇸'),
|
||
(ipaddress.ip_network('40.64.0.0/10'), 'US', 'Microsoft', '🇺🇸'),
|
||
(ipaddress.ip_network('52.96.0.0/12'), 'US', 'Microsoft Office365', '🇺🇸'),
|
||
# Apple
|
||
(ipaddress.ip_network('17.0.0.0/8'), 'US', 'Apple', '🇺🇸'),
|
||
# GitHub
|
||
(ipaddress.ip_network('140.82.112.0/20'), 'US', 'GitHub', '🇺🇸'),
|
||
(ipaddress.ip_network('185.199.108.0/22'), 'US', 'GitHub Pages', '🇺🇸'),
|
||
# Fastly
|
||
(ipaddress.ip_network('151.101.0.0/16'), 'US', 'Fastly CDN', '🇺🇸'),
|
||
(ipaddress.ip_network('199.232.0.0/16'), 'US', 'Fastly CDN', '🇺🇸'),
|
||
# Amazon AWS
|
||
(ipaddress.ip_network('3.0.0.0/8'), 'US', 'Amazon AWS', '🇺🇸'),
|
||
(ipaddress.ip_network('52.0.0.0/11'), 'US', 'Amazon AWS', '🇺🇸'),
|
||
(ipaddress.ip_network('54.0.0.0/8'), 'US', 'Amazon AWS', '🇺🇸'),
|
||
# Fournisseurs & Hébergeurs Français
|
||
(ipaddress.ip_network('51.0.0.0/8'), 'FR', 'OVHcloud', '🇫🇷'),
|
||
(ipaddress.ip_network('141.94.0.0/16'), 'FR', 'OVHcloud', '🇫🇷'),
|
||
(ipaddress.ip_network('164.132.0.0/16'), 'FR', 'OVHcloud', '🇫🇷'),
|
||
(ipaddress.ip_network('37.187.0.0/16'), 'FR', 'OVHcloud', '🇫🇷'),
|
||
(ipaddress.ip_network('178.32.0.0/15'), 'FR', 'OVHcloud', '🇫🇷'),
|
||
(ipaddress.ip_network('91.121.0.0/16'), 'FR', 'OVHcloud', '🇫🇷'),
|
||
(ipaddress.ip_network('62.210.0.0/16'), 'FR', 'Scaleway', '🇫🇷'),
|
||
(ipaddress.ip_network('163.172.0.0/16'), 'FR', 'Scaleway', '🇫🇷'),
|
||
(ipaddress.ip_network('51.15.0.0/16'), 'FR', 'Scaleway', '🇫🇷'),
|
||
(ipaddress.ip_network('195.154.0.0/16'), 'FR', 'Scaleway', '🇫🇷'),
|
||
(ipaddress.ip_network('212.83.128.0/18'), 'FR', 'Scaleway', '🇫🇷'),
|
||
(ipaddress.ip_network('80.10.0.0/15'), 'FR', 'Orange', '🇫🇷'),
|
||
(ipaddress.ip_network('90.0.0.0/8'), 'FR', 'Orange', '🇫🇷'),
|
||
(ipaddress.ip_network('86.200.0.0/13'), 'FR', 'Orange', '🇫🇷'),
|
||
(ipaddress.ip_network('193.252.0.0/16'), 'FR', 'Orange', '🇫🇷'),
|
||
(ipaddress.ip_network('83.192.0.0/12'), 'FR', 'Orange', '🇫🇷'),
|
||
(ipaddress.ip_network('82.64.0.0/14'), 'FR', 'Free', '🇫🇷'),
|
||
(ipaddress.ip_network('212.27.32.0/19'), 'FR', 'Free', '🇫🇷'),
|
||
(ipaddress.ip_network('78.250.0.0/15'), 'FR', 'Free', '🇫🇷'),
|
||
(ipaddress.ip_network('88.160.0.0/11'), 'FR', 'Free', '🇫🇷'),
|
||
(ipaddress.ip_network('91.68.0.0/14'), 'FR', 'Free', '🇫🇷'),
|
||
(ipaddress.ip_network('92.128.0.0/11'), 'FR', 'SFR', '🇫🇷'),
|
||
(ipaddress.ip_network('93.0.0.0/11'), 'FR', 'SFR', '🇫🇷'),
|
||
(ipaddress.ip_network('84.96.0.0/12'), 'FR', 'SFR', '🇫🇷'),
|
||
(ipaddress.ip_network('86.64.0.0/12'), 'FR', 'SFR', '🇫🇷'),
|
||
(ipaddress.ip_network('109.8.0.0/13'), 'FR', 'SFR', '🇫🇷'),
|
||
(ipaddress.ip_network('176.128.0.0/11'), 'FR', 'Bouygues Telecom', '🇫🇷'),
|
||
(ipaddress.ip_network('185.24.0.0/14'), 'FR', 'Bouygues Telecom', '🇫🇷'),
|
||
(ipaddress.ip_network('89.80.0.0/12'), 'FR', 'Bouygues Telecom', '🇫🇷'),
|
||
# Hetzner (Allemagne)
|
||
(ipaddress.ip_network('88.198.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
|
||
(ipaddress.ip_network('138.201.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
|
||
(ipaddress.ip_network('144.76.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
|
||
(ipaddress.ip_network('168.119.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
|
||
(ipaddress.ip_network('159.69.0.0/16'), 'DE', 'Hetzner', '🇩🇪'),
|
||
]
|
||
|
||
def init_geoip_cache():
|
||
try:
|
||
c = db()
|
||
rows = c.execute("SELECT ip, code, country, flag FROM geoip_cache").fetchall()
|
||
c.close()
|
||
with geoip_lock:
|
||
for r in rows:
|
||
GEOIP_CACHE[r[0]] = {
|
||
'is_ip': True,
|
||
'is_local': False,
|
||
'code': r[1] or '',
|
||
'country': r[2] or '',
|
||
'flag': r[3] or '🌐'
|
||
}
|
||
except Exception as e:
|
||
print(f"[geoip] Initialisation cache: {e}", flush=True)
|
||
|
||
def save_geoip_cache_db(ip_str, code, country, flag):
|
||
try:
|
||
c = db()
|
||
c.execute("""
|
||
INSERT OR REPLACE INTO geoip_cache (ip, code, country, flag, created_at)
|
||
VALUES (?, ?, ?, ?, ?)
|
||
""", (ip_str, code, country, flag, time.time()))
|
||
c.commit()
|
||
c.close()
|
||
except Exception:
|
||
pass
|
||
|
||
def enqueue_geoip_lookup(ip_str):
|
||
with geoip_lock:
|
||
if ip_str in geoip_pending or ip_str in GEOIP_CACHE:
|
||
return
|
||
geoip_pending.add(ip_str)
|
||
try:
|
||
geoip_queue.put_nowait(ip_str)
|
||
except queue.Full:
|
||
pass
|
||
|
||
def resolve_ip_country_online(ip_str):
|
||
# 1. Tentative avec ip-api.com
|
||
try:
|
||
url = f"http://ip-api.com/json/{ip_str}?fields=status,country,countryCode"
|
||
req = urllib.request.Request(url, headers={'User-Agent': 'APManageur-GeoIP/1.0'})
|
||
with urllib.request.urlopen(req, timeout=2.0) as resp:
|
||
data = json.loads(resp.read().decode('utf-8', errors='ignore'))
|
||
if data.get('status') == 'success':
|
||
code = (data.get('countryCode') or '').strip().upper()
|
||
cname = (data.get('country') or '').strip()
|
||
if code:
|
||
return {'code': code, 'country': cname, 'flag': country_code_to_flag(code)}
|
||
except Exception:
|
||
pass
|
||
|
||
# 2. Fallback avec freeipapi.com
|
||
try:
|
||
url = f"https://freeipapi.com/api/json/{ip_str}"
|
||
req = urllib.request.Request(url, headers={'User-Agent': 'APManageur-GeoIP/1.0'})
|
||
with urllib.request.urlopen(req, timeout=2.0) as resp:
|
||
data = json.loads(resp.read().decode('utf-8', errors='ignore'))
|
||
code = (data.get('countryCode') or '').strip().upper()
|
||
cname = (data.get('countryName') or '').strip()
|
||
if code:
|
||
return {'code': code, 'country': cname, 'flag': country_code_to_flag(code)}
|
||
except Exception:
|
||
pass
|
||
return None
|
||
|
||
def geoip_worker():
|
||
while True:
|
||
try:
|
||
ip_str = geoip_queue.get(timeout=10)
|
||
except queue.Empty:
|
||
continue
|
||
try:
|
||
res = resolve_ip_country_online(ip_str)
|
||
if res:
|
||
geo = {
|
||
'is_ip': True,
|
||
'is_local': False,
|
||
'code': res['code'],
|
||
'country': res['country'],
|
||
'flag': res['flag']
|
||
}
|
||
with geoip_lock:
|
||
GEOIP_CACHE[ip_str] = geo
|
||
save_geoip_cache_db(ip_str, res['code'], res['country'], res['flag'])
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
with geoip_lock:
|
||
geoip_pending.discard(ip_str)
|
||
geoip_queue.task_done()
|
||
time.sleep(0.35)
|
||
|
||
def get_ip_geo(ip_str):
|
||
if not ip_str or not isinstance(ip_str, str):
|
||
return None
|
||
ip_str = ip_str.strip()
|
||
if ':' in ip_str and len(ip_str) == 17 and ip_str.count(':') == 5:
|
||
return None
|
||
try:
|
||
ip_obj = ipaddress.ip_address(ip_str)
|
||
except Exception:
|
||
return None
|
||
|
||
if ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_link_local:
|
||
return {
|
||
'is_ip': True,
|
||
'is_local': True,
|
||
'code': 'LAN',
|
||
'country': 'Réseau local',
|
||
'flag': '🏠'
|
||
}
|
||
if ip_obj.is_multicast:
|
||
return {
|
||
'is_ip': True,
|
||
'is_local': True,
|
||
'code': 'MCAST',
|
||
'country': 'Multicast',
|
||
'flag': '📡'
|
||
}
|
||
if str(ip_obj) == '255.255.255.255' or ip_obj.is_reserved:
|
||
return {
|
||
'is_ip': True,
|
||
'is_local': True,
|
||
'code': 'BCAST',
|
||
'country': 'Diffusion',
|
||
'flag': '📡'
|
||
}
|
||
|
||
ip_norm = str(ip_obj)
|
||
with geoip_lock:
|
||
if ip_norm in GEOIP_CACHE:
|
||
return GEOIP_CACHE[ip_norm]
|
||
|
||
for net, code, name, flag in KNOWN_NETWORKS:
|
||
try:
|
||
if ip_obj in net:
|
||
res = {'is_ip': True, 'is_local': False, 'code': code, 'country': name, 'flag': flag}
|
||
with geoip_lock:
|
||
GEOIP_CACHE[ip_norm] = res
|
||
save_geoip_cache_db(ip_norm, code, name, flag)
|
||
return res
|
||
except Exception:
|
||
continue
|
||
|
||
enqueue_geoip_lookup(ip_norm)
|
||
return {'is_ip': True, 'is_local': False, 'code': 'WAN', 'country': 'IP Publique', 'flag': '🌐'}
|
||
|
||
try:
|
||
init_geoip_cache()
|
||
threading.Thread(target=geoip_worker, daemon=True).start()
|
||
except Exception as _e_geo:
|
||
print(f"[geoip] Erreur démarrage service: {_e_geo}", flush=True)
|
||
|
||
def extract_tls_sni(data):
|
||
try:
|
||
if len(data) < 44 or data[0] != 0x16: return ''
|
||
if len(data) < 6 or data[5] != 1: return ''
|
||
pos = 43
|
||
if pos >= len(data): return ''
|
||
sess_id_len = data[pos]
|
||
pos += 1 + sess_id_len
|
||
if pos + 2 > len(data): return ''
|
||
ciphers_len = struct.unpack('!H', data[pos:pos+2])[0]
|
||
pos += 2 + ciphers_len
|
||
if pos >= len(data): return ''
|
||
comp_len = data[pos]
|
||
pos += 1 + comp_len
|
||
if pos + 2 > len(data): return ''
|
||
ext_total_len = struct.unpack('!H', data[pos:pos+2])[0]
|
||
pos += 2
|
||
end_ext = min(len(data), pos + ext_total_len)
|
||
while pos + 4 <= end_ext:
|
||
ext_type, ext_len = struct.unpack('!HH', data[pos:pos+4])
|
||
pos += 4
|
||
if ext_type == 0: # SNI extension
|
||
if pos + 5 <= end_ext:
|
||
name_len = struct.unpack('!H', data[pos+3:pos+5])[0]
|
||
name_bytes = data[pos+5:pos+5+name_len]
|
||
return name_bytes.decode('utf-8', errors='ignore').lower().strip()
|
||
break
|
||
pos += ext_len
|
||
except Exception: pass
|
||
return ''
|
||
|
||
def extract_http_host(data):
|
||
try:
|
||
if not data.startswith((b'GET ', b'POST ', b'HEAD ', b'PUT ', b'DELETE ', b'OPTIONS ', b'CONNECT ')):
|
||
return ''
|
||
lines = data.split(b'\r\n')
|
||
for line in lines[1:]:
|
||
if line.lower().startswith(b'host:'):
|
||
host = line.split(b':', 1)[1].strip().decode('utf-8', errors='ignore')
|
||
return host.split(':')[0].lower().strip()
|
||
except Exception: pass
|
||
return ''
|
||
|
||
def hex_dump(data, max_len=256):
|
||
lines = []
|
||
chunk = data[:max_len]
|
||
for i in range(0, len(chunk), 16):
|
||
sub = chunk[i:i+16]
|
||
hex_part = ' '.join(f'{b:02x}' for b in sub)
|
||
ascii_part = ''.join(chr(b) if 32 <= b < 127 else '.' for b in sub)
|
||
lines.append(f'{i:04x} {hex_part:<48} {ascii_part}')
|
||
if len(data) > max_len:
|
||
lines.append(f'... ({len(data) - max_len} octets supplémentaires)')
|
||
return '\n'.join(lines)
|
||
|
||
def parse_packet(raw, ts):
|
||
if len(raw) < 14:
|
||
return None
|
||
dst_mac = ':'.join(f'{b:02x}' for b in raw[:6])
|
||
src_mac = ':'.join(f'{b:02x}' for b in raw[6:12])
|
||
ethertype = struct.unpack('!H', raw[12:14])[0]
|
||
t_str = time.strftime('%H:%M:%S', time.localtime(ts)) + f'.{int((ts % 1) * 1000):03d}'
|
||
|
||
pkt = {
|
||
'ts': ts,
|
||
'time': t_str,
|
||
'src': src_mac,
|
||
'dst': dst_mac,
|
||
'src_mac': src_mac,
|
||
'dst_mac': dst_mac,
|
||
'proto': 'Ethernet',
|
||
'len': len(raw),
|
||
'info': f'EtherType 0x{ethertype:04x}',
|
||
'details': f'Ethernet II, Src: {src_mac}, Dst: {dst_mac}, Type: 0x{ethertype:04x}',
|
||
'hexdump': hex_dump(raw),
|
||
'src_geo': None,
|
||
'dst_geo': None
|
||
}
|
||
|
||
if ethertype == 0x0806 and len(raw) >= 28:
|
||
htype, ptype, hlen, plen, oper = struct.unpack('!HHBBH', raw[14:22])
|
||
if hlen == 6 and plen == 4 and len(raw) >= 42:
|
||
sha = ':'.join(f'{b:02x}' for b in raw[22:28])
|
||
spa = socket.inet_ntoa(raw[28:32])
|
||
tha = ':'.join(f'{b:02x}' for b in raw[32:38])
|
||
tpa = socket.inet_ntoa(raw[38:42])
|
||
pkt['proto'] = 'ARP'
|
||
pkt['src'] = spa
|
||
pkt['dst'] = tpa
|
||
pkt['src_geo'] = get_ip_geo(spa)
|
||
pkt['dst_geo'] = get_ip_geo(tpa)
|
||
if oper == 1:
|
||
pkt['info'] = f'Who has {tpa}? Tell {spa}'
|
||
elif oper == 2:
|
||
pkt['info'] = f'{spa} is at {sha}'
|
||
else:
|
||
pkt['info'] = f'ARP opcode={oper}'
|
||
pkt['details'] = f'Address Resolution Protocol ({oper})\nSender MAC: {sha}\nSender IP: {spa}\nTarget MAC: {tha}\nTarget IP: {tpa}'
|
||
return pkt
|
||
|
||
if ethertype == 0x0800 and len(raw) >= 34:
|
||
ver_ihl = raw[14]
|
||
ihl = (ver_ihl & 0x0f) * 4
|
||
if len(raw) < 14 + ihl: return pkt
|
||
total_len, ident, flags_frag, ttl, proto, chksum = struct.unpack('!HHHBBH', raw[16:26])
|
||
src_ip = socket.inet_ntoa(raw[26:30])
|
||
dst_ip = socket.inet_ntoa(raw[30:34])
|
||
pkt['src'] = src_ip
|
||
pkt['dst'] = dst_ip
|
||
pkt['src_geo'] = get_ip_geo(src_ip)
|
||
pkt['dst_geo'] = get_ip_geo(dst_ip)
|
||
ip_payload = raw[14 + ihl:]
|
||
|
||
if proto == 1 and len(ip_payload) >= 4:
|
||
icmp_type, icmp_code = ip_payload[0], ip_payload[1]
|
||
pkt['proto'] = 'ICMP'
|
||
if icmp_type == 8 and len(ip_payload) >= 8:
|
||
ident_i, seq_i = struct.unpack('!HH', ip_payload[4:8])
|
||
pkt['info'] = f'Echo (ping) request id=0x{ident_i:04x}, seq={seq_i}, ttl={ttl}'
|
||
elif icmp_type == 0 and len(ip_payload) >= 8:
|
||
ident_i, seq_i = struct.unpack('!HH', ip_payload[4:8])
|
||
pkt['info'] = f'Echo (ping) reply id=0x{ident_i:04x}, seq={seq_i}'
|
||
elif icmp_type == 3:
|
||
codes = {0:'Net unreach', 1:'Host unreach', 2:'Protocol unreach', 3:'Port unreach'}
|
||
pkt['info'] = f'Destination unreachable ({codes.get(icmp_code, f"code {icmp_code}")})'
|
||
elif icmp_type == 11:
|
||
pkt['info'] = 'Time-to-live exceeded in transit'
|
||
else:
|
||
pkt['info'] = f'ICMP Type={icmp_type}, Code={icmp_code}'
|
||
pkt['details'] = f'Internet Control Message Protocol\nType: {icmp_type}\nCode: {icmp_code}\nSrc: {src_ip} -> Dst: {dst_ip}'
|
||
return pkt
|
||
|
||
if proto == 17 and len(ip_payload) >= 8:
|
||
src_p, dst_p, udp_len, _ = struct.unpack('!HHHH', ip_payload[:8])
|
||
udp_payload = ip_payload[8:udp_len] if udp_len <= len(ip_payload) else ip_payload[8:]
|
||
|
||
if 53 in (src_p, dst_p) and len(udp_payload) >= 12:
|
||
txid, flags, qdcount, ancount = struct.unpack('!HHHH', udp_payload[:8])
|
||
is_resp = bool(flags & 0x8000)
|
||
pkt['proto'] = 'DNS'
|
||
qname = ''
|
||
try:
|
||
labels = []
|
||
off = 12
|
||
while off < len(udp_payload):
|
||
l = udp_payload[off]
|
||
if l == 0: break
|
||
if (l & 0xc0) == 0xc0: off += 2; break
|
||
off += 1
|
||
labels.append(udp_payload[off:off+l].decode('utf-8', errors='ignore'))
|
||
off += l
|
||
qname = '.'.join(labels)
|
||
except Exception: pass
|
||
|
||
if qname:
|
||
pkt['domain'] = qname
|
||
pkt['domain_source'] = 'DNS'
|
||
|
||
if not is_resp:
|
||
pkt['info'] = f'Standard query 0x{txid:04x} A {qname}' if qname else f'Standard query 0x{txid:04x}'
|
||
else:
|
||
pkt['info'] = f'Standard query response 0x{txid:04x}' + (f' {qname}' if qname else '')
|
||
pkt['details'] = f'Domain Name System ({"Response" if is_resp else "Query"})\nTransaction ID: 0x{txid:04x}\nQuestions: {qdcount}, Answers: {ancount}\nQuery: {qname}'
|
||
return pkt
|
||
|
||
if 67 in (src_p, dst_p) or 68 in (src_p, dst_p):
|
||
pkt['proto'] = 'DHCP'
|
||
msg_type = 'Message'
|
||
if len(udp_payload) >= 240 and udp_payload[236:240] == b'\x63\x82\x53\x63':
|
||
off = 240
|
||
while off + 1 < len(udp_payload):
|
||
opt = udp_payload[off]
|
||
if opt == 255: break
|
||
if opt == 0: off += 1; continue
|
||
opt_len = udp_payload[off+1]
|
||
if opt == 53 and opt_len >= 1 and off + 2 < len(udp_payload):
|
||
t = udp_payload[off+2]
|
||
names = {1:'Discover', 2:'Offer', 3:'Request', 4:'Decline', 5:'ACK', 6:'NAK', 7:'Release', 8:'Inform'}
|
||
msg_type = names.get(t, f'Type {t}')
|
||
break
|
||
off += 2 + opt_len
|
||
pkt['info'] = f'DHCP {msg_type}'
|
||
pkt['details'] = f'Dynamic Host Configuration Protocol\nMessage: {msg_type}\nPort: {src_p} -> {dst_p}'
|
||
return pkt
|
||
|
||
if 5353 in (src_p, dst_p):
|
||
pkt['proto'] = 'mDNS'
|
||
pkt['info'] = f'Multicast DNS ({src_p} -> {dst_p})'
|
||
return pkt
|
||
|
||
pkt['proto'] = 'UDP'
|
||
pkt['info'] = f'{src_p} → {dst_p} Len={len(udp_payload)}'
|
||
pkt['details'] = f'User Datagram Protocol, Src Port: {src_p}, Dst Port: {dst_p}, Length: {udp_len}'
|
||
return pkt
|
||
|
||
if proto == 6 and len(ip_payload) >= 20:
|
||
src_p, dst_p, seq, ack, off_flags = struct.unpack('!HHIIH', ip_payload[:14])
|
||
tcp_off = (off_flags >> 12) * 4
|
||
tcp_flags = off_flags & 0x01ff
|
||
flag_names = []
|
||
if tcp_flags & 0x002: flag_names.append('SYN')
|
||
if tcp_flags & 0x001: flag_names.append('FIN')
|
||
if tcp_flags & 0x004: flag_names.append('RST')
|
||
if tcp_flags & 0x008: flag_names.append('PSH')
|
||
if tcp_flags & 0x010: flag_names.append('ACK')
|
||
if tcp_flags & 0x020: flag_names.append('URG')
|
||
flags_str = '[' + ', '.join(flag_names) + ']' if flag_names else ''
|
||
|
||
tcp_payload = ip_payload[tcp_off:] if len(ip_payload) >= tcp_off else b''
|
||
|
||
if 443 in (src_p, dst_p) or 8443 in (src_p, dst_p):
|
||
pkt['proto'] = 'TLS'
|
||
tls_desc = ''
|
||
sni = extract_tls_sni(tcp_payload)
|
||
if sni:
|
||
pkt['domain'] = sni
|
||
pkt['domain_source'] = 'TLS'
|
||
if len(tcp_payload) >= 5 and tcp_payload[0] in (0x14, 0x15, 0x16, 0x17):
|
||
content_type = tcp_payload[0]
|
||
if content_type == 0x16 and len(tcp_payload) >= 6:
|
||
hs_type = tcp_payload[5]
|
||
names = {1:'Client Hello', 2:'Server Hello', 11:'Certificate', 12:'Server Key Exchange', 14:'Server Hello Done', 16:'Client Key Exchange'}
|
||
tls_desc = names.get(hs_type, f'Handshake ({hs_type})')
|
||
if sni:
|
||
tls_desc += f' [SNI: {sni}]'
|
||
elif content_type == 0x17:
|
||
tls_desc = f'Application Data [{len(tcp_payload)} B]'
|
||
elif content_type == 0x15:
|
||
tls_desc = 'Encrypted Alert'
|
||
pkt['info'] = f'{src_p} → {dst_p} {flags_str} {tls_desc}'.strip()
|
||
pkt['details'] = f'Transport Layer Security\nSrc Port: {src_p}, Dst Port: {dst_p}\n{flags_str}\nPayload: {len(tcp_payload)} bytes' + (f'\nServer Name Indication (SNI): {sni}' if sni else '')
|
||
return pkt
|
||
|
||
if 80 in (src_p, dst_p) or 8080 in (src_p, dst_p):
|
||
pkt['proto'] = 'HTTP'
|
||
http_line = ''
|
||
host = extract_http_host(tcp_payload)
|
||
if host:
|
||
pkt['domain'] = host
|
||
pkt['domain_source'] = 'HTTP'
|
||
if tcp_payload.startswith((b'GET ', b'POST ', b'HEAD ', b'PUT ', b'DELETE ')):
|
||
http_line = tcp_payload.split(b'\r\n')[0].decode('utf-8', errors='ignore')
|
||
elif tcp_payload.startswith(b'HTTP/1.'):
|
||
http_line = tcp_payload.split(b'\r\n')[0].decode('utf-8', errors='ignore')
|
||
if host and host not in http_line:
|
||
http_line = (http_line + f' [Host: {host}]').strip()
|
||
pkt['info'] = f'{src_p} → {dst_p} {flags_str} {http_line}'.strip()
|
||
pkt['details'] = f'Hypertext Transfer Protocol\n{http_line}' + (f'\nHost: {host}' if host else '')
|
||
return pkt
|
||
|
||
pkt['proto'] = 'TCP'
|
||
pkt['info'] = f'{src_p} → {dst_p} {flags_str} Seq={seq} Ack={ack} Len={len(tcp_payload)}'
|
||
pkt['details'] = f'Transmission Control Protocol, Src Port: {src_p}, Dst Port: {dst_p}\nFlags: {flags_str}, Seq: {seq}, Ack: {ack}'
|
||
return pkt
|
||
|
||
if ethertype == 0x86dd and len(raw) >= 54:
|
||
try:
|
||
src_ip6 = socket.inet_ntop(socket.AF_INET6, raw[22:38])
|
||
dst_ip6 = socket.inet_ntop(socket.AF_INET6, raw[38:54])
|
||
pkt['src'] = src_ip6
|
||
pkt['dst'] = dst_ip6
|
||
pkt['src_geo'] = get_ip_geo(src_ip6)
|
||
pkt['dst_geo'] = get_ip_geo(dst_ip6)
|
||
pkt['proto'] = 'IPv6'
|
||
pkt['info'] = f'IPv6 {src_ip6} → {dst_ip6}'
|
||
pkt['details'] = f'Internet Protocol Version 6, Src: {src_ip6}, Dst: {dst_ip6}'
|
||
except Exception:
|
||
pass
|
||
|
||
return pkt
|
||
|
||
def get_wifi_interface():
|
||
global INTERFACE
|
||
env_iface = os.environ.get('AP_INTERFACE', '').strip()
|
||
if env_iface and os.path.exists(f'/sys/class/net/{env_iface}'):
|
||
INTERFACE = env_iface
|
||
return env_iface
|
||
if INTERFACE and os.path.exists(f'/sys/class/net/{INTERFACE}'):
|
||
return INTERFACE
|
||
try:
|
||
for d in os.listdir('/sys/class/net'):
|
||
p = os.path.join('/sys/class/net', d)
|
||
if os.path.isdir(os.path.join(p, 'wireless')) or os.path.isdir(os.path.join(p, 'phy80211')):
|
||
INTERFACE = d
|
||
return d
|
||
except Exception: pass
|
||
try:
|
||
out = subprocess.check_output(['iw', 'dev'], text=True, stderr=subprocess.DEVNULL)
|
||
for line in out.splitlines():
|
||
parts = line.strip().split()
|
||
if len(parts) >= 2 and parts[0] == 'Interface':
|
||
INTERFACE = parts[1]
|
||
return parts[1]
|
||
except Exception: pass
|
||
return INTERFACE or 'wls16b1'
|
||
|
||
def start_capture(target_iface=None):
|
||
global capture_running, capture_thread, capture_pcap_bytes, capture_iface_used, capture_started_at
|
||
with capture_lock:
|
||
if capture_running:
|
||
return True, f"Capture déjà en cours sur {capture_iface_used}"
|
||
if not capture_pcap_bytes:
|
||
capture_pcap_bytes = bytearray(struct.pack('<IHHiIII', 0xa1b2c3d4, 2, 4, 0, 0, 65535, 1))
|
||
capture_running = True
|
||
capture_started_at = time.time()
|
||
# L'analyse des trames doit impérativement se faire sur l'interface Wi-Fi
|
||
wifi_iface = target_iface or get_wifi_interface()
|
||
capture_iface_used = wifi_iface
|
||
capture_thread = threading.Thread(target=capture_worker, args=(wifi_iface,), daemon=True)
|
||
capture_thread.start()
|
||
print(f"[ap-capture] Analyse des trames Wi-Fi lancée sur l'interface : {wifi_iface}", flush=True)
|
||
return True, f"Capture démarrée sur l'interface Wi-Fi ({wifi_iface})"
|
||
|
||
def stop_capture():
|
||
global capture_running, capture_started_at
|
||
with capture_lock:
|
||
capture_running = False
|
||
capture_started_at = 0.0
|
||
return True, "Capture arrêtée"
|
||
|
||
def clear_capture():
|
||
global capture_packets, capture_pcap_bytes, capture_id_counter, capture_stats, captured_domains, capture_started_at
|
||
with capture_lock:
|
||
capture_packets.clear()
|
||
captured_domains.clear()
|
||
capture_id_counter = 0
|
||
capture_pcap_bytes = bytearray(struct.pack('<IHHiIII', 0xa1b2c3d4, 2, 4, 0, 0, 65535, 1))
|
||
for k in capture_stats:
|
||
capture_stats[k] = 0
|
||
if not capture_running:
|
||
capture_started_at = 0.0
|
||
return True, "Capture réinitialisée"
|
||
|
||
def generate_test_traffic():
|
||
def _run():
|
||
try: subprocess.run(['ping', '-c', '1', '-w', '1', '1.1.1.1'], capture_output=True)
|
||
except Exception: pass
|
||
for host in ('connectivitycheck.gstatic.com', 'google.com', 'wikipedia.org', 'dns.google'):
|
||
try: socket.gethostbyname(host)
|
||
except Exception: pass
|
||
threading.Thread(target=_run, daemon=True).start()
|
||
|
||
def capture_worker(iface):
|
||
global capture_running, capture_id_counter, capture_pcap_bytes
|
||
sock = None
|
||
try:
|
||
# Liaison socket AF_PACKET à l'interface Wi-Fi spécifique
|
||
sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
|
||
sock.bind((iface, 0))
|
||
sock.settimeout(0.8)
|
||
print(f"[ap-capture] Écoute des trames liée à l'interface Wi-Fi : {iface}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-capture] Liaison directe sur {iface} : {e}, tentative avec filtre d'interface...", flush=True)
|
||
try:
|
||
sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
|
||
sock.settimeout(0.8)
|
||
except Exception as e2:
|
||
print(f"[ap-capture] Impossible d'ouvrir la socket raw Wi-Fi : {e2}", flush=True)
|
||
capture_running = False
|
||
return
|
||
|
||
while capture_running:
|
||
try:
|
||
raw_pkt, sll = sock.recvfrom(65535)
|
||
if not raw_pkt: continue
|
||
# Filtrer rigoureusement pour ne garder QUE les trames de l'interface Wi-Fi
|
||
if iface and sll and len(sll) > 0:
|
||
recv_iface = sll[0]
|
||
if recv_iface and recv_iface != iface:
|
||
continue
|
||
ts = time.time()
|
||
pkt_dict = parse_packet(raw_pkt, ts)
|
||
if not pkt_dict: continue
|
||
with capture_lock:
|
||
capture_id_counter += 1
|
||
pkt_dict['id'] = capture_id_counter
|
||
capture_packets.append(pkt_dict)
|
||
sec = int(ts)
|
||
usec = int((ts - sec) * 1e6)
|
||
capture_pcap_bytes.extend(struct.pack('<IIII', sec, usec, len(raw_pkt), len(raw_pkt)) + raw_pkt)
|
||
proto_key = pkt_dict['proto'].lower()
|
||
if proto_key in capture_stats:
|
||
capture_stats[proto_key] += 1
|
||
else:
|
||
capture_stats['other'] += 1
|
||
|
||
# Suivi des noms de domaine consultés (DNS, TLS SNI, HTTP Host)
|
||
dom = (pkt_dict.get('domain') or '').strip().lower()
|
||
if dom and '.' in dom and not dom.endswith('.arpa') and not dom.replace('.', '').isdigit():
|
||
client_ip = pkt_dict.get('src') if pkt_dict.get('proto') in ('DNS', 'TLS', 'HTTP') else pkt_dict.get('dst')
|
||
client_name = device_name(client_ip, '') if client_ip else ''
|
||
if dom not in captured_domains:
|
||
if len(captured_domains) > 1000:
|
||
oldest = min(captured_domains.keys(), key=lambda k: captured_domains[k]['count'])
|
||
del captured_domains[oldest]
|
||
captured_domains[dom] = {
|
||
'domain': dom,
|
||
'count': 1,
|
||
'first_seen': ts,
|
||
'last_seen': ts,
|
||
'last_seen_str': pkt_dict.get('time', ''),
|
||
'last_client_ip': client_ip or '',
|
||
'last_client_name': client_name or '',
|
||
'proto': pkt_dict.get('proto', 'DNS')
|
||
}
|
||
else:
|
||
entry = captured_domains[dom]
|
||
entry['count'] += 1
|
||
entry['last_seen'] = ts
|
||
entry['last_seen_str'] = pkt_dict.get('time', '')
|
||
if client_ip:
|
||
entry['last_client_ip'] = client_ip
|
||
if client_name:
|
||
entry['last_client_name'] = client_name
|
||
if len(capture_packets) > 50000:
|
||
del capture_packets[:500]
|
||
if len(capture_pcap_bytes) > 50 * 1024 * 1024:
|
||
header = capture_pcap_bytes[:24]
|
||
capture_pcap_bytes = header + capture_pcap_bytes[10 * 1024 * 1024:]
|
||
except socket.timeout:
|
||
continue
|
||
except Exception:
|
||
if not capture_running: break
|
||
time.sleep(0.05)
|
||
|
||
if sock:
|
||
try: sock.close()
|
||
except Exception: pass
|
||
|
||
# =====================================================================
|
||
# GESTION DU ROUTAGE VPN PAR CLIENT (WireGuard & OpenVPN)
|
||
# =====================================================================
|
||
VPN_DIR_WG = '/etc/wireguard'
|
||
VPN_DIR_OVPN = '/etc/openvpn'
|
||
VPN_RUN_DIR = '/run/ap-vpn'
|
||
VPN_SCRIPT_DIR = '/run/ap-vpn/scripts'
|
||
vpn_lock = threading.RLock()
|
||
connecting_vpn_pids = set()
|
||
connecting_vpn_pids_lock = threading.RLock()
|
||
|
||
def ensure_vpn_dirs():
|
||
for d in (VPN_DIR_WG, VPN_DIR_OVPN, VPN_RUN_DIR, VPN_SCRIPT_DIR):
|
||
try:
|
||
os.makedirs(d, exist_ok=True)
|
||
os.chmod(d, 0o700)
|
||
except OSError: pass
|
||
|
||
def get_next_vpn_table_id():
|
||
c = db()
|
||
rows = c.execute('SELECT table_id FROM vpn_profiles').fetchall()
|
||
c.close()
|
||
used = {r[0] for r in rows if r[0]}
|
||
for tid in range(101, 300):
|
||
if tid not in used:
|
||
return tid
|
||
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):
|
||
rx, tx = 0, 0
|
||
if not iface: return rx, tx
|
||
# 1. Si c'est WireGuard, lecture des compteurs du pilote noyau WireGuard (wg show)
|
||
if iface.startswith('wg_'):
|
||
try:
|
||
res = subprocess.run(['wg', 'show', iface, 'transfer'], capture_output=True, text=True, timeout=2)
|
||
if res.returncode == 0 and res.stdout.strip():
|
||
wg_rx, wg_tx = 0, 0
|
||
for line in res.stdout.splitlines():
|
||
parts = line.strip().split()
|
||
if len(parts) >= 3:
|
||
try:
|
||
wg_rx += int(parts[1])
|
||
wg_tx += int(parts[2])
|
||
except ValueError: pass
|
||
rx = max(rx, wg_rx)
|
||
tx = max(tx, wg_tx)
|
||
except Exception:
|
||
pass
|
||
# 2. Lecture /proc/net/dev (universel pour interfaces kernel dont tun/tap/wg)
|
||
try:
|
||
with open('/proc/net/dev', 'r') as f:
|
||
for line in f:
|
||
if ':' in line:
|
||
dname, ddata = line.split(':', 1)
|
||
if dname.strip() == iface:
|
||
cols = ddata.split()
|
||
if len(cols) >= 9:
|
||
rx = max(rx, int(cols[0]))
|
||
tx = max(tx, int(cols[8]))
|
||
except Exception: pass
|
||
# 3. Sysfs /sys/class/net/<iface>/statistics
|
||
p = f'/sys/class/net/{iface}/statistics'
|
||
try:
|
||
with open(f'{p}/rx_bytes', 'r') as f: rx = max(rx, int(f.read().strip()))
|
||
except (OSError, ValueError): pass
|
||
try:
|
||
with open(f'{p}/tx_bytes', 'r') as f: tx = max(tx, int(f.read().strip()))
|
||
except (OSError, ValueError): pass
|
||
return rx, tx
|
||
|
||
def get_wireguard_handshake_info(iface):
|
||
if not iface or not iface.startswith('wg_'):
|
||
return None, None
|
||
try:
|
||
res = subprocess.run(['wg', 'show', iface, 'latest-handshakes'], capture_output=True, text=True, timeout=2)
|
||
if res.returncode == 0 and res.stdout.strip():
|
||
for line in res.stdout.splitlines():
|
||
parts = line.strip().split()
|
||
if len(parts) >= 2:
|
||
ts = int(parts[1])
|
||
if ts > 0:
|
||
diff = max(0, int(time.time()) - ts)
|
||
if diff < 120:
|
||
return f"Handshake actif (il y a {diff}s)", diff
|
||
elif diff < 3600:
|
||
return f"Dernier handshake il y a {diff // 60} min", diff
|
||
else:
|
||
return f"Dernier handshake il y a {diff // 3600} h", diff
|
||
else:
|
||
return "En attente du handshake (non reçu)", -1
|
||
except Exception:
|
||
pass
|
||
return None, None
|
||
|
||
vpn_public_ip_cache = {}
|
||
|
||
def get_vpn_public_ip(iface, force_refresh=False):
|
||
if not iface or not is_iface_up(iface):
|
||
return ''
|
||
now = time.time()
|
||
cached = vpn_public_ip_cache.get(iface)
|
||
if not force_refresh and cached and (now - cached.get('time', 0)) < 60:
|
||
return cached.get('ip', '')
|
||
|
||
detected_ip = ''
|
||
# 1. Requête Cloudflare directe sans résolution DNS (ultra-rapide < 250ms)
|
||
try:
|
||
res = subprocess.run(['curl', '-4', '-s', '-k', '--interface', iface, '--max-time', '2', 'https://1.1.1.1/cdn-cgi/trace'],
|
||
capture_output=True, text=True, timeout=3)
|
||
if res.returncode == 0:
|
||
m = re.search(r'^ip=([0-9.]+)', res.stdout, re.M)
|
||
if m:
|
||
detected_ip = m.group(1).strip()
|
||
except Exception:
|
||
pass
|
||
|
||
# 2. Requête alternative via les fournisseurs IP publics usuels
|
||
if not detected_ip:
|
||
urls = [
|
||
'https://api.ipify.org',
|
||
'https://icanhazip.com',
|
||
'https://ifconfig.me/ip',
|
||
'https://ipinfo.io/ip'
|
||
]
|
||
for url in urls:
|
||
try:
|
||
res = subprocess.run(['curl', '-4', '-s', '--interface', iface, '--max-time', '2', url],
|
||
capture_output=True, text=True, timeout=3)
|
||
if res.returncode == 0:
|
||
ip_match = re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', res.stdout)
|
||
if ip_match:
|
||
detected_ip = ip_match.group(0).strip()
|
||
break
|
||
except Exception:
|
||
pass
|
||
|
||
# 3. Requête Python native avec socket SO_BINDTODEVICE
|
||
if not detected_ip:
|
||
try:
|
||
class BoundHTTPConnection(http.client.HTTPSConnection):
|
||
def connect(self):
|
||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
try:
|
||
self.sock.setsockopt(socket.SOL_SOCKET, 25, (iface + '\0').encode('utf-8'))
|
||
except Exception:
|
||
pass
|
||
self.sock.settimeout(3.5)
|
||
self.sock.connect((self.host, self.port))
|
||
if self._tunnel_host:
|
||
self._tunnel()
|
||
self.sock = self._context.wrap_socket(self.sock, server_hostname=self.host)
|
||
|
||
class BoundHandler(urllib.request.HTTPSHandler):
|
||
def https_open(self, req):
|
||
return self.do_open(BoundHTTPConnection, req)
|
||
|
||
opener = urllib.request.build_opener(BoundHandler)
|
||
req = urllib.request.Request('https://api.ipify.org', headers={'User-Agent': 'curl/7.88.1'})
|
||
with opener.open(req, timeout=3.5) as resp:
|
||
content = resp.read().decode('utf-8', errors='ignore').strip()
|
||
ip_match = re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', content)
|
||
if ip_match:
|
||
detected_ip = ip_match.group(0).strip()
|
||
except Exception:
|
||
pass
|
||
|
||
ts_now = time.strftime('%H:%M:%S')
|
||
if detected_ip:
|
||
vpn_public_ip_cache[iface] = {'ip': detected_ip, 'time': now, 'last_tested': ts_now}
|
||
try: enqueue_geoip_lookup(detected_ip)
|
||
except Exception: pass
|
||
else:
|
||
if cached:
|
||
cached['last_tested'] = ts_now
|
||
else:
|
||
vpn_public_ip_cache[iface] = {'ip': '', 'time': now, 'last_tested': ts_now}
|
||
return detected_ip
|
||
|
||
def format_vpn_bytes(b):
|
||
if not b or b <= 0: return "0 o"
|
||
if b < 1024: return f"{int(b)} o"
|
||
if b < 1048576: return f"{b / 1024:.1f} Ko"
|
||
if b < 1073741824: return f"{b / 1048576:.2f} Mo"
|
||
if b < 1099511627776: return f"{b / 1073741824:.2f} Go"
|
||
return f"{b / 1099511627776:.2f} To"
|
||
|
||
def prepare_wireguard_config_text(raw_config, table_id):
|
||
content = raw_config.replace('\r\n', '\n').replace('\r', '\n').strip()
|
||
content = re.sub(r"^\s*DNS\s*=.*$", r"# \g<0> (DNS géré localement)", content, flags=re.MULTILINE|re.IGNORECASE)
|
||
# Neutraliser ListenPort pour attribuer un port dynamique par tunnel et éviter les conflits d'adresses
|
||
content = re.sub(r"^\s*ListenPort\s*=.*$", r"# \g<0> (Port dynamique)", content, flags=re.MULTILINE|re.IGNORECASE)
|
||
if re.search(r"^\s*Table\s*=", content, re.MULTILINE|re.IGNORECASE):
|
||
content = re.sub(r"^\s*Table\s*=.*$", f"Table = {table_id}", content, flags=re.MULTILINE|re.IGNORECASE)
|
||
else:
|
||
content = re.sub(r"(\[Interface\])", f"\\1\nTable = {table_id}", content, flags=re.IGNORECASE, count=1)
|
||
return content
|
||
|
||
def prepare_openvpn_config_text(raw_config, script_path, auth_path=None):
|
||
lines = raw_config.replace('\r\n', '\n').replace('\r', '\n').splitlines()
|
||
filtered = []
|
||
for line in lines:
|
||
s = line.strip()
|
||
if s.startswith(('route-noexec', 'script-security', 'route-up', 'auth-user-pass')):
|
||
continue
|
||
filtered.append(line)
|
||
extra = [
|
||
"",
|
||
"# Directives injectées par AP Manageur pour routage isolé PBR",
|
||
"route-noexec",
|
||
"script-security 2",
|
||
f'route-up "{script_path}"'
|
||
]
|
||
if auth_path:
|
||
extra.append(f'auth-user-pass "{auth_path}"')
|
||
return "\n".join(filtered) + "\n" + "\n".join(extra) + "\n"
|
||
|
||
def list_vpn_profiles():
|
||
c = db()
|
||
rows = c.execute('SELECT id, name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, status, last_error, created_at, updated_at FROM vpn_profiles ORDER BY id ASC').fetchall()
|
||
client_counts = {}
|
||
for r in c.execute('SELECT profile_id, count(*) FROM client_vpn_routes WHERE profile_id > 0 GROUP BY profile_id').fetchall():
|
||
client_counts[r[0]] = r[1]
|
||
c.close()
|
||
result = []
|
||
for r in rows:
|
||
pid = r[0]
|
||
vtype = r[2]
|
||
iface = r[7] or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
|
||
raw_status = r[9]
|
||
actual_up = is_iface_up(iface)
|
||
is_connecting_now = False
|
||
with connecting_vpn_pids_lock:
|
||
is_connecting_now = pid in connecting_vpn_pids
|
||
|
||
if actual_up:
|
||
status = "connected"
|
||
elif is_connecting_now:
|
||
status = "connecting"
|
||
elif raw_status == "error":
|
||
status = "error"
|
||
else:
|
||
status = "disconnected"
|
||
rx, tx = read_iface_traffic(iface) if actual_up else (0, 0)
|
||
cache_entry = vpn_public_ip_cache.get(iface, {})
|
||
pub_ip = cache_entry.get('ip', '') if actual_up else ''
|
||
pub_geo = get_ip_geo(pub_ip) if pub_ip else None
|
||
last_tested = cache_entry.get('last_tested', '') if actual_up else ''
|
||
handshake, handshake_sec = get_wireguard_handshake_info(iface) if (actual_up and vtype == 'wireguard') else (None, None)
|
||
result.append({
|
||
'id': pid,
|
||
'name': r[1],
|
||
'type': vtype,
|
||
'config_content': r[3],
|
||
'auth_user': r[4] or '',
|
||
'has_password': bool(r[5]),
|
||
'table_id': r[6],
|
||
'iface': iface,
|
||
'auto_connect': bool(r[8]),
|
||
'status': status,
|
||
'last_error': r[10] or '',
|
||
'created_at': r[11] or '',
|
||
'updated_at': r[12] or '',
|
||
'rx_bytes': rx,
|
||
'tx_bytes': tx,
|
||
'rx_formatted': format_vpn_bytes(rx),
|
||
'tx_formatted': format_vpn_bytes(tx),
|
||
'clients_count': client_counts.get(pid, 0),
|
||
'public_ip': pub_ip,
|
||
'public_ip_geo': pub_geo,
|
||
'last_tested': last_tested,
|
||
'handshake': handshake,
|
||
'handshake_age_seconds': handshake_sec
|
||
})
|
||
return result
|
||
|
||
def get_vpn_profile(pid):
|
||
c = db()
|
||
row = c.execute('SELECT id, name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, status, last_error, created_at, updated_at FROM vpn_profiles WHERE id=?', (pid,)).fetchone()
|
||
c.close()
|
||
if not row: return None
|
||
return {
|
||
'id': row[0], 'name': row[1], 'type': row[2], 'config_content': row[3],
|
||
'auth_user': row[4], 'auth_pass': row[5], 'table_id': row[6], 'iface': row[7],
|
||
'auto_connect': bool(row[8]), 'status': row[9], 'last_error': row[10]
|
||
}
|
||
|
||
def create_or_update_vpn_profile(data):
|
||
ensure_vpn_dirs()
|
||
pid = data.get('id')
|
||
name = str(data.get('name') or 'Profil VPN').strip()
|
||
vtype = str(data.get('type') or 'wireguard').strip().lower()
|
||
if vtype not in ('wireguard', 'openvpn'): vtype = 'wireguard'
|
||
config_content = str(data.get('config_content') or '').strip()
|
||
auth_user = str(data.get('auth_user') or '').strip()
|
||
auth_pass = str(data.get('auth_pass') or '').strip()
|
||
auto_connect = 1 if data.get('auto_connect') else 0
|
||
now = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
c = db()
|
||
if pid:
|
||
pid = int(pid)
|
||
if not auth_pass:
|
||
old = c.execute('SELECT auth_pass FROM vpn_profiles WHERE id=?', (pid,)).fetchone()
|
||
if old: auth_pass = old[0]
|
||
c.execute('UPDATE vpn_profiles SET name=?, type=?, config_content=?, auth_user=?, auth_pass=?, auto_connect=?, updated_at=? WHERE id=?',
|
||
(name, vtype, config_content, auth_user, auth_pass, auto_connect, now, pid))
|
||
new_id = pid
|
||
else:
|
||
table_id = get_next_vpn_table_id()
|
||
cur = c.execute('INSERT INTO vpn_profiles (name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, status, last_error, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, "", ?, "disconnected", "", ?, ?)',
|
||
(name, vtype, config_content, auth_user, auth_pass, table_id, auto_connect, now, now))
|
||
new_id = cur.lastrowid
|
||
iface = f"wg_ap{new_id}" if vtype == "wireguard" else f"tun_ap{new_id}"
|
||
c.execute('UPDATE vpn_profiles SET iface=? WHERE id=?', (iface, new_id))
|
||
c.commit(); c.close()
|
||
return new_id
|
||
|
||
def delete_vpn_profile(pid):
|
||
disconnect_vpn_profile(pid)
|
||
c = db()
|
||
c.execute('DELETE FROM vpn_profiles WHERE id=?', (pid,))
|
||
c.execute('DELETE FROM client_vpn_routes WHERE profile_id=?', (pid,))
|
||
c.commit(); c.close()
|
||
for p in (f"{VPN_DIR_WG}/wg_ap{pid}.conf", f"{VPN_DIR_OVPN}/ovpn_ap{pid}.conf", f"{VPN_DIR_OVPN}/ovpn_ap{pid}.auth", f"{VPN_SCRIPT_DIR}/up_{pid}.sh"):
|
||
try: os.remove(p)
|
||
except OSError: pass
|
||
sync_vpn_client_rules()
|
||
|
||
def connect_vpn_profile(pid, caller_ip=''):
|
||
with connecting_vpn_pids_lock:
|
||
if pid in connecting_vpn_pids:
|
||
return False, 'Connexion déjà en cours pour ce profil'
|
||
connecting_vpn_pids.add(pid)
|
||
try:
|
||
ensure_vpn_dirs()
|
||
prof = get_vpn_profile(pid)
|
||
if not prof: return False, 'Profil VPN introuvable'
|
||
table_id = prof['table_id'] or (100 + pid)
|
||
vtype = prof['type']
|
||
iface = prof['iface'] or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
|
||
c = db()
|
||
c.execute('UPDATE vpn_profiles SET status="connecting", last_error="" WHERE id=?', (pid,))
|
||
c.commit(); c.close()
|
||
# Activer le forwarding IP et désactiver complètement rp_filter (0 = essentiel pour le brouting)
|
||
subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True)
|
||
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.all.forwarding=1'], capture_output=True)
|
||
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.all.rp_filter=0'], capture_output=True)
|
||
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.default.rp_filter=0'], capture_output=True)
|
||
if vtype == 'wireguard':
|
||
conf_path = f"{VPN_DIR_WG}/{iface}.conf"
|
||
prepared = prepare_wireguard_config_text(prof['config_content'], table_id)
|
||
with open(conf_path, 'w', encoding='utf-8') as f:
|
||
f.write(prepared)
|
||
try: os.chmod(conf_path, 0o600)
|
||
except OSError: pass
|
||
|
||
# 1. Vérifier que le module noyau WireGuard est présent
|
||
if not os.path.exists('/sys/module/wireguard'):
|
||
subprocess.run(['modprobe', 'wireguard'], capture_output=True)
|
||
|
||
# 2. Nettoyage préventif de l'interface et de la table PBR
|
||
subprocess.run(['wg-quick', 'down', iface], capture_output=True)
|
||
subprocess.run(['ip', 'link', 'delete', 'dev', iface], capture_output=True)
|
||
subprocess.run(['ip', 'route', 'flush', 'table', str(table_id)], capture_output=True)
|
||
for _ in range(5):
|
||
r_del = subprocess.run(['ip', 'rule', 'del', 'table', str(table_id)], capture_output=True)
|
||
if r_del.returncode != 0: break
|
||
|
||
# 3. Pré-résolution DNS de l'Endpoint WireGuard si c'est un nom de domaine
|
||
ep_m = re.search(r"^\s*Endpoint\s*=\s*([^:\s]+)\s*:\s*(\d+)", prof['config_content'], re.MULTILINE | re.IGNORECASE)
|
||
if ep_m:
|
||
ep_host, ep_port = ep_m.group(1).strip(), int(ep_m.group(2))
|
||
if not re.match(r"^(\d{1,3}\.){3}\d{1,3}$", ep_host) and ':' not in ep_host:
|
||
dns_resolved = False
|
||
for _ in range(3):
|
||
try:
|
||
socket.getaddrinfo(ep_host, ep_port, socket.AF_INET)
|
||
dns_resolved = True
|
||
break
|
||
except Exception:
|
||
time.sleep(0.5)
|
||
if not dns_resolved:
|
||
print(f"[ap-vpn] Attente résolution DNS pour '{ep_host}'...", flush=True)
|
||
|
||
# 4. Exécution protégée de wg-quick up
|
||
with vpn_lock:
|
||
res = subprocess.run(['wg-quick', 'up', iface], capture_output=True, text=True, timeout=10)
|
||
|
||
if res.returncode != 0:
|
||
err_msg = res.stderr.strip() or res.stdout.strip() or 'Erreur wg-quick up'
|
||
print(f"[ap-vpn] Échec wg-quick up '{iface}' : {err_msg}", flush=True)
|
||
c = db()
|
||
c.execute('UPDATE vpn_profiles SET status="error", last_error=? WHERE id=?', (err_msg, pid))
|
||
c.commit(); c.close()
|
||
return False, f"Échec de connexion WireGuard : {err_msg}"
|
||
# Route par défaut garantie dans la table PBR
|
||
subprocess.run(['ip', 'route', 'replace', 'default', 'dev', iface, 'table', str(table_id)], capture_output=True)
|
||
elif vtype == 'openvpn':
|
||
pid_file = f"{VPN_RUN_DIR}/{iface}.pid"
|
||
if os.path.exists(pid_file):
|
||
try:
|
||
with open(pid_file) as pf: old_pid = pf.read().strip()
|
||
if old_pid: subprocess.run(['kill', '-9', old_pid], capture_output=True)
|
||
except Exception: pass
|
||
subprocess.run(['pkill', '-f', f"ovpn_ap{pid}"], capture_output=True)
|
||
script_path = f"{VPN_SCRIPT_DIR}/up_{pid}.sh"
|
||
script_content = f"""#!/bin/sh\nTABLE="{table_id}"\nDEV="$dev"\nGW="$route_vpn_gateway"\nif [ -n "$GW" ]; then\n ip route replace default via "$GW" dev "$DEV" table "$TABLE"\nelse\n ip route replace default dev "$DEV" table "$TABLE"\nfi\nsysctl -w net.ipv4.ip_forward=1 2>/dev/null || true\nsysctl -w net.ipv4.conf.all.forwarding=1 2>/dev/null || true\nsysctl -w net.ipv4.conf.all.rp_filter=0 2>/dev/null || true\nsysctl -w "net.ipv4.conf.$DEV.rp_filter=0" 2>/dev/null || true\n"""
|
||
with open(script_path, 'w', encoding='utf-8') as f:
|
||
f.write(script_content)
|
||
os.chmod(script_path, 0o755)
|
||
auth_path = None
|
||
if prof['auth_user']:
|
||
auth_path = f"{VPN_DIR_OVPN}/{iface}.auth"
|
||
with open(auth_path, 'w', encoding='utf-8') as f:
|
||
f.write(f"{prof['auth_user']}\n{prof['auth_pass']}\n")
|
||
os.chmod(auth_path, 0o600)
|
||
ovpn_conf = f"{VPN_DIR_OVPN}/{iface}.conf"
|
||
prepared_ovpn = prepare_openvpn_config_text(prof['config_content'], script_path, auth_path)
|
||
if not re.search(r"^\s*dev\s+", prepared_ovpn, re.MULTILINE):
|
||
prepared_ovpn = f"dev {iface}\ndev-type tun\n" + prepared_ovpn
|
||
else:
|
||
prepared_ovpn = re.sub(r"^\s*dev\s+.*$", f"dev {iface}\ndev-type tun", prepared_ovpn, flags=re.MULTILINE)
|
||
with open(ovpn_conf, 'w', encoding='utf-8') as f:
|
||
f.write(prepared_ovpn)
|
||
os.chmod(ovpn_conf, 0o600)
|
||
res = subprocess.run(['openvpn', '--config', ovpn_conf, '--daemon', f"ovpn_ap{pid}", '--writepid', pid_file], capture_output=True, text=True)
|
||
if res.returncode != 0:
|
||
err_msg = res.stderr.strip() or res.stdout.strip() or 'Erreur openvpn daemon'
|
||
c = db()
|
||
c.execute('UPDATE vpn_profiles SET status="error", last_error=? WHERE id=?', (err_msg, pid))
|
||
c.commit(); c.close()
|
||
return False, f"Échec de connexion OpenVPN : {err_msg}"
|
||
for _ in range(15):
|
||
time.sleep(0.3)
|
||
if is_iface_up(iface): break
|
||
|
||
# Ajustements réseau communs (WireGuard et OpenVPN)
|
||
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{iface}.rp_filter=0'], capture_output=True)
|
||
import glob
|
||
for p in glob.glob('/proc/sys/net/ipv4/conf/*/rp_filter'):
|
||
try:
|
||
with open(p, 'w') as f: f.write('0')
|
||
except Exception: pass
|
||
for p in glob.glob('/proc/sys/net/ipv4/conf/*/forwarding'):
|
||
try:
|
||
with open(p, 'w') as f: f.write('1')
|
||
except Exception: pass
|
||
# NAT Masquerade
|
||
subprocess.run(['iptables', '-t', 'nat', '-C', 'POSTROUTING', '-o', iface, '-j', 'MASQUERADE'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'nat', '-I', 'POSTROUTING', '1', '-o', iface, '-j', 'MASQUERADE'], capture_output=True)
|
||
# Filtrage FORWARD (essentiel dans Docker / Debian)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-o', iface, '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', iface, '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', 'br0', '-o', iface, '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', iface, '-o', 'br0', '-j', 'ACCEPT'], capture_output=True)
|
||
if INTERFACE:
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', INTERFACE, '-o', iface, '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', iface, '-o', INTERFACE, '-j', 'ACCEPT'], capture_output=True)
|
||
# Clamping MSS TCP (évite le blocage des flux HTTPS/TLS sur tunnel VPN MTU 1420)
|
||
subprocess.run(['iptables', '-t', 'mangle', '-C', 'FORWARD', '-p', 'tcp', '--tcp-flags', 'SYN,RST', 'SYN', '-o', iface, '-j', 'TCPMSS', '--clamp-mss-to-pmtu'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'mangle', '-I', 'FORWARD', '1', '-p', 'tcp', '--tcp-flags', 'SYN,RST', 'SYN', '-o', iface, '-j', 'TCPMSS', '--clamp-mss-to-pmtu'], capture_output=True)
|
||
|
||
# Permettre à la machine locale de router du trafic via l'interface VPN (pour vérification IP publique, ping, etc.)
|
||
rule_prio = 9800 + pid * 2
|
||
subprocess.run(['ip', 'rule', 'del', 'priority', str(rule_prio)], capture_output=True)
|
||
subprocess.run(['ip', 'rule', 'del', 'priority', str(rule_prio + 1)], capture_output=True)
|
||
subprocess.run(['ip', 'rule', 'add', 'oif', iface, 'lookup', str(table_id), 'priority', str(rule_prio)], capture_output=True)
|
||
time.sleep(0.3)
|
||
try:
|
||
r_ip = subprocess.run(['ip', '-4', '-o', 'addr', 'show', 'dev', iface], capture_output=True, text=True)
|
||
if r_ip.returncode == 0:
|
||
m_ip = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+)', r_ip.stdout)
|
||
if m_ip:
|
||
subprocess.run(['ip', 'rule', 'add', 'from', m_ip.group(1), 'lookup', str(table_id), 'priority', str(rule_prio + 1)], capture_output=True)
|
||
except Exception: pass
|
||
|
||
c = db()
|
||
c.execute('UPDATE vpn_profiles SET status="connected", last_error="", iface=? WHERE id=?', (iface, pid))
|
||
c.commit(); c.close()
|
||
log('vpn_connect', f"Connexion VPN : {prof['name']} ({vtype})", caller_ip or 'SYSTEM', 'VPN')
|
||
sync_vpn_client_rules()
|
||
|
||
try:
|
||
vtype_label = "WireGuard" if vtype == "wireguard" else "OpenVPN"
|
||
vars_dict = {
|
||
"name": prof['name'],
|
||
"vpn": prof['name'],
|
||
"profil": prof['name'],
|
||
"type": vtype_label,
|
||
"iface": iface,
|
||
"date": datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')
|
||
}
|
||
dispatch_notification(
|
||
'vpn_profile_connected',
|
||
title=f"🛡️ Tunnel VPN connecté : {prof['name']}",
|
||
message=f"Le profil VPN « {prof['name']} » ({vtype_label}) est désormais connecté avec succès (interface {iface}).",
|
||
details=f"Profil: {prof['name']} | Type: {vtype_label} | Interface: {iface}",
|
||
vars_dict=vars_dict
|
||
)
|
||
except Exception as e_notif:
|
||
print(f"[ap-vpn] Erreur notification connexion profil : {e_notif}", flush=True)
|
||
|
||
# Purge conntrack immédiate pour les clients associés afin que le trafic bascule instantanément vers ce tunnel
|
||
try:
|
||
c_pur = db()
|
||
assigned_macs = [r[0] for r in c_pur.execute('SELECT mac FROM client_vpn_routes WHERE profile_id=?', (pid,)).fetchall()]
|
||
c_pur.close()
|
||
mac_to_ip = get_all_mac_to_ips()
|
||
for mac in assigned_macs:
|
||
ip = mac_to_ip.get(mac.upper(), '')
|
||
if ip and ip not in ('', 'Non attribuée', '—'):
|
||
subprocess.run(['conntrack', '-D', '-s', ip], capture_output=True)
|
||
subprocess.run(['conntrack', '-D', '-d', ip], capture_output=True)
|
||
subprocess.run(['ip', 'neigh', 'flush', 'to', ip], capture_output=True)
|
||
except Exception: pass
|
||
subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True)
|
||
|
||
# Lancer immédiatement en tâche de fond la vérification de l'IP publique
|
||
def _check_ip_bg():
|
||
time.sleep(1.0)
|
||
get_vpn_public_ip(iface, force_refresh=True)
|
||
threading.Thread(target=_check_ip_bg, daemon=True).start()
|
||
|
||
return True, f"Profil {prof['name']} connecté avec succès"
|
||
except Exception as e:
|
||
err_msg = str(e)
|
||
c = db()
|
||
c.execute('UPDATE vpn_profiles SET status="error", last_error=? WHERE id=?', (err_msg, pid))
|
||
c.commit(); c.close()
|
||
return False, f"Erreur de connexion : {err_msg}"
|
||
finally:
|
||
with connecting_vpn_pids_lock:
|
||
connecting_vpn_pids.discard(pid)
|
||
|
||
def disconnect_vpn_profile(pid, caller_ip=''):
|
||
prof = get_vpn_profile(pid)
|
||
if not prof: return False, 'Profil VPN introuvable'
|
||
table_id = prof['table_id'] or (100 + pid)
|
||
vtype = prof['type']
|
||
iface = prof['iface'] or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
|
||
try:
|
||
if vtype == 'wireguard':
|
||
subprocess.run(['wg-quick', 'down', iface], capture_output=True)
|
||
subprocess.run(['ip', 'link', 'delete', 'dev', iface], capture_output=True)
|
||
elif vtype == 'openvpn':
|
||
pid_file = f"{VPN_RUN_DIR}/{iface}.pid"
|
||
if os.path.exists(pid_file):
|
||
try:
|
||
with open(pid_file) as pf: p_id = pf.read().strip()
|
||
if p_id: subprocess.run(['kill', '-9', p_id], capture_output=True)
|
||
except Exception: pass
|
||
try: os.remove(pid_file)
|
||
except OSError: pass
|
||
subprocess.run(['pkill', '-f', f"ovpn_ap{pid}"], capture_output=True)
|
||
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
|
||
subprocess.run(['ip', 'link', 'delete', 'dev', iface], capture_output=True)
|
||
# Nettoyage iptables
|
||
subprocess.run(['iptables', '-t', 'nat', '-D', 'POSTROUTING', '-o', iface, '-j', 'MASQUERADE'], capture_output=True)
|
||
subprocess.run(['iptables', '-D', 'FORWARD', '-o', iface, '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-D', 'FORWARD', '-i', iface, '-m', 'state', '--state', 'RELATED,ESTABLISHED', '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'mangle', '-D', 'FORWARD', '-p', 'tcp', '--tcp-flags', 'SYN,RST', 'SYN', '-o', iface, '-j', 'TCPMSS', '--clamp-mss-to-pmtu'], capture_output=True)
|
||
subprocess.run(['ip', 'route', 'flush', 'table', str(table_id)], capture_output=True)
|
||
# Nettoyage règles locales et cache IP
|
||
vpn_public_ip_cache.pop(iface, None)
|
||
subprocess.run(['ip', 'rule', 'del', 'oif', iface, 'lookup', str(table_id)], capture_output=True)
|
||
try:
|
||
r_ip = subprocess.run(['ip', '-4', '-o', 'addr', 'show', 'dev', iface], capture_output=True, text=True)
|
||
if r_ip.returncode == 0:
|
||
m_ip = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+)', r_ip.stdout)
|
||
if m_ip:
|
||
subprocess.run(['ip', 'rule', 'del', 'from', m_ip.group(1), 'lookup', str(table_id)], capture_output=True)
|
||
except Exception: pass
|
||
c = db()
|
||
c.execute('UPDATE vpn_profiles SET status="disconnected", last_error="" WHERE id=?', (pid,))
|
||
c.commit(); c.close()
|
||
log('vpn_disconnect', f"Déconnexion VPN : {prof['name']} ({vtype})", caller_ip or 'SYSTEM', 'VPN')
|
||
sync_vpn_client_rules()
|
||
|
||
try:
|
||
vtype_label = "WireGuard" if vtype == "wireguard" else "OpenVPN"
|
||
vars_dict = {
|
||
"name": prof['name'],
|
||
"vpn": prof['name'],
|
||
"profil": prof['name'],
|
||
"type": vtype_label,
|
||
"iface": iface,
|
||
"date": datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')
|
||
}
|
||
dispatch_notification(
|
||
'vpn_profile_disconnected',
|
||
title=f"⚠️ Tunnel VPN déconnecté : {prof['name']}",
|
||
message=f"Le profil VPN « {prof['name']} » ({vtype_label}) a été déconnecté (interface {iface}).",
|
||
details=f"Profil: {prof['name']} | Type: {vtype_label} | Interface: {iface}",
|
||
vars_dict=vars_dict
|
||
)
|
||
except Exception as e_notif:
|
||
print(f"[ap-vpn] Erreur notification déconnexion profil : {e_notif}", flush=True)
|
||
|
||
# Purge conntrack immédiate pour tous les clients du profil désactivé
|
||
try:
|
||
c_pur = db()
|
||
assigned_macs = [r[0] for r in c_pur.execute('SELECT mac FROM client_vpn_routes WHERE profile_id=?', (pid,)).fetchall()]
|
||
active_left = c_pur.execute('SELECT COUNT(*) FROM vpn_profiles WHERE status="connected" AND id != ?', (pid,)).fetchone()[0]
|
||
c_pur.close()
|
||
mac_to_ip = get_all_mac_to_ips()
|
||
for mac in assigned_macs:
|
||
ip = mac_to_ip.get(mac.upper(), '')
|
||
if ip and ip not in ('', 'Non attribuée', '—'):
|
||
subprocess.run(['conntrack', '-D', '-s', ip], capture_output=True)
|
||
subprocess.run(['conntrack', '-D', '-d', ip], capture_output=True)
|
||
subprocess.run(['ip', 'neigh', 'flush', 'to', ip], capture_output=True)
|
||
if active_left == 0:
|
||
# Tous les profils VPN sont désormais désactivés : purge conntrack complète
|
||
subprocess.run(['conntrack', '-F'], capture_output=True)
|
||
except Exception: pass
|
||
subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True)
|
||
|
||
return True, f"Profil {prof['name']} déconnecté"
|
||
except Exception as e:
|
||
c = db()
|
||
c.execute('UPDATE vpn_profiles SET status="disconnected", last_error=? WHERE id=?', (str(e), pid))
|
||
c.commit(); c.close()
|
||
sync_vpn_client_rules()
|
||
try:
|
||
subprocess.run(['conntrack', '-F'], capture_output=True)
|
||
subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True)
|
||
except Exception: pass
|
||
return False, str(e)
|
||
|
||
def list_vpn_clients():
|
||
all_devs = all_devices().get('devices', [])
|
||
c = db()
|
||
routes = {row[0].upper(): {'profile_id': row[1], 'kill_switch': row[2]}
|
||
for row in c.execute('SELECT mac, profile_id, kill_switch FROM client_vpn_routes').fetchall()}
|
||
profiles = {row[0]: {'id': row[0], 'name': row[1], 'type': row[2], 'status': row[3], 'iface': row[4]}
|
||
for row in c.execute('SELECT id, name, type, status, iface FROM vpn_profiles').fetchall()}
|
||
c.close()
|
||
seen_macs = set()
|
||
result = []
|
||
for d in all_devs:
|
||
mac = (d.get('mac') or '').upper()
|
||
if not mac or mac in seen_macs: continue
|
||
seen_macs.add(mac)
|
||
route = routes.get(mac, {'profile_id': 0, 'kill_switch': 0})
|
||
pid = route['profile_id']
|
||
prof = profiles.get(pid)
|
||
is_conn = bool(d.get('connected'))
|
||
|
||
eff_status = 'direct'
|
||
if pid > 0 and prof:
|
||
is_connected = (prof['status'] == 'connected' and is_iface_up(prof['iface']))
|
||
if is_connected:
|
||
eff_status = 'routed' if is_conn else 'offline'
|
||
else:
|
||
if is_conn:
|
||
eff_status = 'blocked' if route['kill_switch'] else 'direct_fallback'
|
||
else:
|
||
eff_status = 'offline'
|
||
elif pid > 0 and not prof:
|
||
eff_status = 'direct'
|
||
pid = 0
|
||
elif not is_conn:
|
||
eff_status = 'offline'
|
||
|
||
raw_ip = d.get('ip') or ''
|
||
ip_val = '' if raw_ip in ('Non attribuée', '—') else raw_ip
|
||
|
||
result.append({
|
||
'mac': mac,
|
||
'ip': ip_val,
|
||
'name': d.get('name') or ('Client ' + mac.replace(':', '')[-4:]),
|
||
'online': is_conn,
|
||
'device_type': d.get('device_type') or 'generic',
|
||
'profile_id': pid,
|
||
'profile_name': prof['name'] if (pid > 0 and prof) else 'Connexion directe (Sans VPN)',
|
||
'profile_type': prof['type'] if (pid > 0 and prof) else '',
|
||
'profile_status': prof['status'] if (pid > 0 and prof) else '',
|
||
'kill_switch': route['kill_switch'],
|
||
'routing_status': eff_status,
|
||
'lan_isolated': (eff_status == 'routed')
|
||
})
|
||
|
||
for mac, route in routes.items():
|
||
if mac in seen_macs: continue
|
||
seen_macs.add(mac)
|
||
pid = route['profile_id']
|
||
prof = profiles.get(pid)
|
||
result.append({
|
||
'mac': mac,
|
||
'ip': '',
|
||
'name': 'Client ' + mac.replace(':', '')[-4:],
|
||
'online': False,
|
||
'device_type': 'generic',
|
||
'profile_id': pid,
|
||
'profile_name': prof['name'] if (pid > 0 and prof) else 'Connexion directe (Sans VPN)',
|
||
'profile_type': prof['type'] if (pid > 0 and prof) else '',
|
||
'profile_status': prof['status'] if (pid > 0 and prof) else '',
|
||
'kill_switch': route['kill_switch'],
|
||
'routing_status': 'offline',
|
||
'lan_isolated': False
|
||
})
|
||
|
||
def _vpn_client_sort(c):
|
||
conn_rank = 0 if c['online'] else 1
|
||
routed_rank = 0 if c['profile_id'] > 0 else 1
|
||
return (conn_rank, routed_rank, c['name'].lower())
|
||
|
||
result.sort(key=_vpn_client_sort)
|
||
return result
|
||
|
||
def assign_client_vpn(mac, profile_id, kill_switch):
|
||
mac = (mac or '').strip().upper()
|
||
if not mac: return
|
||
now = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
c = db()
|
||
c.execute('INSERT OR REPLACE INTO client_vpn_routes (mac, profile_id, kill_switch, updated_at) VALUES (?, ?, ?, ?)',
|
||
(mac, int(profile_id), 1 if kill_switch else 0, now))
|
||
c.commit()
|
||
|
||
prof_name = 'Direct WAN (Sans VPN)'
|
||
if int(profile_id) > 0:
|
||
row = c.execute('SELECT name FROM vpn_profiles WHERE id=?', (profile_id,)).fetchone()
|
||
if row: prof_name = row[0]
|
||
c_name_row = c.execute('SELECT name, last_ip FROM client_names WHERE mac=?', (mac,)).fetchone()
|
||
c.close()
|
||
|
||
dev_name = c_name_row[0] if c_name_row else 'Appareil Wi-Fi'
|
||
client_ip = (c_name_row[1] if c_name_row and c_name_row[1] != 'Non attribuée' else '') or station_live_ips.get(mac, '')
|
||
|
||
# 1. Appliquer immédiatement les règles de brouting, ip rule et iptables
|
||
sync_vpn_client_rules()
|
||
|
||
# 2. Vider les connexions conntrack existantes pour ce client afin que la bascule soit instantanée
|
||
if client_ip and client_ip not in ('', 'Non attribuée', '—'):
|
||
subprocess.run(['conntrack', '-D', '-s', client_ip], capture_output=True)
|
||
subprocess.run(['conntrack', '-D', '-d', client_ip], capture_output=True)
|
||
subprocess.run(['ip', 'neigh', 'flush', 'to', client_ip], capture_output=True)
|
||
subprocess.run(['ip', 'route', 'flush', 'cache'], capture_output=True)
|
||
|
||
# 3. Journaliser le changement de profil VPN
|
||
ks_info = " (Kill-Switch: Actif)" if kill_switch else ""
|
||
log('vpn_route', f"Routage VPN : {prof_name}{ks_info}", client_ip or 'Non attribuée', mac)
|
||
|
||
# 4. Notification d'alerte connexion / déconnexion VPN client
|
||
if int(profile_id) > 0:
|
||
dispatch_notification(
|
||
'vpn_client_connected',
|
||
"🛡️ Client routé via VPN",
|
||
f"L'appareil « {dev_name} » ({client_ip or mac}) est désormais connecté et routé via le VPN « {prof_name} ».",
|
||
details={"Nom": dev_name, "IP": client_ip or "—", "MAC": mac, "Profil VPN": prof_name, "Kill-Switch": "Actif" if kill_switch else "Désactivé", "Date": now},
|
||
priority=5,
|
||
level="success",
|
||
vars_dict={"name": dev_name, "ip": client_ip or "—", "mac": mac, "vpn": prof_name, "date": now}
|
||
)
|
||
else:
|
||
dispatch_notification(
|
||
'vpn_client_disconnected',
|
||
"🌐 Client déconnecté du VPN",
|
||
f"L'appareil « {dev_name} » ({client_ip or mac}) n'est plus routé via le VPN (connexion directe WAN).",
|
||
details={"Nom": dev_name, "IP": client_ip or "—", "MAC": mac, "Date": now},
|
||
priority=4,
|
||
level="info",
|
||
vars_dict={"name": dev_name, "ip": client_ip or "—", "mac": mac, "vpn": "Direct WAN", "date": now}
|
||
)
|
||
|
||
def get_local_lan_subnets():
|
||
subnets = []
|
||
host_ips = []
|
||
try:
|
||
import ipaddress
|
||
# 1. Interfaces principales (pont et Wi-Fi)
|
||
for dev in [INTERFACE, get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0')), 'br0', 'eth0']:
|
||
if not dev: continue
|
||
try:
|
||
ip_cidr, _, _ = get_iface_ip_info(dev)
|
||
if ip_cidr and '/' in ip_cidr:
|
||
iface_obj = ipaddress.IPv4Interface(ip_cidr)
|
||
if iface_obj.network.prefixlen >= 16:
|
||
subnets.append(str(iface_obj.network))
|
||
host_ips.append(str(iface_obj.ip))
|
||
except Exception: pass
|
||
# 2. Interfaces système locales
|
||
r = subprocess.run(['ip', '-4', '-o', 'addr', 'show'], capture_output=True, text=True)
|
||
if r.returncode == 0:
|
||
for line in r.stdout.splitlines():
|
||
parts = line.split()
|
||
if len(parts) >= 4:
|
||
d = parts[1]
|
||
c = parts[3]
|
||
if not d.startswith(('wg_', 'tun_', 'ovpn_', 'lo')):
|
||
try:
|
||
iface_obj = ipaddress.IPv4Interface(c)
|
||
if iface_obj.network.prefixlen >= 16 and iface_obj.is_private:
|
||
subnets.append(str(iface_obj.network))
|
||
host_ips.append(str(iface_obj.ip))
|
||
except Exception: pass
|
||
except Exception: pass
|
||
subnets = list(dict.fromkeys(subnets))
|
||
host_ips = list(dict.fromkeys(host_ips))
|
||
if not subnets:
|
||
subnets = ['10.42.0.0/24', '192.168.1.0/24']
|
||
return subnets, host_ips
|
||
|
||
def get_all_mac_to_ips():
|
||
"""Détecte de manière exhaustive l'adresse IP associée à chaque adresse MAC sans appeler clients()."""
|
||
mac_to_ip = {}
|
||
|
||
for m, ip in station_live_ips.items():
|
||
if m and ip and ip not in ('Non attribuée', '—'):
|
||
mac_to_ip[m.upper()] = ip
|
||
|
||
try:
|
||
r = subprocess.run(['ip', 'neigh', 'show'], capture_output=True, text=True, timeout=1)
|
||
if r.returncode == 0:
|
||
for line in r.stdout.splitlines():
|
||
m = re.search(r'^(\S+).*?lladdr ([0-9a-f:]{17})', line, re.I)
|
||
if m and 'FAILED' not in line:
|
||
nip = m.group(1)
|
||
nmac = m.group(2).upper()
|
||
if nmac not in mac_to_ip and not nip.startswith('127.'):
|
||
mac_to_ip[nmac] = nip
|
||
except Exception: pass
|
||
|
||
try:
|
||
for l_mac, l_ip, _ in lease_entries():
|
||
if l_mac and l_ip and l_mac not in mac_to_ip:
|
||
mac_to_ip[l_mac.upper()] = l_ip
|
||
except Exception: pass
|
||
|
||
try:
|
||
c = db()
|
||
for row in c.execute('SELECT mac, last_ip FROM client_names').fetchall():
|
||
m = (row[0] or '').upper()
|
||
ip = row[1] or ''
|
||
if m and ip and m not in mac_to_ip and ip not in ('Non attribuée', '—'):
|
||
mac_to_ip[m] = ip
|
||
for row in c.execute('SELECT mac, ip FROM connection_logs ORDER BY id DESC LIMIT 100').fetchall():
|
||
m = (row[0] or '').upper()
|
||
ip = row[1] or ''
|
||
if m and ip and m not in mac_to_ip and ip not in ('Non attribuée', '—'):
|
||
mac_to_ip[m] = ip
|
||
c.close()
|
||
except Exception: pass
|
||
|
||
return mac_to_ip
|
||
|
||
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."""
|
||
nft_bin = find_bin('nft')
|
||
if not assigned_macs:
|
||
# Aucun client assigné à un VPN : supprimer la table pour ne jamais interférer avec le pont hôte
|
||
if nft_bin:
|
||
subprocess.run([nft_bin, 'delete', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
|
||
return
|
||
|
||
for mod in ['br_netfilter', 'nf_tables', 'nft_compat']:
|
||
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
|
||
blocked_macs = set()
|
||
try:
|
||
blocked_macs.update(blocked_set())
|
||
lims = get_client_limits_dict() or {}
|
||
for m, l in lims.items():
|
||
if l.get('quota_exceeded'):
|
||
blocked_macs.add(m.upper())
|
||
except Exception: pass
|
||
|
||
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
|
||
|
||
# meta broute set 1 : détourne la trame du pont Ethernet directement dans la pile IP locale (L3)
|
||
# meta pkttype set host : force le noyau (ip_forward) à accepter le paquet au lieu de le jeter comme PACKET_OTHERHOST
|
||
cmd_v4 = [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, capture_output=True, text=True)
|
||
if res.returncode != 0:
|
||
print(f"[ap-vpn] Erreur nftables broute {clean_mac} : {res.stderr.strip()}", flush=True)
|
||
else:
|
||
print(f"[ap-vpn] [NFTABLES] Broute actif pour {clean_mac} (meta broute set 1, pkttype host)", flush=True)
|
||
|
||
# Bloquer les fuites IPv6 pour forcer la bascule complète du smartphone en IPv4 via WireGuard
|
||
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)
|
||
|
||
def sync_vpn_client_rules():
|
||
with vpn_lock:
|
||
try:
|
||
c = db()
|
||
profiles = {row[0]: {'id': row[0], 'status': row[1], 'table_id': row[2], 'iface': row[3], 'name': row[4]}
|
||
for row in c.execute('SELECT id, status, table_id, iface, name FROM vpn_profiles').fetchall()}
|
||
client_routes = {row[0].upper(): {'profile_id': row[1], 'kill_switch': row[2]}
|
||
for row in c.execute('SELECT mac, profile_id, kill_switch FROM client_vpn_routes').fetchall()}
|
||
c.close()
|
||
|
||
assigned_macs = [mac for mac, rinfo in client_routes.items() if rinfo.get('profile_id', 0) > 0]
|
||
connected_profiles = [p for p in profiles.values() if p['status'] == 'connected' and is_iface_up(p.get('iface', ''))]
|
||
|
||
# Si aucun appareil n'est routé et aucun VPN n'est actif, désactiver toutes les chaînes pour ne pas impacter l'hôte
|
||
if not assigned_macs and not connected_profiles:
|
||
while subprocess.run(['iptables', '-D', 'INPUT', '-j', 'AP_VPN_INPUT'], capture_output=True).returncode == 0: pass
|
||
subprocess.run(['iptables', '-F', 'AP_VPN_INPUT'], capture_output=True)
|
||
while subprocess.run(['iptables', '-D', 'FORWARD', '-j', 'AP_VPN_ISOLATION'], capture_output=True).returncode == 0: pass
|
||
subprocess.run(['iptables', '-F', 'AP_VPN_ISOLATION'], capture_output=True)
|
||
while subprocess.run(['iptables', '-t', 'nat', '-D', 'PREROUTING', '-j', 'AP_VPN_DNS'], capture_output=True).returncode == 0: pass
|
||
subprocess.run(['iptables', '-t', 'nat', '-F', 'AP_VPN_DNS'], capture_output=True)
|
||
while subprocess.run(['iptables', '-t', 'mangle', '-D', 'PREROUTING', '-j', 'AP_VPN_MANGLE'], capture_output=True).returncode == 0: pass
|
||
subprocess.run(['iptables', '-t', 'mangle', '-F', 'AP_VPN_MANGLE'], capture_output=True)
|
||
subprocess.run(['ebtables', '-t', 'broute', '-F', 'BROUTING'], capture_output=True)
|
||
nft_b = find_bin('nft')
|
||
if nft_b: subprocess.run([nft_b, 'delete', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
|
||
return
|
||
|
||
# 1. Nettoyage des anciennes règles ip rule (plage 9900 - 29999)
|
||
r = subprocess.run(['ip', 'rule', 'show'], capture_output=True, text=True, timeout=2)
|
||
if r.returncode == 0:
|
||
for line in r.stdout.splitlines():
|
||
m = re.match(r"^\s*(\d+):", line)
|
||
if m:
|
||
prio = int(m.group(1))
|
||
if 9900 <= prio <= 29999:
|
||
for _ in range(5):
|
||
if subprocess.run(['ip', 'rule', 'del', 'priority', str(prio)], capture_output=True, timeout=2).returncode != 0:
|
||
break
|
||
|
||
# 2. Réinitialisation de la chaîne iptables mangle AP_VPN_MANGLE
|
||
subprocess.run(['iptables', '-t', 'mangle', '-N', 'AP_VPN_MANGLE'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'mangle', '-F', 'AP_VPN_MANGLE'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'mangle', '-D', 'PREROUTING', '-j', 'AP_VPN_MANGLE'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'mangle', '-I', 'PREROUTING', '1', '-j', 'AP_VPN_MANGLE'], capture_output=True)
|
||
|
||
# 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', '-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)
|
||
|
||
# 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.
|
||
subprocess.run(['iptables', '-t', 'nat', '-N', 'AP_VPN_DNS'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'nat', '-F', 'AP_VPN_DNS'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'nat', '-D', 'PREROUTING', '-j', 'AP_VPN_DNS'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'nat', '-I', 'PREROUTING', '1', '-j', 'AP_VPN_DNS'], capture_output=True)
|
||
|
||
# 4. Réinitialisation des chaînes de filtrage et d'isolation LAN stricte (FORWARD et INPUT)
|
||
subprocess.run(['iptables', '-N', 'AP_VPN_ISOLATION'], capture_output=True)
|
||
subprocess.run(['iptables', '-F', 'AP_VPN_ISOLATION'], capture_output=True)
|
||
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'conntrack', '--ctstate', 'ESTABLISHED,RELATED', '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-p', 'udp', '--dport', '67:68', '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-p', 'udp', '--sport', '67:68', '-j', 'ACCEPT'], capture_output=True)
|
||
|
||
subprocess.run(['iptables', '-N', 'AP_VPN_INPUT'], capture_output=True)
|
||
subprocess.run(['iptables', '-F', 'AP_VPN_INPUT'], capture_output=True)
|
||
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-i', 'lo', '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-m', 'conntrack', '--ctstate', 'ESTABLISHED,RELATED', '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-p', 'udp', '--dport', '67:68', '-j', 'ACCEPT'], capture_output=True)
|
||
|
||
# 5. Détection des adresses IP des clients et réseaux locaux
|
||
mac_to_ip = get_all_mac_to_ips()
|
||
local_subnets, host_ips = get_local_lan_subnets()
|
||
priv_subnets = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '169.254.0.0/16']
|
||
all_isolated_subnets = list(dict.fromkeys(priv_subnets + local_subnets))
|
||
|
||
# Serveur DNS public cible pour les tunnels VPN (Cloudflare 1.1.1.1 ou premier DNS public configuré)
|
||
dns_target = '1.1.1.1'
|
||
dns_list = get_dns_servers()
|
||
if dns_list:
|
||
try:
|
||
import ipaddress
|
||
if not ipaddress.ip_address(dns_list[0]).is_private:
|
||
dns_target = dns_list[0]
|
||
except Exception: pass
|
||
|
||
# 6. Application du brouting natif nftables pour tous les clients assignés (sans exemption LAN)
|
||
assigned_macs = [mac for mac, rinfo in client_routes.items() if rinfo.get('profile_id', 0) > 0]
|
||
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
|
||
active_tables = set()
|
||
lan_ifaces = list(dict.fromkeys(['br0', 'eth0', 'eth1', 'enp0s3', 'enp1s0'] + ([INTERFACE] if INTERFACE else [])))
|
||
|
||
for mac, route_info in client_routes.items():
|
||
pid = route_info.get('profile_id', 0)
|
||
kill_switch = route_info.get('kill_switch', 0)
|
||
if pid <= 0: continue
|
||
prof = profiles.get(pid)
|
||
if not prof: continue
|
||
|
||
table_id = prof['table_id']
|
||
is_connected = (prof['status'] == 'connected' and is_iface_up(prof['iface']))
|
||
client_ip = mac_to_ip.get(mac, '')
|
||
|
||
if is_connected:
|
||
active_tables.add(table_id)
|
||
# A. Marquer les paquets par MAC et par IP dans iptables mangle
|
||
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-m', 'mac', '--mac-source', mac, '-j', 'MARK', '--set-mark', str(table_id)], capture_output=True)
|
||
if client_ip:
|
||
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-s', client_ip, '-j', 'MARK', '--set-mark', str(table_id)], capture_output=True)
|
||
|
||
# B. Redirection DNS transparente vers un serveur DNS public via le VPN
|
||
for proto in ('udp', 'tcp'):
|
||
if client_ip:
|
||
subprocess.run(['iptables', '-t', 'nat', '-A', 'AP_VPN_DNS', '-s', client_ip, '-p', proto, '--dport', '53', '-j', 'DNAT', '--to-destination', f'{dns_target}:53'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'nat', '-A', 'AP_VPN_DNS', '-m', 'mac', '--mac-source', mac, '-p', proto, '--dport', '53', '-j', 'DNAT', '--to-destination', f'{dns_target}:53'], capture_output=True)
|
||
|
||
# C. Isolation stricte de l'hôte AP (INPUT) : le client VPN ne peut pas accéder à l'interface d'administration ou aux services hôte
|
||
if client_ip:
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-s', client_ip, '-j', 'DROP'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
|
||
|
||
# D. Règles de transfert et isolation LAN (FORWARD)
|
||
# 1. Autoriser la sortie vers l'interface VPN
|
||
if client_ip:
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
|
||
# 2. Autoriser le retour depuis l'interface VPN
|
||
if client_ip:
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-i', prof['iface'], '-d', client_ip, '-j', 'ACCEPT'], capture_output=True)
|
||
|
||
# 3. INTERDICTION STRICTE d'accès à toutes les ressources du réseau local (sous-réseaux privés RFC1918 et LAN)
|
||
for sub in all_isolated_subnets:
|
||
if client_ip:
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-d', sub, '-j', 'REJECT', '--reject-with', 'icmp-port-unreachable'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-d', sub, '-j', 'REJECT', '--reject-with', 'icmp-port-unreachable'], capture_output=True)
|
||
|
||
# 4. Interdiction de sortir par les interfaces locales (br0, eth0, wlan)
|
||
for o_if in lan_ifaces:
|
||
if client_ip:
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-o', o_if, '-j', 'DROP'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-o', o_if, '-j', 'DROP'], capture_output=True)
|
||
|
||
# 5. Tout autre paquet provenant de ce client qui ne passe pas par l'interface VPN est rejeté
|
||
if client_ip:
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-j', 'DROP'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
|
||
|
||
# E. Routage VPN par adresse IP dans ip rule (tout le trafic vers table_id, AUCUNE exemption LAN)
|
||
if client_ip:
|
||
subprocess.run(['ip', 'rule', 'add', 'from', client_ip, 'lookup', str(table_id), 'priority', str(prio_base)], capture_output=True)
|
||
prio_base += 1
|
||
if kill_switch:
|
||
subprocess.run(['ip', 'rule', 'add', 'from', client_ip, 'type', 'unreachable', 'priority', str(prio_base)], capture_output=True)
|
||
prio_base += 1
|
||
else:
|
||
if kill_switch:
|
||
# Tunnel VPN coupé et Kill-Switch actif : blocage absolu de tout le trafic
|
||
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-m', 'mac', '--mac-source', mac, '-j', 'DROP'], capture_output=True)
|
||
if client_ip:
|
||
subprocess.run(['iptables', '-t', 'mangle', '-A', 'AP_VPN_MANGLE', '-s', client_ip, '-j', 'DROP'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_ISOLATION', '-s', client_ip, '-j', 'DROP'], capture_output=True)
|
||
subprocess.run(['iptables', '-A', 'AP_VPN_INPUT', '-s', client_ip, '-j', 'DROP'], capture_output=True)
|
||
subprocess.run(['ip', 'rule', 'add', 'from', client_ip, 'type', 'unreachable', 'priority', str(prio_base)], capture_output=True)
|
||
prio_base += 1
|
||
|
||
# 8. Règles ip rule pour fwmark (garantit le routage par paquet marqué même si l'IP n'est pas encore enregistrée)
|
||
for tid in active_tables:
|
||
subprocess.run(['ip', 'rule', 'add', 'fwmark', str(tid), 'lookup', str(tid), 'priority', str(prio_base)], capture_output=True)
|
||
prio_base += 1
|
||
|
||
# 9. S'assurer que chaque interface VPN connectée a sa route default dans sa table et masquerade dans iptables
|
||
for pid, prof in profiles.items():
|
||
if prof['status'] == 'connected' and is_iface_up(prof['iface']):
|
||
subprocess.run(['ip', 'route', 'replace', 'default', 'dev', prof['iface'], 'table', str(prof['table_id'])], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'nat', '-I', 'POSTROUTING', '1', '-o', prof['iface'], '-j', 'MASQUERADE'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', 'br0', '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', prof['iface'], '-o', 'br0', '-j', 'ACCEPT'], capture_output=True)
|
||
if INTERFACE:
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', INTERFACE, '-o', prof['iface'], '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-i', prof['iface'], '-o', INTERFACE, '-j', 'ACCEPT'], capture_output=True)
|
||
subprocess.run(['iptables', '-t', 'mangle', '-I', 'FORWARD', '1', '-p', 'tcp', '--tcp-flags', 'SYN,RST', 'SYN', '-o', prof['iface'], '-j', 'TCPMSS', '--clamp-mss-to-pmtu'], capture_output=True)
|
||
# Permettre à l'hôte de communiquer via le VPN (oif)
|
||
subprocess.run(['ip', 'rule', 'add', 'oif', prof['iface'], 'lookup', str(prof['table_id']), 'priority', str(prio_base)], capture_output=True)
|
||
prio_base += 1
|
||
try:
|
||
r_ip = subprocess.run(['ip', '-4', '-o', 'addr', 'show', 'dev', prof['iface']], capture_output=True, text=True)
|
||
if r_ip.returncode == 0:
|
||
m_ip = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+)', r_ip.stdout)
|
||
if m_ip:
|
||
subprocess.run(['ip', 'rule', 'add', 'from', m_ip.group(1), 'lookup', str(prof['table_id']), 'priority', str(prio_base)], capture_output=True)
|
||
prio_base += 1
|
||
except Exception: pass
|
||
|
||
# 10. Positionner les chaînes d'isolation et d'interception DNS en première position absolue
|
||
subprocess.run(['iptables', '-D', 'FORWARD', '-j', 'AP_VPN_ISOLATION'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'FORWARD', '1', '-j', 'AP_VPN_ISOLATION'], capture_output=True)
|
||
|
||
subprocess.run(['iptables', '-D', 'INPUT', '-j', 'AP_VPN_INPUT'], capture_output=True)
|
||
subprocess.run(['iptables', '-I', 'INPUT', '1', '-j', 'AP_VPN_INPUT'], capture_output=True)
|
||
|
||
# 11. Purger conntrack pour les clients VPN assignés afin de couper immédiatement les flux LAN existants
|
||
for mac in assigned_macs:
|
||
c_ip = mac_to_ip.get(mac, '')
|
||
if c_ip and c_ip not in ('', 'Non attribuée', '—'):
|
||
subprocess.run(['conntrack', '-D', '-s', c_ip], capture_output=True)
|
||
subprocess.run(['conntrack', '-D', '-d', c_ip], capture_output=True)
|
||
|
||
# 12. Appliquer sysctl rp_filter=0 et forwarding partout
|
||
import glob
|
||
for p in glob.glob('/proc/sys/net/ipv4/conf/*/rp_filter'):
|
||
try:
|
||
with open(p, 'w') as f: f.write('0')
|
||
except Exception: pass
|
||
for p in glob.glob('/proc/sys/net/ipv4/conf/*/forwarding'):
|
||
try:
|
||
with open(p, 'w') as f: f.write('1')
|
||
except Exception: pass
|
||
for ifname in ['all', 'default', 'br0']:
|
||
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{ifname}.rp_filter=0'], capture_output=True)
|
||
if INTERFACE:
|
||
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{INTERFACE}.rp_filter=0'], capture_output=True)
|
||
subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True)
|
||
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.all.forwarding=1'], capture_output=True)
|
||
if os.path.exists('/sys/class/net/br0'):
|
||
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.br0.forwarding=1'], capture_output=True)
|
||
print(f"[ap-vpn] Synchronisation des règles VPN terminée ({len(active_tables)} profil(s) actif(s), {len(assigned_macs)} client(s) routé(s) - Isolation LAN activée)", flush=True)
|
||
|
||
except Exception as e:
|
||
print(f"[ap-vpn] Erreur synchronisation règles : {e}", flush=True)
|
||
|
||
def auto_connect_vpn_profiles():
|
||
global app_startup_done
|
||
time.sleep(1.5)
|
||
# 1. Attendre que la route par défaut hôte/Internet soit prête (max 20s)
|
||
for _ in range(40):
|
||
r_gw = subprocess.run(['ip', 'route', 'show', 'default'], capture_output=True, text=True)
|
||
if r_gw.returncode == 0 and r_gw.stdout.strip():
|
||
break
|
||
time.sleep(0.5)
|
||
|
||
# 2. Attendre que la résolution DNS soit fonctionnelle (max 15s)
|
||
for _ in range(30):
|
||
try:
|
||
socket.getaddrinfo('one.one.one.one', 53, socket.AF_INET)
|
||
break
|
||
except Exception:
|
||
time.sleep(0.5)
|
||
|
||
try:
|
||
c = db()
|
||
rows = c.execute('SELECT id, name FROM vpn_profiles WHERE auto_connect = 1 ORDER BY id ASC').fetchall()
|
||
c.close()
|
||
|
||
total_auto = len(rows)
|
||
if total_auto == 0:
|
||
app_startup_done = True
|
||
return
|
||
|
||
for pid, name in rows:
|
||
print(f"[ap-vpn] Connexion automatique au démarrage du profil '{name}' (ID: {pid})...", flush=True)
|
||
for attempt in range(1, 4):
|
||
try:
|
||
ok, msg = connect_vpn_profile(pid)
|
||
if ok:
|
||
prof = get_vpn_profile(pid) or {}
|
||
vtype = prof.get('type', 'wireguard')
|
||
ifc = prof.get('iface') or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
|
||
up = False
|
||
for _ in range(30):
|
||
if is_iface_up(ifc):
|
||
up = True
|
||
break
|
||
time.sleep(0.2)
|
||
if up:
|
||
print(f"[ap-vpn] Profil '{name}' (ID: {pid}, {ifc}) connecté et actif.", flush=True)
|
||
get_vpn_public_ip(ifc, force_refresh=True)
|
||
break
|
||
print(f"[ap-vpn] Tentative {attempt}/3 pour '{name}' : {msg}", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-vpn] Exception tentative {attempt}/3 pour '{name}' : {e}", flush=True)
|
||
time.sleep(1.2)
|
||
time.sleep(0.5)
|
||
|
||
# Synchronisation globale complète de toutes les règles une fois tous les tunnels montés
|
||
sync_vpn_client_rules()
|
||
|
||
except Exception as e:
|
||
print(f"[ap-vpn] Erreur auto_connect_vpn_profiles : {e}", flush=True)
|
||
finally:
|
||
app_startup_done = True
|
||
print(f"[ap-vpn] Initialisation du démarrage terminée (app_startup_done = True)", flush=True)
|
||
|
||
def _mark_startup_done_safety():
|
||
time.sleep(180)
|
||
global app_startup_done
|
||
app_startup_done = True
|
||
threading.Thread(target=_mark_startup_done_safety, daemon=True).start()
|
||
|
||
def vpn_healthcheck_loop():
|
||
"""Effectue un test périodique de connectivité et rafraîchissement d'IP publique toutes les 5 minutes (300 s) en arrière-plan."""
|
||
time.sleep(25)
|
||
while True:
|
||
try:
|
||
c = db()
|
||
active_profs = c.execute('SELECT id, name, type, iface FROM vpn_profiles WHERE status = "connected"').fetchall()
|
||
c.close()
|
||
for pid, name, vtype, iface in active_profs:
|
||
iface = iface or (f"wg_ap{pid}" if vtype == "wireguard" else f"tun_ap{pid}")
|
||
if is_iface_up(iface):
|
||
ip = get_vpn_public_ip(iface, force_refresh=True)
|
||
ts = time.strftime('%H:%M:%S')
|
||
if ip:
|
||
print(f"[ap-vpn-check] [{ts}] Test réussi pour '{name}' ({iface}) : {ip}", flush=True)
|
||
else:
|
||
print(f"[ap-vpn-check] [{ts}] Échec test de connectivité pour '{name}' ({iface})", flush=True)
|
||
except Exception as e:
|
||
print(f"[ap-vpn-check] Erreur boucle test 5 min : {e}", flush=True)
|
||
time.sleep(300)
|
||
|
||
|
||
def get_iconify_ssl_contexts():
|
||
contexts = []
|
||
try:
|
||
contexts.append(ssl.create_default_context())
|
||
except Exception:
|
||
pass
|
||
try:
|
||
contexts.append(ssl._create_unverified_context())
|
||
except Exception:
|
||
pass
|
||
return contexts or [None]
|
||
|
||
def search_iconify_icons(query, limit=36):
|
||
q = (query or '').strip()
|
||
if not q:
|
||
return []
|
||
hosts = [
|
||
'https://api.iconify.design',
|
||
'https://api.simplesvg.com',
|
||
'https://api.unisvg.com'
|
||
]
|
||
headers = {
|
||
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
|
||
'Accept': 'application/json'
|
||
}
|
||
for host in hosts:
|
||
for ctx in get_iconify_ssl_contexts():
|
||
try:
|
||
url = f"{host}/search?query={urllib.parse.quote(q)}&limit={limit}"
|
||
req = urllib.request.Request(url, headers=headers)
|
||
kwargs = {'timeout': 5}
|
||
if ctx:
|
||
kwargs['context'] = ctx
|
||
with urllib.request.urlopen(req, **kwargs) as resp:
|
||
if resp.status == 200:
|
||
raw = json.loads(resp.read().decode('utf-8'))
|
||
icons = raw.get('icons', [])
|
||
if icons:
|
||
return icons
|
||
except Exception:
|
||
continue
|
||
return []
|
||
|
||
def fetch_iconify_svg(clean_name, color=None):
|
||
clean_name = re.sub(r'[^a-zA-Z0-9_\-:/]', '', (clean_name or '').strip())
|
||
if not clean_name:
|
||
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1.15em" height="1.15em" fill="none" stroke="#38bdf8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="4"/></svg>'
|
||
if ':' in clean_name:
|
||
prefix, name = clean_name.split(':', 1)
|
||
clean_path = f"{prefix}/{name}"
|
||
elif '/' in clean_name:
|
||
prefix, name = clean_name.split('/', 1)
|
||
clean_path = f"{prefix}/{name}"
|
||
else:
|
||
prefix = 'mdi'
|
||
name = clean_name
|
||
clean_path = f"mdi/{clean_name}"
|
||
|
||
is_emoji_set = any(prefix.lower().startswith(em) for em in ('noto', 'twemoji', 'openmoji', 'emojione', 'joypixels', 'fluent-emoji', 'fxemoji', 'streamline-emojis', 'blobmoji'))
|
||
hosts = [
|
||
'https://api.iconify.design',
|
||
'https://api.simplesvg.com',
|
||
'https://api.unisvg.com'
|
||
]
|
||
headers = {
|
||
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
|
||
'Accept': 'image/svg+xml,application/json,*/*'
|
||
}
|
||
|
||
# 1. Essayer les endpoints SVG directs
|
||
for host in hosts:
|
||
for ctx in get_iconify_ssl_contexts():
|
||
try:
|
||
url = f"{host}/{clean_path}.svg"
|
||
if color and not is_emoji_set and color != 'currentColor':
|
||
url += f"?color={urllib.parse.quote(color)}"
|
||
req = urllib.request.Request(url, headers=headers)
|
||
kwargs = {'timeout': 5}
|
||
if ctx:
|
||
kwargs['context'] = ctx
|
||
with urllib.request.urlopen(req, **kwargs) as resp:
|
||
if resp.status == 200:
|
||
content = resp.read().decode('utf-8', errors='ignore')
|
||
if '<svg' in content.lower():
|
||
return content
|
||
except Exception:
|
||
continue
|
||
|
||
# 2. Essayer l'API JSON {prefix}.json?icons={name}
|
||
for host in hosts:
|
||
for ctx in get_iconify_ssl_contexts():
|
||
try:
|
||
url = f"{host}/{prefix}.json?icons={urllib.parse.quote(name)}"
|
||
req = urllib.request.Request(url, headers=headers)
|
||
kwargs = {'timeout': 5}
|
||
if ctx:
|
||
kwargs['context'] = ctx
|
||
with urllib.request.urlopen(req, **kwargs) as resp:
|
||
if resp.status == 200:
|
||
data = json.loads(resp.read().decode('utf-8', errors='ignore'))
|
||
icons = data.get('icons', {})
|
||
if name in icons:
|
||
icon_data = icons[name]
|
||
body = icon_data.get('body', '')
|
||
if body:
|
||
w = icon_data.get('width', data.get('width', 24))
|
||
h = icon_data.get('height', data.get('height', 24))
|
||
return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="1.15em" height="1.15em">{body}</svg>'
|
||
except Exception:
|
||
continue
|
||
|
||
# 3. Fallback SVG garanti
|
||
fallback_color = color or '#38bdf8'
|
||
short_label = (name.split('-')[0] if '-' in name else name)[:6].upper()
|
||
return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1.15em" height="1.15em" fill="none" stroke="{fallback_color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="4"/><text x="12" y="16" font-size="9" text-anchor="middle" fill="{fallback_color}" stroke="none" font-weight="bold">{short_label}</text></svg>'
|
||
|
||
|
||
def export_backup_data():
|
||
c = db()
|
||
try:
|
||
preferences = dict(c.execute("SELECT key, value FROM preferences").fetchall())
|
||
vpn_profiles = []
|
||
for r in c.execute("SELECT id, name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, created_at, updated_at FROM vpn_profiles").fetchall():
|
||
vpn_profiles.append({
|
||
'id': r[0], 'name': r[1], 'type': r[2], 'config_content': r[3],
|
||
'auth_user': r[4], 'auth_pass': r[5], 'table_id': r[6], 'iface': r[7],
|
||
'auto_connect': r[8], 'created_at': r[9], 'updated_at': r[10]
|
||
})
|
||
client_vpn_routes = []
|
||
for r in c.execute("SELECT r.mac, r.profile_id, r.kill_switch, r.updated_at, p.name FROM client_vpn_routes r LEFT JOIN vpn_profiles p ON p.id=r.profile_id").fetchall():
|
||
client_vpn_routes.append({
|
||
'mac': r[0], 'profile_id': r[1], 'kill_switch': r[2],
|
||
'updated_at': r[3], 'profile_name': r[4] or ''
|
||
})
|
||
client_names = []
|
||
for r in c.execute("SELECT mac, name, last_ip, last_seen, device_type FROM client_names").fetchall():
|
||
client_names.append({
|
||
'mac': r[0], 'name': r[1], 'last_ip': r[2], 'last_seen': r[3], 'device_type': r[4] or ''
|
||
})
|
||
custom_device_types = []
|
||
has_cdt = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='custom_device_types'").fetchone())
|
||
if has_cdt:
|
||
for r in c.execute("SELECT id, label, icon, desc, sort_order FROM custom_device_types ORDER BY sort_order ASC, id ASC").fetchall():
|
||
custom_device_types.append({
|
||
'id': r[0], 'label': r[1], 'icon': r[2], 'desc': r[3], 'sort_order': r[4]
|
||
})
|
||
blocked_clients = []
|
||
for r in c.execute("SELECT mac, blocked_at FROM blocked_clients").fetchall():
|
||
blocked_clients.append({
|
||
'mac': r[0], 'blocked_at': r[1]
|
||
})
|
||
auth_users = []
|
||
for r in c.execute("SELECT username, password_hash, totp_secret FROM auth_users").fetchall():
|
||
auth_users.append({
|
||
'username': r[0], 'password_hash': r[1], 'totp_secret': r[2]
|
||
})
|
||
auth_passkeys = []
|
||
has_pk = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='auth_passkeys'").fetchone())
|
||
if has_pk:
|
||
for r in c.execute("SELECT id, username, public_key, name, device_type, sign_count, created_at, last_used_at FROM auth_passkeys").fetchall():
|
||
auth_passkeys.append({
|
||
'id': r[0], 'username': r[1], 'public_key': r[2], 'name': r[3],
|
||
'device_type': r[4], 'sign_count': r[5], 'created_at': r[6], 'last_used_at': r[7]
|
||
})
|
||
client_traffic = []
|
||
for r in c.execute("SELECT mac, rx_bytes, tx_bytes, last_updated FROM client_traffic").fetchall():
|
||
client_traffic.append({
|
||
'mac': r[0], 'rx_bytes': r[1], 'tx_bytes': r[2], 'last_updated': r[3]
|
||
})
|
||
client_traffic_daily = []
|
||
for r in c.execute("SELECT mac, traffic_date, rx_bytes, tx_bytes FROM client_traffic_daily").fetchall():
|
||
client_traffic_daily.append({
|
||
'mac': r[0], 'traffic_date': r[1], 'rx_bytes': r[2], 'tx_bytes': r[3]
|
||
})
|
||
connection_logs = []
|
||
for r in c.execute("SELECT id, event_time, event, name, ip, mac FROM connection_logs ORDER BY id DESC LIMIT 150").fetchall():
|
||
connection_logs.append({
|
||
'id': r[0], 'event_time': r[1], 'event': r[2], 'name': r[3], 'ip': r[4], 'mac': r[5]
|
||
})
|
||
client_limits = []
|
||
has_cl = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='client_limits'").fetchone())
|
||
if has_cl:
|
||
for r in c.execute("SELECT mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at FROM client_limits").fetchall():
|
||
client_limits.append({
|
||
'mac': r[0], 'quota_enabled': r[1], 'quota_bytes': r[2], 'quota_period': r[3],
|
||
'bandwidth_enabled': r[4], 'rate_down_kbps': r[5], 'rate_up_kbps': r[6],
|
||
'quota_action': r[7], 'updated_at': r[8]
|
||
})
|
||
return {
|
||
'ap_manageur_backup': {
|
||
'version': '1.0',
|
||
'app_version': APP_VERSION,
|
||
'exported_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||
'export_timestamp': int(time.time()),
|
||
'app_name': preferences.get('app_name', 'Administration de l’AP Wi‑Fi')
|
||
},
|
||
'preferences': preferences,
|
||
'vpn_profiles': vpn_profiles,
|
||
'client_vpn_routes': client_vpn_routes,
|
||
'client_names': client_names,
|
||
'custom_device_types': custom_device_types,
|
||
'client_limits': client_limits,
|
||
'blocked_clients': blocked_clients,
|
||
'auth_users': auth_users,
|
||
'auth_passkeys': auth_passkeys,
|
||
'client_traffic': client_traffic,
|
||
'client_traffic_daily': client_traffic_daily,
|
||
'connection_logs': connection_logs
|
||
}
|
||
finally:
|
||
c.close()
|
||
|
||
|
||
def import_backup_data(payload, options=None):
|
||
if options is None:
|
||
options = {}
|
||
if isinstance(payload, dict) and 'backup' in payload and isinstance(payload['backup'], dict):
|
||
backup = payload['backup']
|
||
options = {**options, **payload.get('options', {})}
|
||
elif isinstance(payload, dict):
|
||
backup = payload
|
||
else:
|
||
raise ValueError("Format de sauvegarde invalide (objet JSON attendu)")
|
||
|
||
restore_prefs = options.get('restore_preferences', True)
|
||
restore_vpn = options.get('restore_vpn', True)
|
||
restore_devices = options.get('restore_devices', True)
|
||
restore_blocked = options.get('restore_blocked', True)
|
||
restore_categories = options.get('restore_categories', True)
|
||
restore_auth = options.get('restore_auth', False)
|
||
restore_traffic = options.get('restore_traffic', True)
|
||
|
||
stats = {
|
||
'preferences': 0,
|
||
'vpn_profiles': 0,
|
||
'client_vpn_routes': 0,
|
||
'client_names': 0,
|
||
'custom_device_types': 0,
|
||
'blocked_clients': 0,
|
||
'auth_users': 0,
|
||
'auth_passkeys': 0
|
||
}
|
||
|
||
ensure_vpn_dirs()
|
||
c = db()
|
||
try:
|
||
# 1. Catégories d'appareils
|
||
if restore_categories and 'custom_device_types' in backup and isinstance(backup['custom_device_types'], list):
|
||
for dt in backup['custom_device_types']:
|
||
dt_id = str(dt.get('id', '')).strip()
|
||
label = str(dt.get('label', '')).strip()
|
||
icon = str(dt.get('icon', '💻')).strip()
|
||
desc = str(dt.get('desc', '')).strip()
|
||
try: order = int(dt.get('sort_order', 0))
|
||
except (ValueError, TypeError): order = 0
|
||
if dt_id and label:
|
||
c.execute('''
|
||
INSERT INTO custom_device_types (id, label, icon, desc, sort_order)
|
||
VALUES (?, ?, ?, ?, ?)
|
||
ON CONFLICT(id) DO UPDATE SET
|
||
label=excluded.label,
|
||
icon=excluded.icon,
|
||
desc=excluded.desc,
|
||
sort_order=excluded.sort_order
|
||
''', (dt_id, label, icon, desc, order))
|
||
stats['custom_device_types'] += 1
|
||
|
||
# 2. Noms d'appareils & types
|
||
if restore_devices and 'client_names' in backup and isinstance(backup['client_names'], list):
|
||
for cn in backup['client_names']:
|
||
mac = str(cn.get('mac', '')).strip().upper()
|
||
name = str(cn.get('name', '')).strip()
|
||
last_ip = str(cn.get('last_ip', '')).strip()
|
||
last_seen = str(cn.get('last_seen', '')).strip()
|
||
device_type = str(cn.get('device_type', '')).strip()
|
||
if mac and name:
|
||
c.execute('''
|
||
INSERT INTO client_names (mac, name, last_ip, last_seen, device_type)
|
||
VALUES (?, ?, ?, ?, ?)
|
||
ON CONFLICT(mac) DO UPDATE SET
|
||
name=excluded.name,
|
||
last_ip=CASE WHEN excluded.last_ip != '' THEN excluded.last_ip ELSE client_names.last_ip END,
|
||
last_seen=CASE WHEN excluded.last_seen != '' THEN excluded.last_seen ELSE client_names.last_seen END,
|
||
device_type=CASE WHEN excluded.device_type != '' THEN excluded.device_type ELSE client_names.device_type END
|
||
''', (mac, name, last_ip, last_seen, device_type))
|
||
stats['client_names'] += 1
|
||
|
||
if 'client_limits' in backup and isinstance(backup['client_limits'], list):
|
||
for cl in backup['client_limits']:
|
||
mac = str(cl.get('mac', '')).strip().upper()
|
||
if mac:
|
||
c.execute('''
|
||
INSERT INTO client_limits (mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||
ON CONFLICT(mac) DO UPDATE SET
|
||
quota_enabled=excluded.quota_enabled,
|
||
quota_bytes=excluded.quota_bytes,
|
||
quota_period=excluded.quota_period,
|
||
bandwidth_enabled=excluded.bandwidth_enabled,
|
||
rate_down_kbps=excluded.rate_down_kbps,
|
||
rate_up_kbps=excluded.rate_up_kbps,
|
||
quota_action=excluded.quota_action,
|
||
updated_at=excluded.updated_at
|
||
''', (
|
||
mac, 1 if cl.get('quota_enabled') else 0, int(cl.get('quota_bytes', 0) or 0),
|
||
str(cl.get('quota_period', 'total')), 1 if cl.get('bandwidth_enabled') else 0,
|
||
int(cl.get('rate_down_kbps', 0) or 0), int(cl.get('rate_up_kbps', 0) or 0),
|
||
str(cl.get('quota_action', 'block')), str(cl.get('updated_at', ''))
|
||
))
|
||
try: sync_client_bandwidth_and_quotas(force=True)
|
||
except Exception: pass
|
||
|
||
# 3. Appareils bloqués
|
||
if restore_blocked and 'blocked_clients' in backup and isinstance(backup['blocked_clients'], list):
|
||
for bl in backup['blocked_clients']:
|
||
mac = str(bl.get('mac', '')).strip().upper()
|
||
b_at = str(bl.get('blocked_at', '')).strip() or time.strftime('%Y-%m-%d %H:%M:%S')
|
||
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)
|
||
except Exception: pass
|
||
|
||
# 4. Préférences et réglages
|
||
if restore_prefs and 'preferences' in backup and isinstance(backup['preferences'], dict):
|
||
for k, v in backup['preferences'].items():
|
||
c.execute("INSERT INTO preferences(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (str(k), str(v)))
|
||
stats['preferences'] += 1
|
||
|
||
# 5. Profils VPN et routage
|
||
if restore_vpn and 'vpn_profiles' in backup and isinstance(backup['vpn_profiles'], list):
|
||
profile_id_map = {}
|
||
for vp in backup['vpn_profiles']:
|
||
old_id = vp.get('id')
|
||
p_name = str(vp.get('name', 'Profil VPN')).strip()
|
||
p_type = str(vp.get('type', 'wireguard')).strip().lower()
|
||
if p_type not in ('wireguard', 'openvpn'): p_type = 'wireguard'
|
||
p_cfg = str(vp.get('config_content', '')).strip()
|
||
p_user = str(vp.get('auth_user', '')).strip()
|
||
p_pass = str(vp.get('auth_pass', '')).strip()
|
||
p_auto = 1 if vp.get('auto_connect') else 0
|
||
now_ts = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
|
||
existing = c.execute('SELECT id FROM vpn_profiles WHERE name=?', (p_name,)).fetchone()
|
||
if existing:
|
||
cur_id = existing[0]
|
||
c.execute('''
|
||
UPDATE vpn_profiles SET
|
||
type=?, config_content=?, auth_user=?, auth_pass=?, auto_connect=?, updated_at=?
|
||
WHERE id=?
|
||
''', (p_type, p_cfg, p_user, p_pass, p_auto, now_ts, cur_id))
|
||
profile_id_map[old_id] = cur_id
|
||
profile_id_map[p_name] = cur_id
|
||
stats['vpn_profiles'] += 1
|
||
else:
|
||
table_id = get_next_vpn_table_id()
|
||
cur = c.execute('''
|
||
INSERT INTO vpn_profiles (name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, status, last_error, created_at, updated_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, "", ?, "disconnected", "", ?, ?)
|
||
''', (p_name, p_type, p_cfg, p_user, p_pass, table_id, p_auto, now_ts, now_ts))
|
||
new_pid = cur.lastrowid
|
||
iface = f"wg_ap{new_pid}" if p_type == "wireguard" else f"tun_ap{new_pid}"
|
||
c.execute('UPDATE vpn_profiles SET iface=? WHERE id=?', (iface, new_pid))
|
||
profile_id_map[old_id] = new_pid
|
||
profile_id_map[p_name] = new_pid
|
||
stats['vpn_profiles'] += 1
|
||
|
||
if 'client_vpn_routes' in backup and isinstance(backup['client_vpn_routes'], list):
|
||
for cr in backup['client_vpn_routes']:
|
||
mac = str(cr.get('mac', '')).strip().upper()
|
||
old_pid = cr.get('profile_id')
|
||
p_name = cr.get('profile_name')
|
||
kill_sw = 1 if cr.get('kill_switch') else 0
|
||
target_pid = profile_id_map.get(old_pid) or profile_id_map.get(p_name) or 0
|
||
if mac and target_pid:
|
||
now_ts = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
c.execute('''
|
||
INSERT INTO client_vpn_routes (mac, profile_id, kill_switch, updated_at)
|
||
VALUES (?, ?, ?, ?)
|
||
ON CONFLICT(mac) DO UPDATE SET
|
||
profile_id=excluded.profile_id,
|
||
kill_switch=excluded.kill_switch,
|
||
updated_at=excluded.updated_at
|
||
''', (mac, target_pid, kill_sw, now_ts))
|
||
stats['client_vpn_routes'] += 1
|
||
try: sync_vpn_client_rules()
|
||
except Exception: pass
|
||
|
||
# 6. Trafic (optionnel)
|
||
if restore_traffic and 'client_traffic' in backup and isinstance(backup['client_traffic'], list):
|
||
for ct in backup['client_traffic']:
|
||
mac = str(ct.get('mac', '')).strip().upper()
|
||
try:
|
||
rx = int(ct.get('rx_bytes', 0))
|
||
tx = int(ct.get('tx_bytes', 0))
|
||
except (ValueError, TypeError): rx, tx = 0, 0
|
||
lu = str(ct.get('last_updated', '')).strip()
|
||
if mac:
|
||
c.execute('''
|
||
INSERT INTO client_traffic (mac, rx_bytes, tx_bytes, last_updated)
|
||
VALUES (?, ?, ?, ?)
|
||
ON CONFLICT(mac) DO UPDATE SET
|
||
rx_bytes=MAX(client_traffic.rx_bytes, excluded.rx_bytes),
|
||
tx_bytes=MAX(client_traffic.tx_bytes, excluded.tx_bytes),
|
||
last_updated=excluded.last_updated
|
||
''', (mac, rx, tx, lu))
|
||
if 'client_traffic_daily' in backup and isinstance(backup['client_traffic_daily'], list):
|
||
for ctd in backup['client_traffic_daily']:
|
||
mac = str(ctd.get('mac', '')).strip().upper()
|
||
t_date = str(ctd.get('traffic_date', '')).strip()
|
||
try:
|
||
rx = int(ctd.get('rx_bytes', 0))
|
||
tx = int(ctd.get('tx_bytes', 0))
|
||
except (ValueError, TypeError): rx, tx = 0, 0
|
||
if mac and t_date:
|
||
c.execute('''
|
||
INSERT INTO client_traffic_daily (mac, traffic_date, rx_bytes, tx_bytes)
|
||
VALUES (?, ?, ?, ?)
|
||
ON CONFLICT(mac, traffic_date) DO UPDATE SET
|
||
rx_bytes=MAX(client_traffic_daily.rx_bytes, excluded.rx_bytes),
|
||
tx_bytes=MAX(client_traffic_daily.tx_bytes, excluded.tx_bytes)
|
||
''', (mac, t_date, rx, tx))
|
||
|
||
# 7. Authentification (si demandée explicitement)
|
||
if restore_auth and 'auth_users' in backup and isinstance(backup['auth_users'], list):
|
||
for u in backup['auth_users']:
|
||
uname = str(u.get('username', '')).strip()
|
||
phash = str(u.get('password_hash', '')).strip()
|
||
totp = u.get('totp_secret')
|
||
if uname and phash:
|
||
c.execute('''
|
||
INSERT INTO auth_users (username, password_hash, totp_secret)
|
||
VALUES (?, ?, ?)
|
||
ON CONFLICT(username) DO UPDATE SET
|
||
password_hash=excluded.password_hash,
|
||
totp_secret=excluded.totp_secret
|
||
''', (uname, phash, totp))
|
||
stats['auth_users'] += 1
|
||
if 'auth_passkeys' in backup and isinstance(backup['auth_passkeys'], list):
|
||
for pk in backup['auth_passkeys']:
|
||
pk_id = str(pk.get('id', '')).strip()
|
||
pk_uname = str(pk.get('username', '')).strip()
|
||
pk_key = str(pk.get('public_key', '')).strip()
|
||
pk_name = str(pk.get('name', '')).strip()
|
||
pk_dev = str(pk.get('device_type', 'security_key')).strip()
|
||
try: pk_count = int(pk.get('sign_count', 0))
|
||
except (ValueError, TypeError): pk_count = 0
|
||
pk_c_at = str(pk.get('created_at', '')).strip()
|
||
pk_u_at = str(pk.get('last_used_at', '')).strip()
|
||
if pk_id and pk_uname and pk_key:
|
||
c.execute('''
|
||
INSERT INTO auth_passkeys (id, username, public_key, name, device_type, sign_count, created_at, last_used_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||
ON CONFLICT(id) DO UPDATE SET
|
||
name=excluded.name,
|
||
sign_count=excluded.sign_count,
|
||
last_used_at=excluded.last_used_at
|
||
''', (pk_id, pk_uname, pk_key, pk_name, pk_dev, pk_count, pk_c_at, pk_u_at))
|
||
stats['auth_passkeys'] += 1
|
||
|
||
c.commit()
|
||
finally:
|
||
c.close()
|
||
return stats
|
||
|
||
|
||
def extract_backup_from_sqlite(db_path):
|
||
conn = sqlite3.connect(db_path)
|
||
conn.row_factory = sqlite3.Row
|
||
c = conn.cursor()
|
||
try:
|
||
def table_exists(tname):
|
||
return bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (tname,)).fetchone())
|
||
|
||
preferences = {}
|
||
if table_exists('preferences'):
|
||
preferences = dict(c.execute("SELECT key, value FROM preferences").fetchall())
|
||
|
||
vpn_profiles = []
|
||
if table_exists('vpn_profiles'):
|
||
for r in c.execute("SELECT id, name, type, config_content, auth_user, auth_pass, table_id, iface, auto_connect, created_at, updated_at FROM vpn_profiles").fetchall():
|
||
vpn_profiles.append({
|
||
'id': r['id'], 'name': r['name'], 'type': r['type'], 'config_content': r['config_content'],
|
||
'auth_user': r['auth_user'], 'auth_pass': r['auth_pass'], 'table_id': r['table_id'], 'iface': r['iface'],
|
||
'auto_connect': r['auto_connect'], 'created_at': r['created_at'], 'updated_at': r['updated_at']
|
||
})
|
||
|
||
client_vpn_routes = []
|
||
if table_exists('client_vpn_routes'):
|
||
q = "SELECT r.mac, r.profile_id, r.kill_switch, r.updated_at, p.name FROM client_vpn_routes r LEFT JOIN vpn_profiles p ON p.id=r.profile_id" if table_exists('vpn_profiles') else "SELECT mac, profile_id, kill_switch, updated_at, '' FROM client_vpn_routes"
|
||
for r in c.execute(q).fetchall():
|
||
client_vpn_routes.append({
|
||
'mac': r[0], 'profile_id': r[1], 'kill_switch': r[2],
|
||
'updated_at': r[3], 'profile_name': r[4] or ''
|
||
})
|
||
|
||
client_names = []
|
||
if table_exists('client_names'):
|
||
for r in c.execute("SELECT mac, name, last_ip, last_seen, device_type FROM client_names").fetchall():
|
||
client_names.append({
|
||
'mac': r['mac'], 'name': r['name'], 'last_ip': r['last_ip'],
|
||
'last_seen': r['last_seen'], 'device_type': r['device_type'] or ''
|
||
})
|
||
|
||
custom_device_types = []
|
||
if table_exists('custom_device_types'):
|
||
for r in c.execute("SELECT id, label, icon, desc, sort_order FROM custom_device_types ORDER BY sort_order ASC, id ASC").fetchall():
|
||
custom_device_types.append({
|
||
'id': r['id'], 'label': r['label'], 'icon': r['icon'], 'desc': r['desc'], 'sort_order': r['sort_order']
|
||
})
|
||
|
||
blocked_clients = []
|
||
if table_exists('blocked_clients'):
|
||
for r in c.execute("SELECT mac, blocked_at FROM blocked_clients").fetchall():
|
||
blocked_clients.append({'mac': r['mac'], 'blocked_at': r['blocked_at']})
|
||
|
||
auth_users = []
|
||
if table_exists('auth_users'):
|
||
for r in c.execute("SELECT username, password_hash, totp_secret FROM auth_users").fetchall():
|
||
auth_users.append({'username': r['username'], 'password_hash': r['password_hash'], 'totp_secret': r['totp_secret']})
|
||
|
||
auth_passkeys = []
|
||
if table_exists('auth_passkeys'):
|
||
for r in c.execute("SELECT id, username, public_key, name, device_type, sign_count, created_at, last_used_at FROM auth_passkeys").fetchall():
|
||
auth_passkeys.append({
|
||
'id': r['id'], 'username': r['username'], 'public_key': r['public_key'], 'name': r['name'],
|
||
'device_type': r['device_type'], 'sign_count': r['sign_count'], 'created_at': r['created_at'], 'last_used_at': r['last_used_at']
|
||
})
|
||
|
||
client_limits = []
|
||
if table_exists('client_limits'):
|
||
for r in c.execute("SELECT mac, quota_enabled, quota_bytes, quota_period, bandwidth_enabled, rate_down_kbps, rate_up_kbps, quota_action, updated_at FROM client_limits").fetchall():
|
||
client_limits.append({
|
||
'mac': r['mac'], 'quota_enabled': r['quota_enabled'], 'quota_bytes': r['quota_bytes'],
|
||
'quota_period': r['quota_period'], 'bandwidth_enabled': r['bandwidth_enabled'],
|
||
'rate_down_kbps': r['rate_down_kbps'], 'rate_up_kbps': r['rate_up_kbps'],
|
||
'quota_action': r['quota_action'], 'updated_at': r['updated_at']
|
||
})
|
||
|
||
return {
|
||
'ap_manageur_backup': {
|
||
'version': '1.0',
|
||
'app_version': APP_VERSION,
|
||
'exported_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||
'export_timestamp': int(time.time()),
|
||
'app_name': preferences.get('app_name', 'Administration de l’AP Wi‑Fi (extrait SQLite)')
|
||
},
|
||
'preferences': preferences,
|
||
'vpn_profiles': vpn_profiles,
|
||
'client_vpn_routes': client_vpn_routes,
|
||
'client_names': client_names,
|
||
'custom_device_types': custom_device_types,
|
||
'client_limits': client_limits,
|
||
'blocked_clients': blocked_clients,
|
||
'auth_users': auth_users,
|
||
'auth_passkeys': auth_passkeys
|
||
}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def inspect_backup_bytes(raw_bytes, filename=''):
|
||
if not raw_bytes:
|
||
raise ValueError("Le fichier de sauvegarde est vide")
|
||
|
||
# 1. Archive ZIP
|
||
if raw_bytes[:4] == b'PK\x03\x04' or filename.lower().endswith('.zip'):
|
||
try:
|
||
with zipfile.ZipFile(io.BytesIO(raw_bytes)) as zf:
|
||
namelist = zf.namelist()
|
||
json_files = [n for n in namelist if n.lower().endswith('.json')]
|
||
target = None
|
||
if 'configuration.json' in json_files:
|
||
target = 'configuration.json'
|
||
elif json_files:
|
||
target = json_files[0]
|
||
|
||
if target:
|
||
content = zf.read(target).decode('utf-8')
|
||
return json.loads(content)
|
||
|
||
# Si pas de JSON mais un fichier SQLite est présent dans le zip
|
||
sqlite_files = [n for n in namelist if n.lower().endswith(('.sqlite3', '.db'))]
|
||
if sqlite_files:
|
||
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.sqlite3')
|
||
try:
|
||
tmp.write(zf.read(sqlite_files[0]))
|
||
tmp.close()
|
||
return extract_backup_from_sqlite(tmp.name)
|
||
finally:
|
||
if os.path.exists(tmp.name):
|
||
try: os.unlink(tmp.name)
|
||
except OSError: pass
|
||
raise ValueError("L'archive ZIP ne contient ni fichier JSON de configuration ni base de données SQLite.")
|
||
except zipfile.BadZipFile:
|
||
raise ValueError("L'archive ZIP est corrompue ou invalide.")
|
||
|
||
# 2. Base SQLite brute
|
||
if raw_bytes[:16] == b'SQLite format 3\x00' or filename.lower().endswith(('.sqlite3', '.db')):
|
||
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.sqlite3')
|
||
try:
|
||
tmp.write(raw_bytes)
|
||
tmp.close()
|
||
return extract_backup_from_sqlite(tmp.name)
|
||
finally:
|
||
if os.path.exists(tmp.name):
|
||
try: os.unlink(tmp.name)
|
||
except OSError: pass
|
||
|
||
# 3. JSON standard
|
||
try:
|
||
text = raw_bytes.decode('utf-8')
|
||
return json.loads(text)
|
||
except Exception as e:
|
||
raise ValueError(f"Fichier de sauvegarde non reconnu (ni ZIP, ni SQLite, ni JSON) : {e}")
|
||
|
||
|
||
API_MSG_I18N = {
|
||
'Authentification réussie': {'en-us': 'Authentication successful', 'en-gb': 'Authentication successful'},
|
||
'Authentification réussie avec': {'en-us': 'Authentication successful with', 'en-gb': 'Authentication successful with'},
|
||
'Erreur export SQLite': {'en-us': 'SQLite export error', 'en-gb': 'SQLite export error'},
|
||
'Erreur génération archive ZIP': {'en-us': 'ZIP archive generation error', 'en-gb': 'ZIP archive generation error'},
|
||
'Erreur génération sauvegarde': {'en-us': 'Backup generation error', 'en-gb': 'Backup generation error'},
|
||
'Erreur lors de la restauration': {'en-us': 'Error during restore', 'en-gb': 'Error during restore'},
|
||
'Impossible d’analyser le fichier': {'en-us': 'Unable to parse file', 'en-gb': 'Unable to parse file'},
|
||
"Impossible d'analyser le fichier": {'en-us': 'Unable to parse file', 'en-gb': 'Unable to parse file'},
|
||
'Passkey enregistrée avec succès !': {'en-us': 'Passkey registered successfully!', 'en-gb': 'Passkey registered successfully!'},
|
||
'enregistrée avec succès !': {'en-us': 'registered successfully!', 'en-gb': 'registered successfully!'},
|
||
'Clé de sécurité renommée avec succès': {'en-us': 'Security key renamed successfully', 'en-gb': 'Security key renamed successfully'},
|
||
'Passkey supprimée avec succès': {'en-us': 'Passkey deleted successfully', 'en-gb': 'Passkey deleted successfully'},
|
||
'Double identification activée avec succès !': {'en-us': 'Two-factor authentication enabled successfully!', 'en-gb': 'Two-factor authentication enabled successfully!'},
|
||
'Nouveaux codes générés avec succès !': {'en-us': 'New recovery codes generated successfully!', 'en-gb': 'New recovery codes generated successfully!'},
|
||
'Double identification désactivée': {'en-us': 'Two-factor authentication disabled', 'en-gb': 'Two-factor authentication disabled'},
|
||
'Session déconnectée avec succès': {'en-us': 'Session disconnected successfully', 'en-gb': 'Session disconnected successfully'},
|
||
'Machine renommée avec succès': {'en-us': 'Machine renamed successfully', 'en-gb': 'Machine renamed successfully'},
|
||
'Activation refusée': {'en-us': 'Activation refused', 'en-gb': 'Activation refused'},
|
||
'Désactivation refusée': {'en-us': 'Deactivation refused', 'en-gb': 'Deactivation refused'},
|
||
'Code refusé': {'en-us': 'Invalid code', 'en-gb': 'Invalid code'},
|
||
'Nom de machine vide': {'en-us': 'Machine name cannot be empty', 'en-gb': 'Machine name cannot be empty'},
|
||
'Token de session manquant': {'en-us': 'Missing session token', 'en-gb': 'Missing session token'},
|
||
'Impossible de déconnecter la session': {'en-us': 'Unable to disconnect session', 'en-gb': 'Unable to disconnect session'},
|
||
'Impossible de renommer la machine': {'en-us': 'Unable to rename machine', 'en-gb': 'Unable to rename machine'},
|
||
'Passkey introuvable': {'en-us': 'Passkey not found', 'en-gb': 'Passkey not found'},
|
||
'Capture déjà en cours sur': {'en-us': 'Capture already running on', 'en-gb': 'Capture already running on'},
|
||
'Capture démarrée sur l': {'en-us': 'Capture started on', 'en-gb': 'Capture started on'},
|
||
'Échec de connexion WireGuard': {'en-us': 'WireGuard connection failed', 'en-gb': 'WireGuard connection failed'},
|
||
'Échec de connexion OpenVPN': {'en-us': 'OpenVPN connection failed', 'en-gb': 'OpenVPN connection failed'},
|
||
'Erreur de connexion': {'en-us': 'Connection error', 'en-gb': 'Connection error'},
|
||
"Nom d'icône manquant": {'en-us': 'Missing icon name', 'en-gb': 'Missing icon name'},
|
||
'Nom d’icône manquant': {'en-us': 'Missing icon name', 'en-gb': 'Missing icon name'},
|
||
'Profil connecté': {'en-us': 'Profile connected', 'en-gb': 'Profile connected'},
|
||
'Profil déconnecté': {'en-us': 'Profile disconnected', 'en-gb': 'Profile disconnected'},
|
||
|
||
'Authentification requise': {'en-us': 'Authentication required', 'en-gb': 'Authentication required'},
|
||
'Nom d’utilisateur ou mot de passe incorrect': {'en-us': 'Incorrect username or password', 'en-gb': 'Incorrect username or password'},
|
||
'Compte non configuré': {'en-us': 'Account not configured', 'en-gb': 'Account not configured'},
|
||
'Mot de passe actuel incorrect': {'en-us': 'Incorrect current password', 'en-gb': 'Incorrect current password'},
|
||
'Les nouveaux mots de passe ne correspondent pas': {'en-us': 'New passwords do not match', 'en-gb': 'New passwords do not match'},
|
||
'Le mot de passe doit contenir au moins 8 caractères': {'en-us': 'Password must be at least 8 characters long', 'en-gb': 'Password must be at least 8 characters long'},
|
||
'Le mot de passe doit contenir entre 8 et 128 caractères': {'en-us': 'Password must be between 8 and 128 characters long', 'en-gb': 'Password must be between 8 and 128 characters long'},
|
||
'Nom d’utilisateur invalide': {'en-us': 'Invalid username', 'en-gb': 'Invalid username'},
|
||
'Nom utilisateur invalide': {'en-us': 'Invalid username', 'en-gb': 'Invalid username'},
|
||
'Code 2FA incorrect': {'en-us': 'Incorrect 2FA code', 'en-gb': 'Incorrect 2FA code'},
|
||
'Code 2FA invalide': {'en-us': 'Invalid 2FA code', 'en-gb': 'Invalid 2FA code'},
|
||
'Code de secours déjà utilisé': {'en-us': 'Backup code already used', 'en-gb': 'Backup code already used'},
|
||
'Profil introuvable': {'en-us': 'Profile not found', 'en-gb': 'Profile not found'},
|
||
'Profil VPN introuvable': {'en-us': 'VPN profile not found', 'en-gb': 'VPN profile not found'},
|
||
'Profil VPN enregistré avec succès': {'en-us': 'VPN profile saved successfully', 'en-gb': 'VPN profile saved successfully'},
|
||
'Profil VPN supprimé avec succès': {'en-us': 'VPN profile deleted successfully', 'en-gb': 'VPN profile deleted successfully'},
|
||
'Contenu du fichier manquant': {'en-us': 'Missing file content', 'en-gb': 'Missing file content'},
|
||
'Format de fichier invalide': {'en-us': 'Invalid file format', 'en-gb': 'Invalid file format'},
|
||
'Nom de l’application invalide': {'en-us': 'Invalid application name', 'en-gb': 'Invalid application name'},
|
||
'Nom court invalide': {'en-us': 'Invalid short name', 'en-gb': 'Invalid short name'},
|
||
'Thème invalide': {'en-us': 'Invalid theme', 'en-gb': 'Invalid theme'},
|
||
'Adresse MAC invalide': {'en-us': 'Invalid MAC address', 'en-gb': 'Invalid MAC address'},
|
||
'Impossible de se connecter au VPN': {'en-us': 'Unable to connect to VPN', 'en-gb': 'Unable to connect to VPN'},
|
||
'Tunnel VPN déconnecté': {'en-us': 'VPN tunnel disconnected', 'en-gb': 'VPN tunnel disconnected'},
|
||
'Le tunnel VPN est actuellement déconnecté': {'en-us': 'VPN tunnel is currently disconnected', 'en-gb': 'VPN tunnel is currently disconnected'},
|
||
'IP publique introuvable via ce tunnel': {'en-us': 'Public IP not found through this tunnel', 'en-gb': 'Public IP not found through this tunnel'},
|
||
'Passkey introuvable': {'en-us': 'Passkey not found', 'en-gb': 'Passkey not found'},
|
||
'Passkey inconnue ou non enregistrée': {'en-us': 'Passkey unknown or not registered', 'en-gb': 'Passkey unknown or not registered'},
|
||
'Passkey supprimée avec succès': {'en-us': 'Passkey deleted successfully', 'en-gb': 'Passkey deleted successfully'},
|
||
'Clé de sécurité renommée avec succès': {'en-us': 'Security key renamed successfully', 'en-gb': 'Security key renamed successfully'},
|
||
'Le nom de la clé ne peut pas être vide': {'en-us': 'Key name cannot be empty', 'en-gb': 'Key name cannot be empty'},
|
||
'Aucune modification': {'en-us': 'No changes', 'en-gb': 'No changes'},
|
||
'Action non autorisée': {'en-us': 'Unauthorized action', 'en-gb': 'Unauthorized action'},
|
||
'Erreur interne du serveur': {'en-us': 'Internal server error', 'en-gb': 'Internal server error'},
|
||
'Erreur interne': {'en-us': 'Internal error', 'en-gb': 'Internal error'},
|
||
'Réglages enregistrés avec succès': {'en-us': 'Settings saved successfully', 'en-gb': 'Settings saved successfully'},
|
||
'Réglages enregistrés': {'en-us': 'Settings saved successfully', 'en-gb': 'Settings saved successfully'},
|
||
'Personnalisation enregistrée sur le serveur': {'en-us': 'Customization saved to server', 'en-gb': 'Customisation saved to server'},
|
||
'Compteur de données remis à zéro': {'en-us': 'Data counter reset to zero', 'en-gb': 'Data counter reset to zero'},
|
||
'Limitations enregistrées': {'en-us': 'Limitations saved successfully', 'en-gb': 'Limitations saved successfully'},
|
||
'Limitations enregistrées avec succès': {'en-us': 'Limitations saved successfully', 'en-gb': 'Limitations saved successfully'},
|
||
'Erreur enregistrement limitations': {'en-us': 'Error saving limitations', 'en-gb': 'Error saving limitations'},
|
||
'Sauvegarde restaurée avec succès': {'en-us': 'Backup restored successfully', 'en-gb': 'Backup restored successfully'},
|
||
'Format de sauvegarde invalide': {'en-us': 'Invalid backup format', 'en-gb': 'Invalid backup format'},
|
||
'Fichier base de données introuvable': {'en-us': 'Database file not found', 'en-gb': 'Database file not found'},
|
||
'Appareil renommé avec succès': {'en-us': 'Device renamed successfully', 'en-gb': 'Device renamed successfully'},
|
||
'Appareil supprimé de l’historique': {'en-us': 'Device deleted from history', 'en-gb': 'Device deleted from history'},
|
||
'Type d’appareil modifié avec succès': {'en-us': 'Device type updated successfully', 'en-gb': 'Device type updated successfully'},
|
||
'Type d’appareil non valide': {'en-us': 'Invalid device type', 'en-gb': 'Invalid device type'},
|
||
'Le nom de la catégorie est obligatoire': {'en-us': 'Category name is required', 'en-gb': 'Category name is required'},
|
||
'Catégorie d’appareil enregistrée avec succès': {'en-us': 'Device category saved successfully', 'en-gb': 'Device category saved successfully'},
|
||
'Catégorie supprimée avec succès': {'en-us': 'Category deleted successfully', 'en-gb': 'Category deleted successfully'},
|
||
'Catégories réinitialisées avec succès': {'en-us': 'Categories reset to default successfully', 'en-gb': 'Categories reset to default successfully'},
|
||
'Assignation VPN du client mise à jour avec succès': {'en-us': 'Client VPN assignment updated successfully', 'en-gb': 'Client VPN assignment updated successfully'},
|
||
'Journaux supprimés': {'en-us': 'Logs cleared', 'en-gb': 'Logs cleared'},
|
||
'Toutes les données et le point d’accès ont été réinitialisés et supprimés': {'en-us': 'All data and the access point have been reset and removed', 'en-gb': 'All data and the access point have been reset and removed'},
|
||
'Double identification activée': {'en-us': 'Two-factor authentication enabled', 'en-gb': 'Two-factor authentication enabled'},
|
||
'Double identification désactivée': {'en-us': 'Two-factor authentication disabled', 'en-gb': 'Two-factor authentication disabled'},
|
||
'La 2FA n’est pas activée': {'en-us': '2FA is not enabled', 'en-gb': '2FA is not enabled'},
|
||
'Identifiants modifiés': {'en-us': 'Credentials updated', 'en-gb': 'Credentials updated'},
|
||
'Compte créé': {'en-us': 'Account created', 'en-gb': 'Account created'},
|
||
'Un compte existe déjà': {'en-us': 'An account already exists', 'en-gb': 'An account already exists'},
|
||
'Session déconnectée avec succès': {'en-us': 'Session logged out successfully', 'en-gb': 'Session logged out successfully'},
|
||
'Réglages des notifications enregistrés avec succès': {'en-us': 'Notification settings saved successfully', 'en-gb': 'Notification settings saved successfully'},
|
||
'Réglages du proxy inversé enregistrés avec succès !': {'en-us': 'Reverse proxy settings saved successfully!', 'en-gb': 'Reverse proxy settings saved successfully!'},
|
||
'SSID ou mot de passe Wi-Fi invalide': {'en-us': 'Invalid Wi-Fi SSID or password', 'en-gb': 'Invalid Wi-Fi SSID or password'},
|
||
'Sécurité Wi-Fi invalide': {'en-us': 'Invalid Wi-Fi security setting', 'en-gb': 'Invalid Wi-Fi security setting'},
|
||
'Délai d’attente dépassé': {'en-us': 'Request timed out', 'en-gb': 'Request timed out'},
|
||
"Délai d'attente dépassé": {'en-us': 'Request timed out', 'en-gb': 'Request timed out'}
|
||
}
|
||
|
||
def translate_api_text(text, lang='fr'):
|
||
if not text or not isinstance(text, str) or not lang or lang == 'fr':
|
||
return text
|
||
lang = lang.lower().strip()
|
||
if text in API_MSG_I18N:
|
||
return API_MSG_I18N[text].get(lang, API_MSG_I18N[text].get('en-us', text))
|
||
for k, v in API_MSG_I18N.items():
|
||
if k in text:
|
||
trans = v.get(lang, v.get('en-us', k))
|
||
text = text.replace(k, trans)
|
||
return text
|
||
|
||
|
||
class Handler(BaseHTTPRequestHandler):
|
||
def get_req_lang(self):
|
||
req_lang = self.headers.get('X-Language', '').strip().lower()
|
||
if not req_lang:
|
||
acc = self.headers.get('Accept-Language', '').strip().lower()
|
||
if acc:
|
||
req_lang = acc.split(',')[0].split(';')[0].strip()
|
||
if not req_lang:
|
||
try: req_lang = get_pref('language', 'fr')
|
||
except Exception: req_lang = 'fr'
|
||
return req_lang or 'fr'
|
||
|
||
def send_json(self, data, status=200):
|
||
req_lang = self.get_req_lang()
|
||
if req_lang.startswith('en') and isinstance(data, dict):
|
||
data = dict(data)
|
||
if 'error' in data and isinstance(data['error'], str):
|
||
data['error'] = translate_api_text(data['error'], req_lang)
|
||
if 'message' in data and isinstance(data['message'], str):
|
||
data['message'] = translate_api_text(data['message'], req_lang)
|
||
body=json.dumps(data,ensure_ascii=False).encode(); self.send_response(status); self.send_header('Content-Type','application/json; charset=utf-8'); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token, X-Language, Accept-Language'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body)
|
||
def do_OPTIONS(self): self.send_response(204); self.send_header('Access-Control-Allow-Origin','*'); self.send_header('Access-Control-Allow-Headers','Content-Type, X-Session-Token'); self.send_header('Access-Control-Allow-Methods','GET, POST, OPTIONS'); self.end_headers()
|
||
def do_GET(self):
|
||
if self.path in ('/','/index.html','/ap_dashboard.html'):
|
||
try: body=open(os.path.join(os.path.dirname(__file__),'index.html'),'rb').read(); self.send_response(200); self.send_header('Content-Type','text/html; charset=utf-8'); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body)
|
||
except OSError: self.send_error(404,'index.html introuvable')
|
||
return
|
||
if self.path in ('/setup', '/setup.html', '/Setup.html', '/Setup.HTML'):
|
||
try:
|
||
body = open(os.path.join(os.path.dirname(__file__), 'setup.html'), 'rb').read()
|
||
self.send_response(200)
|
||
self.send_header('Content-Type', 'text/html; charset=utf-8')
|
||
self.send_header('Content-Length', str(len(body)))
|
||
self.end_headers()
|
||
self.wfile.write(body)
|
||
except OSError:
|
||
self.send_error(404, 'setup.html introuvable')
|
||
return
|
||
if self.path.startswith('/lang/'):
|
||
clean_name = os.path.basename(urllib.parse.urlparse(self.path).path)
|
||
lang_path = os.path.join(os.path.dirname(__file__), 'lang', clean_name)
|
||
if os.path.isfile(lang_path) and clean_name.endswith('.js'):
|
||
try:
|
||
body = open(lang_path, 'rb').read()
|
||
self.send_response(200)
|
||
self.send_header('Content-Type', 'application/javascript; charset=utf-8')
|
||
self.send_header('Content-Length', str(len(body)))
|
||
self.end_headers()
|
||
self.wfile.write(body)
|
||
return
|
||
except OSError: pass
|
||
self.send_error(404, 'Fichier de langue introuvable')
|
||
return
|
||
if self.path == '/favicon.png' or self.path.startswith('/images/'):
|
||
clean_name = 'favicon.png' if self.path == '/favicon.png' else os.path.basename(urllib.parse.urlparse(self.path).path)
|
||
img_path = os.path.join(os.path.dirname(__file__), 'images', clean_name)
|
||
ext = os.path.splitext(clean_name)[1].lower()
|
||
mime_map = {'.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.ico': 'image/x-icon'}
|
||
if os.path.isfile(img_path) and ext in mime_map:
|
||
try:
|
||
body = open(img_path, 'rb').read()
|
||
self.send_response(200)
|
||
self.send_header('Content-Type', mime_map[ext])
|
||
self.send_header('Content-Length', str(len(body)))
|
||
self.end_headers()
|
||
self.wfile.write(body)
|
||
return
|
||
except OSError: pass
|
||
if self.path.startswith('/images/'):
|
||
self.send_error(404, 'Image introuvable')
|
||
return
|
||
if self.path == '/api/auth/status': self.send_json(auth_state()); return
|
||
if self.path == '/api/device-types':
|
||
c = db()
|
||
rows = c.execute('SELECT id, label, icon, desc, sort_order FROM custom_device_types ORDER BY sort_order ASC, id ASC').fetchall()
|
||
c.close()
|
||
items = [{'id': r[0], 'label': r[1], 'icon': r[2], 'desc': r[3], 'sort_order': r[4]} for r in rows]
|
||
self.send_json({'ok': True, 'device_types': items}); return
|
||
if self.path.startswith('/api/icons/search'):
|
||
parsed = urllib.parse.urlparse(self.path)
|
||
qs = urllib.parse.parse_qs(parsed.query)
|
||
q = (qs.get('q', [''])[0]).strip()
|
||
limit = min(int(qs.get('limit', ['36'])[0]), 64)
|
||
icons = search_iconify_icons(q, limit=limit)
|
||
self.send_json({'ok': True, 'icons': icons, 'total': len(icons)})
|
||
return
|
||
if self.path.startswith('/api/icons/svg'):
|
||
parsed = urllib.parse.urlparse(self.path)
|
||
qs = urllib.parse.parse_qs(parsed.query)
|
||
name = (qs.get('name', [''])[0]).strip()
|
||
color = (qs.get('color', [''])[0]).strip()
|
||
as_json = (qs.get('format', [''])[0]).strip().lower() == 'json' or 'application/json' in self.headers.get('Accept', '')
|
||
if not name:
|
||
if as_json: self.send_json({'error': 'Nom d\'icône manquant'}, 400)
|
||
else: self.send_error(400, 'Nom d\'icône manquant')
|
||
return
|
||
svg_content = fetch_iconify_svg(name, color=color)
|
||
if as_json:
|
||
self.send_json({'ok': True, 'svg': svg_content, 'name': name})
|
||
else:
|
||
svg_bytes = svg_content.encode('utf-8')
|
||
self.send_response(200)
|
||
self.send_header('Content-Type', 'image/svg+xml; charset=utf-8')
|
||
self.send_header('Cache-Control', 'public, max-age=86400')
|
||
self.send_header('Content-Length', str(len(svg_bytes)))
|
||
self.end_headers()
|
||
self.wfile.write(svg_bytes)
|
||
return
|
||
if self.path.startswith('/api/backup/export'):
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
parsed = urllib.parse.urlparse(self.path)
|
||
qs = urllib.parse.parse_qs(parsed.query)
|
||
fmt = (qs.get('format', ['zip'])[0]).strip().lower()
|
||
now_str = time.strftime('%Y%m%d-%H%M%S')
|
||
if fmt == 'sqlite':
|
||
if os.path.exists(DB_FILE):
|
||
try:
|
||
with open(DB_FILE, 'rb') as f:
|
||
content = f.read()
|
||
self.send_response(200)
|
||
self.send_header('Content-Type', 'application/x-sqlite3')
|
||
self.send_header('Content-Disposition', f'attachment; filename="ap-manageur-database-{now_str}.sqlite3"')
|
||
self.send_header('Content-Length', str(len(content)))
|
||
self.end_headers()
|
||
self.wfile.write(content)
|
||
log('export_base_sqlite', username(self) or 'Administrateur', request_ip(self), 'SYSTEM')
|
||
return
|
||
except Exception as e:
|
||
self.send_json({'error': f'Erreur export SQLite: {e}'}, 500); return
|
||
else:
|
||
self.send_json({'error': 'Fichier base de données introuvable'}, 404); return
|
||
elif fmt == 'json':
|
||
try:
|
||
backup = export_backup_data()
|
||
json_bytes = json.dumps(backup, ensure_ascii=False, indent=2).encode('utf-8')
|
||
self.send_response(200)
|
||
self.send_header('Content-Type', 'application/json; charset=utf-8')
|
||
self.send_header('Content-Disposition', f'attachment; filename="ap-manageur-backup-{now_str}.json"')
|
||
self.send_header('Content-Length', str(len(json_bytes)))
|
||
self.end_headers()
|
||
self.wfile.write(json_bytes)
|
||
log('export_configuration_json', username(self) or 'Administrateur', request_ip(self), 'SYSTEM')
|
||
return
|
||
except Exception as e:
|
||
self.send_json({'error': f'Erreur génération sauvegarde: {e}'}, 500); return
|
||
else:
|
||
# Format par défaut : Archive ZIP unifiée (Configuration JSON + Base SQLite brute)
|
||
try:
|
||
backup = export_backup_data()
|
||
json_bytes = json.dumps(backup, ensure_ascii=False, indent=2).encode('utf-8')
|
||
buf = io.BytesIO()
|
||
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||
zf.writestr('configuration.json', json_bytes)
|
||
if os.path.exists(DB_FILE):
|
||
try:
|
||
with open(DB_FILE, 'rb') as f_db:
|
||
zf.writestr('ap-dashboard.sqlite3', f_db.read())
|
||
except Exception as e_db:
|
||
print(f"[backup] Inclusion sqlite impossible : {e_db}", flush=True)
|
||
readme_text = (
|
||
f"Sauvegarde AP Manageur ({APP_VERSION})\n"
|
||
f"Date d'export : {datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}\n\n"
|
||
"Contenu de cette archive :\n"
|
||
"- configuration.json : Configuration complète (profils VPN WireGuard & OpenVPN, routage appareils, noms et logos des équipements, catégories, blocage et réglages système).\n"
|
||
"- ap-dashboard.sqlite3 : Base de données SQLite brute complète.\n\n"
|
||
"Restauration :\n"
|
||
"Vous pouvez importer directement cette archive .zip (ou le fichier configuration.json) "
|
||
"dans AP Manageur (Réglages > Zone dangereuse > Importer une sauvegarde).\n"
|
||
)
|
||
zf.writestr('README.txt', readme_text.encode('utf-8'))
|
||
zip_bytes = buf.getvalue()
|
||
self.send_response(200)
|
||
self.send_header('Content-Type', 'application/zip')
|
||
self.send_header('Content-Disposition', f'attachment; filename="ap-manageur-sauvegarde-{now_str}.zip"')
|
||
self.send_header('Content-Length', str(len(zip_bytes)))
|
||
self.end_headers()
|
||
self.wfile.write(zip_bytes)
|
||
log('export_sauvegarde_complete', username(self) or 'Administrateur', request_ip(self), 'SYSTEM')
|
||
return
|
||
except Exception as e:
|
||
self.send_json({'error': f'Erreur génération archive ZIP: {e}'}, 500); return
|
||
if self.path in ('/api/auth/admin', '/api/auth/user'):
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
c = db()
|
||
row = c.execute('SELECT username FROM auth_users LIMIT 1').fetchone()
|
||
c.close()
|
||
admin_user = row[0] if row else (username(self) or 'admin')
|
||
self.send_json({'ok': True, 'username': admin_user}); return
|
||
if self.path == '/api/auth/sessions':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
self.send_json(list_sessions(extract_token(self), self.get_req_lang())); return
|
||
if self.path == '/api/auth/passkey/list':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
u = username(self) or 'admin'
|
||
c = db()
|
||
rows = c.execute('SELECT id, name, device_type, sign_count, created_at, last_used_at FROM auth_passkeys WHERE username=? ORDER BY created_at DESC', (u,)).fetchall()
|
||
c.close()
|
||
is_en = self.get_req_lang().startswith('en')
|
||
never_label = 'Never' if is_en else 'Jamais'
|
||
items = [{'id': r[0], 'name': r[1], 'device_type': r[2], 'sign_count': r[3], 'created_at': r[4], 'last_used_at': r[5] or never_label} for r in rows]
|
||
self.send_json({'ok': True, 'passkeys': items}); return
|
||
if self.path == '/api/settings/proxy':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
cfg = get_reverse_proxy_config()
|
||
raw_sock = self.client_address[0] if hasattr(self, 'client_address') and self.client_address else '127.0.0.1'
|
||
raw_direct = self.headers.get('X-Client-Raw-IP', '').strip()
|
||
self.send_json({
|
||
'ok': True,
|
||
'config': cfg,
|
||
'detected': {
|
||
'real_ip': request_ip(self),
|
||
'raw_direct_ip': raw_direct or raw_sock,
|
||
'socket_ip': raw_sock,
|
||
'x_client_raw_ip': raw_direct or '—',
|
||
'x_forwarded_for': self.headers.get('X-Forwarded-For', '') or '—',
|
||
'x_real_ip': self.headers.get('X-Real-IP', '') or '—',
|
||
'cf_connecting_ip': self.headers.get('CF-Connecting-IP', '') or '—',
|
||
'true_client_ip': self.headers.get('True-Client-IP', '') or '—',
|
||
'x_forwarded_proto': self.headers.get('X-Forwarded-Proto', '') or '—',
|
||
'host': self.headers.get('X-Forwarded-Host', '') or self.headers.get('Host', '') or '—'
|
||
}
|
||
})
|
||
return
|
||
path_only = self.path.split('?')[0]
|
||
if path_only == '/api/preferences':
|
||
c=db(); rows=dict(c.execute("SELECT key,value FROM preferences").fetchall()); c.close()
|
||
self.send_json({
|
||
'theme': rows.get('theme', 'dark'),
|
||
'language': rows.get('language', 'fr'),
|
||
'app_name': rows.get('app_name', 'Administration de l’AP Wi‑Fi'),
|
||
'app_short_name': rows.get('app_short_name', 'AP Manageur')
|
||
})
|
||
return
|
||
if path_only == '/api/notifications/settings':
|
||
if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
self.send_json(get_notifications_settings_public())
|
||
return
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
if path_only == '/api/status': self.send_json(status())
|
||
elif path_only == '/api/clients': self.send_json(clients())
|
||
elif path_only == '/api/clients/blocked': self.send_json(blocked_list())
|
||
elif path_only == '/api/devices': self.send_json(all_devices(self.get_req_lang()))
|
||
elif path_only == '/api/devices/limits':
|
||
parsed = urllib.parse.urlparse(self.path)
|
||
qs = urllib.parse.parse_qs(parsed.query)
|
||
target_mac = (qs.get('mac', [''])[0]).strip().upper()
|
||
lim = get_client_limits_dict(target_mac)
|
||
self.send_json({'ok': True, 'mac': target_mac, 'limits': lim})
|
||
elif path_only == '/api/logs': self.send_json(logs())
|
||
elif path_only == '/api/stats': self.send_json(stats())
|
||
elif path_only == '/api/network/topology': self.send_json(network_topology())
|
||
elif path_only == '/api/vpn/profiles':
|
||
self.send_json({'profiles': list_vpn_profiles()})
|
||
elif path_only == '/api/vpn/clients':
|
||
self.send_json({'clients': list_vpn_clients()})
|
||
elif path_only in ('/api/vpn/check-ip', '/api/vpn/public-ip'):
|
||
qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
|
||
pid = int(qs.get('id', [0])[0])
|
||
prof = get_vpn_profile(pid)
|
||
if not prof: self.send_json({'error':'Profil introuvable'},404); return
|
||
iface = prof.get('iface') or (f"wg_ap{pid}" if prof['type'] == 'wireguard' else f"tun_ap{pid}")
|
||
if not is_iface_up(iface):
|
||
self.send_json({'ok': False, 'error': 'Tunnel VPN déconnecté'}); return
|
||
force = qs.get('force', ['1'])[0] == '1'
|
||
ip = get_vpn_public_ip(iface, force_refresh=force)
|
||
hs, hs_sec = get_wireguard_handshake_info(iface) if prof['type'] == 'wireguard' else (None, None)
|
||
if ip:
|
||
geo = get_ip_geo(ip)
|
||
self.send_json({'ok': True, 'public_ip': ip, 'public_ip_geo': geo, 'handshake': hs, 'handshake_age_seconds': hs_sec, 'iface': iface})
|
||
else:
|
||
self.send_json({'ok': False, 'error': 'IP publique introuvable via ce tunnel', 'handshake': hs, 'handshake_age_seconds': hs_sec, 'iface': iface})
|
||
return
|
||
elif path_only == '/api/notifications/settings':
|
||
self.send_json(get_notifications_settings_public())
|
||
elif path_only == '/api/advanced/capture/status':
|
||
with capture_lock:
|
||
wifi_if = capture_iface_used or get_wifi_interface()
|
||
domain_list = sorted(captured_domains.values(), key=lambda x: (x['count'], x['last_seen']), reverse=True)
|
||
dur = int(time.time() - capture_started_at) if (capture_running and capture_started_at > 0) else 0
|
||
payload = {
|
||
'running': capture_running,
|
||
'started_at': capture_started_at if capture_running else 0,
|
||
'duration_seconds': dur,
|
||
'packet_count': len(capture_packets),
|
||
'buffer_packets': len(capture_packets),
|
||
'total_captured': capture_id_counter,
|
||
'total_packets': capture_id_counter,
|
||
'interface': wifi_if,
|
||
'wifi_interface': wifi_if,
|
||
'stats': dict(capture_stats),
|
||
'unique_domains_count': len(captured_domains),
|
||
'domains': domain_list[:500],
|
||
'pcap_bytes': len(capture_pcap_bytes),
|
||
'pcap_size_bytes': len(capture_pcap_bytes)
|
||
}
|
||
self.send_json(payload)
|
||
elif path_only == '/api/advanced/domains':
|
||
with capture_lock:
|
||
domain_list = sorted(captured_domains.values(), key=lambda x: (x['count'], x['last_seen']), reverse=True)[:500]
|
||
tot_dom = len(captured_domains)
|
||
self.send_json({
|
||
'total_domains': tot_dom,
|
||
'domains': domain_list
|
||
})
|
||
elif path_only == '/api/advanced/capture/packets':
|
||
parsed = urllib.parse.urlparse(self.path)
|
||
qs = urllib.parse.parse_qs(parsed.query)
|
||
try: since = int(qs.get('since', [0])[0])
|
||
except Exception: since = 0
|
||
try: limit = min(50000, max(1, int(qs.get('limit', [1000])[0])))
|
||
except Exception: limit = 1000
|
||
with capture_lock:
|
||
if since > 0:
|
||
pkts = [p for p in capture_packets if p['id'] > since][:limit]
|
||
else:
|
||
pkts = list(capture_packets[-limit:] if limit < len(capture_packets) else capture_packets)
|
||
running = capture_running
|
||
buf_count = len(capture_packets)
|
||
tot_count = capture_id_counter
|
||
|
||
try:
|
||
for p in pkts:
|
||
src_ip = p.get('src')
|
||
src_geo = p.get('src_geo') or {}
|
||
if src_ip and (not p.get('src_geo') or src_geo.get('code') in ('WAN', 'EXT', '')):
|
||
geo = get_ip_geo(src_ip)
|
||
if geo and geo.get('code') not in ('WAN', 'EXT', ''):
|
||
p['src_geo'] = geo
|
||
dst_ip = p.get('dst')
|
||
dst_geo = p.get('dst_geo') or {}
|
||
if dst_ip and (not p.get('dst_geo') or dst_geo.get('code') in ('WAN', 'EXT', '')):
|
||
geo = get_ip_geo(dst_ip)
|
||
if geo and geo.get('code') not in ('WAN', 'EXT', ''):
|
||
p['dst_geo'] = geo
|
||
except Exception as e_geo_update:
|
||
print(f"[ap-capture] Erreur rafraîchissement GeoIP: {e_geo_update}", flush=True)
|
||
|
||
self.send_json({
|
||
'running': running,
|
||
'packet_count': buf_count,
|
||
'buffer_packets': buf_count,
|
||
'total_captured': tot_count,
|
||
'total_packets': tot_count,
|
||
'packets': pkts
|
||
})
|
||
elif path_only == '/api/advanced/geoip':
|
||
parsed = urllib.parse.urlparse(self.path)
|
||
qs = urllib.parse.parse_qs(parsed.query)
|
||
ip_val = qs.get('ip', [''])[0].strip()
|
||
geo = get_ip_geo(ip_val)
|
||
self.send_json({'ip': ip_val, 'geo': geo})
|
||
elif path_only == '/api/advanced/capture/export':
|
||
with capture_lock:
|
||
data = bytes(capture_pcap_bytes)
|
||
if not data:
|
||
data = struct.pack('<IHHiIII', 0xa1b2c3d4, 2, 4, 0, 0, 65535, 1)
|
||
ts_str = time.strftime('%Y%m%d_%H%M%S')
|
||
filename = f"capture_wireshark_{ts_str}.pcap"
|
||
self.send_response(200)
|
||
self.send_header('Content-Type', 'application/vnd.tcpdump.pcap')
|
||
self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
|
||
self.send_header('Content-Length', str(len(data)))
|
||
self.send_header('Access-Control-Allow-Origin', '*')
|
||
self.send_header('Cache-Control', 'no-cache')
|
||
self.end_headers()
|
||
self.wfile.write(data)
|
||
else: self.send_json({'error':'Route inconnue'},404)
|
||
def do_POST(self):
|
||
try: data=read_json(self)
|
||
except Exception: self.send_json({'error':'JSON invalide'},400); return
|
||
if not isinstance(data, dict): self.send_json({'error':'JSON invalide'},400); return
|
||
try:
|
||
if self.path == '/api/auth/setup':
|
||
if auth_state()['configured']: raise ValueError('Un compte existe déjà')
|
||
u=str(data.get('username',''))
|
||
create_user(u,str(data.get('password','')),None)
|
||
log('creation_compte_admin', u, request_ip(self), 'AUTH')
|
||
self.send_json({'ok':True,'message':'Compte créé','two_factor_enabled':False}); return
|
||
if self.path == '/api/login':
|
||
u=str(data.get('username',''))
|
||
row=verify_user(u,str(data.get('password','')))
|
||
if not row:
|
||
log('echec_connexion', u or 'Inconnu', request_ip(self), 'AUTH')
|
||
dispatch_notification('admin_login_failed', "⚠️ Échec de connexion administrateur", f"Une tentative de connexion au compte administrateur a échoué (mot de passe invalide).", details={"Identifiant tenté": u or "Inconnu", "Adresse IP": request_ip(self), "Navigateur": parse_browser(self.headers.get('User-Agent', '')), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=8, level="danger")
|
||
raise ValueError('Utilisateur ou mot de passe incorrect')
|
||
used_recovery = False
|
||
if row[2]:
|
||
otp=data.get('otp')
|
||
if not totp_ok(row[2],otp):
|
||
if not recovery_use(otp):
|
||
log('echec_connexion', row[0], request_ip(self), 'AUTH')
|
||
raise ValueError('Code de double identification incorrect')
|
||
used_recovery = True
|
||
log('connexion_code_recuperation', row[0], request_ip(self), 'AUTH')
|
||
else:
|
||
log('connexion_admin', row[0], request_ip(self), 'AUTH')
|
||
else:
|
||
log('connexion_admin', row[0], request_ip(self), 'AUTH')
|
||
c_name = str(data.get('device_name', '')).strip() or urllib.parse.unquote(self.headers.get('X-Device-Name', ''))
|
||
dispatch_notification('admin_login', "🔒 Connexion au compte administrateur", f"Connexion réussie au compte administrateur « {row[0]} ».", details={"Compte": row[0], "Machine": c_name or "Machine non spécifiée", "Adresse IP": request_ip(self), "Navigateur": parse_browser(self.headers.get('User-Agent', '')), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=5, level="info")
|
||
self.send_json({'ok':True,'token':new_session(row[0], request_ip(self), self.headers.get('User-Agent',''), c_name),'used_recovery':used_recovery}); return
|
||
if self.path == '/api/auth/passkey/login/options':
|
||
c = db()
|
||
pks = c.execute('SELECT id FROM auth_passkeys').fetchall()
|
||
c.close()
|
||
if not pks:
|
||
raise ValueError('Aucune Passkey n’est encore enregistrée sur ce système. Connectez-vous d’abord avec vos identifiants administrateur pour en ajouter une dans Réglages > Compte Administrateur.')
|
||
now = time.time()
|
||
for k in [k for k, v in passkey_pending_challenges.items() if now - v.get('time', 0) > 120]:
|
||
passkey_pending_challenges.pop(k, None)
|
||
raw_chal = secrets.token_bytes(32)
|
||
chal_b64 = b64url_encode(raw_chal)
|
||
passkey_pending_challenges[chal_b64] = {'type': 'login', 'time': time.time()}
|
||
req_host = (self.headers.get('Host') or '').split(':')[0] or 'localhost'
|
||
options = {
|
||
'ok': True,
|
||
'challenge': chal_b64,
|
||
'rpId': req_host,
|
||
'timeout': 60000,
|
||
'userVerification': 'preferred',
|
||
'allowCredentials': [{'type': 'public-key', 'id': r[0]} for r in pks]
|
||
}
|
||
self.send_json(options); return
|
||
if self.path == '/api/auth/passkey/login/verify':
|
||
c_data_b64 = data.get('response', {}).get('clientDataJSON', '')
|
||
if not c_data_b64: raise ValueError('Données clientData manquantes')
|
||
c_data_raw = b64url_decode(c_data_b64)
|
||
c_data = json.loads(c_data_raw.decode('utf-8'))
|
||
if c_data.get('type') != 'webauthn.get':
|
||
raise ValueError('Type d’opération clientData invalide')
|
||
chal = c_data.get('challenge', '')
|
||
p_info = passkey_pending_challenges.pop(chal, None)
|
||
if not p_info or p_info.get('type') != 'login':
|
||
raise ValueError('Challenge invalide ou expiré. Veuillez réessayer.')
|
||
cred_id = str(data.get('id', '')).strip()
|
||
c = db()
|
||
row = c.execute('SELECT id, username, public_key, name, sign_count FROM auth_passkeys WHERE id=?', (cred_id,)).fetchone()
|
||
if not row:
|
||
c.close()
|
||
raise ValueError('Passkey inconnue ou non enregistrée')
|
||
u = row[1]
|
||
pk_info = json.loads(row[2])
|
||
auth_data_raw = b64url_decode(data.get('response', {}).get('authenticatorData', ''))
|
||
sig_raw = b64url_decode(data.get('response', {}).get('signature', ''))
|
||
if len(auth_data_raw) < 37:
|
||
c.close(); raise ValueError('authenticatorData invalide')
|
||
flags = auth_data_raw[32]
|
||
if not (flags & 0x01):
|
||
c.close(); raise ValueError('Présence utilisateur non vérifiée par le capteur')
|
||
c_data_hash = hashlib.sha256(c_data_raw).digest()
|
||
signed_data = auth_data_raw + c_data_hash
|
||
valid_sig = False
|
||
if pk_info.get('alg') == 'ES256':
|
||
pub_x = b64url_decode(pk_info['x'])
|
||
pub_y = b64url_decode(pk_info['y'])
|
||
valid_sig = verify_es256_signature(pub_x, pub_y, sig_raw, signed_data)
|
||
elif pk_info.get('alg') == 'RS256':
|
||
n_bytes = b64url_decode(pk_info['n'])
|
||
e_bytes = b64url_decode(pk_info['e'])
|
||
valid_sig = verify_rs256_signature(n_bytes, e_bytes, sig_raw, signed_data)
|
||
if not valid_sig:
|
||
c.close()
|
||
log('echec_connexion_passkey', u, request_ip(self), 'AUTH')
|
||
raise ValueError('Signature biométrique ou cryptographique de la Passkey invalide')
|
||
new_count = int.from_bytes(auth_data_raw[33:37], 'big')
|
||
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
c.execute('UPDATE auth_passkeys SET sign_count=?, last_used_at=? WHERE id=?', (new_count, now_str, cred_id))
|
||
c.commit(); c.close()
|
||
c_name = str(data.get('device_name', '')).strip() or urllib.parse.unquote(self.headers.get('X-Device-Name', ''))
|
||
dispatch_notification('admin_login', "🔑 Connexion par Passkey réussie", f"Connexion immédiate par Passkey « {row[3]} » sans mot de passe ni 2FA.", details={"Compte": u, "Passkey": row[3], "Machine": c_name or "Machine non spécifiée", "Adresse IP": request_ip(self), "Navigateur": parse_browser(self.headers.get('User-Agent', '')), "Date": time.strftime('%d/%m/%Y %H:%M:%S')}, priority=5, level="info")
|
||
log('connexion_passkey', u, request_ip(self), 'AUTH')
|
||
tok = new_session(u, request_ip(self), self.headers.get('User-Agent', ''), c_name)
|
||
self.send_json({'ok': True, 'token': tok, 'message': f'Authentification réussie avec « {row[3]} » !'}); return
|
||
if self.path == '/api/auth/passkey/register/options':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
u = username(self) or 'admin'
|
||
now = time.time()
|
||
for k in [k for k, v in passkey_pending_challenges.items() if now - v.get('time', 0) > 120]:
|
||
passkey_pending_challenges.pop(k, None)
|
||
raw_chal = secrets.token_bytes(32)
|
||
chal_b64 = b64url_encode(raw_chal)
|
||
passkey_pending_challenges[chal_b64] = {'type': 'register', 'username': u, 'time': time.time()}
|
||
req_host = (self.headers.get('Host') or '').split(':')[0] or 'localhost'
|
||
options = {
|
||
'ok': True,
|
||
'challenge': chal_b64,
|
||
'rp': {'name': 'AP Manageur', 'id': req_host},
|
||
'user': {
|
||
'id': b64url_encode(u.encode('utf-8')),
|
||
'name': u,
|
||
'displayName': u
|
||
},
|
||
'pubKeyCredParams': [
|
||
{'type': 'public-key', 'alg': -7},
|
||
{'type': 'public-key', 'alg': -257}
|
||
],
|
||
'timeout': 60000,
|
||
'attestation': 'none',
|
||
'authenticatorSelection': {
|
||
'residentKey': 'preferred',
|
||
'userVerification': 'preferred'
|
||
}
|
||
}
|
||
self.send_json(options); return
|
||
if self.path == '/api/auth/passkey/register/verify':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
u = username(self) or 'admin'
|
||
c_data_b64 = data.get('response', {}).get('clientDataJSON', '')
|
||
if not c_data_b64: raise ValueError('Données clientData manquantes')
|
||
c_data_raw = b64url_decode(c_data_b64)
|
||
c_data = json.loads(c_data_raw.decode('utf-8'))
|
||
if c_data.get('type') != 'webauthn.create':
|
||
raise ValueError('Type clientData incorrect')
|
||
chal = c_data.get('challenge', '')
|
||
p_info = passkey_pending_challenges.pop(chal, None)
|
||
if not p_info or p_info.get('type') != 'register' or p_info.get('username') != u:
|
||
raise ValueError('Challenge invalide ou expiré')
|
||
att_raw = b64url_decode(data.get('response', {}).get('attestationObject', ''))
|
||
att_obj, _ = decode_cbor(att_raw)
|
||
auth_data = att_obj.get('authData', b'')
|
||
if len(auth_data) < 55:
|
||
raise ValueError('authData trop court')
|
||
flags = auth_data[32]
|
||
if not (flags & 0x01): raise ValueError('Présence utilisateur non vérifiée')
|
||
if not (flags & 0x40): raise ValueError('Données d’attestation absentes')
|
||
id_len = int.from_bytes(auth_data[53:55], 'big')
|
||
cred_id = auth_data[55:55+id_len]
|
||
cred_id_b64 = b64url_encode(cred_id)
|
||
cose_map, _ = decode_cbor(auth_data[55+id_len:])
|
||
alg = cose_map.get(3)
|
||
if alg == -7:
|
||
x_bytes = cose_map.get(-2, b'')
|
||
y_bytes = cose_map.get(-3, b'')
|
||
if len(x_bytes) != 32 or len(y_bytes) != 32:
|
||
raise ValueError('Coordonnées de clé publique P-256 invalides')
|
||
pk_stored = json.dumps({'kty': 'EC', 'crv': 'P-256', 'alg': 'ES256', 'x': b64url_encode(x_bytes), 'y': b64url_encode(y_bytes)})
|
||
elif alg == -257:
|
||
n_bytes = cose_map.get(-1, b'')
|
||
e_bytes = cose_map.get(-2, b'')
|
||
pk_stored = json.dumps({'kty': 'RSA', 'alg': 'RS256', 'n': b64url_encode(n_bytes), 'e': b64url_encode(e_bytes)})
|
||
else:
|
||
raise ValueError(f'Algorithme cryptographique non supporté : {alg}')
|
||
p_name = (data.get('name') or '').strip() or 'Passkey'
|
||
now_str = time.strftime('%Y-%m-%d %H:%M:%S')
|
||
c = db()
|
||
c.execute('''
|
||
INSERT INTO auth_passkeys(id, username, public_key, name, device_type, sign_count, created_at, last_used_at)
|
||
VALUES(?, ?, ?, ?, "security_key", 0, ?, "")
|
||
ON CONFLICT(id) DO UPDATE SET public_key=excluded.public_key, name=excluded.name
|
||
''', (cred_id_b64, u, pk_stored, p_name, now_str))
|
||
c.commit(); c.close()
|
||
log('passkey_enregistree', f"{u} ({p_name})", request_ip(self), 'AUTH')
|
||
self.send_json({'ok': True, 'message': f'Passkey « {p_name} » enregistrée avec succès !'}); return
|
||
if self.path == '/api/auth/passkey/delete':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
cred_id = str(data.get('id', '')).strip()
|
||
if not cred_id: raise ValueError('Identifiant de Passkey manquant')
|
||
c = db()
|
||
c.execute('DELETE FROM auth_passkeys WHERE id=?', (cred_id,))
|
||
c.commit(); c.close()
|
||
log('passkey_supprimee', username(self) or 'admin', request_ip(self), 'AUTH')
|
||
self.send_json({'ok': True, 'message': 'Passkey supprimée avec succès'}); return
|
||
if self.path == '/api/auth/passkey/rename':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
cred_id = str(data.get('id', '')).strip()
|
||
new_name = str(data.get('name', '')).strip()
|
||
if not cred_id: raise ValueError('Identifiant de Passkey manquant')
|
||
if not new_name: raise ValueError('Le nom de la clé ne peut pas être vide')
|
||
c = db()
|
||
row = c.execute('SELECT name FROM auth_passkeys WHERE id=?', (cred_id,)).fetchone()
|
||
if not row:
|
||
c.close()
|
||
raise ValueError('Passkey introuvable')
|
||
old_name = row[0]
|
||
c.execute('UPDATE auth_passkeys SET name=? WHERE id=?', (new_name, cred_id))
|
||
c.commit(); c.close()
|
||
log('passkey_renommee', f"{username(self) or 'admin'} ({old_name} -> {new_name})", request_ip(self), 'AUTH')
|
||
self.send_json({'ok': True, 'message': 'Clé de sécurité renommée avec succès'}); return
|
||
if self.path == '/api/logout':
|
||
log('deconnexion_admin', username(self) or 'Administrateur', request_ip(self), 'AUTH')
|
||
delete_session(self.headers.get('X-Session-Token',''))
|
||
self.send_json({'ok':True}); return
|
||
if self.path in ('/api/auth/sessions/revoke', '/api/auth/sessions/delete'):
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
target_token = str(data.get('token', '')).strip()
|
||
if not target_token: raise ValueError('Token de session manquant')
|
||
s = get_session(target_token)
|
||
target_ip = s.get('ip', '—') if s else '—'
|
||
target_name = s.get('device_name', '') if s else ''
|
||
target_user = s.get('username', 'Administrateur') if s else 'Administrateur'
|
||
curr = extract_token(self)
|
||
is_self = bool(curr and target_token == curr)
|
||
delete_session(target_token)
|
||
log('deconnexion_admin', f"{target_user} ({target_name or 'Session'})", target_ip, 'AUTH')
|
||
self.send_json({
|
||
'ok': True,
|
||
'message': 'Session déconnectée avec succès',
|
||
'is_self': is_self
|
||
})
|
||
return
|
||
if self.path == '/api/auth/sessions/rename':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
target_token = str(data.get('token', '')).strip()
|
||
new_name = str(data.get('name', '')).strip()
|
||
if not target_token: raise ValueError('Token de session manquant')
|
||
if not new_name: raise ValueError('Nom de machine vide')
|
||
if len(new_name) > 64: new_name = new_name[:64]
|
||
s = get_session(target_token)
|
||
if s:
|
||
s['device_name'] = new_name
|
||
try:
|
||
c = db()
|
||
c.execute('UPDATE auth_sessions SET device_name=? WHERE token=?', (new_name, target_token))
|
||
c.commit(); c.close()
|
||
except Exception as e:
|
||
raise RuntimeError(f"Erreur enregistrement nom: {e}")
|
||
log('modification_identifiants', f"Renommage machine -> {new_name}", request_ip(self), 'AUTH')
|
||
self.send_json({'ok': True, 'message': 'Machine renommée avec succès', 'name': new_name})
|
||
return
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
if self.path == '/api/clients/block': set_blocked(str(data.get('mac','')),bool(data.get('blocked',True))); self.send_json({'ok':True}); return
|
||
if self.path == '/api/devices/limits':
|
||
mac = str(data.get('mac', '')).strip().upper()
|
||
if not re.fullmatch(r'[0-9A-F]{2}(:[0-9A-F]{2}){5}', mac):
|
||
self.send_json({'error': 'Adresse MAC invalide'}, 400); return
|
||
try:
|
||
updated_lim = save_client_limits(mac, data)
|
||
name, ip = known_device(mac)
|
||
log('limites_appareil_modifiees', name, ip, mac)
|
||
self.send_json({'ok': True, 'message': 'Limitations enregistrées avec succès', 'limits': updated_lim})
|
||
except Exception as e:
|
||
self.send_json({'error': f'Erreur enregistrement limitations : {e}'}, 400)
|
||
return
|
||
if self.path == '/api/devices/rename':
|
||
mac = str(data.get('mac', '')).strip().upper()
|
||
new_name = str(data.get('name', '')).strip()
|
||
if not mac: raise ValueError('Adresse MAC manquante')
|
||
if not new_name: raise ValueError('Nom manquant')
|
||
c = db()
|
||
c.execute('INSERT INTO client_names(mac, name, last_ip, last_seen) VALUES(?, ?, "Non attribuée", ?) ON CONFLICT(mac) DO UPDATE SET name=excluded.name', (mac, new_name, time.strftime('%Y-%m-%d %H:%M:%S')))
|
||
c.commit(); c.close()
|
||
self.send_json({'ok': True, 'message': 'Appareil renommé avec succès'}); return
|
||
if self.path == '/api/devices/set_type':
|
||
mac = str(data.get('mac', '')).strip().upper()
|
||
dev_type = str(data.get('device_type', '')).strip().lower()
|
||
if not mac: raise ValueError('Adresse MAC manquante')
|
||
c = db()
|
||
known_types = {r[0] for r in c.execute('SELECT id FROM custom_device_types').fetchall()}
|
||
known_types.update({'', 'generic', 'phone', 'tablet', 'laptop', 'desktop', 'tv', 'console', 'iot'})
|
||
if dev_type not in known_types:
|
||
c.close()
|
||
raise ValueError(f'Type d’appareil non valide : {dev_type}')
|
||
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
|
||
if 'device_type' not in cn_cols:
|
||
try:
|
||
c.execute('ALTER TABLE client_names ADD COLUMN device_type TEXT DEFAULT ""')
|
||
c.commit()
|
||
except Exception: pass
|
||
default_name = 'Client ' + mac.replace(':', '')[-4:]
|
||
c.execute('''
|
||
INSERT INTO client_names(mac, name, last_ip, last_seen, device_type)
|
||
VALUES(?, ?, "Non attribuée", ?, ?)
|
||
ON CONFLICT(mac) DO UPDATE SET device_type=excluded.device_type
|
||
''', (mac, default_name, time.strftime('%Y-%m-%d %H:%M:%S'), dev_type))
|
||
c.commit(); c.close()
|
||
self.send_json({'ok': True, 'message': 'Type d’appareil modifié avec succès', 'device_type': dev_type}); return
|
||
if self.path == '/api/device-types/save':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
label = str(data.get('label', '')).strip()
|
||
icon = str(data.get('icon', '')).strip() or '💻'
|
||
desc = str(data.get('desc', '')).strip()
|
||
raw_id = str(data.get('id', '')).strip().lower()
|
||
orig_id = str(data.get('original_id', '')).strip().lower()
|
||
if not label: raise ValueError('Le nom de la catégorie est obligatoire')
|
||
if not raw_id:
|
||
raw_id = re.sub(r'[^a-z0-9_-]', '', label.lower().replace(' ', '_'))[:24]
|
||
if not raw_id:
|
||
raw_id = f"type_{int(time.time())}"
|
||
if not re.fullmatch(r'[a-z0-9_-]{2,32}', raw_id):
|
||
raise ValueError("L'identifiant doit contenir entre 2 et 32 caractères alphanumériques (minuscules, tirets ou underscores)")
|
||
c = db()
|
||
if orig_id and orig_id != raw_id:
|
||
c.execute('UPDATE client_names SET device_type=? WHERE device_type=?', (raw_id, orig_id))
|
||
c.execute('DELETE FROM custom_device_types WHERE id=?', (orig_id,))
|
||
existing = c.execute('SELECT sort_order FROM custom_device_types WHERE id=?', (raw_id,)).fetchone()
|
||
if existing:
|
||
sort_order = existing[0]
|
||
else:
|
||
max_order = c.execute('SELECT COALESCE(MAX(sort_order), 0) FROM custom_device_types').fetchone()[0]
|
||
sort_order = max_order + 1
|
||
c.execute('''
|
||
INSERT INTO custom_device_types(id, label, icon, desc, sort_order)
|
||
VALUES(?, ?, ?, ?, ?)
|
||
ON CONFLICT(id) DO UPDATE SET label=excluded.label, icon=excluded.icon, desc=excluded.desc
|
||
''', (raw_id, label, icon, desc, sort_order))
|
||
c.commit(); c.close()
|
||
log('categorie_appareil_enregistree', f"{username(self) or 'admin'} ({label})", request_ip(self), 'SETTINGS')
|
||
self.send_json({'ok': True, 'message': 'Catégorie d’appareil enregistrée avec succès', 'id': raw_id}); return
|
||
if self.path == '/api/device-types/delete':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
tid = str(data.get('id', '')).strip().lower()
|
||
if not tid: raise ValueError("Identifiant manquant")
|
||
c = db()
|
||
count = c.execute('SELECT COUNT(*) FROM custom_device_types').fetchone()[0]
|
||
if count <= 1:
|
||
c.close()
|
||
raise ValueError("Impossible de supprimer la dernière catégorie d'appareil")
|
||
c.execute("UPDATE client_names SET device_type='generic' WHERE device_type=?", (tid,))
|
||
c.execute('DELETE FROM custom_device_types WHERE id=?', (tid,))
|
||
c.commit(); c.close()
|
||
log('categorie_appareil_supprimee', f"{username(self) or 'admin'} ({tid})", request_ip(self), 'SETTINGS')
|
||
self.send_json({'ok': True, 'message': 'Catégorie supprimée avec succès'}); return
|
||
if self.path == '/api/device-types/reset':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
c = db()
|
||
c.execute('DELETE FROM custom_device_types')
|
||
defaults = [
|
||
('phone', 'Smartphone', '📱', 'iPhone, Android, Galaxy...', 1),
|
||
('tablet', 'Tablette', 'tablet_svg', 'iPad, Galaxy Tab, Kindle...', 2),
|
||
('laptop', 'PC Portable', '💻', 'MacBook, ThinkPad, Laptop...', 3),
|
||
('desktop', 'Ordinateur fixe', '🖥️', 'PC Bureau, Mac Pro, Tour...', 4),
|
||
('tv', 'Smart TV / Box', '📺', 'Apple TV, Chromecast, Box...', 5),
|
||
('console', 'Console de jeux', '🎮', 'PlayStation, Switch, Xbox...', 6),
|
||
('iot', 'Objet connecté', '📟', 'IoT, Caméra, Domotique, RPi...', 7),
|
||
('generic', 'Standard / Autre', '💻', 'Appareil générique / inconnu', 8)
|
||
]
|
||
c.executemany('INSERT INTO custom_device_types(id, label, icon, desc, sort_order) VALUES(?,?,?,?,?)', defaults)
|
||
c.commit(); c.close()
|
||
log('categories_appareils_reinitialisees', username(self) or 'admin', request_ip(self), 'SETTINGS')
|
||
self.send_json({'ok': True, 'message': 'Catégories réinitialisées avec succès'}); return
|
||
if self.path == '/api/devices/delete':
|
||
mac = str(data.get('mac', '')).strip().upper()
|
||
if not mac: raise ValueError('Adresse MAC manquante')
|
||
c = db()
|
||
c.execute('DELETE FROM client_names WHERE UPPER(mac)=?', (mac,))
|
||
c.execute('DELETE FROM client_traffic WHERE UPPER(mac)=?', (mac,))
|
||
c.execute('DELETE FROM client_traffic_daily WHERE UPPER(mac)=?', (mac,))
|
||
c.commit(); c.close()
|
||
self.send_json({'ok': True, 'message': 'Appareil supprimé de l’historique'}); return
|
||
if self.path == '/api/advanced/capture/start':
|
||
target_iface = (data.get('interface') or '').strip() if isinstance(data, dict) else ''
|
||
ok, msg = start_capture(target_iface or None)
|
||
self.send_json({'ok': ok, 'message': msg}); return
|
||
if self.path == '/api/advanced/capture/stop':
|
||
ok, msg = stop_capture()
|
||
self.send_json({'ok': ok, 'message': msg}); return
|
||
if self.path == '/api/advanced/capture/clear':
|
||
ok, msg = clear_capture()
|
||
self.send_json({'ok': ok, 'message': msg}); return
|
||
if self.path == '/api/advanced/domains/clear':
|
||
with capture_lock:
|
||
captured_domains.clear()
|
||
self.send_json({'ok': True, 'message': 'Historique des domaines réinitialisé'}); return
|
||
if self.path == '/api/advanced/capture/test_packet':
|
||
generate_test_traffic()
|
||
self.send_json({'ok': True, 'message': 'Paquets de test DNS et ICMP générés'}); return
|
||
if self.path == '/api/ap/control':
|
||
action=str(data.get('action','')); name=connection_name()
|
||
if not name: raise ValueError('Aucune connexion AP configurée')
|
||
cmd=['nmcli','connection','up' if action=='start' else 'down',name] if action in ('start','stop') else ['nmcli','connection','down',name]
|
||
r=subprocess.run(cmd,capture_output=True,text=True)
|
||
if action=='restart': r=subprocess.run(['nmcli','connection','up',name],capture_output=True,text=True)
|
||
if r.returncode: raise RuntimeError(r.stderr.strip())
|
||
if action in ('start','restart'): mark_ap_started()
|
||
elif action == 'stop':
|
||
try: os.remove(UPTIME_FILE)
|
||
except OSError: pass
|
||
invalidate_status_cache()
|
||
log({'start':'démarrage','stop':'arrêt','restart':'redémarrage'}.get(action,'action'), 'Point d’accès Wi-Fi', ip=request_ip(self), mac='AP'); self.send_json({'ok':True}); return
|
||
if self.path == '/api/setup': self.send_json({'ok':True,'message':'Configuration enregistrée','connection':configure_ap(data,True,caller_ip=request_ip(self))}); return
|
||
if self.path == '/api/settings': self.send_json({'ok':True,'message':'Réglages enregistrés','connection':configure_ap(data,caller_ip=request_ip(self))}); return
|
||
if self.path == '/api/settings/proxy':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
enabled = '1' if data.get('enabled') else '0'
|
||
header = str(data.get('header', 'auto')).strip().lower()
|
||
valid_hdrs = {'auto', 'x-forwarded-for', 'x-real-ip', 'cf-connecting-ip', 'true-client-ip'}
|
||
if header not in valid_hdrs: header = 'auto'
|
||
trust_private = '1' if data.get('trust_all_private', True) else '0'
|
||
trusted_proxies = str(data.get('trusted_proxies', '')).strip()
|
||
c = db()
|
||
c.execute("INSERT INTO preferences(key, value) VALUES('reverse_proxy_enabled', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (enabled,))
|
||
c.execute("INSERT INTO preferences(key, value) VALUES('reverse_proxy_header', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (header,))
|
||
c.execute("INSERT INTO preferences(key, value) VALUES('reverse_proxy_trust_all_private', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (trust_private,))
|
||
c.execute("INSERT INTO preferences(key, value) VALUES('reverse_proxy_trusted_proxies', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (trusted_proxies,))
|
||
c.commit(); c.close()
|
||
log('configuration_proxy_inverse_modifiee', username(self) or 'Administrateur', request_ip(self), 'SETTINGS')
|
||
self.send_json({'ok': True, 'message': 'Réglages du proxy inversé enregistrés avec succès !'}); return
|
||
if self.path == '/api/vpn/profiles':
|
||
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
|
||
pid = create_or_update_vpn_profile(data)
|
||
self.send_json({'ok': True, 'message': 'Profil VPN enregistré avec succès', 'id': pid}); return
|
||
if self.path == '/api/vpn/profiles/delete':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
pid = int(data.get('id', 0))
|
||
delete_vpn_profile(pid)
|
||
self.send_json({'ok': True, 'message': 'Profil VPN supprimé avec succès'}); return
|
||
if self.path == '/api/vpn/connect':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
pid = int(data.get('id', 0))
|
||
ok, msg = connect_vpn_profile(pid, caller_ip=request_ip(self))
|
||
if not ok: self.send_json({'error': msg}, 400); return
|
||
self.send_json({'ok': True, 'message': msg}); return
|
||
if self.path == '/api/vpn/disconnect':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
pid = int(data.get('id', 0))
|
||
ok, msg = disconnect_vpn_profile(pid, caller_ip=request_ip(self))
|
||
self.send_json({'ok': True, 'message': msg}); return
|
||
if self.path in ('/api/vpn/check-ip', '/api/vpn/public-ip'):
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
pid = int(data.get('id', 0))
|
||
prof = get_vpn_profile(pid)
|
||
if not prof: self.send_json({'error':'Profil VPN introuvable'},404); return
|
||
iface = prof.get('iface') or (f"wg_ap{pid}" if prof['type'] == 'wireguard' else f"tun_ap{pid}")
|
||
if not is_iface_up(iface):
|
||
self.send_json({'ok': False, 'error': 'Le tunnel VPN est actuellement déconnecté'}); return
|
||
ip = get_vpn_public_ip(iface, force_refresh=True)
|
||
hs, hs_sec = get_wireguard_handshake_info(iface) if prof['type'] == 'wireguard' else (None, None)
|
||
if ip:
|
||
self.send_json({'ok': True, 'public_ip': ip, 'handshake': hs, 'handshake_age_seconds': hs_sec, 'iface': iface})
|
||
else:
|
||
err = 'Impossible de joindre Internet via ce tunnel VPN. '
|
||
if hs: err += f"({hs}). "
|
||
err += "Vérifiez que le serveur VPN distant est actif et que les clés/AllowedIPs sont correctes."
|
||
self.send_json({'ok': False, 'error': err, 'handshake': hs, 'handshake_age_seconds': hs_sec, 'iface': iface})
|
||
return
|
||
if self.path == '/api/vpn/clients/assign':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
mac = str(data.get('mac', '')).strip().upper()
|
||
pid = int(data.get('profile_id', 0))
|
||
ks = 1 if data.get('kill_switch') else 0
|
||
assign_client_vpn(mac, pid, ks)
|
||
self.send_json({'ok': True, 'message': 'Assignation VPN du client mise à jour avec succès'}); return
|
||
if self.path == '/api/notifications/settings':
|
||
if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
save_notifications_settings(data)
|
||
self.send_json({'ok':True, 'message':'Réglages des notifications enregistrés avec succès'}); return
|
||
if self.path == '/api/notifications/test':
|
||
if auth_state().get('configured') and not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
channel = str(data.get('channel', 'all')).strip().lower()
|
||
test_cfg = data.get('config')
|
||
results = test_notifications(channel, test_config=test_cfg)
|
||
self.send_json({'ok':True, 'results':results}); return
|
||
if self.path == '/api/notifications/stats-report/trigger':
|
||
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
|
||
ok, msg = trigger_manual_stats_report()
|
||
self.send_json({'ok': ok, 'message': msg}); return
|
||
if self.path == '/api/stats/refresh':
|
||
update_background_metrics()
|
||
self.send_json(stats()); return
|
||
if self.path == '/api/logs/clear':
|
||
c=db(); c.execute('DELETE FROM connection_logs'); c.commit(); c.close()
|
||
log('suppression_journaux', username(self) or 'Administrateur', request_ip(self), 'SYSTEM')
|
||
update_background_metrics()
|
||
self.send_json({'ok':True,'message':'Journaux supprimés'}); return
|
||
if self.path == '/api/data/clear':
|
||
name = connection_name()
|
||
names_to_delete = set()
|
||
if name: names_to_delete.add(name)
|
||
out = subprocess.run(['nmcli', '-t', '-g', 'NAME', 'connection', 'show'], capture_output=True, text=True).stdout
|
||
for line in out.splitlines():
|
||
line = line.strip()
|
||
if line.startswith('AP-') or line.startswith('ap-bridge') or line == name:
|
||
names_to_delete.add(line)
|
||
for n in names_to_delete:
|
||
if n:
|
||
subprocess.run(['nmcli', 'connection', 'down', n], capture_output=True, text=True)
|
||
subprocess.run(['nmcli', 'connection', 'delete', n], capture_output=True, text=True)
|
||
teardown_bridge()
|
||
try: os.remove(CONNECTION_FILE)
|
||
except OSError: pass
|
||
try: os.remove(UPTIME_FILE)
|
||
except OSError: pass
|
||
try:
|
||
conf = '/etc/NetworkManager/dnsmasq-shared.d/20-max-clients.conf'
|
||
if os.path.exists(conf): os.remove(conf)
|
||
except OSError: pass
|
||
c=db()
|
||
c.execute('DELETE FROM connection_logs')
|
||
c.execute('DELETE FROM blocked_clients')
|
||
c.execute('DELETE FROM client_names')
|
||
c.execute('DELETE FROM client_traffic')
|
||
c.execute('DELETE FROM client_traffic_daily')
|
||
c.execute('DELETE FROM auth_users')
|
||
c.execute('DROP TABLE IF EXISTS recovery_codes')
|
||
c.execute('DELETE FROM preferences')
|
||
c.execute('DELETE FROM auth_sessions')
|
||
c.commit(); c.close()
|
||
sessions.clear()
|
||
with traffic_lock: station_traffic.clear()
|
||
log('reinitialisation_donnees', 'Système', request_ip(self), 'SYSTEM')
|
||
self.send_json({'ok':True,'message':'Toutes les données et le point d’accès ont été réinitialisés et supprimés'}); return
|
||
if self.path == '/api/backup/inspect':
|
||
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
|
||
fname = str(data.get('filename', 'sauvegarde')).strip()
|
||
b64_content = str(data.get('data_base64', '')).strip()
|
||
raw_json = data.get('backup')
|
||
if raw_json and isinstance(raw_json, dict):
|
||
self.send_json({'ok': True, 'filename': fname, 'backup': raw_json}); return
|
||
if not b64_content:
|
||
self.send_json({'error': 'Contenu du fichier manquant'}, 400); return
|
||
try:
|
||
raw_bytes = base64.b64decode(b64_content)
|
||
backup = inspect_backup_bytes(raw_bytes, fname)
|
||
self.send_json({'ok': True, 'filename': fname, 'backup': backup})
|
||
except Exception as e:
|
||
self.send_json({'error': f'Impossible d’analyser le fichier : {e}'}, 400)
|
||
return
|
||
if self.path == '/api/backup/import':
|
||
if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return
|
||
try:
|
||
if 'data_base64' in data and data['data_base64']:
|
||
raw_bytes = base64.b64decode(data['data_base64'])
|
||
backup = inspect_backup_bytes(raw_bytes, data.get('filename', ''))
|
||
stats = import_backup_data(backup, data.get('options', {}))
|
||
else:
|
||
stats = import_backup_data(data)
|
||
log('import_configuration_complete', username(self) or 'Administrateur', request_ip(self), 'SYSTEM')
|
||
self.send_json({
|
||
'ok': True,
|
||
'message': f"Sauvegarde restaurée avec succès ({stats.get('vpn_profiles',0)} profils VPN, {stats.get('client_names',0)} appareils, {stats.get('preferences',0)} réglages restaurés).",
|
||
'stats': stats
|
||
})
|
||
except Exception as e:
|
||
self.send_json({'error': f'Erreur lors de la restauration: {e}'}, 400)
|
||
return
|
||
if self.path == '/api/auth/2fa/status':
|
||
self.send_json({'enabled':auth_state()['two_factor'],'recovery_remaining':recovery_remaining()}); return
|
||
if self.path == '/api/auth/2fa/enable':
|
||
row=verify_user(username(self),str(data.get('password','')))
|
||
if not row: raise ValueError('Mot de passe incorrect')
|
||
secret=base64.b32encode(secrets.token_bytes(10)).decode('ascii').rstrip('=')
|
||
sessions[self.headers.get('X-Session-Token','')]['pending_2fa']=secret
|
||
log('generation_secret_2fa', username(self), request_ip(self), 'AUTH')
|
||
self.send_json({'ok':True,'message':'Secret généré. Ajoutez-le dans votre application TOTP puis confirmez avec le code affiché.','secret':secret}); return
|
||
if self.path == '/api/auth/2fa/confirm':
|
||
session=sessions.get(self.headers.get('X-Session-Token',''),{})
|
||
secret=session.get('pending_2fa')
|
||
if not secret or not totp_ok(secret,data.get('code')): raise ValueError('Code 2FA invalide')
|
||
row=verify_user(username(self),str(data.get('password','')))
|
||
if not row: raise ValueError('Mot de passe incorrect')
|
||
create_user(row[0],str(data.get('password','')),secret); session.pop('pending_2fa',None)
|
||
log('activation_2fa', username(self), request_ip(self), 'AUTH')
|
||
self.send_json({'ok':True,'message':'Double identification activée. Conservez vos codes de récupération.','recovery_codes':recovery_generate()}); return
|
||
if self.path == '/api/auth/2fa/disable':
|
||
row=verify_user(username(self),str(data.get('password','')))
|
||
if not row: raise ValueError('Mot de passe incorrect')
|
||
if row[2] and not second_factor_ok(row[2],data.get('code')): raise ValueError('Code 2FA invalide')
|
||
create_user(row[0],str(data.get('password','')),None); recovery_clear()
|
||
log('desactivation_2fa', username(self), request_ip(self), 'AUTH')
|
||
self.send_json({'ok':True,'message':'Double identification désactivée'}); return
|
||
if self.path == '/api/auth/2fa/recovery':
|
||
row=verify_user(username(self),str(data.get('password','')))
|
||
if not row: raise ValueError('Mot de passe incorrect')
|
||
if not row[2]: raise ValueError('La 2FA n’est pas activée')
|
||
if not second_factor_ok(row[2],data.get('code')): raise ValueError('Code 2FA invalide')
|
||
log('regeneration_codes_secours', username(self), request_ip(self), 'AUTH')
|
||
self.send_json({'ok':True,'message':'Nouveaux codes générés','recovery_codes':recovery_generate()}); return
|
||
if self.path == '/api/auth/password':
|
||
current=verify_user(username(self),str(data.get('current_password','')))
|
||
if not current: raise ValueError('Mot de passe actuel incorrect')
|
||
new_u = str(data.get('username',username(self)))
|
||
create_user(new_u,str(data.get('password','')),current[2])
|
||
log('modification_identifiants', new_u, request_ip(self), 'AUTH')
|
||
self.send_json({'ok':True,'message':'Identifiants modifiés'}); return
|
||
if self.path == '/api/preferences':
|
||
c=db()
|
||
if 'theme' in data:
|
||
theme=str(data.get('theme',''))
|
||
if theme not in ('dark','light','auto','winxp','futuristic','macos','hacker'): raise ValueError('Thème invalide')
|
||
c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES('theme',?)",(theme,))
|
||
if 'language' in data:
|
||
lang=str(data.get('language','fr')).strip().lower()
|
||
if lang not in ('fr','en-us','en-gb'): lang = 'fr'
|
||
c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES('language',?)",(lang,))
|
||
if 'app_name' in data:
|
||
if not valid_session(self): raise ValueError('Authentification requise')
|
||
app_name=str(data.get('app_name','')).strip()
|
||
if not app_name or len(app_name)>64: raise ValueError('Nom de l’application invalide')
|
||
c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES('app_name',?)",(app_name,))
|
||
if 'app_short_name' in data:
|
||
if not valid_session(self): raise ValueError('Authentification requise')
|
||
app_short_name=str(data.get('app_short_name','')).strip()
|
||
if not app_short_name or len(app_short_name)>32: raise ValueError('Nom court invalide')
|
||
c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES('app_short_name',?)",(app_short_name,))
|
||
c.commit(); c.close()
|
||
log('modification_preferences', username(self) or 'Administrateur', request_ip(self), 'CONFIG')
|
||
self.send_json({'ok':True,'message':'Préférences enregistrées'}); return
|
||
self.send_json({'error':'Route inconnue'},404)
|
||
except (ValueError, RuntimeError, sqlite3.Error) as e:
|
||
print(f"[ap-api] Requête POST {self.path} ({request_ip(self)}) refusée : {e}", flush=True)
|
||
self.send_json({'error':str(e)},400)
|
||
except Exception as e:
|
||
import traceback
|
||
print(f"[ap-error] Erreur interne sur POST {self.path} ({request_ip(self)}) : {e}\n{traceback.format_exc()}", flush=True)
|
||
self.send_json({'error':'Erreur interne'},500)
|
||
def log_message(self,*args): pass
|
||
|
||
connected_stations_order = []
|
||
|
||
def monitor():
|
||
global connected_stations_order
|
||
sync_vpn_counter = 0
|
||
sync_limits_counter = 0
|
||
while True:
|
||
try:
|
||
sync_vpn_counter += 1
|
||
if sync_vpn_counter >= 5:
|
||
sync_vpn_counter = 0
|
||
try:
|
||
sync_vpn_client_rules()
|
||
except Exception:
|
||
pass
|
||
|
||
sync_limits_counter += 1
|
||
if sync_limits_counter >= 2:
|
||
sync_limits_counter = 0
|
||
try:
|
||
sync_client_bandwidth_and_quotas()
|
||
except Exception:
|
||
pass
|
||
|
||
items = clients()
|
||
max_c = get_max_clients()
|
||
# CORRECTION : éjecter en continu les appareils bloqués qui se reconnectent.
|
||
for x in items:
|
||
if x['blocked']: command('iw','dev',INTERFACE,'station','del',x['mac'])
|
||
|
||
active_items = [x for x in items if not x['blocked']]
|
||
if max_c > 0 and len(active_items) > max_c:
|
||
current_macs = [x['mac'] for x in active_items]
|
||
connected_stations_order = [m for m in connected_stations_order if m in current_macs]
|
||
for m in current_macs:
|
||
if m not in connected_stations_order:
|
||
connected_stations_order.append(m)
|
||
|
||
allowed_macs = set(connected_stations_order[:max_c])
|
||
for x in active_items:
|
||
if x['mac'] not in allowed_macs:
|
||
mac = x['mac']
|
||
command('iw','dev',INTERFACE,'station','del',mac)
|
||
log('rejet_limite', x['name'], x['ip'], mac)
|
||
if mac in connected_stations_order:
|
||
connected_stations_order.remove(mac)
|
||
else:
|
||
current_macs = [x['mac'] for x in active_items]
|
||
connected_stations_order = [m for m in connected_stations_order if m in current_macs]
|
||
for m in current_macs:
|
||
if m not in connected_stations_order:
|
||
connected_stations_order.append(m)
|
||
|
||
allowed_set = set(connected_stations_order[:max_c]) if max_c > 0 else None
|
||
update_logs([x for x in items if not x['blocked'] and (allowed_set is None or x['mac'] in allowed_set)])
|
||
|
||
# Analyse continue des métriques et statistiques en arrière-plan
|
||
try:
|
||
update_background_metrics(items)
|
||
except Exception as e_bg:
|
||
print(f"[ap-metrics] Erreur cycle analyse métriques : {e_bg}", flush=True)
|
||
|
||
# En mode pont, si des clients sont connectés sans IP résolue, solliciter l'ARP
|
||
if is_bridge_mode():
|
||
unresolved = [x for x in active_items if x['ip'] in ('', 'Non attribuée')]
|
||
if unresolved:
|
||
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
|
||
ip_cidr, _, _ = get_iface_ip_info(b_name)
|
||
if ip_cidr:
|
||
try:
|
||
import ipaddress
|
||
net = ipaddress.IPv4Interface(ip_cidr).network
|
||
bcast = str(net.broadcast_address)
|
||
subprocess.run(['ping', '-c', '1', '-w', '1', '-b', '-I', b_name, bcast], capture_output=True)
|
||
except Exception: pass
|
||
except Exception as e:
|
||
print(f"[ap-monitor] Erreur surveillance clients : {e}", flush=True)
|
||
time.sleep(2)
|
||
|
||
class UnixServer(ThreadingHTTPServer):
|
||
address_family = socket.AF_UNIX
|
||
daemon_threads = True
|
||
def server_bind(self):
|
||
socketserver.TCPServer.server_bind(self)
|
||
self.server_name, self.server_port = 'localhost', 0
|
||
|
||
if __name__ == '__main__':
|
||
print(f"[ap-api] Initialisation de la base de données et surveillance sur {INTERFACE}...", flush=True)
|
||
db()
|
||
ensure_dnsmasq_dns()
|
||
try:
|
||
c = db()
|
||
c.execute('DELETE FROM auth_sessions WHERE expires < ?', (time.time(),))
|
||
c.execute("UPDATE vpn_profiles SET status='disconnected', last_error='' WHERE status IN ('connecting', 'connected')")
|
||
c.commit(); c.close()
|
||
except Exception as e_db:
|
||
print(f"[ap-vpn] Erreur réinitialisation statut VPN : {e_db}", flush=True)
|
||
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
|
||
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
|
||
if not b_eth:
|
||
candidates = detect_ethernet_interfaces()
|
||
if candidates: b_eth = candidates[0]
|
||
|
||
# Le pont ne doit être configuré que si le setup initial est terminé, le mode est pont et le Wi-Fi actif
|
||
if is_bridge_mode() and auth_state().get('setup_completed') and is_iface_up(INTERFACE):
|
||
clean_stale_router_leases()
|
||
setup_bridge(b_name, b_eth)
|
||
else:
|
||
# En mode AP (par défaut) ou tant que le setup n'est pas terminé, s'assurer que l'Ethernet hôte est totalement libre et le pont démonté
|
||
teardown_bridge(b_name, b_eth)
|
||
apply_radio_defaults()
|
||
try: sync_client_bandwidth_and_quotas(force=True)
|
||
except Exception: pass
|
||
threading.Thread(target=arp_listener, daemon=True).start()
|
||
threading.Thread(target=monitor, daemon=True).start()
|
||
threading.Thread(target=auto_connect_vpn_profiles, daemon=True).start()
|
||
threading.Thread(target=vpn_healthcheck_loop, daemon=True).start()
|
||
threading.Thread(target=update_background_metrics, daemon=True).start()
|
||
threading.Thread(target=stats_report_scheduler_loop, daemon=True).start()
|
||
try: os.remove(SOCKET_PATH)
|
||
except OSError: pass
|
||
server = UnixServer(SOCKET_PATH, Handler)
|
||
os.chmod(SOCKET_PATH, 0o660)
|
||
try: shutil.chown(SOCKET_PATH, user='root', group='www-data')
|
||
except (LookupError, OSError): os.chmod(SOCKET_PATH, 0o666)
|
||
print(f"[ap-api] Serveur API opérationnel sur le socket UNIX {SOCKET_PATH}", flush=True)
|
||
server.serve_forever() |