Files
wifi-gps-mapper-releases/reports/wifi_connections.py
T

942 lines
25 KiB
Python

import html
import json
from reports.access_points import (
format_popup_datetime,
load_access_points,
)
from reports.map_popups import build_standard_popup
from reports.map_service import get_map_style_url
from reports.template import (
ReportContext,
card,
page_begin,
page_end,
)
def verified_passwords(row):
passwords = []
seen = set()
for credential in row["passwords"]:
password = credential.get("password")
if (
not credential.get("verified")
or not isinstance(password, str)
or not password
or password in seen
):
continue
seen.add(password)
passwords.append(password)
return passwords
def classify_access_points(observations):
verified_wpa = []
open_aps = []
for row in observations:
latitude = row.get("latitude")
longitude = row.get("longitude")
if latitude is None or longitude is None:
continue
encryption = str(
row.get("encryption") or ""
).strip().upper()
if encryption == "OPEN":
open_aps.append(row)
elif verified_passwords(row):
verified_wpa.append(row)
return verified_wpa, open_aps
def build_connection_popup(row, is_open):
popup = build_standard_popup(
essid=row["essid"],
bssid=row["bssid"],
vendor=row["vendor"],
encryption=row["encryption"],
cipher=row["cipher"],
akm=row["akm"],
channel=row["channel"],
rssi=row["rssi"],
passwords=row["passwords"],
handshakes=row["handshakes"],
observed_at=format_popup_datetime(
row["observed_at"]
),
latitude=row["latitude"],
longitude=row["longitude"],
access_point_url=(
f"/reports/access-points/{row['bssid']}"
),
)
if is_open:
connect_control = """
<div class="wifi-connection-action">
<button
type="button"
class="wifi-connection-button"
data-wifi-connect
data-bssid="{}"
data-open="true"
>
Подключиться
</button>
</div>
""".format(
html.escape(str(row["bssid"]), quote=True)
)
else:
passwords = verified_passwords(row)
options = "".join(
'<option value="{}">{}</option>'.format(
html.escape(password, quote=True),
html.escape(password),
)
for password in passwords
)
connect_control = """
<div class="wifi-connection-action">
<label>
Проверенный пароль:
<select
class="wifi-connection-password"
data-wifi-password
>
{}
</select>
</label>
<button
type="button"
class="wifi-connection-button"
data-wifi-connect
data-bssid="{}"
data-open="false"
>
Подключиться
</button>
</div>
""".format(
options,
html.escape(str(row["bssid"]), quote=True),
)
return popup + connect_control
def build_wifi_connections_marker_js(observations):
verified_wpa, open_aps = classify_access_points(
observations
)
def make_features(rows, is_open):
features = []
for row in rows:
popup = build_connection_popup(
row,
is_open,
)
features.append({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
float(row["longitude"]),
float(row["latitude"]),
],
},
"properties": {
"popup": popup,
},
})
return features
return (
"const verifiedWpaFeatures = "
+ json.dumps(
make_features(verified_wpa, False),
ensure_ascii=False,
)
+ ";\n"
+ "const openFeatures = "
+ json.dumps(
make_features(open_aps, True),
ensure_ascii=False,
)
+ ";\n"
)
def render_wifi_connections_map(observations, context):
marker_js = build_wifi_connections_marker_js(
observations
)
maplibre_css_url = context.asset_url(
"maplibre/maplibre-gl.css"
)
maplibre_js_url = context.asset_url(
"maplibre/maplibre-gl.js"
)
map_html = """
<div id="map"></div>
<link
rel="stylesheet"
href="__MAPLIBRE_CSS_URL__"
>
<script src="__MAPLIBRE_JS_URL__"></script>
<script>
__MARKER_JS__
const map = new maplibregl.Map({
container: "map",
style:
__MAP_STYLE_URL__,
center: [
30.32,
59.93
],
zoom: 5,
attributionControl: true
});
map.addControl(
new maplibregl.NavigationControl(),
"top-right"
);
map.addControl(
new maplibregl.ScaleControl({
maxWidth: 120,
unit: "metric"
})
);
map.on(
"load",
function()
{
map.addSource(
"verified-wpa",
{
type: "geojson",
data: {
type: "FeatureCollection",
features: verifiedWpaFeatures
}
}
);
map.addSource(
"open-aps",
{
type: "geojson",
data: {
type: "FeatureCollection",
features: openFeatures
}
}
);
map.addLayer({
id: "verified-wpa-points",
type: "circle",
source: "verified-wpa",
paint: {
"circle-radius": 8,
"circle-color": "#43A047",
"circle-stroke-color": "#ffffff",
"circle-stroke-width": 1.5
}
});
map.addLayer({
id: "open-ap-points",
type: "circle",
source: "open-aps",
paint: {
"circle-radius": 8,
"circle-color": "#AB47BC",
"circle-stroke-color": "#ffffff",
"circle-stroke-width": 1.5
}
});
const popupLayers = [
"verified-wpa-points",
"open-ap-points"
];
popupLayers.forEach(
function(layerId)
{
map.on(
"click",
layerId,
function(e)
{
if(
!e.features
||
!e.features.length
)
{
return;
}
const feature = e.features[0];
if(
!feature
||
!feature.properties
)
{
return;
}
new maplibregl.Popup()
.setLngLat(
feature.geometry.coordinates
)
.setHTML(
feature.properties.popup
|| "<b>Access Point</b>"
)
.addTo(map);
updateWifiConnectButtons();
}
);
map.on(
"mouseenter",
layerId,
function()
{
map.getCanvas().style.cursor =
"pointer";
}
);
map.on(
"mouseleave",
layerId,
function()
{
map.getCanvas().style.cursor =
"";
}
);
}
);
document.querySelectorAll(
".session-map-controls input[data-layer]"
).forEach(
function(input)
{
input.addEventListener(
"change",
function()
{
const layerId =
input.dataset.layer === "verified"
? "verified-wpa-points"
: "open-ap-points";
map.setLayoutProperty(
layerId,
"visibility",
input.checked
? "visible"
: "none"
);
}
);
}
);
let wifiConnectionBusy = false;
const wifiInterfaceSelect = document.getElementById(
"wifi-connections-interface"
);
const wifiConnectionMessage = document.getElementById(
"wifi-connections-message"
);
const wifiConnectionWarning = document.getElementById(
"wifi-connections-warning"
);
function setWifiConnectionMessage(text, isError = false) {
if (!wifiConnectionMessage) {
return;
}
wifiConnectionMessage.textContent = text || "";
wifiConnectionMessage.style.color = isError
? "var(--red)"
: "var(--muted)";
}
function updateWifiConnectButtons() {
const interfaceReady = Boolean(
wifiInterfaceSelect
&& wifiInterfaceSelect.value
);
document.querySelectorAll(
"[data-wifi-connect]"
).forEach(function(button) {
button.disabled =
wifiConnectionBusy || !interfaceReady;
});
}
if (wifiInterfaceSelect) {
wifiInterfaceSelect.addEventListener(
"change",
updateWifiConnectButtons
);
}
updateWifiConnectButtons();
document.addEventListener(
"wifi-interfaces-loaded",
updateWifiConnectButtons
);
document.addEventListener(
"click",
async function(event) {
const target = event.target;
if (!(target instanceof Element)) {
return;
}
const button = target.closest(
"[data-wifi-connect]"
);
if (!button || wifiConnectionBusy) {
return;
}
event.preventDefault();
const interfaceName = wifiInterfaceSelect
? wifiInterfaceSelect.value
: "";
if (!interfaceName) {
setWifiConnectionMessage(
"Выберите доступный Wi-Fi интерфейс.",
true
);
return;
}
const bssid = button.dataset.bssid;
const isOpen = button.dataset.open === "true";
if (!bssid) {
setWifiConnectionMessage(
"Не указан BSSID точки доступа.",
true
);
return;
}
let password = null;
if (!isOpen) {
const action = button.closest(
".wifi-connection-action"
);
const passwordSelect = action
? action.querySelector("[data-wifi-password]")
: null;
password = passwordSelect
? passwordSelect.value
: "";
if (!password) {
setWifiConnectionMessage(
"Выберите проверенный пароль.",
true
);
return;
}
}
wifiConnectionBusy = true;
updateWifiConnectButtons();
setWifiConnectionMessage(
"Выполняется подключение к " + bssid + "..."
);
try {
const payload = {
interface: interfaceName,
bssid: bssid
};
if (!isOpen) {
payload.password = password;
}
const response = await fetch(
"/api/network/connect",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
}
);
const data = await response.json();
if (
!response.ok
|| !data.ok
|| data.success === false
) {
throw new Error(
data.error || "Не удалось подключиться."
);
}
setWifiConnectionMessage(
"Подключение успешно: "
+ (data.ssid || bssid)
);
if (
data.vpn_warning
&& wifiConnectionWarning
) {
wifiConnectionWarning.textContent =
data.vpn_warning;
wifiConnectionWarning.hidden = false;
}
} catch (error) {
setWifiConnectionMessage(
error.message
|| "Ошибка подключения к точке доступа.",
true
);
} finally {
wifiConnectionBusy = false;
updateWifiConnectButtons();
}
}
);
const allFeatures =
verifiedWpaFeatures.concat(openFeatures);
if(allFeatures.length === 1)
{
map.jumpTo({
center:
allFeatures[0].geometry.coordinates,
zoom: 15
});
}
else if(allFeatures.length > 1)
{
const bounds =
new maplibregl.LngLatBounds();
allFeatures.forEach(
function(feature)
{
bounds.extend(
feature.geometry.coordinates
);
}
);
map.fitBounds(
bounds,
{
padding: 50,
maxZoom: 15
}
);
}
}
);
window.setTimeout(
function()
{
map.resize();
},
100
);
</script>
"""
map_html = map_html.replace(
"__MAPLIBRE_CSS_URL__",
maplibre_css_url,
)
map_html = map_html.replace(
"__MAPLIBRE_JS_URL__",
maplibre_js_url,
)
map_html = map_html.replace(
"__MARKER_JS__",
marker_js,
)
map_html = map_html.replace(
"__MAP_STYLE_URL__",
json.dumps(get_map_style_url()),
)
return map_html
def render_wifi_connections_page(conn, context=None):
if context is None:
context = ReportContext(
mode="server"
)
observations = load_access_points(conn)
verified_wpa, open_aps = classify_access_points(
observations
)
html = page_begin(
"Wi-Fi Connections",
active="wifi_connections",
context=context,
section_title="Reports",
)
html += card(
"Подключение к Wi-Fi",
"""
<div id="wifi-connections-controls">
<div style="margin-bottom:14px;">
<label for="wifi-connections-interface">
<strong>Wi-Fi интерфейс:</strong>
</label>
<select
id="wifi-connections-interface"
class="search"
style="display:block;width:100%;max-width:400px;"
disabled
>
<option value="">Загрузка интерфейсов...</option>
</select>
</div>
<div
id="wifi-connections-warning"
role="status"
hidden
style="
margin:12px 0;
padding:12px;
border:1px solid var(--yellow);
border-radius:8px;
line-height:1.5;
"
></div>
<div
id="wifi-connections-message"
role="status"
aria-live="polite"
style="margin:12px 0;"
></div>
</div>
<script>
(function() {
const root = document.getElementById(
"wifi-connections-controls"
);
if (!root) {
return;
}
const interfaceSelect = document.getElementById(
"wifi-connections-interface"
);
const message = document.getElementById(
"wifi-connections-message"
);
const warning = document.getElementById(
"wifi-connections-warning"
);
function setMessage(text, isError = false) {
message.textContent = text || "";
message.style.color = isError
? "var(--red)"
: "var(--muted)";
}
function setWarning(text) {
warning.textContent = text || "";
warning.hidden = !text;
}
async function loadInterfaces() {
try {
const response = await fetch(
"/api/network/wifi-devices",
{cache: "no-store"}
);
const data = await response.json();
if (!response.ok || !data.ok) {
throw new Error(
data.error
|| "Не удалось получить Wi-Fi интерфейсы."
);
}
const devices = data.devices || [];
interfaceSelect.replaceChildren();
const placeholder = document.createElement("option");
placeholder.value = "";
placeholder.textContent = devices.length > 1
? "Выберите Wi-Fi интерфейс"
: "Нет доступных интерфейсов";
interfaceSelect.appendChild(placeholder);
devices.forEach(device => {
const option = document.createElement("option");
option.value = device.device;
option.textContent = device.available
? device.device + " (" + device.state + ")"
: device.device + " — " + (
device.reason || device.state
);
option.disabled = !device.available;
interfaceSelect.appendChild(option);
});
const availableDevices = devices.filter(
device => device.available
);
if (availableDevices.length === 1) {
interfaceSelect.value =
availableDevices[0].device;
} else if (
data.selected_device
&& availableDevices.some(device =>
device.device === data.selected_device
)
) {
interfaceSelect.value = data.selected_device;
}
interfaceSelect.disabled =
availableDevices.length <= 1;
if (!devices.length) {
setMessage(
data.error || "Wi-Fi интерфейсы не найдены.",
true
);
} else if (
!devices.some(device => device.available)
) {
setMessage(
devices.map(device =>
device.device + ": " + (
device.reason || device.state
)
).join("; "),
true
);
} else if (availableDevices.length > 1) {
setMessage(
"Выберите доступный Wi-Fi интерфейс."
);
}
if (data.vpn_active) {
setWarning(
"Обнаружено активное VPN-подключение. "
+ "Для надёжной проверки пароля и подключения "
+ "рекомендуется временно отключить VPN. "
+ "Продолжить можно, но успешная работа "
+ "не гарантируется."
);
} else if (data.vpn_error) {
setWarning(
"Не удалось достоверно определить состояние VPN. "
+ "При активном VPN результат операции "
+ "не гарантируется. "
+ "Рекомендуется проверить состояние VPN вручную."
);
}
document.dispatchEvent(
new Event("wifi-interfaces-loaded")
);
} catch (error) {
interfaceSelect.disabled = true;
setMessage(
error.message
|| "Ошибка получения Wi-Fi интерфейсов.",
true
);
document.dispatchEvent(
new Event("wifi-interfaces-loaded")
);
}
}
loadInterfaces();
})();
</script>
"""
)
html += card(
"""
<span class="session-map-title">
<span class="session-map-title-text">
🗺 Wi-Fi Connections
</span>
<span class="session-map-controls">
<label>
<input
type="checkbox"
data-layer="verified"
checked
>
<span class="map-layer-dot map-layer-dot-handshake"></span>
Verified WPA ({})
</label>
<label>
<input
type="checkbox"
data-layer="open"
checked
>
<span class="map-layer-dot map-layer-dot-open"></span>
OPEN ({})
</label>
</span>
</span>
""".format(
len(verified_wpa),
len(open_aps),
),
render_wifi_connections_map(
observations,
context,
),
)
html += page_end()
return html