Files
apmanageur/ap.py
T
2026-11-10 01:22:53 +01:00

5657 lines
273 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
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 = 'V1.9'
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
def device_name(ip, mac):
mac = (mac or '').upper()
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 != '*': return l_host.strip()
try:
journal = command('journalctl','-u','NetworkManager','--no-pager','-n','500')
pattern = r'DHCPACK\([^)]*\)\s+(\S+)\s+([0-9a-f:]{17})\s+(\S+)'
for line in reversed(journal.splitlines()):
match = re.search(pattern, line, re.I)
if match and (match.group(1) == ip or match.group(2).upper() == mac):
hostname = match.group(3).strip()
if hostname and hostname != '*': return hostname
except Exception: pass
if ip and ip not in ('Non attribuée', '—') and not (is_bridge and ip.startswith('10.42.')):
try:
name = socket.gethostbyaddr(ip)[0]
if name and name != ip: return name.split('.')[0]
except (socket.herror, socket.gaierror, OSError): pass
host_line = command('ip','neigh','show',ip)
match = re.search(r'\(([^)]+)\)', host_line)
if match and match.group(1) != ip: return match.group(1)
try:
c = db(); row = c.execute('SELECT name FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close()
if row and row[0]: return row[0]
except sqlite3.Error: pass
return 'Client ' + mac.replace(':', '')[-4:] if mac else 'Nom non communiqué'
# __AUTHENTICATION_IMPLEMENTATION__
def db():
folder = os.path.dirname(DB_FILE)
if folder: os.makedirs(folder, exist_ok=True)
c = sqlite3.connect(DB_FILE)
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)')
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.commit(); return c
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()
rows = dict(c.execute("SELECT key,value FROM preferences").fetchall()); c.close()
return {
'configured': bool(row),
'two_factor': bool(row and row[1]),
'app_name': rows.get('app_name', 'Administration de l’AP Wi‑Fi'),
'app_short_name': rows.get('app_short_name', 'AP Manageur')
}
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)
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=''):
now = time.time()
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 'Machine inconnue',
'os_name': os_name or 'Inconnu',
'browser_name': browser_name or 'Navigateur',
'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):
try: return subprocess.check_output(args, text=True, stderr=subprocess.DEVNULL).strip()
except (subprocess.CalledProcessError, FileNotFoundError): return ''
def read_json(h):
return json.loads(h.rfile.read(int(h.headers.get('Content-Length', '0'))) or b'{}')
def request_ip(h): return h.headers.get('X-Real-IP', '').strip() or h.client_address[0]
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']
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"
full_label = f"Aujourd’hui de {h:02d}h00 à {h:02d}h59"
item = {'period': key, 'hour': h, 'label': label, 'full_label': full_label, '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}"
full_label = f"{DAYS_FR[d.weekday()]} {d.day:02d} {MONTHS_FR[d.month].lower()} {d.year}"
item = {'period': key, 'label': label, 'full_label': full_label, '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}"
full_label = f"Semaine {week_num} (du {mon.day:02d}/{mon.month:02d} au {sun.day:02d}/{sun.month:02d}/{sun.year})"
item = {'period': key, 'start': mon.strftime('%Y-%m-%d'), 'end': sun.strftime('%Y-%m-%d'), 'label': label, 'full_label': full_label, '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}"
full_label = f"{MONTHS_FR[m]} {y}"
item = {'period': key, 'label': label, 'full_label': full_label, '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, 'full_label': f"Année {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.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 = 'connexion' AND l.mac LIKE '%:%'
ORDER BY l.id ASC
''').fetchall()
c.close()
except Exception as e:
rows = []
print(f"[ap-error] Erreur récupération statistiques: {e}", flush=True)
for et, 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 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
for h, item in hours_map.items():
item['unique_clients'] = len(hour_macs[h])
item['devices'] = sorted(list(hour_devs[h].values()))
for k, item in days_map.items():
item['unique_clients'] = len(day_macs[k])
item['devices'] = sorted(list(day_devs[k].values()))
for k, item in weeks_map.items():
item['unique_clients'] = len(week_macs[k])
item['devices'] = sorted(list(week_devs[k].values()))
for k, item in months_map.items():
item['unique_clients'] = len(month_macs[k])
item['devices'] = sorted(list(month_devs[k].values()))
for k, item in years_map.items():
item['unique_clients'] = len(year_macs[k])
item['devices'] = sorted(list(year_devs[k].values()))
if active_items is None:
try: active_items = clients()
except Exception: active_items = []
active_count = len(active_items)
cur_h = now.hour
if cur_h in hours_map and active_items:
for x in active_items:
m = x.get('mac')
n = x.get('name')
if m:
hour_macs[cur_h].add(m)
hour_devs[cur_h][m] = n
hours_map[cur_h]['unique_clients'] = len(hour_macs[cur_h])
if hours_map[cur_h]['total_connections'] < hours_map[cur_h]['unique_clients']:
hours_map[cur_h]['total_connections'] = hours_map[cur_h]['unique_clients']
hours_map[cur_h]['devices'] = sorted(list(hour_devs[cur_h].values()))
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():
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})."
},
"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é)
"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('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
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']
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)
final_title = title
final_message = message
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):
return shutil.which(name) or shutil.which(f'/sbin/{name}') or shutil.which(f'/usr/sbin/{name}') or shutil.which(f'/usr/bin/{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
try:
run_cmd('modprobe', 'br_netfilter')
run_cmd('sysctl', '-w', 'net.bridge.bridge-nf-call-iptables=1')
run_cmd('sysctl', '-w', 'net.bridge.bridge-nf-call-ip6tables=0')
run_cmd('sysctl', '-w', 'net.bridge.bridge-nf-call-arptables=0')
# 1. Autoriser le trafic bridgé dans la table filter FORWARD
run_cmd('iptables', '-I', 'FORWARD', '-m', 'physdev', '--physdev-is-bridged', '-j', 'ACCEPT')
if bridge_name:
run_cmd('iptables', '-I', 'FORWARD', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT')
# 2. Chaîne personnalisée de redirection PREROUTING (DNAT)
run_cmd('iptables', '-t', 'nat', '-N', 'AP_BRIDGE_DNS')
run_cmd('iptables', '-t', 'nat', '-F', 'AP_BRIDGE_DNS')
# Raccorder les requêtes DNS provenant du Wi-Fi vers AP_BRIDGE_DNS
for proto in ('udp', 'tcp'):
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', '-I', 'PREROUTING', '1', '-m', 'physdev', '--physdev-in', 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)
# 3. Chaîne POSTROUTING (MASQUERADE) pour garantir le retour des paquets si AP_DNS est sur le LAN (ex: Pi-hole)
run_cmd('iptables', '-t', 'nat', '-N', 'AP_BRIDGE_DNS_POST')
run_cmd('iptables', '-t', 'nat', '-F', 'AP_BRIDGE_DNS_POST')
for proto in ('udp', 'tcp'):
run_cmd('iptables', '-t', 'nat', '-D', 'POSTROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST')
run_cmd('iptables', '-t', 'nat', '-I', 'POSTROUTING', '1', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST')
for s in dns_servers:
for proto in ('udp', 'tcp'):
run_cmd('iptables', '-t', 'nat', '-A', 'AP_BRIDGE_DNS_POST', '-p', proto, '-d', s, '--dport', '53', '-j', 'MASQUERADE')
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', '-m', 'physdev', '--physdev-in', iface, '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS')
run_cmd('iptables', '-t', 'nat', '-D', 'POSTROUTING', '-p', proto, '--dport', '53', '-j', 'AP_BRIDGE_DNS_POST')
run_cmd('sysctl', '-w', 'net.bridge.bridge-nf-call-iptables=0')
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
# S'assurer que NetworkManager possède le profil du pont master
nm_conns = command('nmcli', '-t', '-g', 'NAME', 'connection', 'show').splitlines()
if bridge_name not in nm_conns and f"ap-bridge-{bridge_name}" not in nm_conns:
subprocess.run([
'nmcli', 'connection', 'add',
'type', 'bridge',
'con-name', bridge_name,
'ifname', bridge_name,
'bridge.stp', 'no',
'ipv4.method', 'disabled',
'ipv6.method', 'disabled'
], capture_output=True)
try: open(CREATED_BRIDGE_FILE, 'w').write(f"{bridge_name}:{bridge_eth or ''}")
except OSError: pass
# Démarrer le pont dans NetworkManager pour qu'il soit prêt à accueillir le slave Wi-Fi
subprocess.run(['nmcli', 'connection', 'up', bridge_name], capture_output=True)
# Si le pont n'existe pas encore au niveau noyau, le créer
if not os.path.exists(bridge_path):
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
if bridge_eth and os.path.exists(f'/sys/class/net/{bridge_eth}') and eth_master != bridge_name:
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)
subprocess.run(['sysctl', '-w', 'net.ipv4.conf.all.arp_accept=1'], capture_output=True)
subprocess.run(['sysctl', '-w', f'net.ipv4.conf.{bridge_name}.arp_accept=1'], capture_output=True)
for nf in ('bridge-nf-call-iptables', 'bridge-nf-call-ip6tables', 'bridge-nf-call-arptables'):
subprocess.run(['sysctl', '-w', f'net.bridge.{nf}=0'], 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)
subprocess.run(['iptables', '-I', 'FORWARD', '-m', 'physdev', '--physdev-is-bridged', '-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)
if not was_created_by_us:
# Pont préexistant sur l'hôte : ne pas le détruire
return
# Supprimer aussi le profil NetworkManager du pont créé par nous
if bridge_name in conns:
subprocess.run(['nmcli', 'connection', 'down', bridge_name], capture_output=True)
subprocess.run(['nmcli', 'connection', 'delete', bridge_name], capture_output=True)
eth = saved_eth or bridge_eth
if eth and os.path.exists(f'/sys/class/net/{eth}') and os.path.exists(bridge_path):
ip_cidr, gw, _ = get_iface_ip_info(bridge_name)
subprocess.run(['ip', 'link', 'set', 'dev', 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', eth], capture_output=True)
if gw:
subprocess.run(['ip', 'route', 'replace', 'default', 'via', gw, 'dev', eth], capture_output=True)
print(f"[ap-bridge] IP {ip_cidr} restaurée sur {eth}.", flush=True)
if os.path.exists(bridge_path):
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 {bridge_name} nettoyé.", flush=True)
try:
if os.path.exists(CREATED_BRIDGE_FILE): os.remove(CREATED_BRIDGE_FILE)
except OSError: pass
def status():
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', ''))
return {'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()}
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 = {}
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]}
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,
'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
})
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]
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'] = 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)',
'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']
dns_servers = get_dns_servers()
if dns_servers:
modify_args += ['ipv4.dns', ' '.join(dns_servers)]
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()
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) > 2000:
del capture_packets[:200]
if len(capture_pcap_bytes) > 20 * 1024 * 1024:
header = capture_pcap_bytes[:24]
capture_pcap_bytes = header + capture_pcap_bytes[5 * 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.Lock()
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}/operstate', 'r') as f:
state = f.read().strip().lower()
return state in ('up', 'unknown')
except OSError: return True
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
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)"
elif diff < 3600:
return f"Dernier handshake il y a {diff // 60} min"
else:
return f"Dernier handshake il y a {diff // 3600} h"
else:
return "En attente du handshake (non reçu)"
except Exception:
pass
return 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 via curl --interface
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', '3', url],
capture_output=True, text=True, timeout=4)
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
# 2. Requête Cloudflare directe sans résolution DNS
if not detected_ip:
try:
res = subprocess.run(['curl', '-4', '-s', '-k', '--interface', iface, '--max-time', '3', 'https://1.1.1.1/cdn-cgi/trace'],
capture_output=True, text=True, timeout=4)
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
# 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.strip()
content = re.sub(r"^\s*DNS\s*=.*$", r"# \g<0> (DNS géré localement)", 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.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)
status = "connected" if (raw_status == "connected" and actual_up) else ("error" if raw_status == "error" else "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 = get_wireguard_handshake_info(iface) if (actual_up and vtype == 'wireguard') else 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
})
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=''):
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()
try:
# 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
subprocess.run(['wg-quick', 'down', iface], capture_output=True)
res = subprocess.run(['wg-quick', 'up', iface], capture_output=True, text=True)
if res.returncode != 0:
err_msg = res.stderr.strip() or res.stdout.strip() or 'Erreur wg-quick up'
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.)
subprocess.run(['ip', 'rule', 'add', 'oif', iface, 'lookup', str(table_id), 'priority', '9900'], 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', '9901'], 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}"
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():
active = clients()
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()}
known_names = dict(c.execute('SELECT mac, name FROM client_names').fetchall())
c.close()
seen_macs = set()
result = []
for cl in active:
mac = (cl.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)
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'
else:
eff_status = 'blocked' if route['kill_switch'] else 'direct_fallback'
elif pid > 0 and not prof:
eff_status = 'direct'
pid = 0
result.append({
'mac': mac,
'ip': cl.get('ip') or '',
'name': cl.get('name') or known_names.get(mac, 'Inconnu'),
'online': True,
'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': known_names.get(mac, 'Appareil mémorisé'),
'online': False,
'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'
})
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."""
mac_to_ip = {}
try:
for cl in clients():
m = (cl.get('mac') or '').upper()
ip = cl.get('ip') or ''
if m and ip and ip not in ('Non attribuée', '—'):
mac_to_ip[m] = ip
except Exception: pass
for m, ip in station_live_ips.items():
if m.upper() not in mac_to_ip and ip:
mac_to_ip[m.upper()] = ip
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
try:
r = subprocess.run(['ip', 'neigh', 'show'], capture_output=True, text=True)
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:
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
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."""
for mod in ['br_netfilter', 'nf_tables', 'nft_compat']:
subprocess.run(['modprobe', mod], capture_output=True)
subprocess.run(['nft', 'add', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
subprocess.run(['nft', 'flush', 'table', 'bridge', 'ap_vpn_broute'], capture_output=True)
subprocess.run(['nft', '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', 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'daddr', 'ff:ff:ff:ff:ff:ff', 'accept'], capture_output=True)
subprocess.run(['nft', 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'udp', 'dport', '67-68', 'accept'], capture_output=True)
subprocess.run(['nft', 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'udp', 'sport', '67-68', 'accept'], capture_output=True)
subprocess.run(['nft', 'add', 'rule', 'bridge', 'ap_vpn_broute', 'prerouting', 'ether', 'type', 'ip', 'ip', 'daddr', '255.255.255.255', 'accept'], capture_output=True)
# Note : Pas d'exemption pour les sous-réseaux locaux (local_subnets).
# Tout le trafic IPv4 des clients VPN (hors DHCP/broadcast) est brouté vers L3
# pour être strictement isolé du réseau local et routé uniquement dans le tunnel VPN.
for mac in assigned_macs:
clean_mac = mac.strip().lower()
if not clean_mac: 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', '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', '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()
# 1. Nettoyage des anciennes règles ip rule (plage 9900 - 29999)
r = subprocess.run(['ip', 'rule', 'show'], capture_output=True, text=True)
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:
while subprocess.run(['ip', 'rule', 'del', 'priority', str(prio)], capture_output=True).returncode == 0:
pass
# 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)
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)
if len(active_tables) == 0:
subprocess.run(['conntrack', '-F'], capture_output=True)
subprocess.run(['ip', 'route', 'flush', 'cache'], 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():
time.sleep(4)
try:
c = db()
rows = c.execute('SELECT id, name FROM vpn_profiles WHERE auto_connect = 1').fetchall()
c.close()
for row in rows:
print(f"[ap-vpn] Connexion automatique au démarrage du profil '{row[1]}' (ID: {row[0]})...", flush=True)
try:
connect_vpn_profile(row[0])
except Exception as e:
print(f"[ap-vpn] Erreur démarrage auto profil {row[0]} : {e}", flush=True)
except Exception as e:
print(f"[ap-vpn] Erreur auto_connect_vpn_profiles : {e}", flush=True)
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)
class Handler(BaseHTTPRequestHandler):
def send_json(self, data, status=200):
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'); 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 == '/api/auth/status': self.send_json(auth_state()); 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))); return
if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return
path_only = self.path.split('?')[0]
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/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 = get_wireguard_handshake_info(iface) if prof['type'] == 'wireguard' else None
if ip:
geo = get_ip_geo(ip)
self.send_json({'ok': True, 'public_ip': ip, 'public_ip_geo': geo, 'handshake': hs, 'iface': iface})
else:
self.send_json({'ok': False, 'error': 'IP publique introuvable via ce tunnel', 'handshake': hs, 'iface': iface})
return
elif path_only == '/api/notifications/settings':
self.send_json(get_notifications_settings_public())
elif 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'),
'app_name': rows.get('app_name', 'Administration de l’AP Wi‑Fi'),
'app_short_name': rows.get('app_short_name', 'AP Manageur')
})
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(2000, max(1, int(qs.get('limit', [200])[0])))
except Exception: limit = 200
with capture_lock:
if since > 0:
pkts = [p for p in capture_packets if p['id'] > since][-limit:]
else:
pkts = list(capture_packets[-limit:])
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/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/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
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/vpn/profiles':
if not valid_session(self): 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 = get_wireguard_handshake_info(iface) if prof['type'] == 'wireguard' else None
if ip:
self.send_json({'ok': True, 'public_ip': ip, 'handshake': hs, '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, '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 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 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/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'): raise ValueError('Thème invalide')
c.execute("INSERT OR REPLACE INTO preferences(key,value) VALUES('theme',?)",(theme,))
if 'app_name' in data:
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:
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
while True:
try:
sync_vpn_counter += 1
if sync_vpn_counter >= 5:
sync_vpn_counter = 0
try:
sync_vpn_client_rules()
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.commit(); c.close()
except Exception: pass
if is_bridge_mode():
clean_stale_router_leases()
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]
setup_bridge(b_name, b_eth)
apply_radio_defaults()
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()