Release WiFiTrip format v2.0.0

This commit is contained in:
2026-11-22 09:55:25 +03:00
parent 427f5759c9
commit cb2e659a57
9 changed files with 1117 additions and 3374 deletions
+3
View File
@@ -112,6 +112,9 @@ reports:
# Количество последних сессий, отображаемых в соответствующих разделах. # Количество последних сессий, отображаемых в соответствующих разделах.
recent_sessions_limit: 10 recent_sessions_limit: 10
# Количество сессий на странице Capture Sessions по умолчанию.
sessions_page_limit: 20
# Настройки журналирования приложения. # Настройки журналирования приложения.
logging: logging:
# Уровень подробности журналов. # Уровень подробности журналов.
+75 -8
View File
@@ -58,8 +58,10 @@ from reports.hashcat import (
) )
from reports.trips_page import render_trips_page from reports.trips_page import render_trips_page
from reports.wifitrip import ( from reports.wifitrip import (
WifitripError,
export_wifitrip, export_wifitrip,
import_wifitrip, import_wifitrip,
select_wifitrip_session_ids,
validate_wifitrip, validate_wifitrip,
) )
from reports.session_page import render_session_page from reports.session_page import render_session_page
@@ -2039,7 +2041,8 @@ def reports_dashboard():
def reports_capture_sessions(): def reports_capture_sessions():
return render_report( return render_report(
generate_capture_sessions generate_capture_sessions,
sessions_page_limit=request.args.get("limit"),
) )
@app.route("/reports/trips/") @app.route("/reports/trips/")
@@ -2050,9 +2053,64 @@ def reports_trips():
) )
@app.route("/reports/trips/preview")
def reports_trips_preview():
conn = connect_database()
try:
session_ids = select_wifitrip_session_ids(
conn,
mode=request.args.get("mode", "all"),
limit=request.args.get("limit", "1"),
date_from=request.args.get("date_from"),
date_to=request.args.get("date_to"),
)
available_count = conn.execute(
"SELECT COUNT(*) FROM capture_sessions"
).fetchone()[0]
except WifitripError as exc:
return jsonify(
{
"error": str(exc),
}
), 400
finally:
close_database(conn)
return jsonify(
{
"count": len(session_ids),
"available_count": available_count,
}
)
@app.route("/reports/trips/export") @app.route("/reports/trips/export")
def reports_trips_export(): def reports_trips_export():
conn = connect_database()
output_path = None
try:
session_ids = select_wifitrip_session_ids(
conn,
mode=request.args.get("mode", "all"),
limit=request.args.get("limit", "1"),
date_from=request.args.get("date_from"),
date_to=request.args.get("date_to"),
)
if not session_ids:
return jsonify(
{
"error": "No capture sessions match the selected criteria.",
}
), 400
filename = ( filename = (
"wifi-gps-mapper-" "wifi-gps-mapper-"
f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}.wifitrip" f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}.wifitrip"
@@ -2070,27 +2128,36 @@ def reports_trips_export():
temp_file.close() temp_file.close()
output_path = ( output_path = temp_path.with_name(
temp_path.with_name(
filename filename
) )
)
temp_path.unlink( temp_path.unlink(
missing_ok=True missing_ok=True
) )
conn = connect_database()
try:
result = export_wifitrip( result = export_wifitrip(
conn, conn,
output_path=output_path, output_path=output_path,
session_ids=session_ids,
) )
except WifitripError as exc:
if output_path is not None:
output_path.unlink(
missing_ok=True
)
return jsonify(
{
"error": str(exc),
}
), 400
except Exception: except Exception:
if output_path is not None:
output_path.unlink( output_path.unlink(
missing_ok=True missing_ok=True
) )
+9
View File
@@ -56,6 +56,15 @@ RECENT_SESSIONS_LIMIT = REPORTS_CONFIG.get(
10 10
) )
try:
SESSIONS_PAGE_LIMIT = int(
REPORTS_CONFIG.get("sessions_page_limit", 20)
)
if SESSIONS_PAGE_LIMIT <= 0:
raise ValueError
except (TypeError, ValueError):
SESSIONS_PAGE_LIMIT = 20
TIMEZONE = CONFIG.get("timezone", "Europe/Moscow") TIMEZONE = CONFIG.get("timezone", "Europe/Moscow")
@lru_cache(maxsize=1) @lru_cache(maxsize=1)
+161 -2
View File
@@ -20,6 +20,7 @@ from pathlib import Path
from .config import ( from .config import (
RECENT_SESSIONS_LIMIT, RECENT_SESSIONS_LIMIT,
SESSIONS_PAGE_LIMIT,
) )
from .utils import ( from .utils import (
@@ -807,8 +808,21 @@ def generate_dashboard(
def generate_capture_sessions( def generate_capture_sessions(
conn, conn,
context=None, context=None,
sessions_page_limit=None,
): ):
if sessions_page_limit is None:
display_limit = SESSIONS_PAGE_LIMIT
elif str(sessions_page_limit).lower() == "all":
display_limit = "all"
else:
try:
display_limit = int(sessions_page_limit)
if display_limit <= 0:
raise ValueError
except (TypeError, ValueError):
display_limit = SESSIONS_PAGE_LIMIT
sessions = all_sessions( sessions = all_sessions(
conn conn
) )
@@ -957,7 +971,7 @@ Total sessions: <b>{len(sessions)}</b>
</article> </article>
""") """)
html += """ html += f"""
<div class="session-list-toolbar"> <div class="session-list-toolbar">
@@ -981,12 +995,40 @@ Total sessions: <b>{len(sessions)}</b>
↓ ↓
</button> </button>
<label for="session-limit">
Show:
</label>
<select id="session-limit">
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="500">500</option>
<option value="all">All</option>
<option value="custom">Custom</option>
</select>
<input
type="number"
id="session-custom-limit"
min="1"
step="1"
placeholder="Number"
aria-label="Custom number of sessions"
style="width: 100px;"
>
<span id="session-count"></span>
</div> </div>
<div <div
class="session-list" class="session-list"
id="session-list" id="session-list"
data-sort-direction="desc" data-sort-direction="desc"
data-display-limit="{display_limit}"
data-default-limit="{SESSIONS_PAGE_LIMIT}"
> >
""" """
@@ -1002,13 +1044,83 @@ Total sessions: <b>{len(sessions)}</b>
const list = document.getElementById("session-list"); const list = document.getElementById("session-list");
const sortSelect = document.getElementById("session-sort"); const sortSelect = document.getElementById("session-sort");
const directionButton = document.getElementById("session-sort-direction"); const directionButton = document.getElementById("session-sort-direction");
const limitSelect = document.getElementById("session-limit");
const customLimitInput = document.getElementById("session-custom-limit");
const sessionCount = document.getElementById("session-count");
if (!list || !sortSelect || !directionButton) { if (
!list ||
!sortSelect ||
!directionButton ||
!limitSelect ||
!customLimitInput ||
!sessionCount
) {
return; return;
} }
let descending = true; let descending = true;
const defaultLimit = Number(list.dataset.defaultLimit) || 20;
const initialLimit = list.dataset.displayLimit;
const predefinedLimits = ["10", "20", "50", "100", "500", "all"];
function getDisplayLimit() {
if (limitSelect.value === "all") {
return "all";
}
if (limitSelect.value === "custom") {
const value = Number(customLimitInput.value);
if (
!Number.isInteger(value) ||
value <= 0
) {
return defaultLimit;
}
return value;
}
return Number(limitSelect.value) || defaultLimit;
}
function updateUrl() {
const params = new URLSearchParams(window.location.search);
const limit = getDisplayLimit();
params.set("limit", String(limit));
const query = params.toString();
const newUrl = window.location.pathname +
(query ? "?" + query : "") +
window.location.hash;
window.history.replaceState({}, "", newUrl);
}
function applyDisplayLimit() {
const cards = Array.from(
list.querySelectorAll(".session-compact-card")
);
const limit = getDisplayLimit();
const visibleCount = limit === "all"
? cards.length
: Math.min(cards.length, limit);
cards.forEach(function (card, index) {
card.style.display = index >= visibleCount ? "none" : "";
});
sessionCount.textContent =
"Showing " + visibleCount + " of " + cards.length;
}
function sortSessions() { function sortSessions() {
const sortBy = sortSelect.value; const sortBy = sortSelect.value;
@@ -1071,6 +1183,8 @@ Total sessions: <b>{len(sessions)}</b>
directionButton.textContent = descending ? "↓" : "↑"; directionButton.textContent = descending ? "↓" : "↑";
list.dataset.sortDirection = descending ? "desc" : "asc"; list.dataset.sortDirection = descending ? "desc" : "asc";
applyDisplayLimit();
} }
sortSelect.addEventListener("change", function () { sortSelect.addEventListener("change", function () {
@@ -1087,6 +1201,51 @@ Total sessions: <b>{len(sessions)}</b>
sortSessions(); sortSessions();
}); });
limitSelect.addEventListener("change", function () {
if (limitSelect.value !== "custom") {
customLimitInput.value = "";
}
if (limitSelect.value === "custom") {
customLimitInput.focus();
}
applyDisplayLimit();
updateUrl();
});
customLimitInput.addEventListener("input", function () {
limitSelect.value = "custom";
const value = Number(customLimitInput.value);
if (
Number.isInteger(value) &&
value > 0
) {
applyDisplayLimit();
updateUrl();
} else {
applyDisplayLimit();
}
});
if (initialLimit === "all") {
limitSelect.value = "all";
} else if (predefinedLimits.includes(initialLimit)) {
limitSelect.value = initialLimit;
} else {
limitSelect.value = "custom";
customLimitInput.value = initialLimit;
}
sortSessions(); sortSessions();
})(); })();
+168 -2
View File
@@ -593,11 +593,13 @@ code {
margin-bottom: 18px; margin-bottom: 18px;
} }
.session-list-toolbar label { .session-list-toolbar label,
.session-list-toolbar #session-count {
color: var(--muted); color: var(--muted);
} }
.session-list-toolbar select { .session-list-toolbar select,
.session-list-toolbar input[type="number"] {
background: var(--surface); background: var(--surface);
color: var(--text); color: var(--text);
@@ -1727,3 +1729,167 @@ body .maplibregl-popup-close-button:hover {
cursor: pointer; cursor: pointer;
font-weight: 600; font-weight: 600;
} }
/* ============================================================
WiFiTrip export selection
============================================================ */
.wifitrip-export-options {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 18px;
margin-top: 22px;
}
.wifitrip-export-mode {
min-width: 0;
padding: 16px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 9px;
transition:
border-color 0.15s ease,
background 0.15s ease;
}
.wifitrip-export-mode:has(.wifitrip-mode-tab input:checked) {
border-color: var(--accent);
background: var(--surface-light);
}
.wifitrip-mode-tab {
display: flex;
align-items: center;
gap: 10px;
min-height: 24px;
color: var(--muted);
font-size: 15px;
font-weight: 700;
cursor: pointer;
}
.wifitrip-mode-tab input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
pointer-events: none;
}
.wifitrip-mode-tab span {
display: block;
width: 100%;
padding: 5px 0 12px;
border-bottom: 2px solid transparent;
transition:
color 0.15s ease,
border-color 0.15s ease;
}
.wifitrip-mode-tab input:checked + span {
color: var(--text);
border-bottom-color: var(--accent);
}
.wifitrip-mode-tab input:focus-visible + span {
outline: 2px solid var(--accent);
outline-offset: 4px;
}
.wifitrip-mode-content {
display: flex;
flex-direction: column;
gap: 9px;
margin-top: 16px;
}
.wifitrip-mode-content label {
color: var(--muted);
font-size: 13px;
}
.wifitrip-mode-content .session-list-toolbar label {
font-size: inherit;
}
.wifitrip-mode-content > select,
.wifitrip-mode-content input[type="date"] {
width: 100%;
min-height: 38px;
padding: 8px 12px;
background: var(--surface);
color: var(--text);
border: 1px solid var(--border);
border-radius: 7px;
font-family: "Bender", Arial, Helvetica, sans-serif;
font-size: 14px;
color-scheme: dark;
}
.wifitrip-mode-content select:focus,
.wifitrip-mode-content input[type="date"]:focus,
.wifitrip-mode-content input[type="number"]:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 2px rgba(105, 167, 255, 0.12);
}
.wifitrip-mode-content select:disabled,
.wifitrip-mode-content input[type="date"]:disabled,
.wifitrip-mode-content input[type="number"]:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.wifitrip-date-fields {
gap: 14px;
}
.wifitrip-date-fields > div {
display: flex;
flex-direction: column;
gap: 9px;
}
.wifitrip-export-footer {
display: flex;
flex-direction: column;
align-items: center;
gap: 14px;
margin-top: 24px;
text-align: center;
}
.wifitrip-export-footer p {
margin: 0;
color: var(--text);
font-weight: 700;
}
.wifitrip-export-footer .button {
min-width: 220px;
text-align: center;
}
.wifitrip-export-footer .button:disabled {
opacity: 0.45;
cursor: not-allowed;
}
@media (max-width: 700px) {
.wifitrip-export-options {
grid-template-columns: 1fr;
gap: 12px;
}
.wifitrip-export-mode {
padding: 14px;
}
.wifitrip-export-footer .button {
width: 100%;
}
}
+425 -25
View File
@@ -234,12 +234,6 @@ def render_trips_page(
page="trips", page="trips",
) )
session_count = conn.execute(
"""
SELECT COUNT(*) AS count
FROM capture_sessions
"""
).fetchone()["count"]
html = page_begin( html = page_begin(
"Trips", "Trips",
@@ -257,44 +251,450 @@ def render_trips_page(
) )
html += """ html += """
<section class="card"> <section class="card">
<h2>Export capture sessions</h2> <h2>Экспорт поездок</h2>
<p> <p>
Export all capture sessions into one Выберите поездки, которые нужно включить
<code>.wifitrip</code> package. в пакет <code>.wifitrip</code>.
</p> </p>
<p> <p>
The package contains logical session data: Пакет содержит данные поездок: GPS-треки,
GPS track, access-point observations, наблюдения точек доступа и рукопожатия.
handshakes and credentials. Physical capture Файлы захвата и пароли не включаются.
files are not included.
</p> </p>
<div class="stats-grid">
"""
html += _stat_card(
"Sessions available",
session_count,
)
html += """
</div>
<form <form
id="wifitrip-export-form"
method="get" method="get"
action="/reports/trips/export" action="/reports/trips/export"
> >
<button type="submit" class="button"> <div class="wifitrip-export-options">
Export all sessions
<div class="wifitrip-export-mode wifitrip-export-mode-active">
<label class="wifitrip-mode-tab">
<input
type="radio"
name="mode"
value="latest"
checked
>
<span>Последние поездки</span>
</label>
<div class="wifitrip-mode-content">
<div class="session-list-toolbar wifitrip-limit-toolbar">
<label for="wifitrip-limit">
Show:
</label>
<select
id="wifitrip-limit"
name="limit"
>
<option value="1" selected>1</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="custom">Custom</option>
<option value="all">All</option>
</select>
<input
type="number"
id="wifitrip-custom-limit"
name="custom_limit"
min="1"
max="1"
step="1"
value="1"
placeholder="Number"
aria-label="Custom number of trips"
style="width: 100px;"
disabled
>
<span id="wifitrip-limit-count"></span>
</div>
</div>
</div>
<div class="wifitrip-export-mode">
<label class="wifitrip-mode-tab">
<input
type="radio"
name="mode"
value="range"
>
<span>По диапазону дат</span>
</label>
<div
id="wifitrip-date-range"
class="wifitrip-mode-content wifitrip-date-fields"
>
<div>
<label for="wifitrip-date-from">
Начальная дата
</label>
<input
type="date"
id="wifitrip-date-from"
name="date_from"
disabled
>
</div>
<div>
<label for="wifitrip-date-to">
Конечная дата
</label>
<input
type="date"
id="wifitrip-date-to"
name="date_to"
disabled
>
</div>
</div>
</div>
</div>
<div class="wifitrip-export-footer">
<p
id="wifitrip-export-preview"
aria-live="polite"
>
Подсчёт поездок...
</p>
<button
type="submit"
id="wifitrip-export-button"
class="button"
disabled
>
Экспортировать поездки
</button> </button>
</div>
</form> </form>
<script>
(function () {
const form = document.getElementById(
"wifitrip-export-form"
);
const limitInput = document.getElementById(
"wifitrip-limit"
);
const customLimitInput = document.getElementById(
"wifitrip-custom-limit"
);
const limitCount = document.getElementById(
"wifitrip-limit-count"
);
const dateFromInput = document.getElementById(
"wifitrip-date-from"
);
const dateToInput = document.getElementById(
"wifitrip-date-to"
);
const preview = document.getElementById(
"wifitrip-export-preview"
);
const exportButton = document.getElementById(
"wifitrip-export-button"
);
if (
!form ||
!limitInput ||
!customLimitInput ||
!limitCount ||
!dateFromInput ||
!dateToInput ||
!preview ||
!exportButton
) {
return;
}
let previewRequest = 0;
let availableSessions = null;
function getMode() {
const selected = form.querySelector(
'input[name="mode"]:checked'
);
return selected ? selected.value : "latest";
}
function updateControls() {
const mode = getMode();
const isRange = mode === "range";
const isCustomLimit =
mode === "latest" && limitInput.value === "custom";
limitInput.disabled = mode !== "latest";
customLimitInput.disabled = mode !== "latest";
customLimitInput.required = isCustomLimit;
customLimitInput.max = String(
Math.max(1, availableSessions || 1)
);
const customOption = limitInput.querySelector(
'option[value="custom"]'
);
if (customOption) {
customOption.disabled = availableSessions === 0;
}
dateFromInput.disabled = !isRange;
dateToInput.disabled = !isRange;
dateFromInput.required = isRange;
dateToInput.required = isRange;
if (isRange && dateFromInput.value) {
dateToInput.min = dateFromInput.value;
} else {
dateToInput.removeAttribute("min");
}
if (isRange && dateToInput.value) {
dateFromInput.max = dateToInput.value;
} else {
dateFromInput.removeAttribute("max");
}
}
async function updatePreview() {
const requestId = ++previewRequest;
updateControls();
const mode = getMode();
const isCustomLimit =
mode === "latest" && limitInput.value === "custom";
if (isCustomLimit) {
const customLimit = Number(customLimitInput.value);
if (availableSessions === null) {
preview.textContent =
"Дождитесь получения количества поездок.";
exportButton.disabled = true;
return;
}
if (
!customLimitInput.value ||
!Number.isInteger(customLimit) ||
customLimit < 1 ||
customLimit > availableSessions
) {
preview.textContent =
"Введите целое число от 1 до " +
availableSessions + ".";
exportButton.disabled = true;
return;
}
}
if (
mode === "range" &&
(
!dateFromInput.value ||
!dateToInput.value
)
) {
preview.textContent =
"Укажите начальную и конечную даты.";
exportButton.disabled = true;
return;
}
if (
mode === "range" &&
dateFromInput.value > dateToInput.value
) {
preview.textContent =
"Начальная дата не может быть позже конечной.";
exportButton.disabled = true;
return;
}
const params = new URLSearchParams();
params.set("mode", mode);
if (mode === "latest") {
params.set(
"limit",
isCustomLimit
? customLimitInput.value
: limitInput.value
);
}
if (mode === "range") {
params.set("date_from", dateFromInput.value);
params.set("date_to", dateToInput.value);
}
preview.textContent = "Подсчёт поездок...";
exportButton.disabled = true;
try {
const response = await fetch(
"/reports/trips/preview?" + params.toString(),
{
headers: {
"Accept": "application/json"
}
}
);
const result = await response.json();
if (requestId !== previewRequest) {
return;
}
if (!response.ok) {
throw new Error(
result.error || "Не удалось подсчитать поездки."
);
}
const count = Number(result.count);
const availableCount = Number(result.available_count);
if (!Number.isInteger(count) || count < 0) {
throw new Error(
"Сервер вернул некорректное количество поездок."
);
}
if (
!Number.isInteger(availableCount) ||
availableCount < 0
) {
throw new Error(
"Сервер вернул некорректное общее количество поездок."
);
}
availableSessions = availableCount;
updateControls();
limitCount.textContent =
"Showing " + count + " of " + availableCount;
preview.textContent =
"Будет экспортировано поездок: " + count;
exportButton.disabled = count === 0;
} catch (error) {
if (requestId !== previewRequest) {
return;
}
limitCount.textContent = "";
preview.textContent =
"Ошибка подсчёта: " + error.message;
exportButton.disabled = true;
}
}
form.addEventListener(
"change",
function (event) {
if (event.target === limitInput) {
if (limitInput.value !== "custom") {
customLimitInput.value = "";
} else {
customLimitInput.focus();
}
}
updatePreview();
}
);
form.addEventListener(
"input",
function (event) {
if (event.target === customLimitInput) {
limitInput.value = "custom";
}
updatePreview();
}
);
form.addEventListener(
"submit",
function (event) {
if (
!form.reportValidity() ||
exportButton.disabled
) {
event.preventDefault();
return;
}
if (
getMode() === "latest" &&
limitInput.value === "custom"
) {
const submittedLimit = document.createElement(
"input"
);
submittedLimit.type = "hidden";
submittedLimit.name = "limit";
submittedLimit.value = customLimitInput.value;
limitInput.disabled = true;
form.appendChild(submittedLimit);
}
}
);
updatePreview();
})();
</script>
</section> </section>
""" """
+143 -532
View File
@@ -24,7 +24,7 @@ logger = logging.getLogger(__name__)
WIFITRIP_FORMAT = "wifitrip" WIFITRIP_FORMAT = "wifitrip"
WIFITRIP_VERSION = 1 WIFITRIP_VERSION = 2
SESSION_HASH_VERSION = 1 SESSION_HASH_VERSION = 1
REQUIRED_FILES = ( REQUIRED_FILES = (
@@ -34,7 +34,6 @@ REQUIRED_FILES = (
"access_points.json", "access_points.json",
"observations.json", "observations.json",
"handshakes.json", "handshakes.json",
"credentials.json",
) )
SHA256_RE = re.compile(r"^[0-9a-f]{64}$") SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
@@ -167,6 +166,12 @@ def _read_package(path):
"Archive contains duplicate file names." "Archive contains duplicate file names."
) )
if "credentials.json" in names:
raise WifitripError(
"Archive contains unsupported file: "
"credentials.json"
)
missing = [ missing = [
name name
for name in REQUIRED_FILES for name in REQUIRED_FILES
@@ -212,7 +217,6 @@ def _validate_package(data):
access_points = data["access_points.json"] access_points = data["access_points.json"]
observations = data["observations.json"] observations = data["observations.json"]
handshakes = data["handshakes.json"] handshakes = data["handshakes.json"]
credentials = data["credentials.json"]
_require_dict( _require_dict(
manifest, manifest,
@@ -238,10 +242,6 @@ def _validate_package(data):
handshakes, handshakes,
"handshakes.json", "handshakes.json",
) )
_require_list(
credentials,
"credentials.json",
)
if manifest.get("format") != WIFITRIP_FORMAT: if manifest.get("format") != WIFITRIP_FORMAT:
raise WifitripError( raise WifitripError(
@@ -659,97 +659,6 @@ def _validate_package(data):
f"handshakes.json[{index}].speed", f"handshakes.json[{index}].speed",
) )
for index, credential in enumerate(
credentials
):
_require_dict(
credential,
f"credentials.json[{index}]",
)
session_hash = credential.get(
"session_hash"
)
bssid = credential.get(
"bssid"
)
handshake_key = credential.get(
"handshake_key"
)
_validate_hash(
session_hash,
f"credentials.json[{index}].session_hash",
)
_require_bssid(
bssid,
f"credentials.json[{index}].bssid",
)
if session_hash not in session_versions:
raise WifitripError(
"Credential references unknown session: "
f"{session_hash}"
)
if bssid not in ap_map:
raise WifitripError(
"Credential references unknown BSSID: "
f"{bssid}"
)
if handshake_key is not None:
_require_string(
handshake_key,
f"credentials.json[{index}].handshake_key",
)
if handshake_key not in handshake_keys.get(
session_hash,
set(),
):
raise WifitripError(
"Credential references unknown handshake_key: "
f"{session_hash}: {handshake_key}"
)
_require_string(
credential.get("password"),
f"credentials.json[{index}].password",
)
if not credential.get("password"):
raise WifitripError(
"Credential password must not be empty."
)
_require_string(
credential.get("source"),
f"credentials.json[{index}].source",
allow_none=True,
)
_require_string(
credential.get("created_at"),
f"credentials.json[{index}].created_at",
allow_none=True,
)
verified = credential.get(
"verified"
)
_require_integer(
verified,
f"credentials.json[{index}].verified",
allow_none=False,
)
if verified not in (0, 1):
raise WifitripError(
"Credential verified must be 0 or 1."
)
def _session_hash(conn, session_id): def _session_hash(conn, session_id):
@@ -891,7 +800,110 @@ def _zip_write_json(archive, filename, value):
) )
def export_wifitrip(conn, output_path=None): def select_wifitrip_session_ids(
conn,
mode="all",
limit=1,
date_from=None,
date_to=None,
):
if mode == "latest":
if str(limit).lower() == "all":
rows = conn.execute(
"""
SELECT id
FROM capture_sessions
ORDER BY start_time DESC, id DESC
"""
).fetchall()
else:
try:
limit = int(limit)
except (TypeError, ValueError):
raise WifitripError(
"Invalid session limit."
)
available_count = conn.execute(
"SELECT COUNT(*) FROM capture_sessions"
).fetchone()[0]
if limit < 1 or limit > available_count:
raise WifitripError(
"Session limit must be between 1 and "
f"{available_count}, or all."
)
rows = conn.execute(
"""
SELECT id
FROM capture_sessions
ORDER BY start_time DESC, id DESC
LIMIT ?
""",
(limit,),
).fetchall()
elif mode == "range":
try:
start_date = datetime.strptime(
date_from,
"%Y-%m-%d",
).date()
end_date = datetime.strptime(
date_to,
"%Y-%m-%d",
).date()
except (TypeError, ValueError):
raise WifitripError(
"A valid start and end date are required."
)
if start_date > end_date:
raise WifitripError(
"Start date must not be later than end date."
)
rows = conn.execute(
"""
SELECT id
FROM capture_sessions
WHERE substr(start_time, 1, 10)
BETWEEN ? AND ?
ORDER BY start_time DESC, id DESC
""",
(
start_date.isoformat(),
end_date.isoformat(),
),
).fetchall()
elif mode == "all":
rows = conn.execute(
"""
SELECT id
FROM capture_sessions
ORDER BY start_time DESC, id DESC
"""
).fetchall()
else:
raise WifitripError(
"Invalid session selection mode."
)
return [
row["id"]
for row in rows
]
def export_wifitrip(
conn,
output_path=None,
session_ids=None,
):
started = time.monotonic() started = time.monotonic()
if output_path is None: if output_path is None:
@@ -909,6 +921,7 @@ def export_wifitrip(conn, output_path=None):
exist_ok=True, exist_ok=True,
) )
if session_ids is None:
sessions = conn.execute( sessions = conn.execute(
""" """
SELECT SELECT
@@ -922,6 +935,34 @@ def export_wifitrip(conn, output_path=None):
""" """
).fetchall() ).fetchall()
else:
selected_ids = [
int(session_id)
for session_id in session_ids
]
if selected_ids:
placeholders = ",".join(
"?" for _ in selected_ids
)
sessions = conn.execute(
f"""
SELECT
id,
start_time,
end_time,
session_hash,
session_hash_version
FROM capture_sessions
WHERE id IN ({placeholders})
ORDER BY start_time DESC, id DESC
""",
selected_ids,
).fetchall()
else:
sessions = []
session_by_id = {} session_by_id = {}
exported_sessions = [] exported_sessions = []
@@ -1118,7 +1159,6 @@ def export_wifitrip(conn, output_path=None):
session_ids, session_ids,
).fetchall() ).fetchall()
handshake_key_by_id = {}
handshake_records = {} handshake_records = {}
handshakes = [] handshakes = []
@@ -1137,13 +1177,6 @@ def export_wifitrip(conn, output_path=None):
f"h{len(records) + 1:06d}" f"h{len(records) + 1:06d}"
) )
handshake_key_by_id[
row["id"]
] = (
session_hash,
handshake_key,
)
records.append( records.append(
handshake_key handshake_key
) )
@@ -1163,111 +1196,6 @@ def export_wifitrip(conn, output_path=None):
} }
) )
session_ap_ids = {}
for row in observation_rows:
session_ap_ids.setdefault(
row["session_id"],
set(),
).add(
row["bssid"]
)
for row in handshake_rows:
session_ap_ids.setdefault(
row["session_id"],
set(),
).add(
row["bssid"]
)
credentials_rows = conn.execute(
"""
SELECT
credentials.id,
credentials.access_point_id,
credentials.handshake_id,
access_points.bssid,
credentials.password,
credentials.source,
credentials.created_at,
credentials.verified,
handshakes.session_id AS handshake_session_id
FROM credentials
JOIN access_points
ON access_points.id =
credentials.access_point_id
LEFT JOIN handshakes
ON handshakes.id =
credentials.handshake_id
ORDER BY credentials.id
"""
).fetchall()
credentials = []
for row in credentials_rows:
if row["handshake_session_id"] is not None:
session_id = row[
"handshake_session_id"
]
if session_id not in session_by_id:
continue
session_hash = session_by_id[
session_id
]["session_hash"]
handshake_ref = (
handshake_key_by_id.get(
row["handshake_id"]
)
)
handshake_key = (
handshake_ref[1]
if handshake_ref
else None
)
credentials.append(
{
"session_hash": session_hash,
"bssid": row["bssid"],
"handshake_key": handshake_key,
"password": row["password"],
"source": row["source"],
"created_at": row["created_at"],
"verified": row["verified"],
}
)
continue
for session_id, bssids in (
session_ap_ids.items()
):
if row["bssid"] not in bssids:
continue
if session_id not in session_by_id:
continue
credentials.append(
{
"session_hash": session_by_id[
session_id
]["session_hash"],
"bssid": row["bssid"],
"handshake_key": None,
"password": row["password"],
"source": row["source"],
"created_at": row["created_at"],
"verified": row["verified"],
}
)
bssids = set() bssids = set()
for observation in observations: for observation in observations:
@@ -1280,11 +1208,6 @@ def export_wifitrip(conn, output_path=None):
handshake["bssid"] handshake["bssid"]
) )
for credential in credentials:
bssids.add(
credential["bssid"]
)
access_points = [ access_points = [
{ {
"bssid": bssid "bssid": bssid
@@ -1368,12 +1291,6 @@ def export_wifitrip(conn, output_path=None):
handshakes, handshakes,
) )
_zip_write_json(
archive,
"credentials.json",
credentials,
)
os.replace( os.replace(
temporary_path, temporary_path,
output_path, output_path,
@@ -1408,9 +1325,6 @@ def export_wifitrip(conn, output_path=None):
"handshakes": len( "handshakes": len(
handshakes handshakes
), ),
"credentials": len(
credentials
),
"file": str(output_path), "file": str(output_path),
"size": size, "size": size,
"duration": duration, "duration": duration,
@@ -1419,11 +1333,10 @@ def export_wifitrip(conn, output_path=None):
logger.info( logger.info(
"Completed .wifitrip export: " "Completed .wifitrip export: "
"sessions=%d observations=%d handshakes=%d " "sessions=%d observations=%d handshakes=%d "
"credentials=%d file=%s size=%d duration=%.3fs", "file=%s size=%d duration=%.3fs",
result["sessions"], result["sessions"],
result["observations"], result["observations"],
result["handshakes"], result["handshakes"],
result["credentials"],
output_path, output_path,
size, size,
duration, duration,
@@ -1604,221 +1517,6 @@ def _session_id_by_hash(
return row["id"] 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): def import_wifitrip(conn, package_path):
started = time.monotonic() started = time.monotonic()
@@ -1836,12 +1534,10 @@ def import_wifitrip(conn, package_path):
gps_tracks = package["gps_tracks.json"] gps_tracks = package["gps_tracks.json"]
observations = package["observations.json"] observations = package["observations.json"]
handshakes = package["handshakes.json"] handshakes = package["handshakes.json"]
credentials = package["credentials.json"]
gps_by_session = {} gps_by_session = {}
observations_by_session = {} observations_by_session = {}
handshakes_by_session = {} handshakes_by_session = {}
credentials_by_session = {}
for point in gps_tracks: for point in gps_tracks:
gps_by_session.setdefault( gps_by_session.setdefault(
@@ -1861,12 +1557,6 @@ def import_wifitrip(conn, package_path):
[], [],
).append(handshake) ).append(handshake)
for credential in credentials:
credentials_by_session.setdefault(
credential["session_hash"],
[],
).append(credential)
result = { result = {
"file": str(package_path), "file": str(package_path),
"sessions": len(sessions), "sessions": len(sessions),
@@ -1917,62 +1607,11 @@ def import_wifitrip(conn, package_path):
f"calculated {calculated_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() conn.commit()
logger.info( logger.info(
"Updated duplicate .wifitrip session " "Validated duplicate .wifitrip session: "
"credentials: hash=%s local_id=%s", "hash=%s local_id=%s",
session_hash, session_hash,
existing_id, existing_id,
) )
@@ -2040,13 +1679,6 @@ def import_wifitrip(conn, package_path):
) )
) )
session_credentials = (
credentials_by_session.get(
session_hash,
[],
)
)
bssids = set() bssids = set()
for observation in session_observations: for observation in session_observations:
@@ -2059,11 +1691,6 @@ def import_wifitrip(conn, package_path):
handshake["bssid"] handshake["bssid"]
) )
for credential in session_credentials:
bssids.add(
credential["bssid"]
)
for bssid in sorted(bssids): for bssid in sorted(bssids):
ap_ids[bssid] = ( ap_ids[bssid] = (
_get_or_create_import_ap( _get_or_create_import_ap(
@@ -2181,8 +1808,6 @@ def import_wifitrip(conn, package_path):
latest_observation, latest_observation,
) )
handshake_ids = {}
for handshake in session_handshakes: for handshake in session_handshakes:
access_point_id = ap_ids[ access_point_id = ap_ids[
handshake["bssid"] handshake["bssid"]
@@ -2218,10 +1843,6 @@ def import_wifitrip(conn, package_path):
), ),
) )
handshake_ids[
handshake["handshake_key"]
] = cursor.lastrowid
if handshake["type"] == "PMKID": if handshake["type"] == "PMKID":
conn.execute( conn.execute(
""" """
@@ -2255,13 +1876,6 @@ def import_wifitrip(conn, package_path):
f"calculated {calculated_hash}" f"calculated {calculated_hash}"
) )
_import_session_credentials(
conn,
session_credentials,
ap_ids,
handshake_ids,
)
conn.commit() conn.commit()
result["imported"] += 1 result["imported"] += 1
@@ -2342,9 +1956,6 @@ def validate_wifitrip(package_path):
"handshakes": len( "handshakes": len(
package["handshakes.json"] package["handshakes.json"]
), ),
"credentials": len(
package["credentials.json"]
),
"session_hash_versions": manifest[ "session_hash_versions": manifest[
"session_hash_versions" "session_hash_versions"
], ],
+94 -35
View File
@@ -59,6 +59,42 @@ def log(message):
) )
def colorize(message, color, stream=None):
stream = stream or sys.stdout
if "NO_COLOR" in os.environ or not stream.isatty():
return message
colors = {
"green": "\033[1;92m",
"yellow": "\033[1;93m",
"red": "\033[1;91m",
"reset": "\033[0m"
}
return f"{colors[color]}{message}{colors['reset']}"
def print_success(message):
print(colorize(message, "green"), flush=True)
def print_warning(message):
print(colorize(message, "yellow"), flush=True)
def print_error(message):
print(
colorize(message, "red", sys.stderr),
file=sys.stderr,
flush=True
)
def print_info(message):
print(message, flush=True)
def project_python(): def project_python():
return PROJECT_ROOT / "venv" / "bin" / "python" return PROJECT_ROOT / "venv" / "bin" / "python"
@@ -663,9 +699,11 @@ def start_service():
) )
if active_project == PROJECT_ROOT: if active_project == PROJECT_ROOT:
log("Менеджер уже запущен из текущего проекта.") print_warning(
"Менеджер уже запущен из текущего проекта."
)
else: else:
log( print_warning(
"Менеджер уже запущен из другого проекта: " "Менеджер уже запущен из другого проекта: "
f"{active_project}. Второй экземпляр не запущен." f"{active_project}. Второй экземпляр не запущен."
) )
@@ -687,6 +725,7 @@ def start_service():
command = [ command = [
"systemd-run", "systemd-run",
"--quiet",
"--user", "--user",
f"--unit={UNIT_NAME}", f"--unit={UNIT_NAME}",
"--service-type=exec", "--service-type=exec",
@@ -700,7 +739,8 @@ def start_service():
subprocess.run( subprocess.run(
command, command,
check=True check=True,
stdout=subprocess.DEVNULL
) )
send_sudo_authentication() send_sudo_authentication()
@@ -721,7 +761,7 @@ def start_service():
timeout=1 timeout=1
) as response: ) as response:
if response.status == 200: if response.status == 200:
log( print_success(
f"Приложение запущено: " f"Приложение запущено: "
f"http://{APP_HOST}:{APP_PORT}" f"http://{APP_HOST}:{APP_PORT}"
) )
@@ -739,7 +779,7 @@ def start_service():
def stop_service(): def stop_service():
if not unit_is_active(): if not unit_is_active():
log("Менеджер не запущен.") print_warning("Менеджер уже остановлен.")
return 0 return 0
active_project = active_service_project() active_project = active_service_project()
@@ -765,7 +805,7 @@ def stop_service():
f"{UNIT_NAME}.service" f"{UNIT_NAME}.service"
) )
log( print_warning(
"Запрошено штатное завершение. " "Запрошено штатное завершение. "
"Если сканер активен, останови его в веб-интерфейсе." "Если сканер активен, останови его в веб-интерфейсе."
) )
@@ -774,33 +814,32 @@ def stop_service():
while unit_is_active(): while unit_is_active():
if not notified: if not notified:
log( print_warning(
"Ожидание завершения приложения и фоновых задач..." "Ожидание завершения приложения и фоновых задач..."
) )
notified = True notified = True
time.sleep(1) time.sleep(1)
log("Сервис остановлен.") print_success("Сервис успешно остановлен.")
return 0 return 0
def show_status(): def show_status():
active = unit_is_active() active = unit_is_active()
print( if active:
"Application:", print_success("Application: RUNNING")
"RUNNING" if active else "STOPPED" else:
) print_error("Application: STOPPED")
if active: if active:
active_project = active_service_project() active_project = active_service_project()
print( print_info(
"Active project:", "Active project: "
active_project if active_project is not None else "UNKNOWN" f"{active_project if active_project is not None else 'UNKNOWN'}"
) )
if active:
try: try:
with urllib.request.urlopen( with urllib.request.urlopen(
f"http://{APP_HOST}:{APP_PORT}/api/status", f"http://{APP_HOST}:{APP_PORT}/api/status",
@@ -827,23 +866,38 @@ def show_status():
f"STOPPED (health: {scanner_health})" f"STOPPED (health: {scanner_health})"
) )
print("Scanner:", scanner_state) if scanner_health == "ACTIVE":
print( print_success(f"Scanner: {scanner_state}")
"GPS test:", elif scanner_health in {"WARNING", "STOPPING"}:
gps.get("state", "unknown") print_warning(f"Scanner: {scanner_state}")
) elif scanner_health == "STOPPED":
print( print_error(f"Scanner: {scanner_state}")
"Network action:", else:
"BUSY" if data.get("network_actions_busy") else "IDLE" print_info(f"Scanner: {scanner_state}")
)
gps_state = gps.get("state", "unknown")
if gps_state in {"FIX", "CONNECTED"}:
print_success(f"GPS test: {gps_state}")
elif gps_state in {"STARTING", "NMEA"}:
print_warning(f"GPS test: {gps_state}")
elif gps_state == "ERROR":
print_error(f"GPS test: {gps_state}")
else:
print_info(f"GPS test: {gps_state}")
if data.get("network_actions_busy"):
print_warning("Network action: BUSY")
else:
print_success("Network action: IDLE")
except Exception as error: except Exception as error:
print(f"Application API: unavailable ({error})") print_error(f"Application API: unavailable ({error})")
print( if style_is_available():
"TileServer:", print_success("TileServer: AVAILABLE")
"AVAILABLE" if style_is_available() else "UNAVAILABLE" else:
) print_error("TileServer: UNAVAILABLE")
if active: if active:
result = systemctl_user( result = systemctl_user(
@@ -855,7 +909,7 @@ def show_status():
) )
if result.returncode == 0: if result.returncode == 0:
print(result.stdout.strip()) print_info(result.stdout.strip())
def install(): def install():
@@ -970,7 +1024,15 @@ def main():
return stop_service() return stop_service()
if args.command == "restart": if args.command == "restart":
if unit_is_active():
print_info("Перезапуск: остановка сервиса.")
stop_service() stop_service()
else:
print_warning(
"Сервис уже остановлен. Этап остановки пропущен."
)
print_info("Перезапуск: запуск сервиса.")
return start_service() return start_service()
parser.print_help() parser.print_help()
@@ -981,10 +1043,7 @@ def main():
subprocess.CalledProcessError, subprocess.CalledProcessError,
OSError OSError
) as error: ) as error:
print( print_error(f"Ошибка: {error}")
f"Ошибка: {error}",
file=sys.stderr
)
return 1 return 1
-2731
View File
File diff suppressed because it is too large Load Diff