Compare commits

...
150 Commits
Author SHA1 Message Date
wildsoft ddafbb613b Update public source 2026-11-19 02:20:29 +03:00
wildsoft 012f209303 Update public source 2026-11-19 00:39:35 +03:00
wildsoft 52fef57721 Update public source 2026-11-17 20:24:26 +03:00
wildsoft 2c621aa8f1 Update public source 2026-11-17 16:06:20 +03:00
wildsoft 2755f6b383 Update public source 2026-11-17 14:57:52 +03:00
wildsoft 6866e02d7a Update public source 2026-11-17 00:01:18 +03:00
wildsoft 899f7436f4 Update public source 2026-11-16 21:33:16 +03:00
wildsoft 2d34fd41fd Update public source 2026-11-16 21:29:39 +03:00
wildsoft c8aa152087 Update public source 2026-11-16 19:18:46 +03:00
wildsoft e850b691c2 Update public source 2026-11-16 19:08:18 +03:00
wildsoft 5994d513c8 Update public source 2026-11-16 18:59:45 +03:00
wildsoft 37a52f004e Update public source 2026-11-16 18:33:44 +03:00
wildsoft 34857e8ed2 Update public source 2026-11-16 18:31:52 +03:00
wildsoft f7d78c0ea6 Update public source 2026-11-15 16:11:27 +03:00
wildsoft b50baedda4 Update public source 2026-11-15 12:12:48 +03:00
wildsoft 7c44fb339e Update public source 2026-11-14 23:51:05 +03:00
wildsoft 705fa62d2c Update public source 2026-11-12 20:32:33 +03:00
wildsoft 267707e271 Update public source 2026-11-12 20:28:48 +03:00
wildsoft a4fda4dcdc Update public source 2026-11-12 20:25:35 +03:00
wildsoft dbecf7b34e Update public source 2026-11-12 20:20:44 +03:00
wildsoft 9c8229517b Update public source 2026-11-12 20:06:47 +03:00
wildsoft c892a96064 Update public source 2026-11-12 20:01:56 +03:00
wildsoft 9e35491e3c Update public source 2026-11-12 19:44:40 +03:00
wildsoft fbc709e750 Update public source 2026-11-12 19:27:37 +03:00
wildsoft 32c9eea487 Update public source 2026-11-12 17:51:54 +03:00
wildsoft d9ebdf9a14 Update public source 2026-11-12 17:48:50 +03:00
wildsoft f9af674230 Update public source 2026-11-12 17:46:17 +03:00
wildsoft 92ccd37846 Update public source 2026-11-12 17:42:52 +03:00
wildsoft bdf44b9a2e Update public source 2026-11-12 17:38:04 +03:00
wildsoft e512ecdd8c Update public source 2026-11-12 15:24:36 +03:00
wildsoft 086cedeb1f Update public source 2026-11-12 15:22:54 +03:00
wildsoft ed83f4f9cc Update public source 2026-11-12 15:14:48 +03:00
wildsoft 6fa7b772e6 Update public source 2026-11-12 14:38:22 +03:00
wildsoft c1a2b960e7 Update public source 2026-11-12 14:11:13 +03:00
wildsoft 7468f6c0d3 Update public source 2026-11-12 13:43:08 +03:00
wildsoft b96a3dfe36 Update public source 2026-11-12 13:41:13 +03:00
wildsoft 7e8d251210 Update public source 2026-11-12 13:36:26 +03:00
wildsoft a0be30dddb Update public source 2026-11-12 10:15:23 +03:00
wildsoft a9358fec17 Update public source 2026-11-12 10:08:44 +03:00
wildsoft 22c3c8b9bb Update public source 2026-11-12 10:07:04 +03:00
wildsoft 2c003062cb Update public source 2026-11-11 19:03:34 +03:00
wildsoft b8dd02f4fa Update public source 2026-11-11 18:30:39 +03:00
wildsoft 6ff1922de6 Update public source 2026-11-11 18:26:43 +03:00
wildsoft 104a23ab2d Update public source 2026-11-11 18:25:32 +03:00
wildsoft c8df4d72d1 Update public source 2026-11-11 18:24:41 +03:00
wildsoft d386e1593d Update public source 2026-10-21 13:39:48 +03:00
wildsoft e45b427c12 Update public source 2026-10-21 13:37:33 +03:00
wildsoft 04a7f08d7d Update public source 2026-10-21 13:27:04 +03:00
wildsoft 05f83fd186 Update public source 2026-10-21 13:07:48 +03:00
wildsoft d5594ace92 Update public source 2026-10-21 13:03:49 +03:00
wildsoft bbcb2c8920 Update public source 2026-10-21 01:52:47 +03:00
wildsoft ab59e68615 Update public source 2026-10-21 01:52:13 +03:00
wildsoft dd182e9e4e Update public source 2026-10-21 01:50:29 +03:00
wildsoft aba6633b1f Update public source 2026-10-21 01:48:43 +03:00
wildsoft bb9e16638e Update public source 2026-10-20 12:46:22 +03:00
wildsoft d519a34145 Update public source 2026-10-19 17:51:35 +03:00
wildsoft edc93c7348 Update public source 2026-10-19 17:50:52 +03:00
wildsoft b6c4e51d39 Update public source 2026-10-19 15:54:35 +03:00
wildsoft ec584c3d9c Update public source 2026-10-19 15:51:15 +03:00
wildsoft e89d4b8651 Update public source 2026-10-17 16:30:32 +03:00
wildsoft 2b25a01d45 Update public source 2026-10-17 06:33:57 +03:00
wildsoft bc5a0b42be Update public source 2026-10-16 18:01:42 +03:00
wildsoft 40e449bbfb Update public source 2026-10-16 17:33:06 +03:00
wildsoft 0ea3107e2a Update public source 2026-10-16 17:22:53 +03:00
wildsoft ab558cec15 Update public source 2026-10-16 16:41:26 +03:00
wildsoft 1a38d37368 Update public source 2026-10-16 16:23:12 +03:00
wildsoft 09198e5ab3 Update public source 2026-10-16 12:15:07 +03:00
wildsoft 8f82969eb5 Update public source 2026-10-16 11:12:09 +03:00
wildsoft 5f31ccd739 Update public source 2026-10-16 09:52:46 +03:00
wildsoft 796d5e6069 Update public source 2026-10-16 09:29:00 +03:00
wildsoft 8996648901 Update public source 2026-10-16 09:23:03 +03:00
wildsoft bb85bfc417 Update public source 2026-10-16 09:07:30 +03:00
wildsoft a7499c1967 Update public source 2026-10-16 09:06:04 +03:00
wildsoft bccb161fec Update public source 2026-10-16 06:36:05 +03:00
wildsoft b5789f9597 Update public source 2026-10-16 06:27:59 +03:00
wildsoft bac6d68fa5 Update public source 2026-10-15 11:52:08 +03:00
wildsoft 71eb550e9f Update public source 2026-10-15 11:43:23 +03:00
wildsoft d0b5b770a6 Update public source 2026-10-15 11:39:31 +03:00
wildsoft 8b711b8409 Update public source 2026-10-14 10:19:23 +03:00
wildsoft b5752efada Update public source 2026-10-14 07:54:07 +03:00
wildsoft 894a36d116 Update public source 2026-10-14 06:59:40 +03:00
wildsoft 93d54db672 Update public source 2026-10-14 06:56:58 +03:00
wildsoft cb902754a1 Update public source 2026-10-14 06:22:33 +03:00
wildsoft 1e37ad7395 Update public source 2026-10-14 06:15:33 +03:00
wildsoft 95a0f6e75a Update public source 2026-10-14 06:09:52 +03:00
wildsoft b33d51f24f Update public source 2026-10-14 06:07:43 +03:00
wildsoft 60b14e1213 Update public source 2026-10-14 05:55:09 +03:00
wildsoft 1503a1f043 Update public source 2026-10-14 05:52:20 +03:00
wildsoft 01cede430a Update public source 2026-10-13 17:39:43 +03:00
wildsoft a887a0e4fd Update public source 2026-10-13 14:42:47 +03:00
wildsoft aefab40378 Update public source 2026-10-13 12:50:29 +03:00
wildsoft 789923bb2b Update public source 2026-10-13 11:47:20 +03:00
wildsoft a584920dec Update public source 2026-10-13 11:43:08 +03:00
wildsoft d94d207d4f Update public source 2026-10-13 10:47:31 +03:00
wildsoft 95b2ec53a9 Update public source 2026-10-13 10:37:49 +03:00
wildsoft 0ed285e8e5 Update public source 2026-10-13 10:15:09 +03:00
wildsoft c5c7c53cd8 Update public source 2026-10-13 09:57:47 +03:00
wildsoft 4aa23c206f Update public source 2026-10-13 09:36:04 +03:00
wildsoft 4876d2de9c Update public source 2026-10-13 08:00:22 +03:00
wildsoft a0ad384f1e Update public source 2026-10-12 04:48:13 +03:00
wildsoft 9dd791cab5 Update public source 2026-10-12 04:29:48 +03:00
wildsoft fb59508d96 Update public source 2026-10-12 04:23:53 +03:00
wildsoft 115b028404 Update public source 2026-10-12 04:14:48 +03:00
wildsoft 4bdc496d42 Update public source 2026-10-12 03:25:00 +03:00
wildsoft 9d64e8979c Update public source 2026-10-12 03:22:48 +03:00
wildsoft 0a4f3810b4 Update public source 2026-10-12 03:12:14 +03:00
wildsoft e8baabf986 Update public source 2026-10-11 15:14:25 +03:00
wildsoft 63ad49f92b Update public source 2026-10-11 14:57:46 +03:00
wildsoft 7236cb0ee6 Update public source 2026-10-11 14:55:24 +03:00
wildsoft af0760d9f4 Update public source 2026-10-11 14:53:36 +03:00
wildsoft 1e92597b34 Update public source 2026-10-11 14:46:11 +03:00
wildsoft ce3063e7d3 Update public source 2026-10-11 14:31:19 +03:00
wildsoft d534912768 Update public source 2026-10-11 14:28:02 +03:00
wildsoft 8b900a7580 Update public source 2026-10-11 12:51:29 +03:00
wildsoft 6124010abb Update public source 2026-10-11 12:43:20 +03:00
wildsoft a8499b80b8 Update public source 2026-10-11 12:27:30 +03:00
wildsoft cf7328182a Update public source 2026-10-11 12:00:14 +03:00
wildsoft dfe5270ee3 Update public source 2026-10-11 09:17:44 +03:00
wildsoft 6832b085ca Update public source 2026-10-11 09:14:06 +03:00
wildsoft 18837b2a08 Update public source 2026-10-11 08:02:54 +03:00
wildsoft 18463d2c8b Update public source 2026-10-11 07:39:58 +03:00
wildsoft 1bc9251419 Update public source 2026-10-11 07:39:24 +03:00
wildsoft 68be4aed6a Update public source 2026-10-11 06:00:13 +03:00
wildsoft bb54467027 Update public source 2026-10-11 05:57:15 +03:00
wildsoft 62570e1afc Update public source 2026-10-11 05:53:40 +03:00
wildsoft 25e92be2ba Update public source 2026-10-11 05:51:43 +03:00
wildsoft d4548c0d46 Update public source 2026-10-11 05:47:23 +03:00
wildsoft d035b68f6f Update public source 2026-10-11 05:12:01 +03:00
wildsoft dbfc52b04a Update public source 2026-10-11 05:11:17 +03:00
wildsoft 82dfedc160 Update public source 2026-10-11 05:08:54 +03:00
wildsoft ae6b4b15e6 Update public source 2026-10-11 04:41:25 +03:00
wildsoft 1469da3694 Update public source 2026-10-11 04:27:42 +03:00
wildsoft 71a4143149 Update public source 2026-10-10 18:27:24 +03:00
wildsoft 18b2becc7f Update public source 2026-10-10 18:17:40 +03:00
wildsoft fc09aa74f8 Update public source 2026-10-10 16:29:40 +03:00
wildsoft d91c2323a1 Update public source 2026-10-10 16:16:36 +03:00
wildsoft 0176387704 Update public source 2026-10-10 16:11:22 +03:00
wildsoft b3f8a304fb Update public source 2026-10-10 16:10:25 +03:00
wildsoft 25595e84ce Update public source 2026-10-10 15:47:07 +03:00
wildsoft e2227bc40e Update public source 2026-10-10 10:47:10 +03:00
wildsoft 20790d33b2 Update public source 2026-10-10 10:45:47 +03:00
wildsoft 2b32203cf3 Update public source 2026-10-10 10:13:47 +03:00
wildsoft 41971b5656 Update public source 2026-10-10 10:10:03 +03:00
wildsoft 0e4548ac8e Update public source 2026-10-10 10:00:44 +03:00
wildsoft de3fa418b1 Update public source 2026-10-10 09:46:31 +03:00
wildsoft a92deba3e2 Update public source 2026-10-10 09:35:37 +03:00
wildsoft aaaf67d7cf Update public source 2026-10-10 09:22:27 +03:00
wildsoft e57293e210 Update public source 2026-10-10 09:18:19 +03:00
wildsoft 9fdf9c436b Update public source 2026-10-10 09:02:15 +03:00
wildsoft c8ac6fbb84 Update public source 2026-10-10 08:40:57 +03:00
58 changed files with 10215 additions and 3200 deletions
+3 -8
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
import logging
from datetime import datetime, timezone
import time
from pathlib import Path
@@ -9,12 +9,7 @@ LOGGER_NAME = "cracklab.client"
class UTCFormatter(logging.Formatter):
converter = staticmethod(
lambda timestamp: datetime.fromtimestamp(
timestamp,
tz=timezone.utc,
).timetuple()
)
converter = staticmethod(time.gmtime)
def _configure(
@@ -37,7 +32,7 @@ def _configure(
)
handler.setFormatter(
UTCFormatter(
"%(asctime)sZ %(levelname)s %(message)s",
"%(asctime)s.%(msecs)03dZ [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
)
+11 -1
View File
@@ -32,6 +32,7 @@ class _ValidatedPackage:
hash_content: bytes
job_bytes: bytes
hash_path: str
package_filename: str
class JobPackageService:
@@ -56,7 +57,7 @@ class JobPackageService:
job_id = validated.job["job_id"]
job_path = (
self._paths.jobs
/ package_path.stem
/ job_id
)
if job_path.exists():
@@ -175,6 +176,7 @@ class JobPackageService:
hash_content=hash_bytes,
job_bytes=job_bytes,
hash_path=hash_name,
package_filename=package_path.name,
)
@staticmethod
@@ -954,6 +956,14 @@ class JobPackageService:
package.hash_content
)
(
temporary_path
/ "package_filename.txt"
).write_text(
package.package_filename,
encoding="utf-8",
)
initialize_state(
temporary_path,
package.job,
+27 -3
View File
@@ -252,10 +252,34 @@ def create_result_package(
job_id = job["job_id"]
destination = (
outbox / f"RESULT-{job_dir.name}.zip"
package_filename_path = (
job_dir / "package_filename.txt"
)
result_filename = f"RESULT-{job_dir.name}.zip"
if package_filename_path.is_file():
package_filename = (
package_filename_path.read_text(
encoding="utf-8"
)
)
if (
not package_filename.startswith("JOB-")
or not package_filename.endswith(".zip")
or Path(package_filename).name != package_filename
):
raise ResultPackageError(
"Invalid original Job package filename."
)
result_filename = (
f"RESULT-{package_filename.removeprefix('JOB-')}"
)
destination = outbox / result_filename
if destination.exists():
raise ResultPackageError(
f"Result package already exists: "
@@ -263,7 +287,7 @@ def create_result_package(
)
fd, temporary = tempfile.mkstemp(
prefix=f".RESULT-{job_dir.name}.",
prefix=f".{destination.stem}.",
suffix=".zip.tmp",
dir=str(outbox),
)
@@ -0,0 +1,30 @@
CREATE TABLE IF NOT EXISTS crack_search_contexts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_hash TEXT NOT NULL UNIQUE,
criteria_json TEXT NOT NULL,
matched_access_point_count INTEGER NOT NULL,
handshake_count INTEGER NOT NULL,
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
CHECK (matched_access_point_count >= 0),
CHECK (handshake_count >= 0),
CHECK (expires_at > created_at)
);
CREATE TABLE IF NOT EXISTS crack_search_context_handshakes (
token_hash TEXT NOT NULL,
handshake_id INTEGER NOT NULL,
PRIMARY KEY (token_hash, handshake_id),
FOREIGN KEY (token_hash)
REFERENCES crack_search_contexts(token_hash)
ON DELETE CASCADE,
FOREIGN KEY (handshake_id)
REFERENCES handshakes(id)
ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_crack_search_contexts_expires
ON crack_search_contexts(expires_at);
CREATE INDEX IF NOT EXISTS idx_crack_search_context_handshakes_handshake
ON crack_search_context_handshakes(handshake_id);
+170 -1
View File
@@ -13,9 +13,32 @@ class HandshakesRepository:
method_id: str,
method_version: int,
limit: int | None,
handshake_ids: list[int] | tuple[int, ...] | None = None,
) -> list[sqlite3.Row]:
if handshake_ids is not None and not handshake_ids:
return []
id_filter = ""
parameters: list[Any] = [
method_id,
method_version,
method_id,
method_version,
]
if handshake_ids is not None:
placeholders = ", ".join(
"?" for _ in handshake_ids
)
id_filter = f"AND h.id IN ({placeholders})"
parameters.extend(handshake_ids)
parameters.append(
limit if limit is not None else -1
)
return self._conn.execute(
"""
f"""
SELECT
h.id AS handshake_id,
h.hash22000,
@@ -45,10 +68,59 @@ class HandshakesRepository:
AND r.method_version = ?
AND r.status = 'ACTIVE'
)
{id_filter}
ORDER BY h.id
LIMIT ?
""",
parameters,
).fetchall()
def list_eligible_for_search_context(
self,
token_hash: str,
method_id: str,
method_version: int,
limit: int | None,
) -> list[sqlite3.Row]:
return self._conn.execute(
"""
SELECT
h.id AS handshake_id,
h.hash22000,
h.access_point_id,
h.captured_at
FROM crack_search_context_handshakes AS sch
INNER JOIN handshakes AS h
ON h.id = sch.handshake_id
WHERE sch.token_hash = ?
AND h.hash22000 IS NOT NULL
AND TRIM(h.hash22000) <> ''
AND NOT EXISTS (
SELECT 1
FROM credentials AS c
WHERE c.handshake_id = h.id
)
AND NOT EXISTS (
SELECT 1
FROM crack_attempts AS a
WHERE a.handshake_id = h.id
AND a.method_id = ?
AND a.method_version = ?
AND a.status = 'COMPLETED'
)
AND NOT EXISTS (
SELECT 1
FROM crack_reservations AS r
WHERE r.handshake_id = h.id
AND r.method_id = ?
AND r.method_version = ?
AND r.status = 'ACTIVE'
)
ORDER BY h.id
LIMIT ?
""",
(
token_hash,
method_id,
method_version,
method_id,
@@ -136,3 +208,100 @@ class HandshakesRepository:
method_version,
),
).fetchone()
def get_search_context_statistics(
self,
token_hash: str,
method_id: str,
method_version: int,
) -> sqlite3.Row:
return self._conn.execute(
"""
SELECT
COUNT(*) AS matched_count,
SUM(
CASE
WHEN h.hash22000 IS NOT NULL
AND TRIM(h.hash22000) <> ''
THEN 1
ELSE 0
END
) AS valid_hash_count,
SUM(
CASE
WHEN h.hash22000 IS NOT NULL
AND TRIM(h.hash22000) <> ''
AND EXISTS (
SELECT 1
FROM credentials AS c
WHERE c.handshake_id = h.id
)
THEN 1
ELSE 0
END
) AS found_count,
SUM(
CASE
WHEN h.hash22000 IS NOT NULL
AND TRIM(h.hash22000) <> ''
AND NOT EXISTS (
SELECT 1
FROM credentials AS c
WHERE c.handshake_id = h.id
)
AND EXISTS (
SELECT 1
FROM crack_attempts AS a
WHERE a.handshake_id = h.id
AND a.method_id = ?
AND a.method_version = ?
AND a.status = 'COMPLETED'
)
THEN 1
ELSE 0
END
) AS covered_count,
SUM(
CASE
WHEN h.hash22000 IS NOT NULL
AND TRIM(h.hash22000) <> ''
AND NOT EXISTS (
SELECT 1
FROM credentials AS c
WHERE c.handshake_id = h.id
)
AND NOT EXISTS (
SELECT 1
FROM crack_attempts AS a
WHERE a.handshake_id = h.id
AND a.method_id = ?
AND a.method_version = ?
AND a.status = 'COMPLETED'
)
AND EXISTS (
SELECT 1
FROM crack_reservations AS r
WHERE r.handshake_id = h.id
AND r.method_id = ?
AND r.method_version = ?
AND r.status = 'ACTIVE'
)
THEN 1
ELSE 0
END
) AS reserved_count
FROM crack_search_context_handshakes AS sch
INNER JOIN handshakes AS h
ON h.id = sch.handshake_id
WHERE sch.token_hash = ?
""",
(
method_id,
method_version,
method_id,
method_version,
method_id,
method_version,
token_hash,
),
).fetchone()
@@ -0,0 +1,112 @@
from __future__ import annotations
import sqlite3
from typing import Any
class SearchContextsRepository:
def __init__(self, conn: sqlite3.Connection) -> None:
self._conn = conn
def create_context(
self,
token_hash: str,
criteria_json: str,
matched_access_point_count: int,
handshake_count: int,
created_at: str,
expires_at: str,
) -> None:
self._conn.execute(
"""
INSERT INTO crack_search_contexts (
token_hash,
criteria_json,
matched_access_point_count,
handshake_count,
created_at,
expires_at
)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
token_hash,
criteria_json,
matched_access_point_count,
handshake_count,
created_at,
expires_at,
),
)
def add_handshakes(
self,
token_hash: str,
handshake_ids: list[int],
) -> None:
self._conn.executemany(
"""
INSERT INTO crack_search_context_handshakes (
token_hash,
handshake_id
)
VALUES (?, ?)
""",
[
(token_hash, handshake_id)
for handshake_id in handshake_ids
],
)
def get_context(
self,
token_hash: str,
) -> sqlite3.Row | None:
return self._conn.execute(
"""
SELECT
id,
token_hash,
criteria_json,
matched_access_point_count,
handshake_count,
created_at,
expires_at
FROM crack_search_contexts
WHERE token_hash = ?
""",
(token_hash,),
).fetchone()
def list_handshake_ids(
self,
token_hash: str,
) -> list[int]:
rows = self._conn.execute(
"""
SELECT handshake_id
FROM crack_search_context_handshakes
WHERE token_hash = ?
ORDER BY handshake_id
""",
(token_hash,),
).fetchall()
return [
int(row["handshake_id"])
for row in rows
]
def delete_expired(
self,
now: str,
) -> int:
cursor = self._conn.execute(
"""
DELETE FROM crack_search_contexts
WHERE expires_at <= ?
""",
(now,),
)
return cursor.rowcount
+3
View File
@@ -1,6 +1,7 @@
from .job_issuance import JobIssuanceService, IssuedJob
from .job_result import JobResultError, JobResultService
from .methods import MethodService, MethodServiceError
from .search_context import SearchContextError, SearchContextService
__all__ = [
"IssuedJob",
@@ -9,4 +10,6 @@ __all__ = [
"JobResultService",
"MethodService",
"MethodServiceError",
"SearchContextError",
"SearchContextService",
]
+9
View File
@@ -95,6 +95,15 @@ class JobExportService:
return value
def format_local_timestamp(self, text: str) -> str:
value = self._parse_utc(text)
local_value = value.astimezone(self._timezone)
return (
local_value.strftime("%Y-%m-%d %H:%M:%S")
+ f" {self._timezone_name}"
)
@staticmethod
def _unique_hash_content(rows) -> tuple[str, int]:
unique_hashes: list[str] = []
+228 -98
View File
@@ -16,7 +16,9 @@ from cracklab.server.services.method_definition import (
MethodDefinitionError,
validate_method_definition,
)
from cracklab.server.services.search_context import (
SearchContextService,
)
class JobIssuanceError(ValueError):
pass
@@ -76,33 +78,55 @@ class JobIssuanceService:
),
}
def get_search_context_statistics(
self,
token_hash: str,
method_id: str,
method_version: int,
) -> dict[str, int]:
row = self._handshakes.get_search_context_statistics(
token_hash,
method_id,
method_version,
)
matched_count = int(row["matched_count"] or 0)
valid_hash_count = int(row["valid_hash_count"] or 0)
found_count = int(row["found_count"] or 0)
covered_count = int(row["covered_count"] or 0)
reserved_count = int(row["reserved_count"] or 0)
return {
"matched_count": matched_count,
"valid_hash_count": valid_hash_count,
"found_count": found_count,
"covered_count": covered_count,
"reserved_count": reserved_count,
"available_count": (
valid_hash_count
- found_count
- covered_count
- reserved_count
),
"unsupported_count": matched_count - valid_hash_count,
}
def issue_job(
self,
method_id: str,
method_version: int,
limit: int | None,
client_id: str | None = None,
handshake_ids: list[int] | tuple[int, ...] | None = None,
) -> IssuedJob | None:
if limit is not None and limit <= 0:
raise ValueError("limit must be greater than zero")
method_version_row = self._methods.get_method_version(
steps = self._prepare_steps(
method_id,
method_version,
)
if method_version_row is None:
raise JobIssuanceError(
f"Method version not found: {method_id} v{method_version}"
)
definition = self._decode_method_definition(
method_version_row["definition_json"],
)
steps = self._build_steps(
method_id,
method_version,
definition,
)
self._conn.execute("BEGIN IMMEDIATE")
@@ -111,101 +135,207 @@ class JobIssuanceService:
method_id,
method_version,
limit,
handshake_ids,
)
if not handshake_rows:
self._conn.rollback()
return None
job_id = f"JOB-{uuid.uuid4().hex[:12].upper()}"
hash_file_name = f"{job_id}.22000"
handshake_ids = tuple(
int(row["handshake_id"])
for row in handshake_rows
return self._issue_job_with_handshakes(
method_id,
method_version,
client_id,
steps,
handshake_rows,
)
unique_hashes: list[str] = []
seen_hashes: set[str] = set()
for row in handshake_rows:
hash22000 = str(row["hash22000"]).strip()
if hash22000 not in seen_hashes:
seen_hashes.add(hash22000)
unique_hashes.append(hash22000)
hash_content = "\n".join(unique_hashes) + "\n"
hash_file_sha256 = hashlib.sha256(
hash_content.encode("utf-8"),
).hexdigest()
created_at = self._jobs.create_job(
job_id=job_id,
method_id=method_id,
method_version=method_version,
status="QUEUED",
hash_file_name=hash_file_name,
hash_file_sha256=hash_file_sha256,
hash_count=len(unique_hashes),
step_count=len(steps),
client_id=client_id,
)
for row in handshake_rows:
self._jobs.add_job_handshake(
job_id=job_id,
handshake_id=int(row["handshake_id"]),
hash22000=str(row["hash22000"]).strip(),
access_point_id=(
int(row["access_point_id"])
if row["access_point_id"] is not None
else None
),
)
self._reservations.create_reservation(
reservation_id=uuid.uuid4().hex,
handshake_id=int(row["handshake_id"]),
method_id=method_id,
method_version=method_version,
job_id=job_id,
client_id=client_id,
)
for step_no, step in enumerate(steps, start=1):
self._jobs.create_job_step(
job_id=job_id,
step_no=step_no,
step_id=step["step_id"],
status="PENDING",
session_name=self._session_name(
job_id,
step["step_id"],
),
definition=step,
)
self._audit.create_event(
event_type="JOB_ISSUED",
job_id=job_id,
client_id=client_id,
method_id=method_id,
method_version=method_version,
details={
"handshake_count": len(handshake_rows),
"hash_count": len(unique_hashes),
"step_count": len(steps),
"hash_file_name": hash_file_name,
},
)
self._conn.commit()
except Exception:
self._conn.rollback()
raise
def issue_job_from_search_context(
self,
token: str,
method_id: str,
method_version: int,
client_id: str | None = None,
) -> IssuedJob | None:
if not isinstance(token, str) or not token:
raise JobIssuanceError(
"Invalid search context token."
)
steps = self._prepare_steps(
method_id,
method_version,
)
token_hash = hashlib.sha256(
token.encode("utf-8"),
).hexdigest()
self._conn.execute("BEGIN IMMEDIATE")
try:
context = SearchContextService(
self._conn,
).get_context(token)
if context is None:
raise JobIssuanceError(
"Search context not found."
)
if context["expired"]:
raise JobIssuanceError(
"Search context expired. Return to Search "
"and export the results again."
)
handshake_rows = (
self._handshakes.list_eligible_for_search_context(
token_hash,
method_id,
method_version,
None,
)
)
if not handshake_rows:
self._conn.rollback()
return None
return self._issue_job_with_handshakes(
method_id,
method_version,
client_id,
steps,
handshake_rows,
)
except Exception:
self._conn.rollback()
raise
def _prepare_steps(
self,
method_id: str,
method_version: int,
) -> list[dict[str, Any]]:
method_version_row = self._methods.get_method_version(
method_id,
method_version,
)
if method_version_row is None:
raise JobIssuanceError(
f"Method version not found: {method_id} v{method_version}"
)
definition = self._decode_method_definition(
method_version_row["definition_json"],
)
return self._build_steps(
method_id,
method_version,
definition,
)
def _issue_job_with_handshakes(
self,
method_id: str,
method_version: int,
client_id: str | None,
steps: list[dict[str, Any]],
handshake_rows: list[sqlite3.Row],
) -> IssuedJob:
job_id = f"JOB-{uuid.uuid4().hex[:12].upper()}"
hash_file_name = f"{job_id}.22000"
handshake_ids = tuple(
int(row["handshake_id"])
for row in handshake_rows
)
unique_hashes: list[str] = []
seen_hashes: set[str] = set()
for row in handshake_rows:
hash22000 = str(row["hash22000"]).strip()
if hash22000 not in seen_hashes:
seen_hashes.add(hash22000)
unique_hashes.append(hash22000)
hash_content = "\n".join(unique_hashes) + "\n"
hash_file_sha256 = hashlib.sha256(
hash_content.encode("utf-8"),
).hexdigest()
created_at = self._jobs.create_job(
job_id=job_id,
method_id=method_id,
method_version=method_version,
status="QUEUED",
hash_file_name=hash_file_name,
hash_file_sha256=hash_file_sha256,
hash_count=len(unique_hashes),
step_count=len(steps),
client_id=client_id,
)
for row in handshake_rows:
self._jobs.add_job_handshake(
job_id=job_id,
handshake_id=int(row["handshake_id"]),
hash22000=str(row["hash22000"]).strip(),
access_point_id=(
int(row["access_point_id"])
if row["access_point_id"] is not None
else None
),
)
self._reservations.create_reservation(
reservation_id=uuid.uuid4().hex,
handshake_id=int(row["handshake_id"]),
method_id=method_id,
method_version=method_version,
job_id=job_id,
client_id=client_id,
)
for step_no, step in enumerate(steps, start=1):
self._jobs.create_job_step(
job_id=job_id,
step_no=step_no,
step_id=step["step_id"],
status="PENDING",
session_name=self._session_name(
job_id,
step["step_id"],
),
definition=step,
)
self._audit.create_event(
event_type="JOB_ISSUED",
job_id=job_id,
client_id=client_id,
method_id=method_id,
method_version=method_version,
details={
"handshake_count": len(handshake_rows),
"hash_count": len(unique_hashes),
"step_count": len(steps),
"hash_file_name": hash_file_name,
},
)
self._conn.commit()
return IssuedJob(
job_id=job_id,
method_id=method_id,
+212
View File
@@ -0,0 +1,212 @@
from __future__ import annotations
import hashlib
import json
import secrets
import sqlite3
from datetime import datetime, timedelta, timezone
from typing import Any
from cracklab.server.repositories.search_contexts import (
SearchContextsRepository,
)
SEARCH_CONTEXT_TTL = timedelta(hours=2)
class SearchContextError(ValueError):
pass
class SearchContextService:
def __init__(self, conn: sqlite3.Connection) -> None:
self._conn = conn
self._repository = SearchContextsRepository(conn)
@staticmethod
def _utc_now() -> datetime:
return datetime.now(timezone.utc)
@staticmethod
def _format_datetime(value: datetime) -> str:
return value.isoformat(
timespec="seconds",
).replace("+00:00", "Z")
@staticmethod
def _token_hash(token: str) -> str:
return hashlib.sha256(
token.encode("utf-8"),
).hexdigest()
@staticmethod
def _normalize_handshake_ids(
handshake_ids: list[int] | tuple[int, ...],
) -> list[int]:
if not isinstance(handshake_ids, (list, tuple)):
raise SearchContextError(
"Invalid handshake ID collection."
)
normalized: set[int] = set()
for handshake_id in handshake_ids:
if (
isinstance(handshake_id, bool)
or not isinstance(handshake_id, int)
or handshake_id <= 0
):
raise SearchContextError(
"Invalid handshake ID."
)
normalized.add(handshake_id)
return sorted(normalized)
def create_context(
self,
criteria: dict[str, Any],
handshake_ids: list[int] | tuple[int, ...],
matched_access_point_count: int,
) -> dict[str, Any]:
if not isinstance(criteria, dict) or not criteria:
raise SearchContextError(
"Search criteria are required."
)
if (
isinstance(matched_access_point_count, bool)
or not isinstance(matched_access_point_count, int)
or matched_access_point_count < 0
):
raise SearchContextError(
"Invalid matched access point count."
)
normalized_ids = self._normalize_handshake_ids(
handshake_ids,
)
try:
criteria_json = json.dumps(
criteria,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
)
except (TypeError, ValueError) as exc:
raise SearchContextError(
"Search criteria cannot be serialized."
) from exc
token = secrets.token_urlsafe(32)
token_hash = self._token_hash(token)
now = self._utc_now()
created_at = self._format_datetime(now)
expires_at = self._format_datetime(
now + SEARCH_CONTEXT_TTL,
)
self._conn.execute("BEGIN IMMEDIATE")
try:
self._repository.create_context(
token_hash=token_hash,
criteria_json=criteria_json,
matched_access_point_count=(
matched_access_point_count
),
handshake_count=len(normalized_ids),
created_at=created_at,
expires_at=expires_at,
)
self._repository.add_handshakes(
token_hash,
normalized_ids,
)
self._conn.commit()
except Exception:
self._conn.rollback()
raise
return {
"token": token,
"created_at": created_at,
"expires_at": expires_at,
"matched_access_point_count": (
matched_access_point_count
),
"handshake_count": len(normalized_ids),
}
def get_context(
self,
token: str,
) -> dict[str, Any] | None:
if not isinstance(token, str) or not token:
return None
token_hash = self._token_hash(token)
row = self._repository.get_context(
token_hash,
)
if row is None:
return None
now = self._format_datetime(
self._utc_now(),
)
return {
"id": int(row["id"]),
"token_hash": row["token_hash"],
"criteria": json.loads(row["criteria_json"]),
"matched_access_point_count": int(
row["matched_access_point_count"]
),
"handshake_count": int(row["handshake_count"]),
"created_at": row["created_at"],
"expires_at": row["expires_at"],
"expired": row["expires_at"] <= now,
}
def list_handshake_ids(
self,
token: str,
) -> list[int]:
if not isinstance(token, str) or not token:
raise SearchContextError(
"Invalid search context token."
)
return self._repository.list_handshake_ids(
self._token_hash(token),
)
def delete_expired(self) -> int:
now = self._format_datetime(
self._utc_now(),
)
self._conn.execute("BEGIN IMMEDIATE")
try:
deleted = self._repository.delete_expired(
now,
)
self._conn.commit()
except Exception:
self._conn.rollback()
raise
return deleted
+83 -17
View File
@@ -21,6 +21,7 @@ from cracklab.server.services.job_issuance import (
JobIssuanceError,
JobIssuanceService,
)
from cracklab.server.services.search_context import SearchContextService
from cracklab.server.services.job_result import (
JobResultError,
JobResultService,
@@ -88,6 +89,13 @@ def dashboard():
def jobs_page():
error = request.args.get("error")
created_job_id = request.args.get("created")
search_context_token = request.values.get(
"search_context_token",
"",
).strip()
search_context = None
search_statistics = None
conn = connect_database()
@@ -138,6 +146,32 @@ def jobs_page():
except ValueError:
selected_version = None
if search_context_token:
search_context = SearchContextService(conn).get_context(
search_context_token,
)
if search_context is not None:
search_context["expires_at_local"] = (
JobExportService(conn).format_local_timestamp(
search_context["expires_at"]
)
)
if (
search_context is not None
and not search_context["expired"]
and selected_method_id
and selected_version is not None
):
search_statistics = (
issuance_service.get_search_context_statistics(
search_context["token_hash"],
selected_method_id,
selected_version,
)
)
if request.method == "POST":
if not selected_method_id:
raise JobIssuanceError(
@@ -154,28 +188,53 @@ def jobs_page():
"limited",
)
if issue_mode == "all":
limit = None
else:
limit_raw = request.form.get(
"limit",
"100",
).strip()
if issue_mode == "search":
try:
limit = int(limit_raw)
except ValueError as exc:
if not search_context_token:
raise JobIssuanceError(
"Количество handshakes должно быть целым числом."
) from exc
"Search context is missing. Return to Search "
"and export the results again."
)
issued_job = issuance_service.issue_job(
method_id=selected_method_id,
method_version=selected_version,
limit=limit,
)
issued_job = (
issuance_service.issue_job_from_search_context(
token=search_context_token,
method_id=selected_method_id,
method_version=selected_version,
)
)
else:
if issue_mode == "all":
limit = None
else:
limit_raw = request.form.get(
"limit",
"100",
).strip()
try:
limit = int(limit_raw)
except ValueError as exc:
raise JobIssuanceError(
"Количество handshakes должно быть целым числом."
) from exc
issued_job = issuance_service.issue_job(
method_id=selected_method_id,
method_version=selected_version,
limit=limit,
)
if issued_job is None:
if issue_mode == "search":
raise JobIssuanceError(
"No handshakes from Search results are available "
"for the selected method and version."
)
raise JobIssuanceError(
"Нет handshakes, доступных для нового job."
)
@@ -186,6 +245,7 @@ def jobs_page():
method_id=selected_method_id,
method_version=selected_version,
created=issued_job.job_id,
search_context_token=search_context_token or None,
)
)
@@ -231,6 +291,9 @@ def jobs_page():
method_names=method_names,
created_job_id=created_job_id,
error=error,
search_context_token=search_context_token,
search_context=search_context,
search_statistics=search_statistics,
)
except (JobIssuanceError, ValueError) as exc:
@@ -278,6 +341,9 @@ def jobs_page():
method_names=method_names,
created_job_id=created_job_id,
error=error,
search_context_token=search_context_token,
search_context=search_context,
search_statistics=search_statistics,
)
finally:
+117 -1
View File
@@ -243,6 +243,17 @@ a:hover {
padding: 30px;
}
.page-section {
margin-bottom: 8px;
color: var(--muted);
font-size: 18px;
font-weight: 600;
letter-spacing: 0.8px;
text-transform: uppercase;
}
.page-title {
margin-top: 0;
@@ -857,6 +868,7 @@ a:hover {
.jobs-stats-grid {
margin-top: 20px;
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 1px;
@@ -883,7 +895,7 @@ a:hover {
}
.jobs-stats-grid .stat-title {
font-size: 12px;
font-size: 14px;
}
.stat-card {
@@ -1193,3 +1205,107 @@ tbody tr:hover {
}
}
#selected-method-label {
margin-left: 12px;
font-size: 20px;
font-weight: 700;
}
.jobs-form-row > label[for="method_id"],
.jobs-form-row > label[for="limit"] {
font-size: 20px;
}
.jobs-method-field {
display: flex;
flex-direction: column;
gap: 7px;
}
.jobs-method-field label {
color: var(--muted);
font-size: 20px;
font-weight: 700;
letter-spacing: 0.4px;
}
.jobs-method-field input,
.jobs-method-field select {
width: 100%;
padding: 11px 12px;
border: 1px solid var(--border);
border-radius: 7px;
background: var(--terminal);
color: var(--text);
font: inherit;
outline: none;
}
.jobs-method-field input:focus,
.jobs-method-field select:focus {
border-color: var(--accent);
}
.jobs-new-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: 24px;
align-items: start;
}
.jobs-method-column,
.jobs-issue-column {
min-width: 0;
}
.jobs-method-column .jobs-form,
.jobs-issue-column .jobs-form {
display: flex;
flex-direction: column;
gap: 14px;
}
#selected-method-label {
display: block;
margin-left: 0;
overflow-wrap: anywhere;
}
.jobs-action-button {
display: block;
width: 100%;
box-sizing: border-box;
text-align: center;
}
.jobs-stats-section {
margin-top: 28px;
}
.jobs-stats-section h3 {
margin-bottom: 0;
}
.jobs-stats-section .jobs-stats-grid {
margin-top: 16px;
margin-bottom: 0;
}
@media (max-width: 768px) {
.jobs-new-layout {
grid-template-columns: minmax(0, 1fr);
gap: 24px;
}
}
.jobs-search-stats-grid {
grid-template-columns: repeat(7, minmax(0, 1fr));
}
@media (max-width: 1100px) {
.jobs-search-stats-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
+11 -1
View File
@@ -29,7 +29,7 @@
<a
class="cracklab-brand"
href="{{ url_for('cracklab.dashboard') }}"
href="{{ url_for('index') }}"
>
<span class="cracklab-brand-title">
WiFi GPS Mapper
@@ -42,6 +42,12 @@
<nav class="cracklab-nav">
<a
href="{{ url_for('reports_dashboard') }}"
>
Reports
</a>
<a
class="{% if active_page == 'dashboard' %}active{% endif %}"
href="{{ url_for('cracklab.dashboard') }}"
@@ -85,6 +91,10 @@
<main class="cracklab-content">
<div class="page-section">
CrackLab
</div>
{% block content %}
{% endblock %}
+1 -1
View File
@@ -7,7 +7,7 @@
{% block content %}
<h1 class="page-title">
CrackLab
Dashboard
</h1>
<div class="page-description">
+249 -80
View File
@@ -5,13 +5,11 @@
{% block content %}
<div class="jobs-page">
<div class="jobs-page-header">
<div>
<h1 class="page-title">Jobs</h1>
<p class="page-description">
Формирование заданий для CrackLab-клиентов.
</p>
</div>
<div>
<h1 class="page-title">Jobs</h1>
<p class="page-description">
Формирование заданий для CrackLab-клиентов.
</p>
</div>
{% if error %}
@@ -63,46 +61,111 @@
<h2>New Job</h2>
<form method="get" class="jobs-form">
<div class="jobs-form-row">
<label for="method_id">Method</label>
<div class="jobs-new-layout">
<div class="jobs-method-column">
<form method="get" class="jobs-form">
<div class="jobs-method-field">
<label for="method_id">Method</label>
<select
id="method_id"
name="method_id"
>
{% for method in methods %}
{% for version in method_versions[method["id"]] %}
<option
value="{{ method["id"] }}"
data-version="{{ version["version"] }}"
{% if selected_method_id == method["id"] and selected_version == version["version"] %}selected{% endif %}
>
{{ method["name"] }} — v{{ version["version"] }}
</option>
{% endfor %}
{% endfor %}
</select>
<select
id="method_id"
name="method_id"
>
{% for method in methods %}
{% for version in method_versions[method["id"]] %}
<option
value="{{ method["id"] }}"
data-version="{{ version["version"] }}"
{% if selected_method_id == method["id"] and selected_version == version["version"] %}selected{% endif %}
>
{{ method["name"] }} — v{{ version["version"] }}
</option>
{% endfor %}
{% endfor %}
</select>
</div>
<input
type="hidden"
name="method_version"
id="method_version"
value="{{ selected_version or '' }}"
>
<span id="selected-method-label"></span>
<button
type="submit"
class="methods-button"
>
Show Statistics
</button>
<input
type="hidden"
name="method_version"
id="method_version"
value="{{ selected_version or '' }}"
>
{% if search_context_token %}
<input
type="hidden"
name="search_context_token"
value="{{ search_context_token }}"
>
{% endif %}
</form>
</div>
</form>
<div class="jobs-issue-column">
<h3>Standard issuance</h3>
<p class="page-description">
Выдача доступных рукопожатий из всей базы CrackLab.
</p>
<form method="post" class="jobs-form">
<input
type="hidden"
name="method_id"
value="{{ selected_method_id }}"
>
<input
type="hidden"
name="method_version"
value="{{ selected_version or '' }}"
>
{% if search_context_token %}
<input
type="hidden"
name="search_context_token"
value="{{ search_context_token }}"
>
{% endif %}
<div class="jobs-method-field">
<label for="limit">Handshakes in job</label>
<input
id="limit"
name="limit"
type="number"
min="1"
value="{{ request.form.get('limit', 100) }}"
>
</div>
<button
type="submit"
name="issue_mode"
value="limited"
class="methods-button jobs-action-button"
>
Form Job
</button>
<button
type="submit"
name="issue_mode"
value="all"
class="methods-button-secondary jobs-action-button"
>
Issue All Available
</button>
</form>
</div>
</div>
{% if statistics %}
<div class="jobs-stats-section">
<h3>Selected Method Statistics</h3>
{% if statistics %}
<div class="jobs-stats-grid">
<div class="jobs-stat-item">
<div class="stat-value">{{ statistics["total_count"] }}</div>
@@ -129,52 +192,158 @@
<div class="stat-title">Available</div>
</div>
</div>
{% endif %}
</div>
{% endif %}
{% if search_context_token %}
<div class="jobs-stats-section">
<h3>Search Results</h3>
<form method="post" class="jobs-form">
<input
type="hidden"
name="method_id"
value="{{ selected_method_id }}"
>
{% if search_context is none %}
<div class="jobs-message jobs-message-error">
Поисковый контекст не найден или недействителен.
Вернитесь в Search и выполните экспорт заново.
</div>
<input
type="hidden"
name="method_version"
value="{{ selected_version or '' }}"
>
{% elif search_context["expired"] %}
<div class="jobs-message jobs-message-error">
Поисковый контекст истёк.
Вернитесь в Search, повторите поиск и экспортируйте
результаты заново.
</div>
<div class="jobs-form-row">
<label for="limit">Handshakes in job</label>
{% else %}
<p class="page-description">
Источник: результаты поиска WiFi GPS Mapper.
Контекст действителен до
{{ search_context["expires_at_local"] }}.
</p>
<input
id="limit"
name="limit"
type="number"
min="1"
value="{{ request.form.get('limit', 100) }}"
>
{% if search_statistics %}
<div class="jobs-stats-grid jobs-search-stats-grid">
<div class="jobs-stat-item">
<div class="stat-value">
{{ search_statistics["matched_count"] }}
</div>
<div class="stat-title">
Handshakes found by Search
</div>
</div>
<button
type="submit"
name="issue_mode"
value="limited"
class="methods-button"
>
Form Job
</button>
<div class="jobs-stat-item">
<div class="stat-value">
{{ search_statistics["available_count"] }}
</div>
<div class="stat-title">
Available
</div>
</div>
<div class="jobs-stat-item">
<div class="stat-value">
{{ search_statistics["matched_count"] - search_statistics["available_count"] }}
</div>
<div class="stat-title">
Skipped
</div>
</div>
<div class="jobs-stat-item">
<div class="stat-value">
{{ search_statistics["found_count"] }}
</div>
<div class="stat-title">
Password Found
</div>
</div>
<div class="jobs-stat-item">
<div class="stat-value">
{{ search_statistics["covered_count"] }}
</div>
<div class="stat-title">
Already Completed
</div>
</div>
<div class="jobs-stat-item">
<div class="stat-value">
{{ search_statistics["reserved_count"] }}
</div>
<div class="stat-title">
Reserved
</div>
</div>
<div class="jobs-stat-item">
<div class="stat-value">
{{ search_statistics["unsupported_count"] }}
</div>
<div class="stat-title">
Unsupported Hash
</div>
</div>
</div>
{% endif %}
<form method="post" class="jobs-form">
<input
type="hidden"
name="method_id"
value="{{ selected_method_id }}"
>
<input
type="hidden"
name="method_version"
value="{{ selected_version or '' }}"
>
<input
type="hidden"
name="search_context_token"
value="{{ search_context_token }}"
>
<button
type="submit"
name="issue_mode"
value="search"
class="methods-button jobs-action-button"
{% if not search_statistics or search_statistics["available_count"] <= 0 %}disabled{% endif %}
>
Form Job from Search
</button>
</form>
{% endif %}
</div>
{% endif %}
<script>
document.addEventListener("DOMContentLoaded", function () {
const methodSelect = document.getElementById("method_id");
const versionInput = document.getElementById("method_version");
const selectedMethodLabel = document.getElementById("selected-method-label");
if (!methodSelect || !versionInput || !selectedMethodLabel) {
return;
}
const updateSelectedMethodLabel = function () {
const selectedOption = methodSelect.options[methodSelect.selectedIndex];
versionInput.value = selectedOption.dataset.version || "";
selectedMethodLabel.textContent =
"Selected: " + selectedOption.textContent.trim();
};
updateSelectedMethodLabel();
methodSelect.addEventListener("change", function () {
updateSelectedMethodLabel();
methodSelect.form.requestSubmit();
});
});
</script>
<button
type="submit"
name="issue_mode"
value="all"
class="methods-button-secondary"
>
Issue All Available
</button>
</div>
</form>
</div>
<div class="card">
@@ -206,7 +375,7 @@
</td>
<td>{{ job["hash_count"] }}</td>
<td>{{ job["handshake_count"] }}</td>
<td>{{ job["created_at"] }}</td>
<td>{{ job["created_at"]|local_datetime }}</td>
<td>
<span class="badge badge-{{ job["status"]|lower }}">
{{ job["status"] }}
+1 -1
View File
@@ -87,7 +87,7 @@
<span>Created</span>
<strong>
{{ method.created_at }}
{{ method.created_at|local_datetime }}
</strong>
</div>
+7 -9
View File
@@ -5,13 +5,11 @@
{% block content %}
<div class="results-page">
<div class="jobs-page-header">
<div>
<h1 class="page-title">Results</h1>
<p class="page-description">
Import completed results from CrackLab clients and review import history.
</p>
</div>
<div>
<h1 class="page-title">Results</h1>
<p class="page-description">
Import completed results from CrackLab clients and review import history.
</p>
</div>
{% if error %}
@@ -71,7 +69,7 @@
<tr>
<th>Job ID</th>
<th>Status</th>
<th>Imported At (UTC)</th>
<th>Imported At</th>
</tr>
</thead>
<tbody>
@@ -83,7 +81,7 @@
{{ result["status"] }}
</span>
</td>
<td>{{ result["imported_at"] }}</td>
<td>{{ result["imported_at"]|local_datetime }}</td>
</tr>
{% endfor %}
</tbody>
+1448 -408
View File
File diff suppressed because it is too large Load Diff
+81
View File
@@ -0,0 +1,81 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ status_code }} — {{ title }} | WiFi GPS Mapper</title>
<link
rel="stylesheet"
href="{{ url_for('static', filename='style.css') }}"
>
<style>
.error-page {
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
}
.error-card {
width: min(100%, 620px);
padding: 36px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
text-align: center;
}
.error-code {
margin: 0 0 18px;
color: var(--accent);
font-size: clamp(48px, 10vw, 88px);
line-height: 1;
}
.error-title {
margin: 0 0 12px;
font-size: clamp(24px, 4vw, 32px);
}
.error-message {
margin: 0 0 28px;
color: var(--muted);
}
.error-home {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 10px 18px;
border-radius: 5px;
background: var(--green);
color: var(--bg);
text-decoration: none;
font-weight: 700;
}
.error-home:hover {
filter: brightness(1.08);
}
</style>
</head>
<body>
<main class="error-page">
<section class="error-card">
<p class="error-code">{{ status_code }}</p>
<h1 class="error-title">{{ title }}</h1>
<p class="error-message">{{ message }}</p>
<a
class="error-home"
href="{{ url_for('index') }}"
>Вернуться на главную</a>
</section>
</main>
</body>
</html>
+21 -4
View File
@@ -46,6 +46,13 @@
REPORTS
</a>
<a
class="header-link"
href="{{ url_for('cracklab.dashboard') }}"
>
CRACKLAB
</a>
<div class="header-scanner-controls">
@@ -740,14 +747,24 @@
Timezone
</label>
<input
<select
id="timezone"
type="text"
value="{{ config.timezone }}"
placeholder="Europe/Moscow"
required
>
{% for timezone in timezone_options %}
<option
value="{{ timezone.value }}"
{% if timezone.value == config.timezone %}selected{% endif %}
>
{{ timezone.label }}
</option>
{% endfor %}
</select>
<div class="config-help">
IANA часовой пояс для отображения времени в UI и отчетах.
В базе данных и обменных файлах время всегда хранится в UTC.
+98
View File
@@ -0,0 +1,98 @@
from datetime import datetime
from zoneinfo import ZoneInfo
TIMEZONES = (
"Pacific/Honolulu",
"America/Anchorage",
"America/Los_Angeles",
"America/Denver",
"America/Chicago",
"America/New_York",
"America/St_Johns",
"America/Sao_Paulo",
"Atlantic/Azores",
"Europe/London",
"Europe/Berlin",
"Europe/Kaliningrad",
"Europe/Moscow",
"Europe/Samara",
"Asia/Yekaterinburg",
"Asia/Omsk",
"Asia/Novosibirsk",
"Asia/Krasnoyarsk",
"Asia/Irkutsk",
"Asia/Yakutsk",
"Asia/Vladivostok",
"Asia/Sakhalin",
"Asia/Magadan",
"Asia/Srednekolymsk",
"Asia/Kamchatka",
"Asia/Dubai",
"Asia/Kolkata",
"Asia/Kathmandu",
"Asia/Dhaka",
"Asia/Bangkok",
"Asia/Shanghai",
"Asia/Tokyo",
"Australia/Adelaide",
"Australia/Sydney",
"Pacific/Chatham",
"Pacific/Auckland",
"Pacific/Kiritimati",
"Etc/UTC",
)
def get_timezone_options(current_timezone):
timezones = list(TIMEZONES)
if current_timezone not in timezones:
timezones.append(current_timezone)
options = []
for timezone_name in timezones:
try:
timezone = ZoneInfo(timezone_name)
offset = datetime.now(
timezone
).utcoffset()
total_minutes = int(
offset.total_seconds() // 60
)
sign = "+" if total_minutes >= 0 else "-"
hours, minutes = divmod(
abs(total_minutes),
60
)
options.append(
{
"value": timezone_name,
"label": (
f"{timezone_name} "
f"UTC{sign}{hours:02d}:{minutes:02d}"
),
"offset": total_minutes
}
)
except Exception:
continue
options.sort(
key=lambda item: (
item["offset"],
item["value"]
)
)
return options
+241 -60
View File
@@ -7,12 +7,12 @@ from reports.template import (
card,
page_begin,
page_end,
page_header,
)
from reports.utils import (
format_datetime as format_report_datetime,
)
from reports.map_popups import build_standard_popup
from reports.map_service import get_map_style_url
def esc(value):
@@ -76,6 +76,7 @@ def load_access_points(conn):
WITH ranked_observations AS (
SELECT
obs.access_point_id,
obs.session_id,
obs.latitude,
obs.longitude,
obs.observed_at,
@@ -99,23 +100,18 @@ def load_access_points(conn):
ap.bssid,
ap.essid,
ap.vendor,
ap.encryption,
ap.cipher,
ap.akm,
ap.has_handshake,
ap.has_pmkid,
ap.is_cracked,
obs.latitude,
obs.longitude,
obs.session_id,
obs.observed_at,
obs.rssi,
obs.channel,
(
SELECT c.password
FROM credentials AS c
WHERE c.access_point_id = ap.id
ORDER BY
c.created_at DESC,
c.id DESC
LIMIT 1
) AS password
obs.channel
FROM access_points AS ap
JOIN ranked_observations AS obs
ON obs.access_point_id = ap.id
@@ -126,7 +122,135 @@ def load_access_points(conn):
""",
)
return rows
if not rows:
return []
credentials = query_all(
conn,
"""
WITH latest_observations AS (
SELECT
obs.access_point_id,
ROW_NUMBER() OVER (
PARTITION BY obs.access_point_id
ORDER BY
obs.observed_at DESC,
obs.id DESC
) AS rn
FROM access_point_observations AS obs
WHERE
obs.latitude IS NOT NULL
AND obs.longitude IS NOT NULL
AND obs.latitude != 0
AND obs.longitude != 0
)
SELECT
c.access_point_id,
c.password,
c.source,
c.verified
FROM credentials AS c
JOIN latest_observations AS obs
ON obs.access_point_id = c.access_point_id
AND obs.rn = 1
ORDER BY
c.created_at DESC,
c.id DESC
""",
)
credentials_by_ap = {}
for credential in credentials:
access_point_id = credential["access_point_id"]
credentials_by_ap.setdefault(
access_point_id,
[],
).append({
"password": credential["password"],
"source": credential["source"],
"verified": credential["verified"],
})
handshakes = query_all(
conn,
"""
WITH ranked_observations AS (
SELECT
obs.access_point_id,
obs.session_id,
ROW_NUMBER() OVER (
PARTITION BY obs.access_point_id
ORDER BY
obs.observed_at DESC,
obs.id DESC
) AS rn
FROM access_point_observations AS obs
WHERE
obs.latitude IS NOT NULL
AND obs.longitude IS NOT NULL
AND obs.latitude != 0
AND obs.longitude != 0
)
SELECT
hs.access_point_id,
hs.session_id,
hs.type,
hs.captured_at
FROM handshakes AS hs
JOIN ranked_observations AS obs
ON obs.access_point_id = hs.access_point_id
AND obs.session_id = hs.session_id
AND obs.rn = 1
ORDER BY
hs.captured_at DESC,
hs.id DESC
""",
)
handshakes_by_ap_session = {}
for handshake in handshakes:
key = (
handshake["access_point_id"],
handshake["session_id"],
)
handshakes_by_ap_session.setdefault(
key,
[],
).append({
"type": handshake["type"],
"captured_at": handshake["captured_at"],
})
observations = []
for row in rows:
observation = dict(row)
access_point_id = observation["id"]
session_id = observation["session_id"]
observation["passwords"] = credentials_by_ap.get(
access_point_id,
[],
)
observation["handshakes"] = (
handshakes_by_ap_session.get(
(access_point_id, session_id),
[],
)
)
observations.append(observation)
return observations
def build_marker_js(observations):
@@ -135,6 +259,7 @@ def build_marker_js(observations):
handshake_features = []
pmkid_features = []
password_features = []
open_features = []
for row in observations:
@@ -147,50 +272,25 @@ def build_marker_js(observations):
):
continue
ssid = (
row["essid"]
if row["essid"] is not None
and str(row["essid"]) != ""
else "—"
)
vendor = (
row["vendor"]
if row["vendor"] is not None
and str(row["vendor"]) != ""
else "—"
)
channel = (
row["channel"]
if row["channel"] is not None
else "—"
)
rssi = (
f"{row['rssi']} dBm"
if row["rssi"] is not None
else "—"
)
password = (
row["password"]
if row["password"] is not None
and str(row["password"]) != ""
else "—"
)
popup = (
f"<b>{esc(ssid)}</b>"
f"<br>MAC: {esc(row['bssid'])}"
f"<br>Vendor: {esc(vendor)}"
f"<br>Channel: {esc(channel)}"
f"<br>RSSI: {esc(rssi)}"
f"<br>Password: {esc(password)}"
f"<br>Date: "
f"{esc(format_popup_datetime(row['observed_at']))}"
f'<br><a href="/reports/access-points/{esc(row["bssid"])}">'
f"Подробнее</a>"
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=latitude,
longitude=longitude,
access_point_url=(
f"/reports/access-points/{row['bssid']}"
),
)
feature = {
@@ -219,11 +319,19 @@ def build_marker_js(observations):
feature
)
if row["is_cracked"] or row["password"]:
if row["is_cracked"] or row["passwords"]:
password_features.append(
feature
)
if (
str(row["encryption"] or "").strip().upper()
== "OPEN"
):
open_features.append(
feature
)
return (
"const apFeatures = "
+ json.dumps(
@@ -249,6 +357,13 @@ def build_marker_js(observations):
ensure_ascii=False,
)
+ ";\n"
+ "const openFeatures = "
+ json.dumps(
open_features,
ensure_ascii=False,
)
+ ";\n"
)
@@ -294,7 +409,7 @@ const map = new maplibregl.Map({
container: "map",
style:
"http://127.0.0.1:8080/styles/server-map/style.json",
__MAP_STYLE_URL__,
center: [
30.32,
@@ -338,6 +453,7 @@ const layerState = {
handshake: true,
password: true,
open: true,
all: false
};
@@ -408,6 +524,10 @@ map.on(
passwordFeatures
);
createSource(
"open-aps",
openFeatures
);
// ==================================================
// All AP clusters
@@ -646,6 +766,38 @@ map.on(
});
// ==================================================
// Open AP points
// ==================================================
map.addLayer({
id: "open-ap-points",
type: "circle",
source: "open-aps",
layout: {
visibility:
layerState.open
? "visible"
: "none"
},
paint: {
"circle-radius": 7,
"circle-color": "#AB47BC",
"circle-stroke-color": "#ffffff",
"circle-stroke-width": 1.5
}
});
// ==================================================
// Popups
@@ -659,7 +811,9 @@ map.on(
"pmkid-points",
"password-points"
"password-points",
"open-ap-points"
];
@@ -915,6 +1069,15 @@ map.on(
}
if(layer === "open")
{
setLayerVisibility(
[
"open-ap-points"
],
input.checked
);
}
if(layer === "all")
{
@@ -1019,6 +1182,11 @@ window.setTimeout(
marker_js,
)
map_html = map_html.replace(
"__MAP_STYLE_URL__",
json.dumps(get_map_style_url()),
)
return map_html
@@ -1044,6 +1212,7 @@ def render_access_points_page(
"📡 Access Points",
active="access_points",
context=context,
section_title="Reports",
)
html += f"""
@@ -1091,6 +1260,18 @@ Time interval:
Password
</label>
<label>
<input
type="checkbox"
data-layer="open"
checked
>
<span
class="map-layer-dot map-layer-dot-open"
></span>
Open AP
</label>
<label>
<input
type="checkbox"
+587 -43
View File
@@ -6,6 +6,7 @@ from collections import defaultdict
from reports.database import query_all, query_one
from reports.utils import (
format_datetime as format_report_datetime,
haversine_m,
)
from reports.template import (
@@ -13,9 +14,9 @@ from reports.template import (
card,
page_begin,
page_end,
page_header,
)
from reports.map_popups import build_standard_popup
from reports.map_service import get_map_style_url
def esc(value):
return html.escape("" if value is None else str(value), quote=True)
@@ -53,24 +54,6 @@ def format_speed(value):
return f"{speed:.1f}"
def haversine_m(lat1, lon1, lat2, lon2):
radius = 6371000.0
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lon2 - lon1)
a = (
math.sin(dphi / 2.0) ** 2
+ math.cos(phi1)
* math.cos(phi2)
* math.sin(dlambda / 2.0) ** 2
)
return 2.0 * radius * math.asin(min(1.0, math.sqrt(a)))
def weighted_mean(values):
if not values:
return None
@@ -687,6 +670,25 @@ def load_credentials(conn, access_point_id):
(access_point_id,),
)
def load_handshakes(conn, access_point_id):
return query_all(
conn,
"""
SELECT
session_id,
type,
captured_at
FROM handshakes
WHERE
access_point_id = ?
AND session_id IS NOT NULL
ORDER BY
session_id,
captured_at DESC,
id DESC
""",
(access_point_id,),
)
def security_text(ap):
values = []
@@ -754,6 +756,28 @@ def build_geojson(observations, ellipse=None, zones=None):
"rssi": item["rssi"],
"speed": item["speed"],
"map_status": item.get("map_status", "normal"),
"popup": build_standard_popup(
essid=item["essid"],
bssid=item["bssid"],
vendor=item["vendor"],
encryption=item["encryption"],
cipher=item["cipher"],
akm=item["akm"],
channel=item["channel"],
rssi=item["rssi"],
passwords=item["passwords"],
handshakes=item["handshakes"],
observed_at=format_datetime(
item["observed_at"]
),
latitude=latitude,
longitude=longitude,
session_url=(
f"/reports/session/{item['session_id']}"
if item["session_id"] is not None
else None
),
),
}
features.append(
@@ -909,7 +933,7 @@ def render_map(geojson, context, title):
const map = new maplibregl.Map({{
container: "access-point-history-map",
style: "http://127.0.0.1:8080/styles/server-map/style.json",
style: {json.dumps(get_map_style_url())},
center: [30.32, 59.93],
zoom: 5
}});
@@ -988,15 +1012,7 @@ def render_map(geojson, context, title):
new maplibregl.Popup()
.setLngLat(e.lngLat)
.setHTML(
"<strong>Наблюдение</strong><br>" +
"Дата: " + escapeHtml(p.observed_at) + "<br>" +
"Сессия: <a href=\\"/reports/session/" +
encodeURIComponent(p.session_id) + "\\">" +
escapeHtml(p.session_id) + "</a><br>" +
"RSSI: " + escapeHtml(p.rssi ?? "—") + "<br>" +
"Скорость: " + escapeHtml(p.speed ?? "—")
)
.setHTML(p.popup || "Нет информации")
.addTo(map);
}});
@@ -1091,7 +1107,6 @@ def render_map(geojson, context, title):
</script>
"""
def render_observation_table(observations):
rows = []
@@ -1146,6 +1161,507 @@ def render_observation_table(observations):
</div>
"""
def render_wifi_connection_card(ap, credentials):
is_open = ap["encryption"] == "OPEN"
password_states = {}
for credential in credentials:
password = credential["password"]
if not password:
continue
if password not in password_states:
password_states[password] = bool(
credential["verified"]
)
elif credential["verified"]:
password_states[password] = True
credential_rows = []
for password, verified in password_states.items():
if verified:
verify_button = """
<button
type="button"
class="button"
data-wifi-action="verify"
disabled
>
Проверен
</button>
"""
connect_disabled = ""
status_text = "Пароль успешно проверен"
else:
verify_button = """
<button
type="button"
class="button"
data-wifi-action="verify"
>
Проверить пароль
</button>
"""
connect_disabled = "disabled"
status_text = "Пароль ещё не проверен"
credential_rows.append(
f"""
<div
class="wifi-credential-row"
data-password="{esc(password)}"
data-verified="{str(verified).lower()}"
style="
padding:12px;
margin:10px 0;
border:1px solid var(--border);
border-radius:8px;
"
>
<div style="margin-bottom:10px;">
<strong>Password:</strong>
<code>{esc(password)}</code>
</div>
<div
data-verification-status
style="
margin-bottom:10px;
color:var(--muted);
"
>
{status_text}
</div>
<div style="display:flex;gap:8px;flex-wrap:wrap;">
{verify_button}
<button
type="button"
class="button"
data-wifi-action="connect"
{connect_disabled}
>
Подключиться
</button>
</div>
</div>
"""
)
if is_open:
actions_html = """
<div style="margin-top:12px;">
<p>
Эта точка доступа не использует пароль.
Проверка пароля не требуется.
</p>
<button
type="button"
class="button"
data-wifi-action="connect"
>
Подключиться
</button>
</div>
"""
elif credential_rows:
actions_html = "".join(credential_rows)
else:
actions_html = """
<div style="padding:8px 0;">
В базе данных нет сохранённых паролей для этой точки доступа.
</div>
"""
return card(
"Проверка пароля и подключение",
f"""
<div
id="wifi-connection-controls"
data-bssid="{esc(ap["bssid"])}"
data-open="{str(is_open).lower()}"
>
<div style="margin-bottom:14px;">
<label for="wifi-connection-interface">
<strong>Wi-Fi интерфейс:</strong>
</label>
<select
id="wifi-connection-interface"
class="search"
style="display:block;width:100%;max-width:400px;"
disabled
>
<option value="">Загрузка интерфейсов...</option>
</select>
</div>
<div
id="wifi-connection-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-connection-message"
role="status"
aria-live="polite"
style="margin:12px 0;"
></div>
<div>
{actions_html}
</div>
</div>
<script>
(function() {{
const root = document.getElementById(
"wifi-connection-controls"
);
if (!root) {{
return;
}}
const interfaceSelect = document.getElementById(
"wifi-connection-interface"
);
const message = document.getElementById(
"wifi-connection-message"
);
const warning = document.getElementById(
"wifi-connection-warning"
);
const isOpen = root.dataset.open === "true";
let devices = [];
let busy = false;
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;
}}
function selectedInterface() {{
const device = devices.find(
item => item.device === interfaceSelect.value
);
if (!device || !device.available) {{
return null;
}}
return device.device;
}}
function updateButtons() {{
const interfaceName = selectedInterface();
root.querySelectorAll(
"[data-wifi-action]"
).forEach(button => {{
const action = button.dataset.wifiAction;
const row = button.closest(
".wifi-credential-row"
);
const verified = row
&& row.dataset.verified === "true";
if (busy || !interfaceName) {{
button.disabled = true;
return;
}}
if (action === "verify") {{
button.disabled = verified;
}}
if (action === "connect") {{
button.disabled = !isOpen && !verified;
}}
}});
interfaceSelect.disabled =
busy || devices.filter(device => device.available).length <= 1;
}}
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 интерфейсы."
);
}}
devices = data.devices || [];
const availableDevices = devices.filter(
device => device.available
);
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);
}});
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;
}}
if (!devices.length) {{
setMessage(
data.error || "Wi-Fi интерфейсы не найдены.",
true
);
}} else if (!availableDevices.length) {{
const reasons = devices
.map(device => device.reason)
.filter(Boolean);
setMessage(
reasons.join(" ")
|| "Нет доступных Wi-Fi интерфейсов.",
true
);
}} else if (availableDevices.length > 1) {{
setMessage(
"Выберите интерфейс, через который выполнять операцию."
);
}}
if (data.wireguard_active) {{
setWarning(
"Обнаружено активное соединение WireGuard. "
+ "При необходимости отключите VPN вручную. "
+ "Приложение не изменяет состояние WireGuard."
);
}} else if (data.wireguard_error) {{
setWarning(
"Не удалось проверить состояние WireGuard: "
+ data.wireguard_error
);
}}
updateButtons();
}} catch (error) {{
setMessage(
error.message || "Ошибка получения Wi-Fi интерфейсов.",
true
);
}}
}}
root.addEventListener("change", function(event) {{
if (event.target === interfaceSelect) {{
updateButtons();
}}
}});
root.addEventListener("click", async function(event) {{
const button = event.target.closest(
"[data-wifi-action]"
);
if (!button || busy || button.disabled) {{
return;
}}
const interfaceName = selectedInterface();
if (!interfaceName) {{
setMessage(
"Выберите доступный Wi-Fi интерфейс.",
true
);
return;
}}
const action = button.dataset.wifiAction;
const row = button.closest(
".wifi-credential-row"
);
const password = row
? row.dataset.password
: null;
const endpoint = action === "verify"
? "/api/network/verify"
: "/api/network/connect";
busy = true;
updateButtons();
setMessage(
action === "verify"
? "Выполняется проверка пароля..."
: "Выполняется подключение..."
);
try {{
const response = await fetch(
endpoint,
{{
method: "POST",
headers: {{
"Content-Type": "application/json"
}},
body: JSON.stringify({{
interface: interfaceName,
bssid: root.dataset.bssid,
password: password
}})
}}
);
const data = await response.json();
if (
!response.ok
|| !data.ok
|| data.success === false
) {{
throw new Error(
data.error || "Операция завершилась ошибкой."
);
}}
if (action === "verify") {{
if (!data.verified) {{
throw new Error(
"Сервер не подтвердил проверку пароля."
);
}}
row.dataset.verified = "true";
const status = row.querySelector(
"[data-verification-status]"
);
status.textContent = "Пароль успешно проверен";
status.style.color = "var(--green)";
button.textContent = "Проверен";
setMessage(
"Пароль успешно проверен. Теперь доступно подключение."
);
}} else {{
setMessage(
"Подключение успешно: "
+ (data.ssid || root.dataset.bssid)
);
}}
if (data.wireguard_warning) {{
setWarning(data.wireguard_warning);
}}
}} catch (error) {{
setMessage(
error.message || "Ошибка выполнения операции.",
true
);
}} finally {{
busy = false;
updateButtons();
}}
}});
loadInterfaces();
}})();
</script>
"""
)
def render_access_point_page(
conn,
@@ -1159,14 +1675,11 @@ def render_access_point_page(
if not ap:
page = page_begin(
"Access Point",
active="access_points",
context=context,
)
page += page_header(
"Точка доступа не найдена",
"BSSID: " + esc(bssid),
active="access_points",
context=context,
section_title="Reports",
)
page += card(
@@ -1183,6 +1696,26 @@ def render_access_point_page(
observations_raw = load_observations(conn, ap["id"])
observations = valid_observations(observations_raw)
credentials = load_credentials(conn, ap["id"])
handshakes = load_handshakes(conn, ap["id"])
handshakes_by_session = defaultdict(list)
for handshake in handshakes:
handshakes_by_session[
handshake["session_id"]
].append({
"type": handshake["type"],
"captured_at": handshake["captured_at"],
})
popup_credentials = [
{
"password": credential["password"],
"source": credential["source"],
"verified": credential["verified"],
}
for credential in credentials
]
if ap["is_cracked"]:
map_status = "cracked"
@@ -1195,7 +1728,16 @@ def render_access_point_page(
for item in observations:
map_item = dict(item)
map_item["map_status"] = map_status
map_item["bssid"] = ap["bssid"]
map_item["vendor"] = ap["vendor"]
map_item["passwords"] = popup_credentials
map_item["handshakes"] = handshakes_by_session.get(
item["session_id"],
[],
)
map_observations.append(map_item)
statistics = calculate_statistics(observations_raw)
@@ -1214,14 +1756,11 @@ def render_access_point_page(
)
page = page_begin(
f"AP {ap['bssid']}",
active="access_points",
context=context,
)
page += page_header(
f"📡 {esc(ap['essid'] or 'Access Point')}",
f"BSSID: {esc(ap['bssid'])}",
active="access_points",
context=context,
section_title="Reports",
)
page += f"""
@@ -1399,6 +1938,11 @@ def render_access_point_page(
"""
)
page += render_wifi_connection_card(
ap,
credentials,
)
if estimated_center:
estimated_coordinates = (
f"{estimated_center['latitude']:.6f}, "
+25 -4
View File
@@ -10,6 +10,7 @@
по всему проекту.
"""
from functools import lru_cache
from pathlib import Path
import yaml
@@ -55,10 +56,30 @@ RECENT_SESSIONS_LIMIT = REPORTS_CONFIG.get(
10
)
TIMEZONE = CONFIG.get(
"timezone",
"Europe/Moscow"
)
TIMEZONE = CONFIG.get("timezone", "Europe/Moscow")
@lru_cache(maxsize=1)
def _load_timezone(mtime_ns, size):
with CONFIG_FILE.open("r", encoding="utf-8") as fp:
config = yaml.safe_load(fp) or {}
timezone_name = config.get("timezone", "Europe/Moscow")
if not isinstance(timezone_name, str) or not timezone_name:
return "Europe/Moscow"
return timezone_name
def get_timezone():
try:
stat = CONFIG_FILE.stat()
except OSError:
return "Europe/Moscow"
try:
return _load_timezone(stat.st_mtime_ns, stat.st_size)
except (OSError, yaml.YAMLError):
return TIMEZONE
# ============================================================
# Каталог отчёта
+272 -29
View File
@@ -23,6 +23,7 @@ from .config import (
)
from .utils import (
esc,
format_datetime,
)
@@ -32,8 +33,6 @@ from .template import (
page_end,
page_header,
card,
stat,
@@ -69,7 +68,7 @@ from .sessions import (
# ============================================================
def format_session_folder(capture_file):
if not capture_file:
if not capture_file or not str(capture_file).startswith("captures/"):
return "-"
folder = Path(capture_file).parent.name
@@ -287,7 +286,7 @@ def essid_block(conn):
rows = top_essid(
conn,
limit=20
limit=15
)
html = """
@@ -496,7 +495,17 @@ def session_card(
<tr>
<td><b>Imported</b></td>
<tr>
<td><b>Session origin</b></td>
<td>{session.get("origin", "Unknown")}</td>
</tr>
<tr>
<td><b>Capture started</b></td>
<td>{format_datetime(session.get("start_time"))}</td>
@@ -617,7 +626,7 @@ def sessions_block(
return card(
"🚗 Recent Capture Sessions",
f"🚗 Recent {RECENT_SESSIONS_LIMIT} Sessions",
"""
@@ -679,7 +688,7 @@ Show all sessions
return card(
"🚗 Recent Capture Sessions",
f"🚗 Recent {RECENT_SESSIONS_LIMIT} Sessions",
html,
@@ -695,16 +704,19 @@ def generate_dashboard(
html = page_begin(
title="WiFi GPS Mapper",
title="Dashboard",
description=(
"Database overview"
"Overview of collected Wi-Fi data, access points, "
"capture sessions, and vendors."
),
active="dashboard",
context=context,
section_title="Reports",
)
# --------------------------------------------------------
@@ -803,44 +815,179 @@ def generate_capture_sessions(
html = page_begin(
title="Capture Sessions",
title="🚗 Capture Sessions",
description="All capture sessions",
description=f"""
All capture sessions
<br>
Total sessions: <b>{len(sessions)}</b>
""",
active="capture_sessions",
context=context,
)
section_title="Reports",
html += page_header(
"🚗 Capture Sessions",
f"""
Total sessions:
<b>{len(sessions)}</b>
"""
)
cards = []
for session in sessions:
cards.append(
session_card(
session,
context,
)
session_id = session["id"]
trip_start = session.get("trip_start")
trip_end = session.get("trip_end")
duration_seconds = ""
if trip_start and trip_end:
from .utils import parse_datetime
start = parse_datetime(trip_start)
end = parse_datetime(trip_end)
if start is not None and end is not None:
duration_seconds = max(
0,
int((end - start).total_seconds())
)
distance_m = session.get("distance_m")
distance_html = ""
distance_sort = ""
if distance_m is not None:
distance_sort = str(distance_m)
if distance_m >= 1000:
distance_label = (
f"{distance_m / 1000:.2f} km"
)
else:
distance_label = (
f"{distance_m:.0f} m"
)
distance_html = f"""
<span class="session-compact-stat">
🛣️ <b>Distance:</b> {distance_label}
</span>
"""
trip_start_html = (
format_datetime(trip_start)
if trip_start
else "-"
)
trip_end_html = (
format_datetime(trip_end)
if trip_end
else "-"
)
duration_html = (
esc(session.get("duration"))
if session.get("duration")
else "-"
)
access_points = session.get("access_points", 0)
cards.append(f"""
<article
class="session-compact-card"
data-session-id="{esc(session_id)}"
data-date="{esc(trip_start or "")}"
data-duration="{duration_seconds}"
data-distance="{distance_sort}"
data-access-points="{esc(access_points)}"
>
<div class="session-compact-main">
<div class="session-compact-title">
🚗 Session #{esc(session_id)}
</div>
<div class="session-compact-details">
<span>
<b>Trip start:</b> {trip_start_html}
</span>
<span>
<b>Trip end:</b> {trip_end_html}
</span>
<span>
<b>Duration:</b> {duration_html}
</span>
</div>
<div class="session-compact-stats">
{distance_html}
<span class="session-compact-stat">
📶 <b>Access Points:</b> {esc(access_points)}
</span>
</div>
</div>
<a
class="session-compact-link"
href="{esc(context.session_url(session_id))}"
>
View session →
</a>
</article>
""")
html += """
<div class="report-grid">
<div class="session-list-toolbar">
<label for="session-sort">
Sort by:
</label>
<select id="session-sort">
<option value="date">Date</option>
<option value="duration">Duration</option>
<option value="distance">Distance</option>
<option value="access-points">Access Points</option>
</select>
<button
type="button"
id="session-sort-direction"
aria-label="Reverse sort direction"
title="Reverse sort direction"
>
↓
</button>
</div>
<div
class="session-list"
id="session-list"
data-sort-direction="desc"
>
"""
html += "\n".join(cards)
@@ -849,6 +996,102 @@ Total sessions:
</div>
<script>
(function () {
const list = document.getElementById("session-list");
const sortSelect = document.getElementById("session-sort");
const directionButton = document.getElementById("session-sort-direction");
if (!list || !sortSelect || !directionButton) {
return;
}
let descending = true;
function sortSessions() {
const sortBy = sortSelect.value;
const cards = Array.from(
list.querySelectorAll(".session-compact-card")
);
cards.sort(function (a, b) {
if (sortBy === "distance") {
const missingA = a.dataset.distance === "";
const missingB = b.dataset.distance === "";
if (missingA !== missingB) {
return missingA ? 1 : -1;
}
}
let valueA;
let valueB;
if (sortBy === "date") {
valueA = Date.parse(a.dataset.date) || 0;
valueB = Date.parse(b.dataset.date) || 0;
} else if (sortBy === "duration") {
valueA = Number(a.dataset.duration) || 0;
valueB = Number(b.dataset.duration) || 0;
} else if (sortBy === "distance") {
valueA = Number(a.dataset.distance) || 0;
valueB = Number(b.dataset.distance) || 0;
} else {
valueA = Number(a.dataset.accessPoints) || 0;
valueB = Number(b.dataset.accessPoints) || 0;
}
if (valueA === valueB) {
return Number(a.dataset.sessionId)
- Number(b.dataset.sessionId);
}
const result = valueA - valueB;
return descending ? -result : result;
});
cards.forEach(function (card) {
list.appendChild(card);
});
directionButton.textContent = descending ? "↓" : "↑";
list.dataset.sortDirection = descending ? "desc" : "asc";
}
sortSelect.addEventListener("change", function () {
descending = true;
sortSessions();
});
directionButton.addEventListener("click", function () {
descending = !descending;
sortSessions();
});
sortSessions();
})();
</script>
"""
html += page_end()
+2 -1
View File
@@ -53,7 +53,8 @@ def render_hashcat_page(
"hashcat --show."
),
"hashcat",
context
context,
section_title="Reports",
)
if message:
-1
View File
@@ -253,4 +253,3 @@ def main():
if __name__ == "__main__":
main()
+265
View File
@@ -0,0 +1,265 @@
import html
def escape_html(value):
if value is None:
return "—"
return html.escape(
str(value),
quote=True,
)
def display_value(value):
if value is None or str(value).strip() == "":
return "—"
return escape_html(value)
def format_security(
encryption=None,
cipher=None,
akm=None,
):
parts = []
for value in (
encryption,
cipher,
akm,
):
if value is None:
continue
value = str(value).strip()
if not value or value == "—":
continue
if value not in parts:
parts.append(value)
return " / ".join(
escape_html(value)
for value in parts
) or "—"
def aggregate_credentials(credentials):
"""
Aggregate credentials by exact password value.
A password is verified if at least one matching
database record has verified=1.
Sources are combined without duplicates.
"""
aggregated = {}
for credential in credentials or []:
password = credential["password"]
if password is None or str(password) == "":
continue
password = str(password)
if password not in aggregated:
aggregated[password] = {
"password": password,
"verified": False,
"sources": [],
}
item = aggregated[password]
if credential["verified"]:
item["verified"] = True
source = credential["source"]
if source is not None:
source = str(source).strip()
if source and source not in item["sources"]:
item["sources"].append(source)
return list(aggregated.values())
def format_credentials(credentials):
aggregated = aggregate_credentials(credentials)
if not aggregated:
return "—"
items = []
for credential in aggregated:
password = escape_html(
credential["password"]
)
verified_class = (
"verified"
if credential["verified"]
else "unverified"
)
verified_label = (
"Проверен"
if credential["verified"]
else "Не проверен"
)
sources = ", ".join(
escape_html(source)
for source in credential["sources"]
) or "—"
items.append(
"<div "
f"class=\"map-popup-password "
f"map-popup-password-{verified_class}\">"
f"<b>{password}</b>"
f"<div class=\"map-popup-password-status "
f"map-popup-password-status-{verified_class}\">"
f"{verified_label}"
"</div>"
f"<div>Source: {sources}</div>"
"</div>"
)
return "".join(items)
def format_capture_materials(
handshakes,
):
"""
Count logical EAPOL and PMKID records.
This does not count packets or unique hashes.
"""
counts = {
"EAPOL": 0,
"PMKID": 0,
}
for handshake in handshakes or []:
capture_type = str(
handshake["type"] or ""
).strip().upper()
if "PMKID" in capture_type:
counts["PMKID"] += 1
elif "EAPOL" in capture_type:
counts["EAPOL"] += 1
parts = []
for capture_type in ("EAPOL", "PMKID"):
count = counts[capture_type]
if count:
parts.append(
f"{capture_type} × {count}"
)
return ", ".join(parts) if parts else "—"
def build_standard_popup(
*,
essid=None,
bssid=None,
vendor=None,
encryption=None,
cipher=None,
akm=None,
channel=None,
rssi=None,
passwords=None,
handshakes=None,
observed_at=None,
latitude=None,
longitude=None,
access_point_url=None,
session_url=None,
):
rows = [
f"<b>{display_value(essid)}</b>",
f"BSSID: {display_value(bssid)}",
f"Vendor: {display_value(vendor)}",
(
"Security: "
+ format_security(
encryption,
cipher,
akm,
)
),
f"Channel: {display_value(channel)}",
]
if rssi is not None:
rows.append(
f"RSSI: {escape_html(rssi)} dBm"
)
rows.extend([
(
"Password:<br>"
+ format_credentials(passwords)
),
(
"Материалы захвата: "
+ escape_html(
format_capture_materials(handshakes)
)
),
f"Дата наблюдения: {display_value(observed_at)}",
])
if latitude is not None and longitude is not None:
coordinates = (
f"{float(latitude):.6f}, "
f"{float(longitude):.6f}"
)
rows.append(
"Координаты: "
f"{escape_html(coordinates)}"
"<br>"
"<button "
"type=\"button\" "
"class=\"map-popup-copy\" "
f"data-coordinates=\"{escape_html(coordinates)}\" "
"onclick=\"copyMapCoordinates(this)\">"
"Copy"
"</button>"
)
if session_url:
rows.append(
f'<a href="{escape_html(session_url)}">'
"Сессия наблюдения</a>"
)
if access_point_url:
rows.append(
f'<a href="{escape_html(access_point_url)}">'
"Подробнее</a>"
)
return "<br>".join(rows)
+21
View File
@@ -0,0 +1,21 @@
"""
Centralized map service configuration.
"""
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from src.tileserver_config import load_tileserver_config
MAP_STYLE_URL = load_tileserver_config(PROJECT_ROOT)["style_url"]
def get_map_style_url():
return MAP_STYLE_URL
+448 -467
View File
File diff suppressed because it is too large Load Diff
+478 -444
View File
File diff suppressed because it is too large Load Diff
+93
View File
@@ -33,8 +33,85 @@ from datetime import datetime
from .utils import (
format_duration,
format_size,
haversine_m,
)
def load_gps_track(conn, session_id):
rows = query_all(
conn,
"""
SELECT
latitude,
longitude
FROM gps_track
WHERE
session_id=?
ORDER BY
timestamp
""",
(
session_id,
),
)
track = []
for row in rows:
latitude = row[0]
longitude = row[1]
if (
latitude is None
or longitude is None
):
continue
if (
latitude == 0
or longitude == 0
):
continue
track.append(
{
"lat": latitude,
"lon": longitude,
}
)
return track
def gps_track_distance(track):
if not track:
return None
return sum(
haversine_m(
first["lat"],
first["lon"],
second["lat"],
second["lon"],
)
for first, second in zip(track, track[1:])
)
def session_origin(capture_file):
if not capture_file:
return "Unknown"
capture_file = str(capture_file)
if (
capture_file == "imported.wifitrip"
or capture_file.startswith("wifitrip:")
):
return "Imported from .wifitrip"
if capture_file.startswith("captures/"):
return "Local capture"
return "Unknown"
# ============================================================
# Список всех поездок
@@ -530,6 +607,10 @@ def session_statistics(
"capture_file": capture_file,
"origin": session_origin(
capture_file
),
}
# ============================================================
@@ -887,6 +968,18 @@ def session_card_data(
trip_start,
trip_end
)
else:
stat["duration"] = None
track = load_gps_track(
conn,
session_id
)
distance_m = gps_track_distance(track)
if distance_m is not None:
stat["distance_m"] = distance_m
stat["directory_size"] = format_size(
+285
View File
@@ -255,6 +255,17 @@ a:hover {
padding: 30px;
}
.page-section {
margin-bottom: 8px;
color: var(--muted);
font-size: 18px;
font-weight: 600;
letter-spacing: 0.8px;
text-transform: uppercase;
}
.page-title {
margin-top: 0;
@@ -568,6 +579,168 @@ code {
gap: 24px;
}
/* ============================================================
Capture sessions list
============================================================ */
.session-list-toolbar {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 18px;
}
.session-list-toolbar label {
color: var(--muted);
}
.session-list-toolbar select {
background: var(--surface);
color: var(--text);
border: 1px solid var(--border);
border-radius: 7px;
padding: 8px 12px;
font-size: 14px;
}
.session-list-toolbar button {
background: var(--surface);
color: var(--text);
border: 1px solid var(--border);
border-radius: 7px;
padding: 7px 13px;
font-size: 18px;
cursor: pointer;
}
.session-list-toolbar button:hover {
border-color: var(--accent);
}
.session-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.session-compact-card {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
width: 100%;
box-sizing: border-box;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 10px;
padding: 16px 20px;
box-shadow:
0 2px 8px rgba(0, 0, 0, 0.16);
}
.session-compact-main {
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
}
.session-compact-title {
color: var(--text);
font-size: 20px;
font-weight: 600;
}
.session-compact-details,
.session-compact-stats {
display: flex;
flex-wrap: wrap;
gap: 10px 24px;
color: var(--muted);
font-size: 15px;
}
.session-compact-details b,
.session-compact-stats b {
color: var(--text);
}
.session-compact-link {
flex-shrink: 0;
color: var(--accent);
font-weight: 600;
text-decoration: none;
white-space: nowrap;
}
.session-compact-link:hover {
text-decoration: underline;
}
@media (max-width: 600px) {
.session-compact-card {
align-items: flex-start;
flex-direction: column;
gap: 14px;
padding: 15px;
}
.session-compact-details,
.session-compact-stats {
flex-direction: column;
gap: 7px;
}
.session-list-toolbar {
flex-wrap: wrap;
}
}
.vendor-sync {
width: 100%;
}
@@ -629,6 +802,9 @@ code {
background: #E53935;
}
.map-layer-dot-open {
background: #AB47BC;
}
.map-layer-dot-all {
background: #43A047;
@@ -796,6 +972,28 @@ code {
margin-top: 20px;
}
.search-fields {
display: grid;
grid-template-columns:
repeat(3, minmax(0, 1fr));
gap: 16px;
margin-bottom: 16px;
}
.search-field {
min-width: 0;
}
.search-field .search-input {
width: 100%;
box-sizing: border-box;
}
.search-label {
display: block;
@@ -1221,6 +1419,13 @@ code {
}
.search-popup-category.open {
background: rgba(171, 71, 188, 0.16);
color: #AB47BC;
}
.search-popup-section {
margin-top: 9px;
@@ -1279,6 +1484,10 @@ code {
@media (max-width: 700px) {
.search-fields {
grid-template-columns: 1fr;
}
.search-input-row {
flex-direction: column;
}
@@ -1321,6 +1530,53 @@ body .maplibregl-popup-content {
0 8px 24px rgba(0, 0, 0, 0.35);
}
body .maplibregl-popup-content .map-popup-password {
margin-top: 6px;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 6px;
background: rgba(0, 0, 0, 0.12);
word-break: break-word;
}
body .maplibregl-popup-content
.map-popup-password-verified {
border-color: rgba(69, 212, 131, 0.35);
background: rgba(69, 212, 131, 0.08);
}
body .maplibregl-popup-content
.map-popup-password-verified > b {
color: #45d483;
}
body .maplibregl-popup-content
.map-popup-password-status {
margin-top: 3px;
font-size: 12px;
}
body .maplibregl-popup-content
.map-popup-password-status-verified {
color: #45d483;
}
body .maplibregl-popup-content
.map-popup-password-status-unverified {
color: #8b98a6;
}
/* Popup arrow */
@@ -1442,3 +1698,32 @@ body .maplibregl-popup-close-button:hover {
.hashcat-preflight .stats-grid {
margin-top: 20px;
}
.wifi-connection-action {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
margin-top: 12px;
}
.wifi-connection-action label {
display: flex;
flex-direction: column;
gap: 5px;
font-size: 13px;
}
.wifi-connection-password {
max-width: 100%;
}
.wifi-connection-button {
padding: 8px 14px;
border: 0;
border-radius: 6px;
background: var(--green);
color: #ffffff;
cursor: pointer;
font-weight: 600;
}
+3
View File
@@ -291,6 +291,9 @@ def encryption_statistics(conn):
FROM access_points
WHERE encryption IS NOT NULL
AND TRIM(encryption) != ''
GROUP BY encryption
ORDER BY total DESC
+65 -42
View File
@@ -199,6 +199,40 @@ function filterTable(id,value)
}}
}}
async function copyMapCoordinates(button)
{{
const coordinates = button.dataset.coordinates;
if (!coordinates)
return;
const originalText = button.textContent;
try
{{
if (!navigator.clipboard || !navigator.clipboard.writeText)
throw new Error("Clipboard API unavailable");
await navigator.clipboard.writeText(coordinates);
button.textContent = "Скопировано";
setTimeout(() =>
{{
button.textContent = originalText;
}}, 1500);
}}
catch (error)
{{
button.textContent = "Ошибка копирования";
setTimeout(() =>
{{
button.textContent = originalText;
}}, 2000);
}}
}}
</script>
</head>
@@ -228,6 +262,12 @@ def navigation(
menu = [
(
"cracklab",
"CrackLab",
"/cracklab/",
),
(
"dashboard",
"Dashboard",
@@ -263,15 +303,15 @@ def navigation(
),
(
"vendors",
"Vendors",
"/reports/vendors/",
"wifi_connections",
"Wi-Fi Connections",
"/reports/wifi-connections/",
),
(
"hashcat",
"Hashes",
"/reports/hashcat/",
"vendors",
"Vendors",
"/reports/vendors/",
),
]
@@ -349,6 +389,8 @@ def page_begin(
context=None,
section_title="",
):
if context is None:
@@ -369,10 +411,26 @@ def page_begin(
context,
)
html += f"""
html += """
<div class="content">
"""
if section_title:
html += f"""
<div class="page-section">
{section_title}
</div>
"""
html += f"""
<h1 class="page-title">
{title}
@@ -395,41 +453,6 @@ def page_begin(
return html
# ============================================================
# Page header
# ============================================================
def page_header(
title,
description="",
):
html = f"""
<h1 class="page-title">
{title}
</h1>
"""
if description:
html += f"""
<div class="page-description">
{description}
</div>
"""
return html
# ============================================================
# Page end
+1
View File
@@ -249,6 +249,7 @@ def render_trips_page(
),
"trips",
context,
section_title="Reports",
)
html += _message(
+20 -3
View File
@@ -20,14 +20,31 @@ from __future__ import annotations
import csv
import html
import math
import os
from datetime import datetime, timezone
from pathlib import Path
from zoneinfo import ZoneInfo
from .config import TIMEZONE
from .config import get_timezone
def haversine_m(lat1, lon1, lat2, lon2):
radius = 6371000.0
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlambda = math.radians(lon2 - lon1)
a = (
math.sin(dphi / 2.0) ** 2
+ math.cos(phi1)
* math.cos(phi2)
* math.sin(dlambda / 2.0) ** 2
)
return 2.0 * radius * math.asin(min(1.0, math.sqrt(a)))
# ============================================================
# HTML
@@ -141,7 +158,7 @@ def format_datetime(
if dt is None:
return safe(text)
display_timezone = ZoneInfo(TIMEZONE)
display_timezone = ZoneInfo(get_timezone())
return dt.astimezone(
display_timezone
@@ -403,7 +420,7 @@ def modified(path):
if not path.exists():
return "-"
display_timezone = ZoneInfo(TIMEZONE)
display_timezone = ZoneInfo(get_timezone())
return datetime.fromtimestamp(
path.stat().st_mtime,
+161 -201
View File
@@ -517,13 +517,6 @@ def update_block(
oui = preview["oui"]
build = preview["build"]
ap = preview["ap"]
ap_total = (
ap["unknown_to_vendor"]
+ ap["vendor_to_vendor"]
+ ap["vendor_to_unknown"]
)
if oui["identical"]:
@@ -531,20 +524,6 @@ def update_block(
<p>
База OUI не изменилась. Обновление не требуется.
</p>
"""
elif ap_total == 0:
status_html = """
<p>
База OUI содержит изменения, но существующие записи
AP не требуют изменения vendor.
</p>
<p>
Обновление базы OUI можно применить отдельно.
Оно обновит справочник для будущих определений vendor.
</p>
"""
else:
@@ -552,8 +531,7 @@ AP не требуют изменения vendor.
status_html = """
<p>
База OUI содержит изменения.
Сначала проверьте изменения в справочнике, затем при
необходимости выберите синхронизацию vendor у существующих AP.
Проверьте результаты перед применением обновления.
</p>
"""
@@ -619,11 +597,7 @@ AP не требуют изменения vendor.
"""
if oui["identical"]:
pass
else:
if not oui["identical"]:
html += f"""
<form
@@ -638,148 +612,6 @@ AP не требуют изменения vendor.
value="{escape(token)}"
>
"""
if ap_total > 0:
html += """
<div class="vendor-sync">
<hr>
<h2>
Синхронизация существующих AP
</h2>
<p>
Следующие параметры не изменяют саму базу OUI.
Они определяют, какие изменения vendor применить
к уже существующим записям WiFi AP.
</p>
<table>
<tr>
<th>Изменение vendor</th>
<th>Количество</th>
<th>Применить</th>
</tr>
<tr>
<td>
<strong>Unknown → Vendor</strong>
<details>
<summary>Что это означает?</summary>
<p>
Заполнить поле vendor у существующих AP, для которых
vendor сейчас неизвестен. Новое значение определяется
по обновлённой базе OUI.
</p>
</details>
</td>
<td>""" + str(ap["unknown_to_vendor"]) + """</td>
<td>
<input
type="checkbox"
name="unknown_to_vendor"
value="1"
checked
onchange="updateVendorApplyCount()"
>
</td>
</tr>
<tr>
<td>
<strong>Vendor → другой Vendor</strong>
<details>
<summary>Что это означает?</summary>
<p>
Заменить текущее значение vendor, если обновлённая
база OUI определяет тот же AP как принадлежащий
другому vendor.
</p>
</details>
</td>
<td>""" + str(ap["vendor_to_vendor"]) + """</td>
<td>
<input
type="checkbox"
name="vendor_to_vendor"
value="1"
onchange="updateVendorApplyCount()"
>
</td>
</tr>
<tr>
<td>
<strong>Vendor → Unknown</strong>
<details>
<summary>Что это означает?</summary>
<p>
Удалить текущее значение vendor, если обновлённая
база OUI больше не позволяет определить vendor
для данного AP.
</p>
</details>
</td>
<td>""" + str(ap["vendor_to_unknown"]) + """</td>
<td>
<input
type="checkbox"
name="vendor_to_unknown"
value="1"
onchange="updateVendorApplyCount()"
>
</td>
</tr>
</table>
<p>
Выбрано изменений AP:
<strong id="vendor-apply-count">""" + str(
ap["unknown_to_vendor"]
) + """</strong>
</p>
<p>
Синхронизация AP необязательна. Снятые категории
не будут изменять существующие записи AP.
</p>
</div>
"""
else:
html += """
<div class="vendor-sync vendor-sync-empty">
<hr>
<h2>
Синхронизация существующих AP
</h2>
<p>
Существующие записи AP не требуют изменения vendor.
Для этого обновления синхронизация AP недоступна.
</p>
</div>
"""
html += """
<div class="vendor-actions">
<button type="submit" class="button">
@@ -792,51 +624,173 @@ vendor сейчас неизвестен. Новое значение опред
"""
if ap_total > 0:
return html
def recalculate_block(job=None):
html = """
<div class="card">
<h2>
Перерасчёт производителей точек доступа
</h2>
<p>
Операция проверяет все записи AP по установленной базе OUI.
Она заполняет неизвестные значения, обновляет устаревшие
названия производителей и очищает значения, которые больше
не определяются.
</p>
"""
if job is None:
html += """
<form
method="POST"
action="/reports/vendors/recalculate"
onsubmit="return confirm('Запустить полный перерасчёт производителей всех точек доступа?');"
>
<button type="submit" class="button">
Пересчитать производителей AP
</button>
</form>
"""
elif job["status"] == "ready":
result = job["result"]
labels = (
("total", "Всего точек доступа"),
("checked", "Проверено"),
("updated", "Изменено"),
("filled", "Заполнено"),
("refreshed", "Обновлено"),
("cleared", "Очищено"),
("unknown", "Неизвестный производитель"),
("unchanged", "Без изменений")
)
html += """
<p>
Перерасчёт завершён.
</p>
<table>
<tr>
<th>Показатель</th>
<th>Количество</th>
</tr>
"""
for key, label in labels:
html += f"""
<tr>
<td>{label}</td>
<td>{result[key]}</td>
</tr>
"""
html += """
</table>
"""
elif job["status"] == "error":
html += f"""
<p>
Ошибка перерасчёта:
</p>
<p>
<strong>{escape(job["error"] or "Неизвестная ошибка")}</strong>
</p>
<form
method="POST"
action="/reports/vendors/recalculate"
>
<button type="submit" class="button">
Повторить перерасчёт
</button>
</form>
"""
else:
html += f"""
<p id="vendor-recalc-status">
{escape(job["message"] or "Перерасчёт выполняется")}
</p>
<script>
function updateVendorApplyCount() {{
(function() {{
let total = 0;
const jobId = {job["id"]!r};
const fields = [
[
"unknown_to_vendor",
{ap["unknown_to_vendor"]}
],
[
"vendor_to_vendor",
{ap["vendor_to_vendor"]}
],
[
"vendor_to_unknown",
{ap["vendor_to_unknown"]}
]
];
const statusElement = document.getElementById(
"vendor-recalc-status"
);
for (const field of fields) {{
async function checkStatus() {{
const checkbox = document.querySelector(
'input[name="' + field[0] + '"]'
);
try {{
const response = await fetch(
"/reports/vendors/recalculate/status/" + jobId
);
if (!response.ok) {{
statusElement.textContent =
"Не удалось получить статус задачи (HTTP " +
response.status +
")";
return;
}}
const data = await response.json();
if (data.message) {{
statusElement.textContent = data.message;
}}
if (data.status === "ready" || data.status === "error") {{
window.location.href =
"/reports/vendors/?recalc_job_id=" + jobId;
return;
}}
}} catch (error) {{
statusElement.textContent = error.message;
if (checkbox && checkbox.checked) {{
total += field[1];
}}
window.setTimeout(checkStatus, 1000);
}}
document.getElementById(
"vendor-apply-count"
).textContent = total;
}}
</script>
window.setTimeout(checkStatus, 1000);
}})();
</script>
"""
html += """
</div>
"""
return html
def render_vendors_page(
conn,
service,
@@ -844,7 +798,8 @@ def render_vendors_page(
token=None,
message=None,
context=None,
job=None
job=None,
recalc_job=None
):
status = service.status()
@@ -855,6 +810,7 @@ def render_vendors_page(
),
active="vendors",
context=context,
section_title="Reports",
)
if message:
@@ -895,6 +851,10 @@ def render_vendors_page(
job
)
html += recalculate_block(
recalc_job
)
html += page_end()
return html
return html
+937
View File
@@ -0,0 +1,937 @@
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.wireguard_warning
&& wifiConnectionWarning
) {
wifiConnectionWarning.textContent =
data.wireguard_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.wireguard_active) {
setWarning(
"Обнаружено активное соединение WireGuard. "
+ "При необходимости отключите VPN вручную. "
+ "Приложение не изменяет состояние WireGuard."
);
} else if (data.wireguard_error) {
setWarning(
"Не удалось проверить состояние WireGuard: "
+ data.wireguard_error
);
}
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
+312 -72
View File
@@ -1604,6 +1604,221 @@ def _session_id_by_hash(
return row["id"]
def _map_existing_handshake_ids(
conn,
session_id,
session_handshakes,
):
rows = conn.execute(
"""
SELECT
handshakes.id,
access_points.bssid,
handshakes.type,
handshakes.hash22000,
handshakes.message_pair,
handshakes.captured_at,
handshakes.latitude,
handshakes.longitude,
handshakes.speed
FROM handshakes
JOIN access_points
ON access_points.id =
handshakes.access_point_id
WHERE handshakes.session_id=?
ORDER BY handshakes.id
""",
(session_id,),
).fetchall()
if len(rows) != len(session_handshakes):
raise WifitripError(
"Existing session handshake count does not "
"match the .wifitrip package."
)
expected_keys = [
f"h{index:06d}"
for index in range(
1,
len(session_handshakes) + 1,
)
]
package_keys = {
handshake["handshake_key"]
for handshake in session_handshakes
}
if package_keys != set(expected_keys):
raise WifitripError(
"Existing session handshake keys do not "
"match the exported sequence."
)
fields = (
"bssid",
"type",
"hash22000",
"message_pair",
"captured_at",
"latitude",
"longitude",
"speed",
)
local_ids_by_signature = {}
for row in rows:
signature = tuple(
row[field]
for field in fields
)
local_ids_by_signature.setdefault(
signature,
[],
).append(row["id"])
signature_positions = {}
handshake_ids = {}
ordered_handshakes = sorted(
session_handshakes,
key=lambda handshake: (
handshake["handshake_key"]
),
)
for handshake in ordered_handshakes:
signature = tuple(
handshake[field]
for field in fields
)
local_ids = local_ids_by_signature.get(
signature,
)
position = signature_positions.get(
signature,
0,
)
if local_ids is None or position >= len(local_ids):
raise WifitripError(
"Existing session handshake mapping "
"does not match the .wifitrip package."
)
handshake_ids[
handshake["handshake_key"]
] = local_ids[position]
signature_positions[signature] = position + 1
return handshake_ids
def _import_session_credentials(
conn,
session_credentials,
ap_ids,
handshake_ids,
):
for credential in session_credentials:
access_point_id = ap_ids[
credential["bssid"]
]
handshake_id = None
if credential["handshake_key"] is not None:
handshake_id = handshake_ids[
credential["handshake_key"]
]
existing_verified = conn.execute(
"""
SELECT COALESCE(MAX(verified), 0)
FROM credentials
WHERE access_point_id=?
AND password=?
""",
(
access_point_id,
credential["password"],
),
).fetchone()[0]
effective_verified = int(
bool(existing_verified)
or bool(credential["verified"])
)
existing_credential = conn.execute(
"""
SELECT id
FROM credentials
WHERE access_point_id=?
AND handshake_id IS ?
AND password=?
LIMIT 1
""",
(
access_point_id,
handshake_id,
credential["password"],
),
).fetchone()
if existing_credential is None:
conn.execute(
"""
INSERT INTO credentials (
access_point_id,
handshake_id,
password,
source,
created_at,
verified
)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
access_point_id,
handshake_id,
credential["password"],
credential["source"],
credential["created_at"],
effective_verified,
),
)
if effective_verified:
conn.execute(
"""
UPDATE credentials
SET verified=1
WHERE access_point_id=?
AND password=?
""",
(
access_point_id,
credential["password"],
),
)
conn.execute(
"""
UPDATE access_points
SET is_cracked=1
WHERE id=?
""",
(access_point_id,),
)
def import_wifitrip(conn, package_path):
started = time.monotonic()
@@ -1687,12 +1902,97 @@ def import_wifitrip(conn, package_path):
if existing_id is not None:
result["duplicates"] += 1
logger.info(
"Skipping duplicate .wifitrip session: "
"hash=%s local_id=%s",
session_hash,
existing_id,
)
try:
conn.execute("BEGIN")
calculated_hash = _session_hash(
conn,
existing_id,
)
if calculated_hash != session_hash:
raise WifitripError(
"Existing session hash verification failed: "
f"expected {session_hash}, "
f"calculated {calculated_hash}"
)
session_handshakes = (
handshakes_by_session.get(
session_hash,
[],
)
)
session_credentials = (
credentials_by_session.get(
session_hash,
[],
)
)
bssids = {
handshake["bssid"]
for handshake in session_handshakes
}
bssids.update(
credential["bssid"]
for credential in session_credentials
)
created_access_points = set()
ap_ids = {}
for bssid in sorted(bssids):
ap_ids[bssid] = (
_get_or_create_import_ap(
conn,
bssid,
created_access_points,
)
)
handshake_ids = (
_map_existing_handshake_ids(
conn,
existing_id,
session_handshakes,
)
)
_import_session_credentials(
conn,
session_credentials,
ap_ids,
handshake_ids,
)
conn.commit()
logger.info(
"Updated duplicate .wifitrip session "
"credentials: hash=%s local_id=%s",
session_hash,
existing_id,
)
except Exception as exc:
conn.rollback()
result["failed"] += 1
result["failed_sessions"].append(
{
"session_hash": session_hash,
"error": str(exc),
}
)
logger.exception(
"Failed to update duplicate .wifitrip session: "
"hash=%s",
session_hash,
)
continue
@@ -1955,72 +2255,12 @@ def import_wifitrip(conn, package_path):
f"calculated {calculated_hash}"
)
for credential in session_credentials:
access_point_id = ap_ids[
credential["bssid"]
]
handshake_id = None
if credential[
"handshake_key"
] is not None:
handshake_id = handshake_ids[
credential[
"handshake_key"
]
]
existing_credential = conn.execute(
"""
SELECT id
FROM credentials
WHERE access_point_id=?
AND handshake_id IS ?
AND password=?
LIMIT 1
""",
(
access_point_id,
handshake_id,
credential["password"],
),
).fetchone()
if existing_credential is not None:
continue
conn.execute(
"""
INSERT INTO credentials (
access_point_id,
handshake_id,
password,
source,
created_at,
verified
)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
access_point_id,
handshake_id,
credential["password"],
credential["source"],
credential["created_at"],
credential["verified"],
),
)
conn.execute(
"""
UPDATE access_points
SET
is_cracked=1
WHERE id=?
""",
(access_point_id,),
)
_import_session_credentials(
conn,
session_credentials,
ap_ids,
handshake_ids,
)
conn.commit()
+12 -5
View File
@@ -434,6 +434,7 @@ class Database:
if (
"handshake_id" in column_names
and "verified" in column_names
and has_provenance_unique
):
return
@@ -486,10 +487,16 @@ class Database:
)
""")
verified_expression = (
"verified"
if "verified" in column_names
else "0"
)
if "handshake_id" in column_names:
self.conn.execute(
"""
f"""
INSERT INTO credentials
(
id,
@@ -507,7 +514,7 @@ class Database:
password,
source,
created_at,
verified
{verified_expression}
FROM credentials_old
"""
)
@@ -515,7 +522,7 @@ class Database:
else:
self.conn.execute(
"""
f"""
INSERT INTO credentials
(
id,
@@ -531,7 +538,7 @@ class Database:
password,
source,
created_at,
verified
{verified_expression}
FROM credentials_old
"""
)
@@ -879,7 +886,7 @@ class Database:
"""
UPDATE capture_sessions
SET end_time=?
SET end_time=COALESCE(end_time, ?)
WHERE id=?
""",
+91 -121
View File
@@ -4,8 +4,6 @@ import logging
import sqlite3
import csv
from vendor_import import VendorImporter
class EnvironmentChecker:
"""
Проверка окружения проекта.
@@ -63,14 +61,16 @@ class EnvironmentChecker:
self.check_hcxdumptool_version()
self.check_vendor_database()
self.log.info(
"Environment OK"
)
vendor_database_ok = self.check_vendor_database()
if vendor_database_ok:
self.log.info(
"Environment OK"
)
else:
self.log.warning(
"Environment checks completed; vendor lookup unavailable"
)
# ---------------------------------------------------------
# Проверка бинарника
@@ -174,141 +174,111 @@ class EnvironmentChecker:
database = self.config.vendor_database
rebuild = False
if not database.exists():
self.log.warning(
"Vendor database not found"
"Vendor database not found: %s",
database
)
rebuild = True
return False
elif database.stat().st_size == 0:
if database.stat().st_size == 0:
self.log.warning(
"Vendor database is empty"
"Vendor database is empty: %s",
database
)
rebuild = True
return False
else:
connection = None
try:
try:
connection = sqlite3.connect(
database
)
cursor = connection.cursor()
cursor.execute(
"SELECT name FROM sqlite_master "
"WHERE type='table' "
"AND name='oui'"
)
if cursor.fetchone() is None:
raise RuntimeError(
"vendors table not found"
)
cursor.execute(
"SELECT COUNT(*) FROM oui"
)
records = cursor.fetchone()[0]
if records < 50000:
raise RuntimeError(
f"Only {records} records"
)
cursor.execute(
"SELECT value "
"FROM metadata "
"WHERE key='import_status'"
)
row = cursor.fetchone()
if (
row is None
or
row[0] != "ok"
):
raise RuntimeError(
"Invalid import_status"
)
connection.close()
self.log.info(
f"Vendor database: OK ({records} records)"
)
return
except KeyboardInterrupt:
self.log.warning(
"Download cancelled by user"
)
raise
except Exception as error:
self.log.warning(
f"Vendor database is invalid: {error}"
)
rebuild = True
if rebuild:
database.unlink(
missing_ok=True
connection = sqlite3.connect(
f"{database.resolve().as_uri()}?mode=ro",
uri=True
)
self.log.info(
"Creating vendor database..."
cursor = connection.cursor()
cursor.execute(
"SELECT name FROM sqlite_master "
"WHERE type='table' "
"AND name='oui'"
)
importer = VendorImporter(
self.config
)
importer.bootstrap()
if not database.exists():
if cursor.fetchone() is None:
raise RuntimeError(
"oui table not found"
)
"Unable to create vendor database."
cursor.execute(
"SELECT COUNT(*) FROM oui"
)
records = cursor.fetchone()[0]
if records < 50000:
raise RuntimeError(
f"Only {records} records"
)
cursor.execute(
"SELECT name FROM sqlite_master "
"WHERE type='table' "
"AND name='metadata'"
)
if cursor.fetchone() is None:
raise RuntimeError(
"metadata table not found"
)
cursor.execute(
"SELECT value "
"FROM metadata "
"WHERE key='import_status'"
)
row = cursor.fetchone()
if row is None or row[0] != "ok":
raise RuntimeError(
"Invalid import_status"
)
self.log.info(
"Vendor database created"
"Vendor database: OK (%s records)",
records
)
return True
except sqlite3.Error as error:
self.log.warning(
"Vendor database is invalid: %s",
error
)
return False
except RuntimeError as error:
self.log.warning(
"Vendor database is invalid: %s",
error
)
return False
finally:
if connection is not None:
connection.close()
+64 -5
View File
@@ -16,6 +16,8 @@ class GPSTestService:
self.cfg = cfg
self.callback = callback
self.source = None
self.source_lock = threading.Lock()
self.thread = None
self.stop_event = threading.Event()
@@ -76,6 +78,34 @@ class GPSTestService:
self.stop_event.set()
with self.source_lock:
source = self.source
if source is None:
return
connection = getattr(
source,
"socket",
None
)
if connection is not None:
try:
connection.shutdown(2)
except OSError:
pass
try:
source.close()
except Exception as error:
self.emit(
f"[GPS TEST] Stop close error: {error}"
)
def worker(self):
@@ -93,11 +123,19 @@ class GPSTestService:
self.cfg
)
with self.source_lock:
self.source = source
if self.stop_event.is_set():
return
self.emit(
"[GPS TEST] Connecting to GPS source..."
)
file = source.open()
if self.stop_event.is_set():
return
self.state = "CONNECTED"
@@ -122,6 +160,10 @@ class GPSTestService:
line = file.readline()
if not line:
if self.stop_event.wait(0.1):
break
continue
self.nmea_count += 1
@@ -199,15 +241,28 @@ class GPSTestService:
except Exception as error:
self.state = "ERROR"
self.error = str(error)
if not self.stop_event.is_set():
self.emit(
f"[GPS TEST] GPS source error: {error}"
)
self.state = "ERROR"
self.error = str(error)
self.emit(
f"[GPS TEST] GPS source error: {error}"
)
finally:
if file is not None:
try:
file.close()
except Exception as error:
self.emit(
f"[GPS TEST] File close error: {error}"
)
if source is not None:
try:
@@ -219,6 +274,10 @@ class GPSTestService:
f"[GPS TEST] Close error: {error}"
)
with self.source_lock:
if self.source is source:
self.source = None
self.running = False
if self.state != "ERROR":
+992
View File
@@ -0,0 +1,992 @@
import argparse
import getpass
import json
import os
import shutil
import signal
import socket
import stat
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from tileserver_config import load_tileserver_config
from runtime_paths import get_node_path, get_runtime_env
TILESERVER_CONFIG_DATA = load_tileserver_config(PROJECT_ROOT)
UNIT_NAME = "wifi-gps-mapper"
APP_HOST = "127.0.0.1"
APP_PORT = 5000
TILE_HOST = TILESERVER_CONFIG_DATA["host"]
TILE_PORT = TILESERVER_CONFIG_DATA["port"]
TILE_STYLE_URL = TILESERVER_CONFIG_DATA["style_url"]
TILESERVER_DIR = TILESERVER_CONFIG_DATA["directory"]
TILESERVER_ENTRY = TILESERVER_CONFIG_DATA["entry"]
TILESERVER_CONFIG = TILESERVER_CONFIG_DATA["config"]
TILESERVER_CONFIG_PATH = TILESERVER_CONFIG_DATA["config_path"]
STARTUP_TIMEOUT = 30
POLL_INTERVAL = 0.5
AUTH_SOCKET_PATH = Path(
os.environ.get(
"XDG_RUNTIME_DIR",
f"/run/user/{os.getuid()}"
)
) / "wifi-gps-mapper-auth.sock"
class LifecycleError(RuntimeError):
pass
def log(message):
print(
f"[WiFi GPS Mapper] {message}",
flush=True
)
def project_python():
return PROJECT_ROOT / "venv" / "bin" / "python"
def style_is_available(timeout=2):
try:
request = urllib.request.Request(
TILE_STYLE_URL,
headers={"Accept": "application/json"}
)
with urllib.request.urlopen(
request,
timeout=timeout
) as response:
if response.status != 200:
return False
content_type = response.headers.get(
"Content-Type",
""
)
payload = json.loads(
response.read().decode("utf-8")
)
return (
isinstance(payload, dict)
and "version" in payload
and (
"sources" in payload
or "layers" in payload
)
)
except (
OSError,
ValueError,
urllib.error.URLError
):
return False
def port_is_open(host, port):
with socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
) as connection:
connection.settimeout(0.5)
return connection.connect_ex(
(host, port)
) == 0
def start_tileserver():
if style_is_available():
log(
"TileServer уже работает. "
"Используется внешний экземпляр."
)
return None
if port_is_open(TILE_HOST, TILE_PORT):
raise LifecycleError(
f"Порт {TILE_PORT} занят, но ожидаемый "
f"стиль {TILESERVER_CONFIG_DATA['style']} недоступен. "
"Чужой процесс не будет остановлен."
)
try:
node = str(get_node_path())
except FileNotFoundError as error:
raise LifecycleError(
"Локальный Node.js не найден."
) from error
if not TILESERVER_ENTRY.is_file():
raise LifecycleError(
f"Не найден TileServer entry point: "
f"{TILESERVER_ENTRY}"
)
config_path = TILESERVER_CONFIG_PATH
if not config_path.is_file():
raise LifecycleError(
f"Не найден TileServer config: {config_path}"
)
command = [
node,
str(TILESERVER_ENTRY),
"--config",
TILESERVER_CONFIG,
"--bind",
TILE_HOST,
"--port",
str(TILE_PORT)
]
log("Запускается TileServer...")
process = subprocess.Popen(
command,
cwd=TILESERVER_DIR,
stdin=subprocess.DEVNULL,
env=get_runtime_env()
)
deadline = time.monotonic() + STARTUP_TIMEOUT
while time.monotonic() < deadline:
if process.poll() is not None:
raise LifecycleError(
"TileServer завершился во время запуска "
f"(код {process.returncode})."
)
if style_is_available():
log(
f"TileServer запущен, PID {process.pid}."
)
return process
time.sleep(POLL_INTERVAL)
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
raise LifecycleError(
"TileServer не стал доступен за "
f"{STARTUP_TIMEOUT} секунд."
)
def stop_owned_tileserver(process):
if process is None or process.poll() is not None:
return
log("Останавливается принадлежащий менеджеру TileServer.")
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
def wait_for_scanner(app_module):
notified = False
while True:
with app_module.scanner_lock:
starting = app_module.scanner_starting
network_active = app_module.network_action_active
process = app_module.scanner_process
reader = app_module.scanner_output_thread
running = (
process is not None
and process.poll() is None
)
if not starting and not network_active and not running:
break
if not notified:
log(
"Ожидание завершения сканера или сетевой операции. "
"Если сканер работает, останови его кнопкой "
"Stop в веб-интерфейсе."
)
notified = True
time.sleep(POLL_INTERVAL)
if process is not None:
process.wait()
if reader is not None and reader is not threading.current_thread():
reader.join()
log("Сканер и поток чтения его вывода завершены.")
def stop_gps_test(app_module):
with app_module.gps_test_lock:
service = app_module.gps_test_service
if service is None:
return
thread = service.thread
if thread is None or not thread.is_alive():
return
log("Останавливается GPS-тест.")
service.stop()
if thread is not threading.current_thread():
thread.join()
log("GPS-тест завершён.")
def join_background_threads(app_module):
for name in (
"vendor_update_thread",
"vendor_recalc_thread"
):
thread = getattr(app_module, name, None)
if thread is None or thread is threading.current_thread():
continue
if thread.is_alive():
log(f"Ожидание фоновой задачи: {name}.")
thread.join()
log("Фоновые задачи завершены.")
def receive_sudo_authentication(shutdown_event):
runtime_dir = AUTH_SOCKET_PATH.parent
if not runtime_dir.is_dir():
raise LifecycleError(
f"Не найден runtime-каталог: {runtime_dir}"
)
if AUTH_SOCKET_PATH.exists() or AUTH_SOCKET_PATH.is_symlink():
try:
socket_info = AUTH_SOCKET_PATH.lstat()
except OSError as error:
raise LifecycleError(
f"Не удалось проверить Unix-сокет: {error}"
) from error
if (
not stat.S_ISSOCK(socket_info.st_mode)
or socket_info.st_uid != os.getuid()
):
raise LifecycleError(
f"Путь занят посторонним объектом: {AUTH_SOCKET_PATH}"
)
AUTH_SOCKET_PATH.unlink()
auth_socket = socket.socket(
socket.AF_UNIX,
socket.SOCK_STREAM
)
try:
auth_socket.bind(str(AUTH_SOCKET_PATH))
AUTH_SOCKET_PATH.chmod(0o600)
auth_socket.listen(1)
auth_deadline = time.monotonic() + STARTUP_TIMEOUT + 60
auth_socket.settimeout(POLL_INTERVAL)
log("Ожидание sudo-аутентификации от CLI...")
while True:
if shutdown_event.is_set():
raise LifecycleError(
"Ожидание sudo-аутентификации прервано остановкой."
)
if time.monotonic() >= auth_deadline:
raise LifecycleError(
"Не получен пароль sudo за отведённое время."
)
try:
connection, _ = auth_socket.accept()
break
except socket.timeout:
continue
with connection:
connection.settimeout(10)
password = bytearray()
while True:
chunk = connection.recv(1024)
if not chunk:
break
password.extend(chunk)
if len(password) > 4096:
raise LifecycleError(
"Получен недопустимо длинный пароль."
)
if not password:
connection.sendall(b"AUTH_FAILED")
raise LifecycleError(
"Получен пустой пароль sudo."
)
result = subprocess.run(
["sudo", "-S", "-p", "", "-v"],
input=bytes(password) + b"\n",
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
check=False
)
for index in range(len(password)):
password[index] = 0
if result.returncode != 0:
connection.sendall(b"AUTH_FAILED")
raise LifecycleError(
"sudo-аутентификация не пройдена."
)
connection.sendall(b"AUTH_OK")
log("sudo-аутентификация успешно пройдена.")
except socket.timeout as error:
raise LifecycleError(
"Не получен пароль sudo за отведённое время."
) from error
finally:
auth_socket.close()
try:
socket_info = AUTH_SOCKET_PATH.lstat()
if (
stat.S_ISSOCK(socket_info.st_mode)
and socket_info.st_uid == os.getuid()
):
AUTH_SOCKET_PATH.unlink()
except FileNotFoundError:
pass
def send_sudo_authentication():
deadline = time.monotonic() + STARTUP_TIMEOUT
connection = None
while connection is None:
if not unit_is_active():
raise LifecycleError(
"Менеджер завершился до подключения CLI. "
"Проверь журнал: "
f"journalctl --user -u {UNIT_NAME}.service"
)
if time.monotonic() >= deadline:
raise LifecycleError(
"Не удалось подключиться к сокету "
"sudo-аутентификации."
)
candidate = socket.socket(
socket.AF_UNIX,
socket.SOCK_STREAM
)
try:
candidate.settimeout(POLL_INTERVAL)
candidate.connect(str(AUTH_SOCKET_PATH))
connection = candidate
except OSError:
candidate.close()
time.sleep(POLL_INTERVAL)
password = ""
try:
password = getpass.getpass("Введите пароль sudo: ")
connection.settimeout(10)
connection.sendall(password.encode("utf-8") + b"\n")
password = ""
connection.shutdown(socket.SHUT_WR)
response = connection.recv(32)
finally:
password = ""
connection.close()
if response != b"AUTH_OK":
raise LifecycleError(
"Менеджер отклонил sudo-аутентификацию."
)
def run_server():
os.chdir(PROJECT_ROOT)
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
src_path = str(PROJECT_ROOT / "src")
if src_path not in sys.path:
sys.path.insert(0, src_path)
tileserver_process = None
server = None
server_thread = None
app_module = None
shutdown_event = threading.Event()
shutdown_started = False
def request_shutdown(signum, frame):
nonlocal shutdown_started
if shutdown_started:
return
shutdown_started = True
log("Получен сигнал завершения.")
if app_module is not None:
app_module.request_lifecycle.begin_shutdown()
shutdown_event.set()
signal.signal(signal.SIGTERM, request_shutdown)
signal.signal(signal.SIGINT, request_shutdown)
try:
receive_sudo_authentication(shutdown_event)
tileserver_process = start_tileserver()
from gui import app as app_module
if not app_module.check_sudo():
raise LifecycleError(
"sudo-аутентификация менеджера недоступна."
)
app_module.sudo_keepalive_stop_event.clear()
app_module.sudo_keepalive_thread = threading.Thread(
target=app_module.sudo_keepalive,
args=(app_module.sudo_keepalive_stop_event,),
name="sudo-keepalive",
daemon=True
)
app_module.sudo_keepalive_thread.start()
from werkzeug.serving import make_server
server = make_server(
APP_HOST,
APP_PORT,
app_module.app,
threaded=True
)
server_thread = threading.Thread(
target=server.serve_forever,
name="flask-server",
daemon=False
)
server_thread.start()
log(
f"Веб-интерфейс запущен: "
f"http://{APP_HOST}:{APP_PORT}"
)
shutdown_event.wait()
except Exception:
if app_module is not None:
app_module.request_lifecycle.begin_shutdown()
raise
finally:
if app_module is not None:
app_module.request_lifecycle.begin_shutdown()
log("Ожидание завершения активных HTTP-запросов.")
app_module.request_lifecycle.wait_for_drain()
stop_gps_test(app_module)
wait_for_scanner(app_module)
join_background_threads(app_module)
app_module.sudo_keepalive_stop_event.set()
keepalive = app_module.sudo_keepalive_thread
if (
keepalive is not None
and keepalive is not threading.current_thread()
):
keepalive.join()
if server is not None:
log("Остановка Flask-сервера.")
server.shutdown()
if server_thread is not None:
server_thread.join()
stop_owned_tileserver(tileserver_process)
log("Менеджер завершил работу.")
def run_sudo_validation():
try:
result = subprocess.run(
["sudo", "-v"],
check=False
)
except OSError as error:
raise LifecycleError(
f"Не удалось запустить sudo: {error}"
) from error
if result.returncode != 0:
raise LifecycleError(
"Проверка sudo не пройдена."
)
def systemctl_user(*arguments, check=True):
command = [
"systemctl",
"--user",
*arguments
]
return subprocess.run(
command,
check=check,
text=True,
capture_output=True
)
def active_service_project():
result = systemctl_user(
"show",
f"{UNIT_NAME}.service",
"--property=WorkingDirectory",
"--value",
check=False
)
if result.returncode != 0:
return None
working_directory = result.stdout.strip()
if not working_directory:
return None
try:
return Path(working_directory).resolve()
except (OSError, RuntimeError):
return None
def unit_is_active():
result = systemctl_user(
"is-active",
"--quiet",
f"{UNIT_NAME}.service",
check=False
)
return result.returncode == 0
def start_service():
if unit_is_active():
active_project = active_service_project()
if active_project is None:
raise LifecycleError(
"Сервис уже активен, но не удалось определить "
"каталог проекта. Второй экземпляр не будет запущен."
)
if active_project == PROJECT_ROOT:
log("Менеджер уже запущен из текущего проекта.")
else:
log(
"Менеджер уже запущен из другого проекта: "
f"{active_project}. Второй экземпляр не запущен."
)
return 0
if port_is_open(APP_HOST, APP_PORT):
raise LifecycleError(
f"Порт приложения {APP_PORT} занят. "
"Чужой процесс не будет остановлен."
)
python = project_python()
if not python.is_file():
raise LifecycleError(
f"Не найден Python виртуального окружения: {python}"
)
command = [
"systemd-run",
"--user",
f"--unit={UNIT_NAME}",
"--service-type=exec",
"--property=KillMode=process",
"--collect",
f"--working-directory={PROJECT_ROOT}",
str(python),
str(PROJECT_ROOT / "src" / "lifecycle_manager.py"),
"--serve"
]
subprocess.run(
command,
check=True
)
send_sudo_authentication()
deadline = time.monotonic() + STARTUP_TIMEOUT
while time.monotonic() < deadline:
if not unit_is_active():
raise LifecycleError(
"Сервис завершился во время запуска. "
"Проверь журнал: "
f"journalctl --user -u {UNIT_NAME}.service"
)
try:
with urllib.request.urlopen(
f"http://{APP_HOST}:{APP_PORT}/api/status",
timeout=1
) as response:
if response.status == 200:
log(
f"Приложение запущено: "
f"http://{APP_HOST}:{APP_PORT}"
)
return 0
except OSError:
pass
time.sleep(POLL_INTERVAL)
raise LifecycleError(
"Приложение не ответило за время запуска. "
f"Проверь journalctl --user -u {UNIT_NAME}.service"
)
def stop_service():
if not unit_is_active():
log("Менеджер не запущен.")
return 0
active_project = active_service_project()
if active_project is None:
raise LifecycleError(
"Не удалось определить проект работающего сервиса. "
"Остановка отменена."
)
if active_project != PROJECT_ROOT:
raise LifecycleError(
f"Сервис запущен из другого проекта: {active_project}. "
f"Остановка из {PROJECT_ROOT} отменена."
)
run_sudo_validation()
systemctl_user(
"kill",
"--kill-whom=main",
"--signal=SIGTERM",
f"{UNIT_NAME}.service"
)
log(
"Запрошено штатное завершение. "
"Если сканер активен, останови его в веб-интерфейсе."
)
notified = False
while unit_is_active():
if not notified:
log(
"Ожидание завершения приложения и фоновых задач..."
)
notified = True
time.sleep(1)
log("Сервис остановлен.")
return 0
def show_status():
active = unit_is_active()
print(
"Application:",
"RUNNING" if active else "STOPPED"
)
if active:
active_project = active_service_project()
print(
"Active project:",
active_project if active_project is not None else "UNKNOWN"
)
if active:
try:
with urllib.request.urlopen(
f"http://{APP_HOST}:{APP_PORT}/api/status",
timeout=2
) as response:
data = json.loads(
response.read().decode("utf-8")
)
scanner = data.get("status", {})
gps = data.get("gps_test", {})
scanner_running = scanner.get("running", False)
scanner_health = scanner.get("health", "unknown")
scanner_pid = scanner.get("pid")
if scanner_running:
scanner_state = (
f"RUNNING (PID {scanner_pid}, "
f"health: {scanner_health})"
)
else:
scanner_state = (
f"STOPPED (health: {scanner_health})"
)
print("Scanner:", scanner_state)
print(
"GPS test:",
gps.get("state", "unknown")
)
print(
"Network action:",
"BUSY" if data.get("network_actions_busy") else "IDLE"
)
except Exception as error:
print(f"Application API: unavailable ({error})")
print(
"TileServer:",
"AVAILABLE" if style_is_available() else "UNAVAILABLE"
)
if active:
result = systemctl_user(
"show",
f"{UNIT_NAME}.service",
"--property=MainPID",
"--property=ActiveState",
check=False
)
if result.returncode == 0:
print(result.stdout.strip())
def install():
python = project_python()
if not python.is_file():
raise LifecycleError(
f"Не найдено виртуальное окружение: {python}"
)
if shutil.which("systemd-run") is None:
raise LifecycleError("Не найден systemd-run.")
if shutil.which("systemctl") is None:
raise LifecycleError("Не найден systemctl.")
if shutil.which("sudo") is None:
raise LifecycleError("Не найден sudo.")
try:
get_node_path()
except FileNotFoundError as error:
raise LifecycleError(
"Локальный Node.js не найден."
) from error
if not TILESERVER_ENTRY.is_file():
raise LifecycleError(
f"Не найден TileServer entry point: {TILESERVER_ENTRY}"
)
if not TILESERVER_CONFIG_PATH.is_file():
raise LifecycleError(
"Не найден TileServer config: "
f"{TILESERVER_CONFIG_PATH}"
)
check = subprocess.run(
[
str(python),
"-c",
"import flask, werkzeug"
],
check=False
)
if check.returncode != 0:
raise LifecycleError(
"Flask или Werkzeug недоступны в venv."
)
cli_path = PROJECT_ROOT / "wifi-gps-mapper"
if not cli_path.is_file():
raise LifecycleError(
f"Не найден CLI-файл: {cli_path}"
)
cli_path.chmod(
cli_path.stat().st_mode | 0o111
)
systemctl_user("show-environment")
log("Проверка окружения пройдена.")
log(f"CLI: {cli_path}")
log("TileServer не устанавливался и не изменялся.")
def main():
parser = argparse.ArgumentParser(
prog="wifi-gps-mapper"
)
parser.add_argument(
"--serve",
action="store_true",
help=argparse.SUPPRESS
)
parser.add_argument(
"command",
nargs="?",
choices=(
"install",
"start",
"status",
"stop",
"restart"
)
)
args = parser.parse_args()
try:
if args.serve:
run_server()
return 0
if args.command == "install":
install()
return 0
if args.command == "start":
return start_service()
if args.command == "status":
show_status()
return 0
if args.command == "stop":
return stop_service()
if args.command == "restart":
stop_service()
return start_service()
parser.print_help()
return 2
except (
LifecycleError,
subprocess.CalledProcessError,
OSError
) as error:
print(
f"Ошибка: {error}",
file=sys.stderr
)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+23 -28
View File
@@ -1,7 +1,10 @@
import logging
from pathlib import Path
from logging_config import (
LOG_DATE_FORMAT,
LOG_FORMAT,
UTCFormatter,
)
def setup_logger():
@@ -13,36 +16,28 @@ def setup_logger():
)
file_handler = logging.FileHandler(
"logs/project.log"
)
console_handler = logging.StreamHandler()
for handler in (
file_handler,
console_handler,
):
handler.setFormatter(
UTCFormatter(
LOG_FORMAT,
datefmt=LOG_DATE_FORMAT,
)
)
logging.basicConfig(
level=logging.INFO,
format=(
"%(asctime)s "
"[%(levelname)s] "
"%(name)s: "
"%(message)s"
),
handlers=[
logging.FileHandler(
"logs/project.log"
),
logging.StreamHandler()
]
file_handler,
console_handler,
],
)
+16
View File
@@ -0,0 +1,16 @@
import logging
import time
LOG_FORMAT = (
"%(asctime)s.%(msecs)03dZ "
"[%(levelname)s] "
"%(name)s: "
"%(message)s"
)
LOG_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"
class UTCFormatter(logging.Formatter):
converter = staticmethod(time.gmtime)
-229
View File
@@ -1,229 +0,0 @@
import csv
import logging
class OUIImporter:
def __init__(
self,
resolver,
files
):
self.logger = logging.getLogger(
"oui-import"
)
self.resolver = resolver
self.files = files
# =====================================================
# Импорт IEEE
# =====================================================
def import_database(self):
count = 0
skipped = 0
stats = {
"MA-L": 0,
"MA-M": 0,
"MA-S": 0
}
for filename in self.files:
if not filename.exists():
self.logger.warning(
f"{filename.name} not found"
)
continue
self.logger.info(
f"Importing {filename.name}"
)
with open(
filename,
"r",
encoding="utf-8",
errors="ignore"
) as file:
reader = csv.DictReader(
file
)
for row in reader:
registry = row.get(
"Registry"
)
assignment = row.get(
"Assignment"
)
organization = row.get(
"Organization Name"
)
if not registry:
continue
if registry not in stats:
continue
if not assignment:
skipped += 1
continue
if not organization:
skipped += 1
continue
assignment = (
assignment
.replace(
"-",
""
)
.replace(
":",
""
)
.replace(
".",
""
)
.strip()
.upper()
)
if not all(
char in "0123456789ABCDEF"
for char in assignment
):
skipped += 1
continue
if len(
assignment
) not in (
6,
7,
9
):
skipped += 1
continue
result = self.resolver.add_vendor(
assignment,
organization.strip(),
registry
)
if result:
count += 1
stats[
registry
] += 1
else:
skipped += 1
self.resolver.commit()
total = self.resolver.count()
self.logger.info(
f"Imported: {count}"
)
self.logger.info(
f"Skipped: {skipped}"
)
self.logger.info(
f"Database records: {total}"
)
return {
"imported": count,
"skipped": skipped,
"total": total,
"stats": stats
}
+52 -15
View File
@@ -1,7 +1,7 @@
import subprocess
import logging
import csv
import sqlite3
from datetime import datetime, timedelta, timezone
import pynmea2
from scapy.all import PcapNgReader
@@ -9,6 +9,11 @@ from scapy.layers.dot11 import Dot11
from scapy.layers.eap import EAPOL
from bisect import bisect_left
from vendor import VendorResolver
from logging_config import (
LOG_DATE_FORMAT,
LOG_FORMAT,
UTCFormatter,
)
class CaptureParser:
@@ -25,9 +30,17 @@ class CaptureParser:
#
# Определение производителей
#
self.vendor = VendorResolver(
self.config.vendor_database
)
try:
self.vendor = VendorResolver(
self.config.vendor_database
)
except sqlite3.Error as exc:
self.vendor = None
logging.getLogger("parser").warning(
"OUI database unavailable: %s",
exc
)
self.log = logging.getLogger(
"parser"
@@ -64,8 +77,9 @@ class CaptureParser:
session.parser_log
)
formatter = logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s"
formatter = UTCFormatter(
LOG_FORMAT,
datefmt=LOG_DATE_FORMAT,
)
handler.setFormatter(
@@ -317,8 +331,10 @@ class CaptureParser:
timestamp
)
vendor = self.vendor.lookup(
row[2]
vendor = (
self.vendor.lookup(row[2])
if self.vendor
else "Unknown"
)
@@ -347,7 +363,7 @@ class CaptureParser:
"country":
row[7],
"vendor":
vendor,
@@ -487,7 +503,22 @@ class CaptureParser:
# WPA*02*hash*APMAC*CLIENTMAC*ESSID*...
hash_type = parts[1]
handshake_type = {
"01": "PMKID",
"02": "EAPOL"
}.get(hash_type)
if handshake_type is None:
self.log.warning(
"Unsupported WPA hash type: %s",
hash_type
)
continue
hash22000 = line
ap_bssid = self.normalize_mac(
@@ -498,10 +529,16 @@ class CaptureParser:
parts[4]
)
captured_at = self.find_handshake_time(
ap_bssid,
client_mac
)
if handshake_type == "EAPOL":
captured_at = self.find_handshake_time(
ap_bssid,
client_mac
)
else:
captured_at = None
gps = self.gps_from_timestamp(
captured_at
@@ -559,7 +596,7 @@ class CaptureParser:
"type":
"EAPOL",
handshake_type,
"hash22000":
+220
View File
@@ -0,0 +1,220 @@
import threading
import time
class RequestLifecycleMiddleware:
ALLOWED_DURING_SHUTDOWN = {
("GET", "/"),
("HEAD", "/"),
("GET", "/api/status"),
("GET", "/api/gps-test"),
("POST", "/scanner/stop"),
("POST", "/gps-test/stop"),
}
UNTRACKED_DURING_SHUTDOWN = {
("GET", "/"),
("HEAD", "/"),
("GET", "/api/status"),
("GET", "/api/gps-test"),
}
STATIC_PREFIXES = (
"/static/",
"/reports/static/",
)
def __init__(self, application):
self.application = application
self._condition = threading.Condition()
self._shutdown_requested = False
self._active_requests = 0
@property
def shutdown_requested(self):
with self._condition:
return self._shutdown_requested
@property
def active_requests(self):
with self._condition:
return self._active_requests
def begin_shutdown(self):
with self._condition:
self._shutdown_requested = True
self._condition.notify_all()
def wait_for_drain(self, timeout=None):
deadline = (
None
if timeout is None
else time.monotonic() + timeout
)
with self._condition:
while self._active_requests:
remaining = (
None
if deadline is None
else deadline - time.monotonic()
)
if remaining is not None and remaining <= 0:
return False
self._condition.wait(remaining)
return True
def _is_allowed_during_shutdown(self, method, path):
if (method, path) in self.ALLOWED_DURING_SHUTDOWN:
return True
if method not in ("GET", "HEAD"):
return False
return any(
path.startswith(prefix)
for prefix in self.STATIC_PREFIXES
)
def _release_request(self):
with self._condition:
self._active_requests -= 1
self._condition.notify_all()
def __call__(self, environ, start_response):
method = environ.get("REQUEST_METHOD", "GET").upper()
path = environ.get("PATH_INFO", "/")
track_request = True
with self._condition:
if self._shutdown_requested:
if not self._is_allowed_during_shutdown(
method,
path
):
body = b"Application is shutting down.\n"
start_response(
"503 Service Unavailable",
[
("Content-Type", "text/plain; charset=utf-8"),
("Content-Length", str(len(body))),
("Retry-After", "5"),
("Cache-Control", "no-store"),
]
)
return [body]
if (
(method, path) in self.UNTRACKED_DURING_SHUTDOWN
or (
method in ("GET", "HEAD")
and any(
path.startswith(prefix)
for prefix in self.STATIC_PREFIXES
)
)
):
track_request = False
if track_request:
self._active_requests += 1
if not track_request:
return self.application(
environ,
start_response
)
try:
response = self.application(
environ,
start_response
)
except BaseException:
self._release_request()
raise
return _TrackedIterable(
response,
self._release_request
)
class _TrackedIterable:
def __init__(self, iterable, release):
self._iterable = iterable
self._iterator = iter(iterable)
self._release = release
self._closed = False
def __iter__(self):
return self
def __next__(self):
try:
return next(self._iterator)
except BaseException:
self.close()
raise
def close(self):
if self._closed:
return
self._closed = True
try:
close = getattr(
self._iterable,
"close",
None
)
if close is not None:
close()
finally:
self._release()
+42
View File
@@ -0,0 +1,42 @@
import os
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
NODE_BIN_DIR = PROJECT_ROOT / "runtime" / "node" / "bin"
def _runtime_executable(name):
executable = NODE_BIN_DIR / name
if not executable.is_file() or not os.access(executable, os.X_OK):
raise FileNotFoundError(
f"Локальный исполняемый файл {name} не найден: {executable}"
)
return executable
def get_node_path():
return _runtime_executable("node")
def get_npm_path():
return _runtime_executable("npm")
def get_npx_path():
return _runtime_executable("npx")
def get_runtime_env():
environment = os.environ.copy()
current_path = environment.get("PATH", "")
environment["PATH"] = (
f"{NODE_BIN_DIR}{os.pathsep}{current_path}"
if current_path
else str(NODE_BIN_DIR)
)
return environment
-1
View File
@@ -275,4 +275,3 @@ class Session:
self.gps_positions += 1
+105
View File
@@ -0,0 +1,105 @@
"""
Shared TileServer configuration loader.
"""
import os
from pathlib import Path
import yaml
DEFAULT_ENTRY = "node_modules/tileserver-gl-light/src/main.js"
DEFAULT_CONFIG = "config.json"
DEFAULT_STYLE = "server-map"
def load_tileserver_config(project_root):
project_root = Path(project_root).expanduser().resolve()
config_file = project_root / "config" / "config.yaml"
try:
with config_file.open("r", encoding="utf-8") as file:
application_config = yaml.safe_load(file) or {}
except (OSError, yaml.YAMLError) as error:
raise RuntimeError(
f"Не удалось загрузить конфигурацию {config_file}: {error}"
) from error
if not isinstance(application_config, dict):
raise RuntimeError(
"Корень config/config.yaml должен быть YAML-объектом."
)
section = application_config.get("tileserver", {})
if not isinstance(section, dict):
raise RuntimeError(
"Раздел tileserver в config/config.yaml должен быть YAML-объектом."
)
directory_value = os.environ.get(
"WIFI_GPS_TILESERVER_DIR",
section.get("directory", "map-server")
)
directory = Path(directory_value).expanduser()
if "WIFI_GPS_TILESERVER_DIR" not in os.environ and not directory.is_absolute():
directory = project_root / directory
directory = directory.resolve()
entry_from_environment = "WIFI_GPS_TILESERVER_ENTRY" in os.environ
entry_value = os.environ.get(
"WIFI_GPS_TILESERVER_ENTRY",
section.get("entry", DEFAULT_ENTRY)
)
entry = Path(entry_value).expanduser()
if not entry.is_absolute() and not entry_from_environment:
entry = directory / entry
config_value = os.environ.get(
"WIFI_GPS_TILESERVER_CONFIG",
section.get("config", DEFAULT_CONFIG)
)
config = Path(config_value).expanduser()
config_path = config if config.is_absolute() else directory / config
host = str(section.get("host", "127.0.0.1")).strip()
try:
port = int(
os.environ.get(
"WIFI_GPS_TILESERVER_PORT",
section.get("port", 8080)
)
)
except (TypeError, ValueError) as error:
raise RuntimeError("Некорректный порт TileServer.") from error
if not host:
raise RuntimeError("Не задан host для TileServer.")
if not 1 <= port <= 65535:
raise RuntimeError(f"Некорректный порт TileServer: {port}")
style = str(section.get("style", DEFAULT_STYLE)).strip().strip("/")
if not style:
raise RuntimeError("Не задан style для TileServer.")
return {
"host": host,
"port": port,
"directory": directory,
"entry": entry,
"config": str(config),
"config_path": config_path,
"style": style,
"style_url": (
f"http://{host}:{port}/styles/{style}/style.json"
),
}
+20 -10
View File
@@ -8,24 +8,34 @@ class VendorResolver:
def __init__(
self,
database
database,
writable=False
):
self.db_path = Path(database)
self.writable = writable
if writable:
self.db_path.parent.mkdir(
parents=True,
exist_ok=True
)
self.db_path.parent.mkdir(
parents=True,
exist_ok=True
)
self.conn = sqlite3.connect(
self.db_path
)
self.create_tables()
self.conn = sqlite3.connect(
self.db_path
)
else:
self.conn = sqlite3.connect(
f"{self.db_path.resolve().as_uri()}?mode=ro",
uri=True
)
self.create_tables()
self.conn.execute(
"SELECT 1 FROM oui LIMIT 0"
)
-314
View File
@@ -1,314 +0,0 @@
import logging
import urllib.request
import datetime
import time
from pathlib import Path
from vendor import VendorResolver
from oui_import import OUIImporter
PROJECT_ROOT = (
Path(__file__).resolve().parent.parent
)
DATABASE_DIR = (
PROJECT_ROOT
/
"database"
)
OUI_DATABASE = (
DATABASE_DIR
/
"oui.sqlite"
)
HTTP_HEADERS = {
"User-Agent":
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 "
"(KHTML, like Gecko) "
"Chrome/138.0 Safari/537.36"
}
DOWNLOAD_RETRIES = 3
DOWNLOAD_TIMEOUT = 60
CSV_FILES = {
"oui.csv": "oui",
"mam.csv": "mam",
"oui36.csv": "oui36",
}
class VendorImporter:
def __init__(
self,
config
):
self.config = config
self.log = logging.getLogger(
"vendor_import"
)
DATABASE_DIR.mkdir(
parents=True,
exist_ok=True
)
# ---------------------------------------------------------
# Загрузка IEEE CSV
# ---------------------------------------------------------
def download_csv_files(self):
for filename, key in CSV_FILES.items():
url = self.config.vendor_sources[key]
destination = (
DATABASE_DIR
/
filename
)
success = False
for attempt in range(
1,
DOWNLOAD_RETRIES + 1
):
self.log.info(
f"Downloading {filename} "
f"(attempt {attempt}/{DOWNLOAD_RETRIES})"
)
try:
request = urllib.request.Request(
url,
headers=HTTP_HEADERS
)
with urllib.request.urlopen(
request,
timeout=DOWNLOAD_TIMEOUT
) as response:
if response.status != 200:
raise RuntimeError(
f"HTTP {response.status}"
)
data = response.read()
if len(data) < 1000:
raise RuntimeError(
"Downloaded file is too small"
)
text = data.decode(
"utf-8",
errors="ignore"
)
if "Assignment" not in text:
raise RuntimeError(
"Invalid IEEE CSV"
)
destination.write_bytes(
data
)
size = (
destination.stat().st_size
/ 1024
/ 1024
)
self.log.info(
f"{filename} downloaded "
f"({size:.2f} MB)"
)
success = True
break
except KeyboardInterrupt:
self.log.info(
"CSV download cancelled"
)
raise
except Exception as error:
self.log.warning(
f"{filename}: {error}"
)
if destination.exists():
destination.unlink()
if attempt < DOWNLOAD_RETRIES:
time.sleep(2)
if not success:
raise RuntimeError(
f"Unable to download {filename}"
)
# ---------------------------------------------------------
# Полное создание IEEE базы
# ---------------------------------------------------------
def bootstrap(self):
OUI_DATABASE.unlink(
missing_ok=True
)
self.download_csv_files()
resolver = VendorResolver(
OUI_DATABASE
)
importer = OUIImporter(
resolver,
[
DATABASE_DIR
/
filename
for filename
in CSV_FILES
]
)
result = importer.import_database()
total = result["total"]
stats = result["stats"]
if (
stats["MA-L"] < 35000
or
stats["MA-M"] < 5000
or
stats["MA-S"] < 5000
):
resolver.close()
OUI_DATABASE.unlink(
missing_ok=True
)
raise RuntimeError(
"IEEE database verification failed.\n\n"
f"MA-L: {stats['MA-L']}\n"
f"MA-M: {stats['MA-M']}\n"
f"MA-S: {stats['MA-S']}"
)
resolver.set_metadata(
"last_import",
datetime.datetime.now(
datetime.timezone.utc
).isoformat().replace(
"+00:00",
"Z"
)
)
resolver.set_metadata(
"records",
total
)
resolver.set_metadata(
"schema_version",
1
)
resolver.set_metadata(
"import_status",
"ok"
)
resolver.commit()
resolver.close()
self.log.info(
"IEEE database created: "
f"{total} records"
)
+322 -98
View File
@@ -214,10 +214,6 @@ class VendorService:
candidate
)
ap_impact = self._calculate_ap_impact(
candidate
)
progress(
"ready",
message="Обновление готово к применению"
@@ -232,8 +228,7 @@ class VendorService:
),
"sources": downloaded,
"build": build_stats,
"oui": oui_diff,
"ap": ap_impact
"oui": oui_diff
}
except Exception:
@@ -1157,6 +1152,15 @@ class VendorService:
.upper()
)
if (
len(normalized) != 12
or any(
character not in "0123456789ABCDEF"
for character in normalized
)
):
return None
for length in (
9,
7,
@@ -1205,11 +1209,13 @@ class VendorService:
"access_points table is missing"
)
column_info = conn.execute(
"PRAGMA table_info(access_points)"
).fetchall()
columns = {
row[1]
for row in conn.execute(
"PRAGMA table_info(access_points)"
).fetchall()
for row in column_info
}
required = {
@@ -1217,24 +1223,292 @@ class VendorService:
"vendor"
}
if not required.issubset(
columns
):
primary_key_columns = [
row
for row in column_info
if row[5] > 0
]
id_column = next(
(
row
for row in column_info
if row[1] == "id"
),
None
)
if (
not required.issubset(columns)
or id_column is None
or str(id_column[2]).upper() != "INTEGER"
or id_column[5] != 1
or len(primary_key_columns) != 1
):
raise ValueError(
"Invalid WiFi database schema"
)
# ============================================================
# Recalculate access point vendors
# ============================================================
def recalculate_ap_vendors(
self,
progress_callback=None
):
def progress(
stage,
message=None
):
if progress_callback is not None:
progress_callback(
stage,
None,
message
)
if not self.vendor_database.is_file():
raise FileNotFoundError(
f"OUI database not found: {self.vendor_database}"
)
if not self.wifi_database.is_file():
raise FileNotFoundError(
f"WiFi database not found: {self.wifi_database}"
)
oui_conn = None
wifi_conn = None
try:
oui_uri = (
f"{self.vendor_database.resolve().as_uri()}"
"?mode=ro"
)
oui_conn = sqlite3.connect(
oui_uri,
uri=True,
timeout=30
)
self._validate_schema(
oui_conn
)
wifi_conn = sqlite3.connect(
self.wifi_database,
timeout=30
)
self._validate_wifi_schema(
wifi_conn
)
wifi_conn.execute(
"BEGIN IMMEDIATE"
)
total = wifi_conn.execute(
"""
SELECT COUNT(*)
FROM access_points
"""
).fetchone()[0]
stats = {
"total": total,
"checked": 0,
"updated": 0,
"filled": 0,
"refreshed": 0,
"cleared": 0,
"unknown": 0,
"unchanged": 0
}
def iter_rows():
last_id = None
while True:
if last_id is None:
batch = wifi_conn.execute(
"""
SELECT
id,
bssid,
vendor
FROM access_points
ORDER BY id
LIMIT 1000
"""
).fetchall()
else:
batch = wifi_conn.execute(
"""
SELECT
id,
bssid,
vendor
FROM access_points
WHERE id > ?
ORDER BY id
LIMIT 1000
""",
(
last_id,
)
).fetchall()
if not batch:
break
last_id = batch[-1][0]
yield from batch
placeholders = (
None,
"",
"-",
"Unknown"
)
progress(
"recalculating",
f"Проверка точек доступа: {total}"
)
progress_interval = max(
1,
total // 100
)
def report_progress():
if (
stats["checked"] % progress_interval == 0
or stats["checked"] == total
):
progress(
"recalculating",
(
f"Проверено {stats['checked']} "
f"из {total}"
)
)
for ap_id, bssid, current_vendor in iter_rows():
stats["checked"] += 1
new_vendor = self._lookup_vendor(
oui_conn,
bssid
)
is_placeholder = (
current_vendor in placeholders
)
if new_vendor is None:
stats["unknown"] += 1
if is_placeholder:
stats["unchanged"] += 1
report_progress()
continue
desired_vendor = None
stats["cleared"] += 1
else:
desired_vendor = new_vendor
if current_vendor == desired_vendor:
stats["unchanged"] += 1
report_progress()
continue
if is_placeholder:
stats["filled"] += 1
else:
stats["refreshed"] += 1
wifi_conn.execute(
"""
UPDATE access_points
SET vendor=?
WHERE id=?
""",
(
desired_vendor,
ap_id
)
)
stats["updated"] += 1
report_progress()
progress(
"committing",
"Сохранение результатов"
)
wifi_conn.commit()
progress(
"ready",
"Перерасчёт завершён"
)
return stats
except Exception:
if wifi_conn is not None:
wifi_conn.rollback()
raise
finally:
if wifi_conn is not None:
wifi_conn.close()
if oui_conn is not None:
oui_conn.close()
# ============================================================
# Apply
# ============================================================
def apply(
self,
preview,
unknown_to_vendor=True,
vendor_to_vendor=False,
vendor_to_unknown=False
preview
):
candidate = Path(
@@ -1260,58 +1534,8 @@ class VendorService:
"identical"
]
selected = {
"unknown_to_vendor":
bool(
unknown_to_vendor
),
"vendor_to_vendor":
bool(
vendor_to_vendor
),
"vendor_to_unknown":
bool(
vendor_to_unknown
)
}
selected_count = 0
if selected[
"unknown_to_vendor"
]:
selected_count += preview[
"ap"
][
"unknown_to_vendor"
]
if selected[
"vendor_to_vendor"
]:
selected_count += preview[
"ap"
][
"vendor_to_vendor"
]
if selected[
"vendor_to_unknown"
]:
selected_count += preview[
"ap"
][
"vendor_to_unknown"
]
result = {
"oui_updated": False,
"wifi_updated": 0,
"selected": selected,
"selected_count": selected_count
"oui_updated": False
}
try:
@@ -1332,15 +1556,6 @@ class VendorService:
"oui_updated"
] = True
if selected_count:
result[
"wifi_updated"
] = self._apply_wifi_changes(
preview,
selected
)
return result
finally:
@@ -1524,6 +1739,35 @@ class VendorService:
f"{database_type}-"
)
timestamp = datetime.now(
timezone.utc
).strftime(
"%Y%m%d-%H%M%S-%f"
)
backup = (
self.backup_directory
/
(
f"{prefix}"
f"{timestamp}"
f".sqlite3"
)
)
try:
shutil.copy2(
database,
backup
)
except Exception:
try:
backup.unlink()
except OSError:
pass
raise
backups = sorted(
self.backup_directory.glob(
f"{prefix}*.sqlite*"
@@ -1532,32 +1776,12 @@ class VendorService:
reverse=True
)
while len(
backups
) >= self.BACKUP_LIMIT:
oldest = backups.pop()
for old_backup in backups[self.BACKUP_LIMIT:]:
try:
oldest.unlink()
old_backup.unlink()
except OSError:
pass
backup = (
self.backup_directory
/
(
f"{prefix}"
f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}"
f".sqlite3"
)
)
shutil.copy2(
database,
backup
)
return backup
# ============================================================
-373
View File
@@ -1,373 +0,0 @@
import logging
import urllib.request
from pathlib import Path
from vendor import VendorResolver
from vendor_import import (
VendorImporter,
CSV_FILES
)
logger = logging.getLogger(
"vendor-update"
)
class VendorUpdater:
def __init__(
self,
cfg
):
self.cfg = cfg
self.project_root = (
Path(__file__)
.resolve()
.parent
.parent
)
self.database = (
self.project_root
/ "database"
/ "oui.sqlite"
)
self.csv_files = [
self.project_root
/ "database"
/ filename
for filename
in CSV_FILES
]
# =====================================================
# Проверка CSV
# =====================================================
def csv_exists(
self
):
for file in self.csv_files:
if not file.exists():
return False
return True
# =====================================================
# Проверка базы
# =====================================================
def database_exists(
self
):
return self.database.exists()
# =====================================================
# Проверка metadata
# =====================================================
def metadata_exists(
self
):
resolver = VendorResolver(
self.database
)
result = resolver.has_metadata(
"last_import"
)
resolver.close()
return result
# =====================================================
# Создание базы IEEE
# =====================================================
def create_database(
self
):
logger.info(
"Creating IEEE OUI database..."
)
importer = VendorImporter(
self.cfg
)
importer.import_database()
logger.info(
"IEEE database created"
)
# =====================================================
# Проверка IEEE базы
# =====================================================
def check(
self
):
logger.info(
"Checking IEEE vendor database..."
)
#
# База уже существует
#
if self.database_exists():
if self.database.stat().st_size < 10000:
logger.warning(
"IEEE database corrupted"
)
self.database.unlink()
self.check()
return
logger.info(
"IEEE database found"
)
if self.metadata_exists():
logger.info(
"IEEE metadata found"
)
return
logger.warning(
"IEEE metadata missing"
)
resolver = VendorResolver(
self.database
)
if resolver.count() == 0:
resolver.close()
logger.warning(
"IEEE database is empty"
)
self.database.unlink()
self.check()
return
resolver.set_metadata(
"last_import",
"unknown"
)
resolver.commit()
resolver.close()
logger.info(
"IEEE metadata restored"
)
return
#
# Базы нет
#
logger.warning(
"IEEE database not found"
)
#
# Проверяем CSV
#
if not self.csv_exists():
logger.warning(
"IEEE CSV files not found"
)
self.download_csv()
logger.info(
"IEEE CSV files found"
)
#
# Создаем базу
#
self.create_database()
# =====================================================
# Загрузка IEEE CSV
# =====================================================
def download_csv(
self
):
logger.info(
"Downloading IEEE CSV files..."
)
self.database.parent.mkdir(
parents=True,
exist_ok=True
)
downloads = [
(
self.cfg.vendor_sources[key],
self.project_root
/
"database"
/
filename
)
for filename, key
in CSV_FILES.items()
]
for url, filename in downloads:
logger.info(
f"Downloading {filename.name}"
)
try:
urllib.request.urlretrieve(
url,
filename
)
except Exception as error:
logger.error(
f"Download failed: {filename.name}"
)
raise RuntimeError(
str(error)
)
if not filename.exists():
raise RuntimeError(
f"{filename.name} download failed"
)
if filename.stat().st_size < 1000:
raise RuntimeError(
f"{filename.name} is too small"
)
size = (
filename.stat().st_size
/ 1024
/ 1024
)
logger.info(
f"{filename.name} downloaded "
f"({size:.2f} MB)"
)
logger.info(
"IEEE CSV download finished"
)
File diff suppressed because it is too large Load Diff
-1
View File
@@ -2729,4 +2729,3 @@ def import_wifitrip(
)
return result