From 4df1918a5b7c5b9b5198fc5d1d1f5bb6834355e9 Mon Sep 17 00:00:00 2001 From: yoannmultigaming Date: Sun, 22 Nov 2026 19:41:12 +0100 Subject: [PATCH] APmanageur Wi-Fi V1.0 --- ap.py | 368 ++++++++++++++++++++++++++++++++++++++++++++++---- index.html | 7 +- lang/en-gb.js | 1 + lang/en-us.js | 1 + lang/fr.js | 1 + version.json | 4 +- 6 files changed, 351 insertions(+), 31 deletions(-) diff --git a/ap.py b/ap.py index 0a6fbea..c348c2e 100644 --- a/ap.py +++ b/ap.py @@ -338,8 +338,257 @@ def is_valid_mac(mac): clean = mac.strip().upper().replace('-', ':') return bool(re.fullmatch(r'[0-9A-F]{2}(:[0-9A-F]{2}){5}', clean)) -_device_name_cache = {} # mac -> (name, timestamp) +_device_name_cache = {} # mac -> (name, expiry_timestamp) _journal_dhcp_cache = {'time': 0, 'entries': {}} +station_live_names = {} # mac -> hostname réel capturé en direct (DHCP, mDNS, NetBIOS, DNS) + +def clean_extracted_hostname(name): + """Nettoie et valide un nom d'hôte extrait du réseau (DHCP, mDNS, NetBIOS, DNS).""" + if not name or not isinstance(name, str): + return '' + name = name.strip('\x00 \t\r\n') + for suffix in ('.local', '.lan', '.home', '.domain', '.localdomain', '.fritz.box', '.livebox', '.bbox', '.sfr'): + if name.lower().endswith(suffix): + name = name[:-len(suffix)] + name = re.sub(r'[^a-zA-Z0-9_\-\.\s]', '', name).strip() + if len(name) < 2 or len(name) > 64: + return '' + if re.fullmatch(r'\d{1,3}(\.\d{1,3}){3}', name): + return '' + if re.fullmatch(r'([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}', name): + return '' + if name.lower() in ('localhost', 'unknown', 'none', 'null', 'client', 'gateway', 'router', 'wpad', 'in-addr', 'ip6'): + return '' + return name + +def extract_dhcp_hostname_from_udp(payload): + """Extrait le nom d'hôte de l'option DHCP 12 (Host Name) ou option 81 (Client FQDN) d'un paquet DHCP.""" + try: + cookie_idx = payload.find(b'\x63\x82\x53\x63') + if cookie_idx < 0: + return '' + idx = cookie_idx + 4 + length = len(payload) + hostname = '' + fqdn = '' + while idx < length: + opt = payload[idx] + if opt == 255: + break + if opt == 0: + idx += 1 + continue + if idx + 1 >= length: + break + opt_len = payload[idx + 1] + opt_data = payload[idx + 2 : idx + 2 + opt_len] + if opt == 12: + try: + hostname = opt_data.decode('utf-8', errors='ignore') + except Exception: + pass + elif opt == 81 and opt_len >= 3: + try: + raw_fqdn = opt_data[3:] + if raw_fqdn and raw_fqdn[0] < 32: + parts = [] + p_idx = 0 + while p_idx < len(raw_fqdn): + plen = raw_fqdn[p_idx] + if plen == 0: + break + p_idx += 1 + parts.append(raw_fqdn[p_idx:p_idx+plen].decode('utf-8', errors='ignore')) + p_idx += plen + fqdn = '.'.join(parts) + else: + fqdn = raw_fqdn.decode('utf-8', errors='ignore') + except Exception: + pass + idx += 2 + opt_len + return clean_extracted_hostname(hostname) or clean_extracted_hostname(fqdn) + except Exception: + return '' + +def extract_dns_name_from_packet(payload): + """Extrait le premier nom d'hôte complet d'un paquet DNS, mDNS (5353) ou LLMNR (5355).""" + try: + if len(payload) < 12: + return '' + idx = 12 + length = len(payload) + labels = [] + while idx < length: + lbl_len = payload[idx] + if lbl_len == 0: + break + if lbl_len > 63 or idx + 1 + lbl_len > length: + return '' + idx += 1 + labels.append(payload[idx:idx+lbl_len].decode('utf-8', errors='ignore')) + idx += lbl_len + if not labels: + return '' + full_domain = '.'.join(labels) + if len(labels) == 2 and labels[1].lower() == 'local': + return clean_extracted_hostname(labels[0]) + elif len(labels) == 1: + return clean_extracted_hostname(labels[0]) + elif full_domain.lower().endswith('.local'): + return clean_extracted_hostname(labels[0]) + return clean_extracted_hostname(full_domain) + except Exception: + return '' + +def build_netbios_status_query(): + """Génère un paquet NetBIOS Node Status Query (UDP 137).""" + return b'\x13\x37\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x20CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\x00\x00\x21\x00\x01' + +def parse_netbios_response(data): + """Extrait le nom de machine NetBIOS d'une réponse Node Status.""" + try: + if len(data) < 57: + return '' + num_names = data[56] + offset = 57 + for _ in range(num_names): + if offset + 18 > len(data): + break + raw_name = data[offset : offset + 15].decode('ascii', errors='ignore').strip() + name_type = data[offset + 15] + if name_type == 0x00 and raw_name and not raw_name.startswith('__MSBROWSE__'): + cleaned = clean_extracted_hostname(raw_name) + if cleaned: + return cleaned + offset += 18 + return '' + except Exception: + return '' + +def quick_reverse_dns(ip): + """Résolution DNS inverse rapide (les box internet Freebox/Livebox/etc. enregistrent les noms d'hôtes).""" + if not ip or ip in ('Non attribuée', '—', '127.0.0.1') or ip.startswith(('0.', '169.254.', '255.')): + return '' + try: + res = socket.getnameinfo((ip, 0), socket.NI_NAMEREQD) + if res and res[0]: + cleaned = clean_extracted_hostname(res[0]) + if cleaned: + return cleaned + except Exception: + pass + return '' + +def query_netbios_name(ip): + """Interroge le nom NetBIOS d'un client Windows / NAS / Samba sur UDP 137.""" + if not ip or ip in ('Non attribuée', '—', '127.0.0.1') or ip.startswith(('0.', '169.254.', '255.')): + return '' + sock = None + try: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.settimeout(0.35) + pkt = build_netbios_status_query() + sock.sendto(pkt, (ip, 137)) + resp, _ = sock.recvfrom(1024) + return parse_netbios_response(resp) + except Exception: + pass + finally: + if sock: + try: sock.close() + except Exception: pass + return '' + +def record_live_device_name(mac, name, ip=None): + """Enregistre immédiatement le vrai nom d'un appareil détecté lors de la connexion.""" + if not mac or not name: + return + mac = mac.upper() + name = clean_extracted_hostname(name) + if not name or name.startswith('Client ') or name == 'Nom non communiqué': + return + + station_live_names[mac] = name + now = time.time() + _device_name_cache[mac] = (name, now + 300) + + try: + c = db() + ts = time.strftime('%Y-%m-%d %H:%M:%S') + row = c.execute("SELECT name FROM client_names WHERE UPPER(mac)=?", (mac,)).fetchone() + if not row: + c.execute("INSERT INTO client_names (mac, name, last_ip, last_seen) VALUES (?, ?, ?, ?)", + (mac, name, ip or '', ts)) + elif row[0] in ('Nom non communiqué', '', None) or row[0].startswith('Client '): + if ip and ip not in ('Non attribuée', '', '—'): + c.execute("UPDATE client_names SET name=?, last_ip=?, last_seen=? WHERE UPPER(mac)=?", + (name, ip, ts, mac)) + else: + c.execute("UPDATE client_names SET name=?, last_seen=? WHERE UPPER(mac)=?", + (name, ts, mac)) + elif ip and ip not in ('Non attribuée', '', '—'): + c.execute("UPDATE client_names SET last_ip=?, last_seen=? WHERE UPPER(mac)=?", (ip, ts, mac)) + + # Mettre à jour rétroactivement les logs très récents qui avaient un nom générique + c.execute(''' + UPDATE connection_logs + SET name = ? + WHERE UPPER(mac) = ? + AND (name LIKE 'Client %' OR name = 'Nom non communiqué' OR name = '' OR name IS NULL) + AND id >= (SELECT COALESCE(MAX(id)-20, 0) FROM connection_logs) + ''', (name, mac)) + c.commit() + c.close() + except Exception: + pass + +def resolve_client_hostname_now(ip, mac): + """Résout de manière active et multicanale le vrai nom d'hôte d'un client Wi-Fi.""" + mac = (mac or '').upper() + if mac in station_live_names: + return station_live_names[mac] + + try: + c = db() + row = c.execute("SELECT name FROM client_names WHERE UPPER(mac)=?", (mac,)).fetchone() + c.close() + if row and row[0] and not row[0].startswith('Client ') and row[0] != 'Nom non communiqué': + station_live_names[mac] = row[0] + return row[0] + except Exception: + pass + + 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 != '*': + cl = clean_extracted_hostname(l_host) + if cl: + record_live_device_name(mac, cl, ip) + return cl + dhcp_entries = get_journal_dhcp_entries() + if mac in dhcp_entries: + cl = clean_extracted_hostname(dhcp_entries[mac]) + if cl: + record_live_device_name(mac, cl, ip) + return cl + + if ip and ip not in ('Non attribuée', '—'): + rdns = quick_reverse_dns(ip) + if rdns: + record_live_device_name(mac, rdns, ip) + return rdns + + if ip and ip not in ('Non attribuée', '—'): + nb_name = query_netbios_name(ip) + if nb_name: + record_live_device_name(mac, nb_name, ip) + return nb_name + + return '' def get_journal_dhcp_entries(): now = time.time() @@ -366,8 +615,11 @@ def device_name(ip, mac): mac = (mac or '').upper() now = time.time() if mac and mac in _device_name_cache: - c_name, c_time = _device_name_cache[mac] - if now - c_time < 30: + c_name, c_exp = _device_name_cache[mac] + if not c_name.startswith('Client ') and c_name != 'Nom non communiqué': + if now < c_exp: + return c_name + elif now < c_exp: return c_name # 1. Base de données client_names (nom personnalisé ou précédemment appris) @@ -375,48 +627,65 @@ def device_name(ip, mac): try: c = db(); row = c.execute('SELECT name FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close() if row and row[0] and not row[0].startswith('Client ') and row[0] != 'Nom non communiqué': - _device_name_cache[mac] = (row[0], now) + _device_name_cache[mac] = (row[0], now + 300) return row[0] except sqlite3.Error: pass - # 2. Baux DHCP dnsmasq + # 2. Nom capturé en direct (DHCP sniffer, mDNS, LLMNR, NetBIOS) + if mac and mac in station_live_names: + _device_name_cache[mac] = (station_live_names[mac], now + 300) + return station_live_names[mac] + + # 3. Résolution active immédiate (Reverse DNS, NetBIOS, Baux) + if ip and ip not in ('Non attribuée', '—'): + res_name = resolve_client_hostname_now(ip, mac) + if res_name: + _device_name_cache[mac] = (res_name, now + 300) + return res_name + + # 4. Baux DHCP dnsmasq (NAT) try: is_bridge = is_bridge_mode() except Exception: is_bridge = False if not is_bridge: for l_mac, l_ip, l_host in reversed(lease_entries()): if l_mac == mac or (ip and l_ip == ip): if l_host and l_host != '*': - name = l_host.strip() - _device_name_cache[mac] = (name, now) - return name - # 3. Journal DHCP NetworkManager (avec cache et timeout 1s) + name = clean_extracted_hostname(l_host) + if name: + record_live_device_name(mac, name, ip) + _device_name_cache[mac] = (name, now + 300) + return name dhcp_entries = get_journal_dhcp_entries() if mac in dhcp_entries: - name = dhcp_entries[mac] - _device_name_cache[mac] = (name, now) - return name + name = clean_extracted_hostname(dhcp_entries[mac]) + if name: + record_live_device_name(mac, name, ip) + _device_name_cache[mac] = (name, now + 300) + return name - # 4. Table des voisins ARP (ip neigh) + # 5. Table des voisins ARP (ip neigh) if ip and ip not in ('Non attribuée', '—') and not (is_bridge and ip.startswith('10.42.')): host_line = command('ip', 'neigh', 'show', ip, timeout=1) match = re.search(r'\(([^)]+)\)', host_line) if match and match.group(1) != ip: - name = match.group(1) - _device_name_cache[mac] = (name, now) - return name + name = clean_extracted_hostname(match.group(1)) + if name: + record_live_device_name(mac, name, ip) + _device_name_cache[mac] = (name, now + 300) + return name - # 5. Nom en base même si générique + # 6. Nom en base même si générique if mac: try: c = db(); row = c.execute('SELECT name FROM client_names WHERE mac=?', (mac,)).fetchone(); c.close() if row and row[0]: - _device_name_cache[mac] = (row[0], now) + _device_name_cache[mac] = (row[0], now + 1.5) return row[0] except sqlite3.Error: pass fallback = 'Client ' + mac.replace(':', '')[-4:] if mac else 'Nom non communiqué' if mac: - _device_name_cache[mac] = (fallback, now) + _device_name_cache[mac] = (fallback, now + 1.5) return fallback # __AUTHENTICATION_IMPLEMENTATION__ @@ -4114,7 +4383,7 @@ def blocked_set(): 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.""" + """Écoute passivement les trames réseau (IPv4, ARP, DHCP, mDNS, LLMNR, NetBIOS) pour capturer en temps réel l'IP et le vrai nom d'hôte des clients.""" try: s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) except Exception as e: @@ -4131,12 +4400,40 @@ def arp_listener(): 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]) + valid_sip = None 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 + if not (is_bridge and sip.startswith('10.42.')) and not (not is_bridge and not sip.startswith('10.42.')): + station_live_ips[smac] = sip + valid_sip = sip + + # Inspection des paquets UDP (protocole 17) pour extraire le vrai nom d'hôte + if raw[23] == 17: + try: + ihl = (raw[14] & 0x0F) * 4 + if len(raw) >= 14 + ihl + 8: + udp_hdr = raw[14 + ihl : 14 + ihl + 8] + sport, dport = struct.unpack('!HH', udp_hdr[:4]) + udp_payload = raw[14 + ihl + 8 :] + + # A. DHCP (ports 67 / 68) : Option 12 (Host Name) et Option 81 (Client FQDN) + if sport in (67, 68) or dport in (67, 68): + dhcp_host = extract_dhcp_hostname_from_udp(udp_payload) + if dhcp_host: + record_live_device_name(smac, dhcp_host, valid_sip) + + # B. mDNS (5353) et LLMNR (5355) : diffusion du nom d'hôte .local + elif dport in (5353, 5355) or sport in (5353, 5355): + mdns_host = extract_dns_name_from_packet(udp_payload) + if mdns_host and not mdns_host.startswith('_') and not mdns_host.endswith('.arpa'): + record_live_device_name(smac, mdns_host, valid_sip) + + # C. NetBIOS (port 137) + elif dport == 137 or sport == 137: + nb_host = parse_netbios_response(udp_payload) + if nb_host: + record_live_device_name(smac, nb_host, valid_sip) + except Exception: + pass # 2. Trame ARP (0x0806) elif eth_type == b'\x08\x06' and len(raw) >= 42: @@ -4373,7 +4670,15 @@ def clients(): 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) + blocked = mac in blocked_macs + if mac in station_live_names: + name = station_live_names[mac] + else: + name = device_name(ip if ip != 'Non attribuée' else '', mac) + if (name.startswith('Client ') or name == 'Nom non communiqué') and ip != 'Non attribuée': + res_n = resolve_client_hostname_now(ip, mac) + if res_n: + name = res_n now_ts = time.strftime('%Y-%m-%d %H:%M:%S') try: c = db() @@ -4954,6 +5259,9 @@ def all_devices(lang='fr'): name = nd['name'] if not name and ld.get('name'): name = ld['name'] + if not name or name.startswith('Client '): + if mac in station_live_names: + name = station_live_names[mac] if not name: name = 'Client ' + mac.replace(':', '')[-4:] @@ -5559,6 +5867,14 @@ def update_logs(items): # 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: + # Si le nom est générique ou inconnu, tenter une résolution active du vrai nom d'hôte avant de journaliser + if mac in station_live_names: + x['name'] = station_live_names[mac] + elif x['name'].startswith('Client ') or x['name'] == 'Nom non communiqué': + real_n = resolve_client_hostname_now(x['ip'] if x['ip'] != 'Non attribuée' else '', mac) + if real_n: + x['name'] = real_n + record_live_device_name(mac, real_n, x['ip'] if x['ip'] != 'Non attribuée' else None) 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: diff --git a/index.html b/index.html index bb52aba..95eb70d 100644 --- a/index.html +++ b/index.html @@ -9408,7 +9408,7 @@ ${vpnBadgeTopo} const ipLabel = c.ip || t('not_assigned', 'Non attribuée'); const nameLabel = String(c.name || t('name_unknown', 'Nom non communiqué')).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';'); const blockBtnLabel = c.blocked ? t('btn_unblock', 'Débloquer') : t('btn_block', 'Bloquer'); - const quotaBtnLabel = '⚖️ ' + t('th_quota', 'Quota'); + const quotaBtnLabel = '⚖️ ' + t('btn_quota', 'Quota'); return `
${String(c.name || '?')[0].toUpperCase()}
${nameLabel}
${ipLabel}${c.mac || '—'}${vpnHtml}${signalQuality(c.signal_dbm, c)}${speedHtml}
`; }).join('') : `${t('no_clients', 'Aucun client connecté')}`; @@ -9537,7 +9537,8 @@ ${vpnBadgeTopo} let devIp = ipDisp; if ((!devName || devName === 'Nom non communiqué' || devIp === 'Non attribuée') && log.mac && log.mac.includes(':')) { const mUpper = log.mac.toUpperCase(); - const known = (typeof allDevicesCache !== 'undefined' && Array.isArray(allDevicesCache)) ? allDevicesCache.find(d => d.mac && d.mac.toUpperCase() === mUpper) : null; + const known = ((typeof devicesDataCache !== 'undefined' && Array.isArray(devicesDataCache)) ? devicesDataCache.find(d => d.mac && d.mac.toUpperCase() === mUpper) : null) || + ((typeof clients !== 'undefined' && Array.isArray(clients)) ? clients.find(c => c.mac && c.mac.toUpperCase() === mUpper) : null); if (known) { if (!devName || devName === 'Nom non communiqué') devName = known.name; if (devIp === 'Non attribuée' && known.ip && known.ip !== 'Non attribuée') devIp = known.ip; @@ -9734,7 +9735,7 @@ ${vpnBadgeTopo} ${firstSeenHtml}
- + diff --git a/lang/en-gb.js b/lang/en-gb.js index 3d221fc..12e22f3 100644 --- a/lang/en-gb.js +++ b/lang/en-gb.js @@ -879,6 +879,7 @@ window.I18N['en-gb'] = { "th_passkey_name": "PASSKEY NAME", "th_period": "PERIOD", "th_proto": "PROTO", + "btn_quota": "Quota", "th_quota": "ALLOWANCE & SPEED", "th_routing": "INTERNET ROUTING", "th_signal": "SIGNAL", diff --git a/lang/en-us.js b/lang/en-us.js index 8d4c419..1a2fe86 100644 --- a/lang/en-us.js +++ b/lang/en-us.js @@ -879,6 +879,7 @@ window.I18N['en-us'] = { "th_passkey_name": "PASSKEY NAME", "th_period": "PERIOD", "th_proto": "PROTO", + "btn_quota": "Quota", "th_quota": "QUOTA & SPEED", "th_routing": "INTERNET ROUTING", "th_signal": "SIGNAL", diff --git a/lang/fr.js b/lang/fr.js index c199ee1..7d2120b 100644 --- a/lang/fr.js +++ b/lang/fr.js @@ -879,6 +879,7 @@ window.I18N['fr'] = { "th_passkey_name": "NOM DE LA PASSKEY", "th_period": "PÉRIODE", "th_proto": "PROTO", + "btn_quota": "Quota", "th_quota": "QUOTA & DÉBIT", "th_routing": "ROUTAGE INTERNET", "th_signal": "SIGNAL", diff --git a/version.json b/version.json index 44503c4..6632d94 100644 --- a/version.json +++ b/version.json @@ -1,5 +1,5 @@ { "version": "V5.5", - "commit": "204b9b1abb26eb3dd675f5f3ba89782a7d6d944b", - "build_date": "2026-11-22T16:57:07Z" + "commit": "4a36ad70e5a6095bcc541c8c44e9c7652cf9d610", + "build_date": "2026-11-22T18:29:15Z" } \ No newline at end of file