Files
wifi-gps-mapper-releases/src/wifitrip.py
T
2026-11-18 00:31:29 +03:00

2732 lines
58 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WiFi GPS Mapper — .wifitrip import/export service.
Формат .wifitrip представляет собой ZIP-контейнер с логическим
содержимым одной или нескольких capture sessions.
Модуль не открывает SQLite самостоятельно.
Соединение передаётся вызывающим коду.
Используется одновременно:
• CLI;
• server-side Reports.
Локальные SQLite IDs никогда не являются идентификаторами обмена.
"""
import hashlib
import json
import logging
import os
import tempfile
import zipfile
from datetime import datetime, timezone
from pathlib import Path
# ============================================================
# Constants
# ============================================================
WIFITRIP_FORMAT = "wifitrip"
WIFITRIP_VERSION = 1
SESSION_HASH_VERSION = 1
REQUIRED_FILES = (
"manifest.json",
"sessions.json",
"access_points.json",
"gps_tracks.json",
"observations.json",
"handshakes.json",
"credentials.json",
)
MAX_JSON_SIZE = 512 * 1024 * 1024
logger = logging.getLogger(
"wifi-gps-mapper.wifitrip"
)
# ============================================================
# Exceptions
# ============================================================
class WifitripError(Exception):
"""Base exception for .wifitrip errors."""
class WifitripValidationError(WifitripError):
"""Archive validation failed."""
class WifitripHashMismatchError(WifitripError):
"""Imported session hash does not match restored data."""
# ============================================================
# Result helpers
# ============================================================
def _new_session_result(
session_hash,
):
return {
"session_hash": session_hash,
"status": "FAILED",
"error": None,
"access_points": 0,
"gps_points": 0,
"observations": 0,
"handshakes": 0,
"credentials": 0,
}
# ============================================================
# JSON helpers
# ============================================================
def _json_dump(
value,
):
return json.dumps(
value,
ensure_ascii=False,
indent=2,
sort_keys=True,
allow_nan=False,
)
def _read_json(
archive,
filename,
):
try:
info = archive.getinfo(
filename
)
except KeyError as error:
raise WifitripValidationError(
f"Required file is missing: {filename}"
) from error
if info.file_size > MAX_JSON_SIZE:
raise WifitripValidationError(
f"File is too large: {filename}"
)
try:
content = archive.read(
filename
).decode(
"utf-8"
)
except UnicodeDecodeError as error:
raise WifitripValidationError(
f"File is not valid UTF-8: {filename}"
) from error
try:
return json.loads(
content
)
except json.JSONDecodeError as error:
raise WifitripValidationError(
f"Invalid JSON in {filename}: "
f"{error}"
) from error
def _ensure_list(
value,
filename,
):
if not isinstance(
value,
list,
):
raise WifitripValidationError(
f"{filename} must contain a JSON array."
)
return value
def _ensure_dict(
value,
filename,
):
if not isinstance(
value,
dict,
):
raise WifitripValidationError(
f"{filename} must contain a JSON object."
)
return value
# ============================================================
# General helpers
# ============================================================
def _utc_now():
return datetime.now(
timezone.utc
).isoformat().replace(
"+00:00",
"Z"
)
def _normalise_bssid(
value,
):
if value is None:
return ""
return str(
value
).strip().lower()
def _require_string(
record,
field,
context,
):
value = record.get(
field
)
if not isinstance(
value,
str,
):
raise WifitripValidationError(
f"{context}: {field} must be a string."
)
if not value.strip():
raise WifitripValidationError(
f"{context}: {field} must not be empty."
)
return value
def _optional_number(
value,
field,
context,
):
if value is None:
return None
if isinstance(
value,
bool,
):
raise WifitripValidationError(
f"{context}: {field} must be numeric or null."
)
if not isinstance(
value,
(int, float),
):
raise WifitripValidationError(
f"{context}: {field} must be numeric or null."
)
return value
def _optional_integer(
value,
field,
context,
):
if value is None:
return None
if isinstance(
value,
bool,
):
raise WifitripValidationError(
f"{context}: {field} must be an integer or null."
)
if not isinstance(
value,
int,
):
raise WifitripValidationError(
f"{context}: {field} must be an integer or null."
)
return value
def _validate_bssid(
value,
context,
):
bssid = _normalise_bssid(
value
)
compact = bssid.replace(
":",
""
).replace(
"-",
""
)
if len(compact) != 12:
raise WifitripValidationError(
f"{context}: invalid BSSID: {value}"
)
try:
int(
compact,
16,
)
except ValueError as error:
raise WifitripValidationError(
f"{context}: invalid BSSID: {value}"
) from error
return bssid
# ============================================================
# Session hash
# ============================================================
def _canonical_json(
value,
):
return json.dumps(
value,
ensure_ascii=False,
separators=(",", ":"),
allow_nan=False,
)
def _calculate_session_hash(
conn,
session_id,
):
session = conn.execute(
"""
SELECT
start_time,
end_time
FROM capture_sessions
WHERE id=?
""",
(
session_id,
)
).fetchone()
if session is None:
raise WifitripError(
f"Session not found: {session_id}"
)
gps_rows = conn.execute(
"""
SELECT
timestamp,
latitude,
longitude
FROM gps_track
WHERE session_id=?
ORDER BY sequence_no
""",
(
session_id,
)
).fetchall()
handshake_rows = conn.execute(
"""
SELECT
access_points.bssid,
handshakes.type,
handshakes.hash22000,
handshakes.message_pair,
handshakes.captured_at
FROM handshakes
JOIN access_points
ON access_points.id =
handshakes.access_point_id
WHERE handshakes.session_id=?
ORDER BY
access_points.bssid,
handshakes.type,
handshakes.hash22000,
handshakes.message_pair,
handshakes.captured_at
""",
(
session_id,
)
).fetchall()
handshake_data = [
[
row["bssid"],
row["type"],
row["hash22000"],
row["message_pair"],
row["captured_at"],
]
for row in handshake_rows
]
if gps_rows:
gps_data = [
[
row["timestamp"],
row["latitude"],
row["longitude"],
]
for row in gps_rows
]
canonical = [
"GPS_SESSION_V1",
gps_data,
handshake_data,
]
else:
observation_rows = conn.execute(
"""
SELECT
observations.observed_at,
access_points.bssid
FROM access_point_observations AS observations
JOIN access_points
ON access_points.id =
observations.access_point_id
WHERE observations.session_id=?
ORDER BY
observations.observed_at,
access_points.bssid
""",
(
session_id,
)
).fetchall()
observation_data = [
[
row["observed_at"],
row["bssid"],
]
for row in observation_rows
]
canonical = [
"NON_GPS_SESSION_V1",
session["start_time"],
session["end_time"],
observation_data,
handshake_data,
]
payload = _canonical_json(
canonical
).encode(
"utf-8"
)
return hashlib.sha256(
payload
).hexdigest()
# ============================================================
# Export queries
# ============================================================
def _get_sessions_for_export(
conn,
session_ids=None,
):
if session_ids is None:
return conn.execute(
"""
SELECT
id,
start_time,
end_time,
session_hash,
session_hash_version
FROM capture_sessions
WHERE
session_hash IS NOT NULL
AND TRIM(session_hash) != ''
AND session_hash_version IS NOT NULL
ORDER BY id
"""
).fetchall()
ids = list(
session_ids
)
if not ids:
return []
placeholders = ",".join(
"?"
for _ in ids
)
return conn.execute(
f"""
SELECT
id,
start_time,
end_time,
session_hash,
session_hash_version
FROM capture_sessions
WHERE
id IN ({placeholders})
AND session_hash IS NOT NULL
AND TRIM(session_hash) != ''
AND session_hash_version IS NOT NULL
ORDER BY id
""",
ids,
).fetchall()
def _get_session_type(
conn,
session_id,
):
gps_count = conn.execute(
"""
SELECT COUNT(*)
FROM gps_track
WHERE session_id=?
""",
(
session_id,
)
).fetchone()[0]
if gps_count:
return "gps"
return "non_gps"
def _get_access_points(
conn,
session_ids,
):
if not session_ids:
return []
placeholders = ",".join(
"?"
for _ in session_ids
)
rows = conn.execute(
f"""
SELECT DISTINCT
access_points.bssid
FROM access_points
WHERE access_points.id IN (
SELECT access_point_id
FROM access_point_observations
WHERE session_id IN ({placeholders})
UNION
SELECT access_point_id
FROM handshakes
WHERE session_id IN ({placeholders})
UNION
SELECT access_point_id
FROM credentials
WHERE access_point_id IN (
SELECT access_point_id
FROM handshakes
WHERE session_id IN ({placeholders})
)
)
ORDER BY access_points.bssid
""",
(
*session_ids,
*session_ids,
*session_ids,
),
).fetchall()
return [
{
"bssid": row["bssid"],
}
for row in rows
]
def _get_gps_tracks(
conn,
sessions,
):
records = []
for session in sessions:
rows = conn.execute(
"""
SELECT
sequence_no,
latitude,
longitude,
speed,
timestamp
FROM gps_track
WHERE session_id=?
ORDER BY sequence_no
""",
(
session["id"],
)
).fetchall()
for row in rows:
records.append(
{
"session_hash":
session["session_hash"],
"sequence_no":
row["sequence_no"],
"latitude":
row["latitude"],
"longitude":
row["longitude"],
"speed":
row["speed"],
"timestamp":
row["timestamp"],
}
)
return records
def _get_observations(
conn,
sessions,
):
records = []
for session in sessions:
rows = conn.execute(
"""
SELECT
access_points.bssid,
observations.observed_at,
observations.latitude,
observations.longitude,
observations.speed,
observations.rssi,
observations.channel,
observations.frequency,
observations.essid,
observations.encryption,
observations.cipher,
observations.akm,
observations.country
FROM access_point_observations AS observations
JOIN access_points
ON access_points.id =
observations.access_point_id
WHERE observations.session_id=?
ORDER BY
observations.observed_at,
access_points.bssid,
observations.id
""",
(
session["id"],
)
).fetchall()
for row in rows:
records.append(
{
"session_hash":
session["session_hash"],
"bssid":
row["bssid"],
"observed_at":
row["observed_at"],
"latitude":
row["latitude"],
"longitude":
row["longitude"],
"speed":
row["speed"],
"rssi":
row["rssi"],
"channel":
row["channel"],
"frequency":
row["frequency"],
"essid":
row["essid"],
"encryption":
row["encryption"],
"cipher":
row["cipher"],
"akm":
row["akm"],
"country":
row["country"],
}
)
return records
def _get_handshakes(
conn,
sessions,
):
records = []
handshake_maps = {}
for session in sessions:
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()
session_map = {}
for index, row in enumerate(
rows,
start=1,
):
handshake_key = (
f"h{index:06d}"
)
session_map[
row["id"]
] = handshake_key
records.append(
{
"session_hash":
session["session_hash"],
"handshake_key":
handshake_key,
"bssid":
row["bssid"],
"type":
row["type"],
"hash22000":
row["hash22000"],
"message_pair":
row["message_pair"],
"captured_at":
row["captured_at"],
"latitude":
row["latitude"],
"longitude":
row["longitude"],
"speed":
row["speed"],
}
)
handshake_maps[
session["id"]
] = session_map
return records, handshake_maps
def _get_credentials(
conn,
sessions,
handshake_maps,
):
records = []
for session in sessions:
rows = conn.execute(
"""
SELECT
credentials.id,
access_points.bssid,
credentials.handshake_id,
credentials.password,
credentials.source,
credentials.created_at,
credentials.verified
FROM credentials
JOIN access_points
ON access_points.id =
credentials.access_point_id
WHERE
credentials.handshake_id IN (
SELECT id
FROM handshakes
WHERE session_id=?
)
OR (
credentials.handshake_id IS NULL
AND credentials.access_point_id IN (
SELECT access_point_id
FROM access_point_observations
WHERE session_id=?
)
)
ORDER BY credentials.id
""",
(
session["id"],
session["id"],
)
).fetchall()
session_map = handshake_maps.get(
session["id"],
{},
)
for row in rows:
handshake_key = None
if row["handshake_id"] is not None:
handshake_key = session_map.get(
row["handshake_id"]
)
if handshake_key is None:
raise WifitripError(
"Credential references a handshake "
"outside the exported session."
)
records.append(
{
"session_hash":
session["session_hash"],
"bssid":
row["bssid"],
"handshake_key":
handshake_key,
"password":
row["password"],
"source":
row["source"],
"created_at":
row["created_at"],
"verified":
row["verified"],
}
)
return records
# ============================================================
# Export
# ============================================================
def _build_export_package(
conn,
session_ids=None,
):
sessions = _get_sessions_for_export(
conn,
session_ids,
)
session_records = []
session_hashes = set()
for session in sessions:
session_hash = str(
session["session_hash"]
).strip()
if session_hash in session_hashes:
raise WifitripError(
f"Duplicate session hash in database: "
f"{session_hash}"
)
session_hashes.add(
session_hash
)
calculated_hash = _calculate_session_hash(
conn,
session["id"],
)
if calculated_hash != session_hash:
raise WifitripHashMismatchError(
"Stored session hash does not match "
f"session {session['id']}: "
f"{session_hash}"
)
session_records.append(
{
"session_hash":
session_hash,
"session_hash_version":
session["session_hash_version"],
"start_time":
session["start_time"],
"end_time":
session["end_time"],
"session_type":
_get_session_type(
conn,
session["id"],
),
}
)
access_points = _get_access_points(
conn,
[
session["id"]
for session in sessions
],
)
gps_tracks = _get_gps_tracks(
conn,
sessions,
)
observations = _get_observations(
conn,
sessions,
)
handshakes, handshake_maps = _get_handshakes(
conn,
sessions,
)
credentials = _get_credentials(
conn,
sessions,
handshake_maps,
)
manifest = {
"format": WIFITRIP_FORMAT,
"format_version": WIFITRIP_VERSION,
"created_at": _utc_now(),
"sessions": len(
session_records
),
"session_hash_versions": sorted(
{
record["session_hash_version"]
for record in session_records
}
),
}
return {
"manifest": manifest,
"sessions": session_records,
"access_points": access_points,
"gps_tracks": gps_tracks,
"observations": observations,
"handshakes": handshakes,
"credentials": credentials,
}
def export_wifitrip(
conn,
output_path,
session_ids=None,
):
started_at = datetime.now(
timezone.utc
)
output_path = Path(
output_path
)
output_path.parent.mkdir(
parents=True,
exist_ok=True,
)
package = _build_export_package(
conn,
session_ids,
)
output_fd = None
temporary_path = None
try:
output_fd, temporary_path = tempfile.mkstemp(
prefix=".wifitrip-",
suffix=".tmp",
dir=str(
output_path.parent
),
)
os.close(
output_fd
)
output_fd = None
with zipfile.ZipFile(
temporary_path,
"w",
compression=zipfile.ZIP_DEFLATED,
compresslevel=6,
) as archive:
for filename in REQUIRED_FILES:
key = filename[:-5]
archive.writestr(
filename,
_json_dump(
package[key]
).encode(
"utf-8"
),
)
os.replace(
temporary_path,
output_path,
)
temporary_path = None
finally:
if output_fd is not None:
os.close(
output_fd
)
if temporary_path is not None:
try:
os.unlink(
temporary_path
)
except FileNotFoundError:
pass
size = output_path.stat().st_size
duration = (
datetime.now(
timezone.utc
) - started_at
).total_seconds()
result = {
"output": str(
output_path
),
"size": size,
"duration": duration,
"sessions": len(
package["sessions"]
),
"access_points": len(
package["access_points"]
),
"gps_points": len(
package["gps_tracks"]
),
"observations": len(
package["observations"]
),
"handshakes": len(
package["handshakes"]
),
"credentials": len(
package["credentials"]
),
}
logger.info(
"wifitrip export completed: "
"file=%s size=%d sessions=%d "
"access_points=%d gps_points=%d "
"observations=%d handshakes=%d "
"credentials=%d duration=%.3fs",
output_path,
size,
result["sessions"],
result["access_points"],
result["gps_points"],
result["observations"],
result["handshakes"],
result["credentials"],
duration,
)
return result
# ============================================================
# Package validation
# ============================================================
def _validate_manifest(
manifest,
):
_ensure_dict(
manifest,
"manifest.json",
)
if manifest.get(
"format"
) != WIFITRIP_FORMAT:
raise WifitripValidationError(
"Unsupported package format."
)
if manifest.get(
"format_version"
) != WIFITRIP_VERSION:
raise WifitripValidationError(
"Unsupported .wifitrip format version: "
f"{manifest.get('format_version')}"
)
sessions = manifest.get(
"sessions"
)
if not isinstance(
sessions,
int,
) or isinstance(
sessions,
bool,
):
raise WifitripValidationError(
"manifest.sessions must be an integer."
)
if sessions < 0:
raise WifitripValidationError(
"manifest.sessions must not be negative."
)
versions = manifest.get(
"session_hash_versions"
)
if not isinstance(
versions,
list,
):
raise WifitripValidationError(
"manifest.session_hash_versions "
"must be an array."
)
for version in versions:
if version != SESSION_HASH_VERSION:
raise WifitripValidationError(
"Unsupported session hash version: "
f"{version}"
)
def _validate_sessions(
records,
):
sessions = {}
versions = set()
for index, record in enumerate(
records
):
context = (
f"sessions.json[{index}]"
)
_ensure_dict(
record,
context,
)
session_hash = _require_string(
record,
"session_hash",
context,
)
session_hash_version = _optional_integer(
record.get(
"session_hash_version"
),
"session_hash_version",
context,
)
if session_hash_version != SESSION_HASH_VERSION:
raise WifitripValidationError(
f"{context}: unsupported "
"session_hash_version."
)
if session_hash in sessions:
raise WifitripValidationError(
f"{context}: duplicate session_hash."
)
start_time = _require_string(
record,
"start_time",
context,
)
end_time = record.get(
"end_time"
)
if end_time is not None and not isinstance(
end_time,
str,
):
raise WifitripValidationError(
f"{context}: end_time must be "
"a string or null."
)
session_type = record.get(
"session_type"
)
if session_type not in (
"gps",
"non_gps",
):
raise WifitripValidationError(
f"{context}: invalid session_type."
)
sessions[
session_hash
] = {
"session_hash":
session_hash,
"session_hash_version":
session_hash_version,
"start_time":
start_time,
"end_time":
end_time,
"session_type":
session_type,
}
versions.add(
session_hash_version
)
return sessions, versions
def _validate_access_points(
records,
):
access_points = {}
for index, record in enumerate(
records
):
context = (
f"access_points.json[{index}]"
)
_ensure_dict(
record,
context,
)
bssid = _validate_bssid(
record.get(
"bssid"
),
context,
)
if bssid in access_points:
raise WifitripValidationError(
f"{context}: duplicate BSSID."
)
access_points[
bssid
] = {
"bssid": bssid,
}
return access_points
def _validate_gps_tracks(
records,
sessions,
):
sequence_numbers = {}
for index, record in enumerate(
records
):
context = (
f"gps_tracks.json[{index}]"
)
_ensure_dict(
record,
context,
)
session_hash = _require_string(
record,
"session_hash",
context,
)
if session_hash not in sessions:
raise WifitripValidationError(
f"{context}: unknown session_hash."
)
sequence_no = _optional_integer(
record.get(
"sequence_no"
),
"sequence_no",
context,
)
if sequence_no is None or sequence_no < 0:
raise WifitripValidationError(
f"{context}: invalid sequence_no."
)
key = (
session_hash,
sequence_no,
)
if key in sequence_numbers:
raise WifitripValidationError(
f"{context}: duplicate sequence_no."
)
sequence_numbers[key] = True
for field in (
"latitude",
"longitude",
"speed",
):
_optional_number(
record.get(
field
),
field,
context,
)
timestamp = record.get(
"timestamp"
)
if timestamp is not None and not isinstance(
timestamp,
str,
):
raise WifitripValidationError(
f"{context}: timestamp must "
"be a string or null."
)
def _validate_observations(
records,
sessions,
access_points,
):
for index, record in enumerate(
records
):
context = (
f"observations.json[{index}]"
)
_ensure_dict(
record,
context,
)
session_hash = _require_string(
record,
"session_hash",
context,
)
if session_hash not in sessions:
raise WifitripValidationError(
f"{context}: unknown session_hash."
)
bssid = _validate_bssid(
record.get(
"bssid"
),
context,
)
if bssid not in access_points:
raise WifitripValidationError(
f"{context}: unknown BSSID."
)
_require_string(
record,
"observed_at",
context,
)
for field in (
"latitude",
"longitude",
"speed",
):
_optional_number(
record.get(
field
),
field,
context,
)
for field in (
"rssi",
"channel",
"frequency",
):
_optional_integer(
record.get(
field
),
field,
context,
)
for field in (
"essid",
"encryption",
"cipher",
"akm",
"country",
):
value = record.get(
field
)
if value is not None and not isinstance(
value,
str,
):
raise WifitripValidationError(
f"{context}: {field} must "
"be a string or null."
)
def _validate_handshakes(
records,
sessions,
access_points,
):
handshake_keys = {}
for index, record in enumerate(
records
):
context = (
f"handshakes.json[{index}]"
)
_ensure_dict(
record,
context,
)
session_hash = _require_string(
record,
"session_hash",
context,
)
if session_hash not in sessions:
raise WifitripValidationError(
f"{context}: unknown session_hash."
)
handshake_key = _require_string(
record,
"handshake_key",
context,
)
key = (
session_hash,
handshake_key,
)
if key in handshake_keys:
raise WifitripValidationError(
f"{context}: duplicate handshake_key."
)
handshake_keys[key] = True
bssid = _validate_bssid(
record.get(
"bssid"
),
context,
)
if bssid not in access_points:
raise WifitripValidationError(
f"{context}: unknown BSSID."
)
_require_string(
record,
"type",
context,
)
for field in (
"hash22000",
"message_pair",
"captured_at",
):
value = record.get(
field
)
if value is not None and not isinstance(
value,
str,
):
raise WifitripValidationError(
f"{context}: {field} must "
"be a string or null."
)
for field in (
"latitude",
"longitude",
"speed",
):
_optional_number(
record.get(
field
),
field,
context,
)
return handshake_keys
def _validate_credentials(
records,
sessions,
access_points,
handshake_keys,
):
for index, record in enumerate(
records
):
context = (
f"credentials.json[{index}]"
)
_ensure_dict(
record,
context,
)
session_hash = _require_string(
record,
"session_hash",
context,
)
if session_hash not in sessions:
raise WifitripValidationError(
f"{context}: unknown session_hash."
)
bssid = _validate_bssid(
record.get(
"bssid"
),
context,
)
if bssid not in access_points:
raise WifitripValidationError(
f"{context}: unknown BSSID."
)
password = _require_string(
record,
"password",
context,
)
handshake_key = record.get(
"handshake_key"
)
if handshake_key is not None:
if not isinstance(
handshake_key,
str,
):
raise WifitripValidationError(
f"{context}: handshake_key must "
"be a string or null."
)
if (
session_hash,
handshake_key,
) not in handshake_keys:
raise WifitripValidationError(
f"{context}: unknown handshake_key."
)
for field in (
"source",
"created_at",
):
value = record.get(
field
)
if value is not None and not isinstance(
value,
str,
):
raise WifitripValidationError(
f"{context}: {field} must "
"be a string or null."
)
verified = record.get(
"verified"
)
if not isinstance(
verified,
(int, bool),
):
raise WifitripValidationError(
f"{context}: verified must be numeric."
)
def _load_package(
path,
):
path = Path(
path
)
if not path.exists():
raise FileNotFoundError(
f"File not found:\n{path}"
)
if not path.is_file():
raise ValueError(
f"Not a regular file:\n{path}"
)
try:
archive = zipfile.ZipFile(
path,
"r",
)
except zipfile.BadZipFile as error:
raise WifitripValidationError(
"Input file is not a valid ZIP archive."
) from error
try:
names = archive.namelist()
if len(names) != len(
set(names)
):
raise WifitripValidationError(
"Archive contains duplicate file names."
)
missing = [
filename
for filename in REQUIRED_FILES
if filename not in names
]
if missing:
raise WifitripValidationError(
"Archive is missing required files: "
+ ", ".join(
missing
)
)
manifest = _read_json(
archive,
"manifest.json",
)
sessions = _read_json(
archive,
"sessions.json",
)
access_points = _read_json(
archive,
"access_points.json",
)
gps_tracks = _read_json(
archive,
"gps_tracks.json",
)
observations = _read_json(
archive,
"observations.json",
)
handshakes = _read_json(
archive,
"handshakes.json",
)
credentials = _read_json(
archive,
"credentials.json",
)
finally:
archive.close()
_validate_manifest(
manifest
)
sessions = _ensure_list(
sessions,
"sessions.json",
)
access_points = _ensure_list(
access_points,
"access_points.json",
)
gps_tracks = _ensure_list(
gps_tracks,
"gps_tracks.json",
)
observations = _ensure_list(
observations,
"observations.json",
)
handshakes = _ensure_list(
handshakes,
"handshakes.json",
)
credentials = _ensure_list(
credentials,
"credentials.json",
)
session_map, versions = _validate_sessions(
sessions
)
if manifest["sessions"] != len(
sessions
):
raise WifitripValidationError(
"manifest.sessions does not match sessions.json."
)
if set(
manifest["session_hash_versions"]
) != versions:
raise WifitripValidationError(
"manifest.session_hash_versions "
"does not match sessions.json."
)
access_point_map = _validate_access_points(
access_points
)
_validate_gps_tracks(
gps_tracks,
session_map,
)
_validate_observations(
observations,
session_map,
access_point_map,
)
handshake_keys = _validate_handshakes(
handshakes,
session_map,
access_point_map,
)
_validate_credentials(
credentials,
session_map,
access_point_map,
handshake_keys,
)
return {
"manifest": manifest,
"sessions": sessions,
"access_points": access_points,
"gps_tracks": gps_tracks,
"observations": observations,
"handshakes": handshakes,
"credentials": credentials,
}
def preflight_wifitrip(
path,
):
started_at = datetime.now(
timezone.utc
)
package = _load_package(
path
)
session_hashes = {
record["session_hash"]
for record in package["sessions"]
}
result = {
"valid": True,
"file": str(
path
),
"format_version":
package["manifest"]["format_version"],
"sessions": len(
package["sessions"]
),
"access_points": len(
package["access_points"]
),
"gps_points": len(
package["gps_tracks"]
),
"observations": len(
package["observations"]
),
"handshakes": len(
package["handshakes"]
),
"credentials": len(
package["credentials"]
),
"session_hashes": len(
session_hashes
),
"duration": (
datetime.now(
timezone.utc
) - started_at
).total_seconds(),
}
logger.info(
"wifitrip preflight successful: "
"file=%s sessions=%d access_points=%d "
"gps_points=%d observations=%d "
"handshakes=%d credentials=%d",
path,
result["sessions"],
result["access_points"],
result["gps_points"],
result["observations"],
result["handshakes"],
result["credentials"],
)
return result
# ============================================================
# Import helpers
# ============================================================
def _session_exists_by_hash(
conn,
session_hash,
session_hash_version,
):
row = conn.execute(
"""
SELECT id
FROM capture_sessions
WHERE
session_hash=?
AND session_hash_version=?
LIMIT 1
""",
(
session_hash,
session_hash_version,
),
).fetchone()
if row is None:
return None
return row["id"]
def _get_or_create_import_ap(
conn,
bssid,
):
row = conn.execute(
"""
SELECT id
FROM access_points
WHERE bssid=?
""",
(
bssid,
),
).fetchone()
if row is not None:
return row["id"], False
cursor = conn.execute(
"""
INSERT INTO access_points (
bssid
)
VALUES (?)
""",
(
bssid,
),
)
return cursor.lastrowid, True
def _import_gps_tracks(
conn,
session_id,
session_hash,
gps_tracks,
):
records = [
record
for record in gps_tracks
if record["session_hash"] == session_hash
]
for record in sorted(
records,
key=lambda value: value["sequence_no"],
):
conn.execute(
"""
INSERT INTO gps_track (
session_id,
sequence_no,
latitude,
longitude,
speed,
timestamp
)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
session_id,
record["sequence_no"],
record["latitude"],
record["longitude"],
record["speed"],
record["timestamp"],
),
)
return len(
records
)
def _import_observations(
conn,
session_id,
session_hash,
observations,
ap_map,
):
records = [
record
for record in observations
if record["session_hash"] == session_hash
]
for record in records:
bssid = _normalise_bssid(
record["bssid"]
)
access_point_id = ap_map[
bssid
]
conn.execute(
"""
INSERT INTO access_point_observations (
access_point_id,
session_id,
observed_at,
latitude,
longitude,
speed,
rssi,
channel,
frequency,
essid,
encryption,
cipher,
akm,
country
)
VALUES (
?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?
)
""",
(
access_point_id,
session_id,
record["observed_at"],
record["latitude"],
record["longitude"],
record["speed"],
record["rssi"],
record["channel"],
record["frequency"],
record["essid"],
record["encryption"],
record["cipher"],
record["akm"],
record["country"],
),
)
return len(
records
)
def _import_handshakes(
conn,
session_id,
session_hash,
handshakes,
ap_map,
):
records = [
record
for record in handshakes
if record["session_hash"] == session_hash
]
handshake_map = {}
for record in records:
bssid = _normalise_bssid(
record["bssid"]
)
access_point_id = ap_map[
bssid
]
cursor = conn.execute(
"""
INSERT INTO handshakes (
access_point_id,
session_id,
type,
hash22000,
message_pair,
captured_at,
latitude,
longitude,
speed
)
VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?
)
""",
(
access_point_id,
session_id,
record["type"],
record["hash22000"],
record["message_pair"],
record["captured_at"],
record["latitude"],
record["longitude"],
record["speed"],
),
)
local_id = cursor.lastrowid
handshake_map[
record["handshake_key"]
] = local_id
if record["type"] == "PMKID":
conn.execute(
"""
UPDATE access_points
SET has_pmkid=1
WHERE id=?
""",
(
access_point_id,
),
)
if record["type"] == "EAPOL":
conn.execute(
"""
UPDATE access_points
SET has_handshake=1
WHERE id=?
""",
(
access_point_id,
),
)
return len(
records
), handshake_map
def _update_imported_ap_statistics(
conn,
ap_map,
session_id,
):
for access_point_id in ap_map.values():
row = conn.execute(
"""
SELECT
COUNT(*) AS count,
MIN(observed_at) AS first_seen,
MAX(observed_at) AS last_seen
FROM access_point_observations
WHERE
access_point_id=?
AND session_id=?
""",
(
access_point_id,
session_id,
),
).fetchone()
if row["count"] == 0:
continue
latest = conn.execute(
"""
SELECT
observed_at,
latitude,
longitude,
speed,
rssi,
channel,
frequency,
essid,
encryption,
cipher,
akm,
country
FROM access_point_observations
WHERE
access_point_id=?
AND session_id=?
ORDER BY
observed_at DESC,
id DESC
LIMIT 1
""",
(
access_point_id,
session_id,
),
).fetchone()
current = conn.execute(
"""
SELECT
first_seen,
last_seen
FROM access_points
WHERE id=?
""",
(
access_point_id,
),
).fetchone()
first_seen = row["first_seen"]
if current["first_seen"] is not None:
first_seen = min(
current["first_seen"],
first_seen,
)
last_seen = row["last_seen"]
if current["last_seen"] is not None:
last_seen = max(
current["last_seen"],
last_seen,
)
conn.execute(
"""
UPDATE access_points
SET
first_seen=?,
last_seen=?,
times_seen=
COALESCE(times_seen, 0)
+ ?,
last_rssi=?,
last_latitude=?,
last_longitude=?,
last_speed=?,
channel=?,
frequency=?,
essid=?,
encryption=?,
cipher=?,
akm=?,
country=?
WHERE id=?
""",
(
first_seen,
last_seen,
row["count"],
latest["rssi"],
latest["latitude"],
latest["longitude"],
latest["speed"],
latest["channel"],
latest["frequency"],
latest["essid"],
latest["encryption"],
latest["cipher"],
latest["akm"],
latest["country"],
access_point_id,
),
)
def _import_credentials(
conn,
session_hash,
credentials,
ap_map,
handshake_map,
):
records = [
record
for record in credentials
if record["session_hash"] == session_hash
]
imported = 0
for record in records:
bssid = _normalise_bssid(
record["bssid"]
)
access_point_id = ap_map[
bssid
]
handshake_id = None
if record["handshake_key"] is not None:
handshake_id = handshake_map[
record["handshake_key"]
]
existing = conn.execute(
"""
SELECT id
FROM credentials
WHERE
access_point_id=?
AND password=?
LIMIT 1
""",
(
access_point_id,
record["password"],
),
).fetchone()
if existing 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,
record["password"],
record["source"],
record["created_at"],
record["verified"],
),
)
conn.execute(
"""
UPDATE access_points
SET is_cracked=1
WHERE id=?
""",
(
access_point_id,
),
)
imported += 1
return imported
def _import_session(
conn,
package,
session_record,
):
session_hash = session_record[
"session_hash"
]
session_hash_version = session_record[
"session_hash_version"
]
result = _new_session_result(
session_hash
)
existing_id = _session_exists_by_hash(
conn,
session_hash,
session_hash_version,
)
if existing_id is not None:
result["status"] = "DUPLICATE"
return result
try:
conn.execute(
"BEGIN"
)
cursor = conn.execute(
"""
INSERT INTO capture_sessions (
start_time,
end_time,
capture_file,
session_hash,
session_hash_version
)
VALUES (?, ?, ?, ?, ?)
""",
(
session_record["start_time"],
session_record["end_time"],
"imported.wifitrip",
session_hash,
session_hash_version,
),
)
session_id = cursor.lastrowid
ap_records = package[
"access_points"
]
referenced_bssids = set()
for record in package[
"observations"
]:
if record["session_hash"] == session_hash:
referenced_bssids.add(
_normalise_bssid(
record["bssid"]
)
)
for record in package[
"handshakes"
]:
if record["session_hash"] == session_hash:
referenced_bssids.add(
_normalise_bssid(
record["bssid"]
)
)
for record in package[
"credentials"
]:
if record["session_hash"] == session_hash:
referenced_bssids.add(
_normalise_bssid(
record["bssid"]
)
)
package_bssids = {
_normalise_bssid(
record["bssid"]
)
for record in ap_records
}
ap_map = {}
for bssid in sorted(
referenced_bssids
):
if bssid not in package_bssids:
raise WifitripValidationError(
"Session references an AP not present "
"in access_points.json: "
f"{bssid}"
)
access_point_id, _ = (
_get_or_create_import_ap(
conn,
bssid,
)
)
ap_map[
bssid
] = access_point_id
result["access_points"] = len(
ap_map
)
result["gps_points"] = _import_gps_tracks(
conn,
session_id,
session_hash,
package["gps_tracks"],
)
result["observations"] = _import_observations(
conn,
session_id,
session_hash,
package["observations"],
ap_map,
)
(
result["handshakes"],
handshake_map,
) = _import_handshakes(
conn,
session_id,
session_hash,
package["handshakes"],
ap_map,
)
calculated_hash = _calculate_session_hash(
conn,
session_id,
)
if calculated_hash != session_hash:
raise WifitripHashMismatchError(
"Session hash mismatch: "
f"expected {session_hash}, "
f"calculated {calculated_hash}"
)
_update_imported_ap_statistics(
conn,
ap_map,
session_id,
)
result["credentials"] = _import_credentials(
conn,
session_hash,
package["credentials"],
ap_map,
handshake_map,
)
conn.commit()
result["status"] = "NEW"
logger.info(
"wifitrip session imported: "
"hash=%s access_points=%d "
"gps_points=%d observations=%d "
"handshakes=%d credentials=%d",
session_hash,
result["access_points"],
result["gps_points"],
result["observations"],
result["handshakes"],
result["credentials"],
)
return result
except Exception as error:
conn.rollback()
result["status"] = "FAILED"
result["error"] = str(
error
)
logger.error(
"wifitrip session import failed: "
"hash=%s error=%s",
session_hash,
error,
)
return result
# ============================================================
# Import
# ============================================================
def import_wifitrip(
conn,
path,
):
started_at = datetime.now(
timezone.utc
)
package = _load_package(
path
)
results = []
for session_record in package[
"sessions"
]:
result = _import_session(
conn,
package,
session_record,
)
results.append(
result
)
imported = sum(
1
for result in results
if result["status"] == "NEW"
)
duplicates = sum(
1
for result in results
if result["status"] == "DUPLICATE"
)
failed = sum(
1
for result in results
if result["status"] == "FAILED"
)
duration = (
datetime.now(
timezone.utc
) - started_at
).total_seconds()
result = {
"file": str(
path
),
"valid": True,
"sessions": len(
results
),
"imported": imported,
"duplicates": duplicates,
"failed": failed,
"results": results,
"duration": duration,
}
logger.info(
"wifitrip import completed: "
"file=%s sessions=%d imported=%d "
"duplicates=%d failed=%d duration=%.3fs",
path,
result["sessions"],
imported,
duplicates,
failed,
duration,
)
return result