feat(arnavi): add qualified B2 protocols, USB provisioning and SIM evidence

This commit is contained in:
DCCONSTRUCTIONS
2026-09-28 18:43:32 +03:00
parent fb33a6d45c
commit b6efae3272
20 changed files with 2858 additions and 0 deletions
@@ -0,0 +1 @@
"""Arnavi B2 operator-host preparation protocol; independent of onboard Node."""
@@ -0,0 +1,55 @@
"""Core-side cellular observations from the existing durable INTERNAL journal.
The receiver/installer wire codec remains unchanged. Framing and checksums are
validated by that codec before projecting TAG8, TAG201 and TAG99 (DS2 table 6).
Network codes describe the serving network, not SIM ownership, a phone number,
the APN contract or proof that both SIMs have simultaneous data connections.
"""
from typing import Any
from .internal import parse_package
from .sim_network import decode_pairs
def parse_telemetry_package(data: bytes) -> tuple[int, list[dict[str, Any]]] | None:
parsed = parse_package(data)
if parsed is None:
return None
offset = 2
for packet in parsed[1]:
size = int.from_bytes(data[offset + 1 : offset + 3], "little")
end = offset + 8 + size
if data[offset] == 1:
values: dict[int, set[bytes]] = {}
for i in range(offset + 7, end - 1, 5):
values.setdefault(data[i], set()).add(data[i + 1 : i + 5])
# Conflicting repeated scalar tags do not establish an observation.
tags = {key: next(iter(parts)) for key, parts in values.items() if len(parts) == 1}
pairs = decode_pairs(values)
if pairs:
packet["sim_identifiers"] = pairs # Private; never merge into public cellular.
cellular: dict[str, Any] = {}
if 99 in tags:
state = int.from_bytes(tags[99], "little")
cellular["status"] = {
"gsm_state": (state >> 2) & 7,
"active_sim": 1 + ((state >> 5) & 1),
"sim_states": {"1": (state >> 6) & 7, "2": (state >> 9) & 7},
}
networks = {}
for slot, tag in (("1", 8), ("2", 201)):
if tag in tags:
value = tags[tag]
mcc = int.from_bytes(value[1:3], "little")
networks[slot] = {
"mcc": mcc if 1 <= mcc <= 999 else None,
"mnc": value[0],
"signal": value[3] if value[3] <= 31 else None,
}
if networks:
cellular["networks"] = networks
if cellular:
packet["cellular"] = cellular
offset = end
return parsed
@@ -0,0 +1,106 @@
"""Offline coverage audit; never emits configuration values or contacts a service.
Metadata is reference material, not permission to write a parameter. Presence,
portable overlay support and physical qualification are deliberately separate.
"""
import argparse
import hashlib
import json
from pathlib import Path
from . import profiles
from .usb_protocol import ProtocolError, decode_configuration
ENDPOINTS = {1, 2, 3, 4, 6, 7, 8, 9, 111, 112, 113, 114}
ACCESS = {67, 68, 69, 89, 90, 91}
def audit(raw, metadata, owner):
config = decode_configuration(raw)
data = metadata["data"]
views = {view["alias"]: view for view in data["settingViewList"]}
known = {view["setting"]["number"] for view in views.values()}
present = {record.number for record in config.records}
portable = profiles.portable(config)
scalars = {int(n) for n in portable["parameters"]}
# Check identity-preserving overlay, not hypothetical compatibility inferred
# from a newer web schema's defaults or numeric widths.
unchanged = profiles.prepare(config, portable).encode() == raw
sections = []
for section in data["sectionList"]:
numbers = {
views[alias]["setting"]["number"]
for subsection in section["subSectionList"]
for alias in subsection["settingViewAliasList"]
if alias in views
}
sections.append(
{
"id": section["id"],
"declared_records": sorted(numbers),
"present_records": sorted(numbers & present),
"portable_scalars": sorted(numbers & scalars),
"specialized_records": sorted(numbers & present & (ENDPOINTS | ACCESS | {72})),
"preserved_only": sorted(numbers & present - scalars - ENDPOINTS - ACCESS - {72}),
"absent_records": sorted(numbers - present),
}
)
def channel(host_field, port_field):
try:
host, port = config.text(host_field), config.integer(port_field, 2)
except ProtocolError:
return "unavailable"
if not host and port == 0:
return "disabled"
if not host or port == 0:
return "inconsistent"
return "owner" if (host, port) == owner else "other"
channels = {
"monitoring_1": channel(1, 2),
"monitoring_2": channel(3, 4),
"monitoring_3": channel(111, 112),
"monitoring_4": channel(113, 114),
"configuration": channel(70, 71),
}
return {
"schema": "missioncore.b2-configuration-audit/v1",
"configuration_sha256": hashlib.sha256(raw).hexdigest(),
"record_count": len(config.records),
"byte_count": len(raw),
"portable_scalar_count": len(scalars),
"portable_scalar_ids": sorted(scalars),
"portable_catalog_missing": sorted({int(n) for n in profiles.FIELD_MAP} - present),
"portable_catalog_incompatible": sorted(
({int(n) for n in profiles.FIELD_MAP} & present) - scalars
),
"unknown_to_metadata": sorted(present - known),
"known_metadata_absent": sorted(known - present),
"portable_noop_exact": unchanged,
"channels": channels,
"owner_channels_only": channels["configuration"] == "owner"
and any(channels[f"monitoring_{n}"] == "owner" for n in range(1, 5))
and all(value in {"owner", "disabled"} for value in channels.values()),
"sections": sections,
"qualification": "Byte coverage only; no write, peripheral or firmware qualification.",
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--configuration", type=Path, required=True)
parser.add_argument("--metadata", type=Path, required=True)
parser.add_argument("--owner-host", required=True)
parser.add_argument("--owner-port", type=int, required=True)
args = parser.parse_args()
raw = args.configuration.read_bytes()
schema = args.metadata.read_bytes()
result = audit(raw, json.loads(schema), (args.owner_host, args.owner_port))
result["metadata_sha256"] = hashlib.sha256(schema).hexdigest()
print(json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
@@ -0,0 +1,42 @@
"""Versioned public carrier settings; never inferred from a phone or ICCID.
These are publicly documented APN access strings, not subscriber credentials.
Private/M2M contracts need their own explicitly configured connectivity.
"""
from dataclasses import dataclass
@dataclass(frozen=True)
class CarrierPreset:
label: str
apn: str
username: str
password: str
source: str
PRESETS = {
"ru-mts-public-v1": CarrierPreset(
"МТС — обычный мобильный интернет",
"internet.mts.ru",
"mts",
"mts",
"https://support.mts.ru/mts_mobilnyy_internet/nastroiki-mobilnogo-interneta/"
"kak-nastroit-internet-na-telefone",
),
"ru-megafon-public-v1": CarrierPreset(
"МегаФон — обычный мобильный интернет",
"internet",
"gdata",
"gdata",
"https://t.me/s/megafon_online?after=1143",
),
}
# Official model 231 schema; physical SIM identity is separate from these fields.
SIM_FIELDS = {1: (67, 68, 69), 2: (89, 90, 91)}
def catalog() -> list[dict[str, str]]:
return [{"id": key, "label": item.label, "apn": item.apn} for key, item in PRESETS.items()]
@@ -0,0 +1,104 @@
"""Operator-host adapter; USB discovery never depends on a vehicle's Node."""
import json
import time
from pathlib import Path
from typing import Any
from . import profiles
from .sim_observation_store import snapshot_details
from .usb_protocol import decode_configuration
from .usb_read import UsbReadError, read_snapshot
from .usb_write import apply_bootstrap, bootstrap_target
class B2Enrollment:
model_id = profiles.MODEL
def catalog(self) -> dict[str, Any]:
return profiles.catalog()
def validate_policy(self, value: dict[str, Any]) -> dict[str, Any]:
return profiles.Policy.model_validate(value).model_dump()
def observation_details(self, snapshot: Path) -> dict[str, Any]:
details = snapshot_details(snapshot)
try:
config = decode_configuration((snapshot / "configuration.bin").read_bytes())
except (OSError, ValueError):
return {**details, "output_modes": {}}
return {
**details,
"output_modes": {
str(record.number - 16): record.value[0]
for record in config.records
if record.number in (20, 21, 22) and len(record.value) == 1
},
}
def inspect(self, evidence: Path) -> dict[str, Any]:
try:
summary = read_snapshot(evidence)
except UsbReadError as exc:
messages = {
"usb_device_not_found": "B2 не найден. Подключите USB-кабель с передачей данных.",
"choose_one_usb_device": "Подключено несколько B2. Оставьте один для регистрации.",
"unsupported_operator_host": "Чтение B2 по USB поддерживается на Mac оператора.",
}
raise ValueError(
messages.get(
str(exc),
"Не удалось прочитать B2. Проверьте USB и закройте другие конфигураторы.",
)
) from None
summary["read_at"] = time.time()
directory = Path(str(summary.pop("evidence_directory")))
identity = json.loads((directory / "identity.json").read_text())
config = decode_configuration((directory / "configuration.bin").read_bytes())
policy = profiles.portable(config)
summary["supported_profile_fields"] = list(policy["parameters"])
summary.update(self.observation_details(directory))
return {
"identity_key": identity["imei"],
"model_id": self.model_id,
"evidence_id": directory.name,
"observed": summary,
"settings": policy,
}
def check_policy(
self, candidate: dict[str, Any], evidence: Path, policy: dict[str, Any]
) -> None:
config = decode_configuration(
(evidence / candidate["evidence_id"] / "configuration.bin").read_bytes()
)
# Shape/firmware validation only. Resolve the actual card at network admission.
check = {**policy, "connectivity": {**policy["connectivity"], "automatic": False}}
profiles.prepare(config, check)
def apply(self, instance: dict[str, Any], evidence: Path) -> dict[str, Any]:
try:
result = apply_bootstrap(
evidence / instance["evidence_id"], instance["settings"], evidence
)
except UsbReadError:
raise ValueError("Не удалось открыть B2. Проверьте USB и повторите чтение.") from None
update: dict[str, Any] = {"operation": result, "policy_state": result["state"]}
# Refresh only from a separately validated read of the same tracker.
try:
snapshot = self.inspect(evidence)
if snapshot["identity_key"] == instance["identity_key"]:
config = decode_configuration(
(evidence / snapshot["evidence_id"] / "configuration.bin").read_bytes()
)
matches = bootstrap_target(config, instance["settings"]).encode() == config.encode()
if result["state"] in ("applied", "unchanged") and not matches:
update["policy_state"] = "uncertain"
update.update(observed=snapshot["observed"], evidence_id=snapshot["evidence_id"])
elif result["state"] in ("applied", "unchanged"):
update["policy_state"] = "uncertain"
except (OSError, ValueError):
# Acknowledged/readback operation remains in evidence, but UI cannot
# claim the device's present state without the final observation.
update["policy_state"] = "uncertain"
return update
@@ -0,0 +1,15 @@
"""Verified manufacturer file identities, not permission to flash a tracker."""
KNOWN_IMAGES = {
"bf71fc531b02917eac076d7b718b51698f3d787562ca37c959bb1c9954fe9927": {
"version": "0.05",
"source_url": "https://8888.arusnavi.ru/Arnavi%20B2/"
"%D0%9F%D1%80%D0%BE%D1%88%D0%B8%D0%B2%D0%BA%D0%B8/"
"231%20%28B2%29%20-0.05.dfw",
},
"36135a214f62bfeac7f049fdedb1cb7c717b676cfe6027f7c72a026c39988625": {
"version": "0.06",
# Downloaded from the B2 row of the authenticated manufacturer catalogue.
"source_url": "https://ws.arusnavi.ru/#/firmwares",
},
}
@@ -0,0 +1,99 @@
"""ARNavi INTERNAL HEADER2 / packages. Only telemetry, never device commands.
Primary specification: docs.google.com/spreadsheets/d/
15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU (HEADER2, PACKAGE, TAG).
The standalone VPS release carries this exact module (verified in its manifest).
"""
import math
import struct
from typing import Any
MAX_PACKAGE = 65536
def identity(header: bytes) -> str:
if len(header) != 10 or header[:2] != b"\xff\x23":
raise ValueError("unsupported header")
value = str(int.from_bytes(header[2:], "little"))
if len(value) != 15:
raise ValueError("invalid identity")
return value
def header_ack(timestamp: int) -> bytes:
data = struct.pack("<I", timestamp)
return bytes([0x7B, 4, 0, sum(data) % 256]) + data + b"}"
def package_ack(number: int) -> bytes:
if not 1 <= number <= 251:
raise ValueError("invalid package number")
return bytes([0x7B, 0, number, 0x7D])
def parse_package(data: bytes) -> tuple[int, list[dict[str, Any]]] | None:
"""Return consumed bytes and packets; incomplete input has no side effects."""
if len(data) > MAX_PACKAGE:
raise ValueError("package too large")
if len(data) < 2:
return None
if data[0] != 0x5B or not 1 <= data[1] <= 251:
raise ValueError("invalid package")
offset = 2
packets: list[dict[str, Any]] = []
while offset < len(data):
if data[offset] == 0x5D:
if not packets:
raise ValueError("empty package")
return offset + 1, packets
if len(data) - offset < 3:
return None
size = int.from_bytes(data[offset + 1 : offset + 3], "little")
end = offset + 8 + size
if size > 32768 or end >= MAX_PACKAGE:
raise ValueError("packet too large")
if end > len(data):
return None
payload = data[offset + 3 : end - 1]
if sum(payload) % 256 != data[end - 1]:
raise ValueError("checksum mismatch")
# Unknown packet types remain durably stored in the original package.
if data[offset] == 1:
if size % 5:
raise ValueError("invalid TAG data")
timestamp = int.from_bytes(payload[:4], "little")
tags = {payload[i]: payload[i + 1 : i + 5] for i in range(4, len(payload), 5)}
packet: dict[str, Any] = {"measured_at": timestamp, "position": None}
# TAG6 mode 1 is a bitmask of logical input/output states. It is
# independent of GNSS and does not prove a physical relay contact.
for i in range(4, len(payload), 5):
if payload[i : i + 2] == b"\x06\x01":
mask = int.from_bytes(payload[i + 3 : i + 5], "little")
packet["outputs"] = {str(pin): bool(mask & (1 << pin)) for pin in (4, 5, 6)}
if all(tag in tags for tag in (3, 4, 5)):
lat, lon = struct.unpack("<f", tags[3])[0], struct.unpack("<f", tags[4])[0]
nav = tags[5]
source = "lbs" if nav[2] == 254 else "wifi" if nav[2] == 255 else "gnss"
satellites = (nav[2] & 15) + (nav[2] >> 4) if source == "gnss" else None
if (
math.isfinite(lat)
and math.isfinite(lon)
and -90 <= lat <= 90
and -180 <= lon <= 180
and (lat != 0 or lon != 0)
and (source != "gnss" or satellites is not None and satellites >= 4)
):
packet["position"] = {
"latitude": lat,
"longitude": lon,
"source": source,
"satellites": satellites,
"course": nav[0] * 2,
"speed_kmh": nav[3] * 1.852,
}
packets.append(packet)
else:
packets.append({"measured_at": int.from_bytes(payload[:4], "little"), "position": None})
offset = end
return None
@@ -0,0 +1,217 @@
"""Portable B2 policy, not a clone of a device's complete configuration.
Only reviewed non-identifying fields enter profiles. Missing means preserve;
zero is an explicit value. Firmware defaults and unknown records never leak in.
"""
from typing import Any, Literal, Self
from pydantic import BaseModel, ConfigDict, Field, model_validator
from . import connectivity
from .usb_protocol import Configuration, ProtocolError, prepare_server_slot
MODEL = "arnavi-b2"
# number, width, minimum, maximum, group, operator label
FIELDS = [
(25, 2, 0, 65535, "Траектория", "Интервал при стоянке, с"),
(63, 1, 0, 255, "Траектория", "Изменение курса, °"),
(64, 2, 0, 65535, "Траектория", "Расстояние между точками, м"),
(75, 1, 0, 255, "Траектория", "Изменение скорости, км/ч"),
(119, 2, 0, 65535, "Роуминг", "Интервал при стоянке, с"),
(120, 1, 0, 255, "Роуминг", "Изменение курса, °"),
(121, 2, 0, 65535, "Роуминг", "Расстояние между точками, м"),
(122, 1, 0, 255, "Роуминг", "Изменение скорости, км/ч"),
(128, 1, 0, 10, "Движение", "Чувствительность"),
(129, 1, 0, 255, "Движение", "Задержка срабатывания, с"),
(131, 1, 0, 255, "Движение", "Удар"),
(132, 1, 0, 255, "Движение", "Наклон"),
(241, 1, 0, 255, "Навигация", "Минимальное число спутников"),
(242, 1, 0, 255, "Навигация", "Максимальный HDOP × 10"),
(243, 2, -10000, 10000, "Навигация", "Минимальная высота, м"),
(244, 2, -10000, 10000, "Навигация", "Максимальная высота, м"),
(245, 1, 0, 255, "Навигация", "Минимальная мгновенная скорость, км/ч"),
(246, 1, 0, 255, "Навигация", "Максимальная мгновенная скорость, км/ч"),
(247, 2, 0, 65535, "Навигация", "Максимальная средняя скорость, км/ч"),
(248, 2, 0, 65535, "Навигация", "Максимальное время фильтрации, с"),
]
for start, label in [
(144, "Порог, mg"),
(160, "Длительность превышения, мс"),
(176, "Задержка сброса, мс"),
]:
for index in range(16):
group = ("Разгон", "Торможение", "Угловое ускорение", "Вертикальное ускорение")[index // 4]
FIELDS.append((start + index, 2, 0, 65535, group, f"Уровень {index % 4 + 1}: {label}"))
for start, label in [(192, "Порог, км/ч"), (198, "Длительность, с"), (204, "Порог сброса, км/ч")]:
for index in range(6):
FIELDS.append(
(start + index, 1, 0, 255, "Превышение скорости", f"Уровень {index + 1}: {label}")
)
FIELD_MAP = {str(row[0]): row for row in FIELDS}
class Endpoint(BaseModel):
model_config = ConfigDict(extra="forbid")
host: str = Field(min_length=1, max_length=49)
port: int = Field(ge=1, le=65535, strict=True)
slot: int = Field(ge=1, le=4, strict=True)
@model_validator(mode="after")
def valid_host(self) -> Self:
# Reuse the qualified DNS/IP grammar without building a device frame.
from .usb_protocol import Setting
numbers = {1: (1, 2, 9), 2: (3, 4, 8), 3: (111, 112, 7), 4: (113, 114, 6)}[self.slot]
dummy = Configuration(tuple(Setting(n, b"") for n in numbers))
prepare_server_slot(dummy, slot=self.slot, host=self.host, port=self.port)
return self
class Connectivity(BaseModel):
model_config = ConfigDict(extra="forbid")
strategy: Literal["preserve", "manual", "operator", "sim", "both", "native"] = "preserve"
apn1: str = Field(default="", max_length=29, pattern=r"^[A-Za-z0-9.-]*$")
apn2: str = Field(default="", max_length=29, pattern=r"^[A-Za-z0-9.-]*$")
apn: str | None = Field(default=None, max_length=29, pattern=r"^[A-Za-z0-9.-]*$")
preset_id: str | None = None
sim_slot: int = Field(default=1, ge=1, le=2, strict=True)
activate: bool = Field(default=False, strict=True)
automatic: bool = Field(default=False, strict=True)
@model_validator(mode="after")
def explicit_apn(self) -> Self:
if self.automatic and (self.strategy != "sim" or not self.activate or self.apn is not None):
raise ValueError("Автоподбор доступен для выбранной SIM без ручного APN.")
if (self.strategy != "sim" and (self.apn is not None or self.activate)) or (
self.strategy == "sim" and self.apn is None and not self.activate
):
raise ValueError("Укажите APN выбранной SIM.")
if self.strategy == "manual" and not self.apn1:
raise ValueError("Укажите APN основной SIM.")
if self.strategy != "manual" and (self.apn1 or self.apn2):
raise ValueError("APN задаётся только в ручном режиме.")
if self.strategy == "operator":
if self.preset_id not in connectivity.PRESETS:
raise ValueError("Выберите настройки оператора.")
elif self.preset_id is not None:
raise ValueError("Оператор задаётся только при выборе стандартных настроек.")
return self
class Policy(BaseModel):
model_config = ConfigDict(extra="forbid")
schema_version: Literal[1] = 1
endpoint: Endpoint | None = None
connectivity: Connectivity = Field(default_factory=Connectivity)
parameters: dict[str, int] = Field(default_factory=dict, max_length=len(FIELDS))
@model_validator(mode="before")
@classmethod
def strict_values(cls, value: Any) -> dict[str, Any]:
if not isinstance(value, dict):
raise ValueError("Некорректный профиль.")
params = value.get("parameters", {})
if not isinstance(params, dict):
raise ValueError("Некорректные параметры.")
for key, val in params.items():
spec = FIELD_MAP.get(key)
if spec is None or type(val) is not int or not spec[2] <= val <= spec[3]:
raise ValueError("Профиль содержит неизвестный параметр или недопустимое значение.")
for lo, hi in [(243, 244), (245, 246)]:
if str(lo) in params and str(hi) in params and params[str(lo)] > params[str(hi)]:
raise ValueError("Минимальное значение превышает максимальное.")
return value
def portable(config: Configuration) -> dict[str, Any]:
parameters = {}
for number, width, low, high, *_ in FIELDS:
try:
raw = config.value(number)
value = int.from_bytes(raw, "big", signed=low < 0)
if len(raw) == width and low <= value <= high:
parameters[str(number)] = value
except ProtocolError:
pass # Missing on this firmware is not the same as a zero default.
return Policy(parameters=parameters).model_dump()
def prepare(
config: Configuration,
policy: dict[str, Any],
*,
automatic_access: tuple[str, str, str] | None = None,
) -> Configuration:
"""Offline overlay; reject fields absent in target firmware, preserve all others."""
from .usb_protocol import Setting
parsed = Policy.model_validate(policy)
values = {}
for key, value in parsed.parameters.items():
number, width, low, *_ = FIELD_MAP[key]
if len(config.value(number)) != width:
raise ProtocolError("profile_incompatible_with_target")
values[number] = value.to_bytes(width, "big", signed=low < 0)
if parsed.connectivity.strategy == "sim":
if parsed.connectivity.automatic:
if automatic_access is None:
raise ProtocolError("sim_access_not_resolved")
for number, text in zip(
connectivity.SIM_FIELDS[parsed.connectivity.sim_slot], automatic_access, strict=True
):
config.value(number)
values[number] = config.replacement_text(number, text)
if parsed.connectivity.apn is not None:
number = connectivity.SIM_FIELDS[parsed.connectivity.sim_slot][0]
config.value(number)
values[number] = config.replacement_text(number, parsed.connectivity.apn)
if parsed.connectivity.activate:
# Model 231 field 72: bits 10/20 prohibit GPRS on SIM 1/2.
# This is exclusive selection, not a preference with failover.
flags = config.integer(72, 4) & ~((1 << 10) | (1 << 20))
flags |= 1 << (20 if parsed.connectivity.sim_slot == 1 else 10)
values[72] = flags.to_bytes(4, "big")
elif parsed.connectivity.strategy in ("both", "native"):
# Permission for either SIM, not a priority or a guaranteed failover timer.
values[72] = (config.integer(72, 4) & ~((1 << 10) | (1 << 20))).to_bytes(4, "big")
if parsed.connectivity.strategy == "native":
# An explicit portable policy, never inferred from missing identities
# or installed operators. Both complete access triples are cleared.
for numbers in connectivity.SIM_FIELDS.values():
for number in numbers:
config.value(number)
values[number] = config.replacement_text(number, "")
elif parsed.connectivity.strategy == "manual":
for number, apn in [(67, parsed.connectivity.apn1), (89, parsed.connectivity.apn2)]:
config.value(number)
values[number] = config.replacement_text(number, apn)
elif parsed.connectivity.strategy == "operator":
preset = connectivity.PRESETS[str(parsed.connectivity.preset_id)]
for number, access_value in zip(
connectivity.SIM_FIELDS[parsed.connectivity.sim_slot],
(preset.apn, preset.username, preset.password),
strict=True,
):
config.value(number) # Reject firmware without the requested SIM fields.
values[number] = config.replacement_text(number, access_value)
result = Configuration(
tuple(Setting(r.number, values.get(r.number, r.value)) for r in config.records)
)
if parsed.endpoint:
result = prepare_server_slot(result, **parsed.endpoint.model_dump())
return result
def catalog() -> dict[str, Any]:
return {
"id": MODEL,
"label": "ARNavi B2",
"profile_schema": 1,
"usb_write_firmware": ["0.01"],
"connectivity_presets": connectivity.catalog(),
"fields": [
{"key": str(n), "min": low, "max": high, "group": group, "label": label}
for n, _, low, high, group, label in FIELDS
],
}
@@ -0,0 +1,45 @@
"""Card-specific access selection. A public carrier preset is a candidate, not proof."""
from typing import Any
from .connectivity import PRESETS
from .sim_network import binding
from .sim_observation_store import SimObservationStore
HOME_PRESETS = {"25001": "ru-mts-public-v1", "25002": "ru-megafon-public-v1"}
def resolve(
value: dict[str, Any] | None, store: SimObservationStore, slot: str, *, now: float
) -> dict[str, Any]:
sid = binding(value, slot, now=now)
if not sid or not value:
return {"state": "waiting_identity"}
card = store.resolve_firmware_sid(value.get("tracker"), sid)
if not card:
return {"state": "unknown_card"}
known = store.verified_access(value["tracker"], card["card_ref"])
if known:
access = tuple(known["access"])
source = "verified_card"
else:
preset = PRESETS.get(HOME_PRESETS.get(card["home_network"], ""))
if not preset:
return {"state": "unsupported_operator", "card_ref": card["card_ref"]}
access = (preset.apn, preset.username, preset.password)
source = "carrier_candidate"
return {
"state": "ready",
"source": source,
"card_ref": card["card_ref"],
"home_network": card["home_network"],
"firmware_sid": sid,
"access": access,
}
def public(value: dict[str, Any]) -> dict[str, Any]:
result = {k: value[k] for k in ("state", "source", "home_network", "card_ref") if k in value}
if "access" in value:
result["apn"] = value["access"][0]
return result
@@ -0,0 +1,188 @@
"""SIM evidence, not APN policy or permission to write to a slot.
B2 231/0.01 can return a short SID in I7 while its modem transcript contains
the full CCID. A decimal firmware SID can also differ from the raw CCID.
Keep those sources separate. Only a contiguous, slot-labelled modem exchange
associates CCID with IMSI; time proximity and slot numbers alone do not.
"""
import hashlib
import re
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from .usb_protocol import Identity, ProtocolError
# Exact observed framing; no .* joining across commands, errors or SIM switches.
_MODEM = re.compile(
rb"(?:\A|(?<=\n))AT\+CCID[\r\n]+([0-9A-Fa-f]{15,22})[\r\n]+OK[\r\n]+"
rb">SID([01])=([0-9]{1,22})[\r\n]+"
rb"AT\+CIMI[\r\n]+([0-9]{15})[\r\n]+OK[\r\n]+HC([01])=([0-9]{5,6})\r?\n"
)
MAX_CAPTURE_BYTES = 1_000_000
def reported_state(value: str | None) -> str:
if not value:
return "not_reported" # Does not establish that the slot is empty.
return "incomplete" if len(value) < 19 else "unverified"
@dataclass(frozen=True)
class ModemObservation:
slot: int
raw_ccid: str = field(repr=False)
firmware_sid: str = field(repr=False)
imsi: str = field(repr=False)
home_network: str
start_offset: int
end_offset: int
@property
def ccid_format(self) -> str:
if re.fullmatch(r"[0-9]{19,20}", self.raw_ccid):
return "decimal"
if re.fullmatch(r"[0-9]{18}[fF]{2}", self.raw_ccid):
return "vendor_ff"
return "unqualified"
@property
def qualified(self) -> bool:
# Qualification of the observed exchange, NOT a canonical ICCID claim.
return (
self.ccid_format != "unqualified"
and len(self.firmware_sid) == 20
and self.imsi.startswith(self.home_network)
and not self.imsi.startswith("000")
)
def public(self) -> dict[str, Any]:
return {
"source": "usb_modem_exchange",
"qualified_exchange": self.qualified,
"ccid_format": self.ccid_format,
"ccid_length": len(self.raw_ccid),
"sid_length": len(self.firmware_sid),
"ccid_equals_sid": self.raw_ccid == self.firmware_sid,
"imsi_length": len(self.imsi),
"home_network": self.home_network if self.qualified else None,
"start_offset": self.start_offset,
"end_offset": self.end_offset,
}
def modem_observations(raw: bytes) -> tuple[ModemObservation, ...]:
if len(raw) > MAX_CAPTURE_BYTES:
raise ProtocolError("sim_capture_limit_exceeded")
result = []
for match in _MODEM.finditer(raw):
if match[2] != match[5]:
continue
result.append(
ModemObservation(
int(match[2]) + 1,
match[1].decode("ascii"),
match[3].decode("ascii"),
match[4].decode("ascii"),
match[6].decode("ascii"),
match.start(),
match.end(),
)
)
return tuple(result)
def unique_exchange(values: tuple[ModemObservation, ...]) -> ModemObservation | None:
if not values or not all(value.qualified for value in values):
return None
signatures = {
(value.raw_ccid, value.firmware_sid, value.imsi, value.home_network) for value in values
}
return values[-1] if len(signatures) == 1 else None
@dataclass(frozen=True)
class SimCapture:
capture_id: str
tracker: str = field(repr=False)
started_at: str
completed_at: str
usb_session: str
raw_sha256: str
reported: tuple[str | None, str | None] = field(repr=False)
exchanges: tuple[ModemObservation, ...] = field(repr=False)
def for_slot(self, slot: int) -> tuple[ModemObservation, ...]:
return tuple(value for value in self.exchanges if value.slot == slot)
def unique_for_slot(self, slot: int) -> ModemObservation | None:
value = unique_exchange(self.for_slot(slot))
other = self.for_slot(3 - slot)
if value and any((v.raw_ccid, v.imsi) == (value.raw_ccid, value.imsi) for v in other):
return None
return value
def public(self) -> dict[str, Any]:
slots = []
for slot, sid in enumerate(self.reported, 1):
values = self.for_slot(slot)
unique = self.unique_for_slot(slot)
slots.append(
{
"slot": slot,
"reported": {
"source": "usb_i7",
"state": reported_state(sid),
"length": len(sid or ""),
},
"modem_state": (
"not_observed" if not values else "observed" if unique else "unresolved"
),
"modem_observations": [value.public() for value in values],
# This only compares the two reports; it is not a fresh card binding.
"readback_matches_modem_sid": unique.firmware_sid == sid if unique else None,
}
)
return {
"schema": "arnavi-sim-observation/v1",
"capture_id": self.capture_id,
"started_at": self.started_at,
"completed_at": self.completed_at,
"slots": slots,
"automatic_write_authorized": False,
}
def capture_from_read(identity: Identity, raw: bytes, receipt: dict[str, Any]) -> SimCapture:
"""Only completed, stable USB reads. No inference of boot time from USB session."""
try:
before, after = receipt["usb_before"], receipt["usb_after"]
started, completed = receipt["started_at_utc"], receipt["completed_at_utc"]
start_time, end_time = datetime.fromisoformat(started), datetime.fromisoformat(completed)
capture_id = receipt["session_id"]
if (
receipt["status"] != "settings_read"
or before != after
or not isinstance(before["session"], str)
or not re.fullmatch(r"arnavi-read-[a-f0-9]{32}", capture_id)
or start_time.tzinfo is None
or end_time.tzinfo is None
or end_time < start_time
or hashlib.sha256(raw).hexdigest() != receipt["raw_sha256"]
or len(raw) > MAX_CAPTURE_BYTES
or identity.model_code != 231
):
raise ValueError
except (KeyError, TypeError, ValueError):
raise ProtocolError("sim_capture_unqualified") from None
return SimCapture(
capture_id,
identity.imei,
started,
completed,
before["session"],
receipt["raw_sha256"],
(identity.iccid1_reported, identity.iccid2_reported),
modem_observations(raw) if identity.firmware == "0.01" else (),
)
@@ -0,0 +1,158 @@
"""Private, time-scoped SIM SID observations from the INTERNAL packet journal.
The wire format calls these ICCID, but B2 231/0.01 reports a firmware SID that
can differ from the modem's raw CCID. Never normalize it or infer an operator.
Only paired tags inside one validated packet establish a SID observation.
"""
from __future__ import annotations
import copy
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from .sim_observation_store import SimObservationStore
def binding(value: dict[str, Any] | None, slot: str, *, now: float) -> str | None:
"""Retained startup identity with fresh presence, never a fresh SID claim.
B2 does not repeat SID tags in ordinary packets. A binding survives silence
only while current registration continues and no removal/search/conflict
invalidated it. Buffered startup data cannot establish this binding.
"""
slots = (value or {}).get("slots", {})
state = slots.get(slot, {})
observed, status = state.get("observation", {}), state.get("status", {})
sid = observed.get("firmware_sid")
if (
observed.get("state") == "observed"
and isinstance(sid, str)
and observed.get("measured_at", 0) >= state.get("invalidated_at", 0)
and 0 <= observed.get("received_at", 0) - observed.get("measured_at", 0) < 90
and observed.get("measured_at", 0) <= now
and status.get("value") in (1, 5)
and 0 <= now - status.get("measured_at", 0) < 90
and sum(s.get("observation", {}).get("firmware_sid") == sid for s in slots.values()) == 1
):
return sid
return None
def decode_pairs(values: dict[int, set[bytes]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for slot, first, second in (("1", 253, 254), ("2", 202, 203)):
if first not in values and second not in values:
continue
if any(len(values.get(tag, set())) != 1 for tag in (first, second)):
result[slot] = {"state": "unresolved"}
continue
parts = [int.from_bytes(next(iter(values[tag])), "little") for tag in (first, second)]
if any(part >= 1_000_000_000 for part in parts):
result[slot] = {"state": "unresolved"}
elif parts == [0, 0]:
result[slot] = {"state": "not_reported"} # Not proof of absence.
else:
result[slot] = {"state": "observed", "firmware_sid": f"89{parts[0]:09d}{parts[1]:09d}"}
if (
len(result) == 2
and result["1"].get("firmware_sid")
and result["1"].get("firmware_sid") == result["2"].get("firmware_sid")
):
result = {slot: {"state": "unresolved"} for slot in result}
return result
def merge(
previous: dict[str, Any] | None,
packet: dict[str, Any],
*,
host_id: str,
sequence: int,
received: float,
tracker: str | None,
) -> dict[str, Any] | None:
"""Called in the same transaction as the raw journal and its pull cursor."""
measured = packet["measured_at"]
if not 946684800 < measured <= received + 300:
return previous
states = packet.get("cellular", {}).get("status", {}).get("sim_states", {})
pairs = packet.get("sim_identifiers", {})
if not states and not pairs:
return previous
value = (
copy.deepcopy(previous)
if previous and previous["host_id"] == host_id and previous.get("tracker") == tracker
else {"host_id": host_id, "tracker": tracker, "slots": {}}
)
for slot in ("1", "2"):
state = value["slots"].setdefault(slot, {})
old_status = state.get("status", {})
if slot in states and measured > old_status.get("measured_at", 0):
current = states[slot]
if current == 0 or (
current != old_status.get("value")
and (current == 2 or old_status.get("value") == 0)
):
state["invalidated_at"] = measured
state["status"] = {"value": current, "measured_at": measured}
if slot not in pairs:
continue
old = state.get("observation", {})
if measured < old.get("measured_at", 0):
continue
if measured == old.get("measured_at"):
# Equal-time contradictions cannot be resolved by arrival order.
if any(old.get(key) != pairs[slot].get(key) for key in ("state", "firmware_sid")):
state["observation"] = {
**{k: v for k, v in old.items() if k != "firmware_sid"},
"state": "unresolved",
}
continue
state["observation"] = {
**pairs[slot],
"measured_at": measured,
"received_at": received,
"journal_sequence": sequence,
}
return value
def public(value: dict[str, Any], store: SimObservationStore, *, now: float) -> dict[str, Any]:
slots = {}
sids = [state.get("observation", {}).get("firmware_sid") for state in value["slots"].values()]
for slot, state in value["slots"].items():
observation = state.get("observation")
if not observation:
continue
measured, received = observation["measured_at"], observation["received_at"]
invalidated = measured < state.get("invalidated_at", 0)
sid = observation.get("firmware_sid")
ambiguous = bool(sid and sids.count(sid) > 1)
alias = (
store.resolve_firmware_sid(value.get("tracker"), sid) if sid and not ambiguous else None
)
slots[slot] = {
"state": observation["state"],
"source": "vps_internal_sim_tags",
"measured_at": measured,
"received_at": received,
"journal_sequence": observation["journal_sequence"],
"invalidated": invalidated,
"ambiguous_slot_binding": ambiguous,
# A freshly received buffered packet must not become a fresh identity.
"observation_fresh": bool(
not invalidated
and not ambiguous
and 0 <= now - measured < 90
and 0 <= received - measured < 90
),
"known_card": alias,
"binding_current": binding(value, slot, now=now) is not None,
}
return {
"schema": "arnavi-network-sim-observation/v1",
"host_id": value["host_id"],
"slots": slots,
"automatic_write_authorized": False,
}
@@ -0,0 +1,250 @@
"""Private append-only B2 SIM observations, independent of slot APN settings.
Short I7 reads are retained but never replace the last modem observation. A
card reference compares exact raw CCID + IMSI within one tracker; it is neither
a normalized ICCID nor an authorization to apply an old intent to that slot.
"""
import json
import os
import sqlite3
import uuid
from contextlib import closing
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
from typing import Any
from .sim_identity import MAX_CAPTURE_BYTES, SimCapture, capture_from_read
from .usb_protocol import Identity, ProtocolError, parse_identity, response_fields
def load_capture(snapshot: Path) -> SimCapture:
try:
identity = Identity(**json.loads((snapshot / "identity.json").read_text()))
receipt = json.loads((snapshot / "receipt.json").read_text())
response = snapshot / "response.bin"
if response.stat().st_size > MAX_CAPTURE_BYTES:
raise ValueError
raw = response.read_bytes()
if parse_identity(response_fields(raw)) != identity:
raise ValueError
capture = capture_from_read(identity, raw, receipt)
if capture.capture_id != snapshot.name:
raise ValueError
return capture
except (OSError, ValueError, TypeError, KeyError):
raise ProtocolError("sim_snapshot_unavailable") from None
class SimObservationStore:
def __init__(self, evidence: Path) -> None:
self.path = evidence / "sim-identity" / "observations.sqlite3"
def _connect(self, *, create: bool = False) -> sqlite3.Connection:
parent = self.path.parent
if create:
parent.mkdir(mode=0o700, exist_ok=True)
if parent.is_symlink() or parent.stat().st_mode & 0o077:
raise ProtocolError("sim_store_unavailable")
if create:
try:
fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
except FileExistsError:
pass
else:
os.close(fd)
if self.path.is_symlink() or self.path.stat().st_mode & 0o077:
raise ProtocolError("sim_store_unavailable")
db = sqlite3.connect(
self.path.as_uri() + ("?mode=rw" if create else "?mode=ro"), uri=True, timeout=5
)
db.execute("PRAGMA synchronous=FULL")
return db
def record(self, capture: SimCapture) -> dict[str, Any]:
body = json.dumps(asdict(capture), sort_keys=True)
started = datetime.fromisoformat(capture.started_at).timestamp()
completed = datetime.fromisoformat(capture.completed_at).timestamp()
with closing(self._connect(create=True)) as db, db:
db.executescript("""
CREATE TABLE IF NOT EXISTS captures(
id TEXT PRIMARY KEY, tracker TEXT NOT NULL, started REAL NOT NULL,
completed REAL NOT NULL, body TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS cards(
id TEXT PRIMARY KEY, tracker TEXT NOT NULL, raw_ccid TEXT NOT NULL,
imsi TEXT NOT NULL, UNIQUE(tracker, raw_ccid, imsi));
CREATE TABLE IF NOT EXISTS modem_observations(
capture TEXT NOT NULL, slot INTEGER NOT NULL, card TEXT NOT NULL,
body TEXT NOT NULL, PRIMARY KEY(capture, slot));
CREATE INDEX IF NOT EXISTS captures_tracker_time
ON captures(tracker, completed DESC);
""")
db.execute("BEGIN IMMEDIATE")
existing = db.execute("SELECT body FROM captures WHERE id=?", (capture.capture_id,))
previous = existing.fetchone()
if previous is not None:
if previous[0] != body:
raise ProtocolError("sim_capture_id_conflict")
else:
db.execute(
"INSERT INTO captures VALUES(?,?,?,?,?)",
(capture.capture_id, capture.tracker, started, completed, body),
)
values = [capture.unique_for_slot(slot) for slot in (1, 2)]
for value in values:
if value is None:
continue
db.execute(
"INSERT OR IGNORE INTO cards VALUES(?,?,?,?)",
(uuid.uuid4().hex, capture.tracker, value.raw_ccid, value.imsi),
)
card = db.execute(
"SELECT id FROM cards WHERE tracker=? AND raw_ccid=? AND imsi=?",
(capture.tracker, value.raw_ccid, value.imsi),
).fetchone()[0]
db.execute(
"INSERT INTO modem_observations VALUES(?,?,?,?)",
(
capture.capture_id,
value.slot,
card,
json.dumps(value.public(), sort_keys=True),
),
)
return self.public(capture)
def public(self, capture: SimCapture) -> dict[str, Any]:
result = capture.public()
if not self.path.exists():
return result
started = datetime.fromisoformat(capture.started_at).timestamp()
with closing(self._connect()) as db:
stored = db.execute(
"SELECT body FROM captures WHERE id=?", (capture.capture_id,)
).fetchone()
if stored and stored[0] != json.dumps(asdict(capture), sort_keys=True):
raise ProtocolError("sim_capture_id_conflict")
for slot in result["slots"]:
observed = db.execute(
"SELECT m.card FROM modem_observations m JOIN captures c ON c.id=m.capture "
"WHERE c.id=? AND c.tracker=? AND m.slot=?",
(capture.capture_id, capture.tracker, slot["slot"]),
).fetchone()
slot["captured_card_ref"] = observed[0] if observed else None
previous = db.execute(
"SELECT c.id,c.completed,m.card,m.body FROM captures c "
"JOIN modem_observations m ON m.capture=c.id "
"WHERE c.tracker=? AND m.slot=? AND c.completed < ? "
"ORDER BY c.completed DESC,c.id DESC LIMIT 1",
(capture.tracker, slot["slot"], started),
).fetchone()
slot["previous_modem_observation"] = (
{
"capture_id": previous[0],
"completed_at_epoch": previous[1],
"card_ref": previous[2],
"observation": json.loads(previous[3]),
"historical": True,
"current_slot_binding": False,
}
if previous
else None
)
return result
def resolve_firmware_sid(self, tracker: str | None, sid: str) -> dict[str, Any] | None:
"""Exact SID alias from a qualified USB exchange, across slots, never from I7.
Existing journals need no rewrite. Only captures with qualified modem
observations are searched; ordinary short USB reads do not grow this set.
Multiple raw CCID/IMSI pairs for the alias fail closed.
"""
if not tracker or not self.path.exists():
return None
try:
matches = set()
with closing(self._connect()) as db:
rows = db.execute(
"SELECT c.body,m.slot,k.id,k.raw_ccid,k.imsi FROM modem_observations m "
"JOIN captures c ON c.id=m.capture JOIN cards k ON k.id=m.card "
"WHERE c.tracker=? AND k.tracker=?",
(tracker, tracker),
)
for body, slot, card, raw_ccid, imsi in rows:
for exchange in json.loads(body)["exchanges"]:
if (
exchange["slot"] == slot
and exchange["firmware_sid"] == sid
and exchange["raw_ccid"] == raw_ccid
and exchange["imsi"] == imsi
):
matches.add((card, exchange["home_network"]))
if len(matches) != 1:
return None
card, home = matches.pop()
return {"card_ref": card, "home_network": home, "source": "usb_modem_sid_alias"}
except (OSError, ProtocolError, sqlite3.Error, ValueError, KeyError, TypeError):
return None
def verified_access(self, tracker: str, card: str) -> dict[str, Any] | None:
if not self.path.exists():
return None
with closing(self._connect()) as db:
if not db.execute(
"SELECT 1 FROM sqlite_master WHERE name='verified_access'"
).fetchone():
return None
row = db.execute(
"SELECT a.body FROM verified_access a JOIN cards c ON c.id=a.card "
"WHERE c.tracker=? AND a.card=?",
(tracker, card),
).fetchone()
return json.loads(row[0]) if row else None
def remember_access(
self,
tracker: str,
card: str,
access: tuple[str, str, str],
*,
operation: str,
verified_at: float,
configuration_sha256: str,
) -> None:
"""Private proof cache; caller requires readback AND card-bound GPRS evidence."""
with closing(self._connect(create=True)) as db, db:
db.execute(
"CREATE TABLE IF NOT EXISTS verified_access("
"card TEXT PRIMARY KEY, body TEXT NOT NULL)"
)
if not db.execute(
"SELECT 1 FROM cards WHERE id=? AND tracker=?", (card, tracker)
).fetchone():
raise ProtocolError("sim_card_unknown")
body = json.dumps(
{
"access": access,
"operation": operation,
"verified_at": verified_at,
"configuration_sha256": configuration_sha256,
}
)
db.execute(
"INSERT INTO verified_access VALUES(?,?) ON CONFLICT(card) "
"DO UPDATE SET body=excluded.body "
"WHERE json_extract(excluded.body,'$.verified_at') "
">= json_extract(verified_access.body,'$.verified_at')",
(card, body),
)
def snapshot_details(snapshot: Path, *, record: bool = False) -> dict[str, Any]:
try:
capture = load_capture(snapshot)
store = SimObservationStore(snapshot.parent)
result = store.record(capture) if record else store.public(capture)
except (OSError, ProtocolError, sqlite3.Error):
# Do not turn evidence/storage errors into "no SIM", or leak raw identifiers.
return {"sim_identity": {"state": "unavailable", "automatic_write_authorized": False}}
return {"sim_identity": result}
@@ -0,0 +1,230 @@
"""Qualified B2 USB reads and lossless offline configuration handling.
Source: official Configurator_251111.exe SettingsGet / UpdateTypeInfo and SF
parser, qualified against a physical B2 on 2026-09-26. No cloud dependency.
This module provides no hardware configuration-write command.
"""
import base64
import binascii
import hashlib
import json
import re
from dataclasses import dataclass, field
READ_IDENTITY = b">I 7\r\n"
READ_SETTINGS = b">D 15;0\r\n"
MAX_CONFIG_BYTES = 65539
_LINE = re.compile(rb"(?m)^(?:> )?>([A-Z][A-Z0-9]*)=([^\r\n]*)\r?\n")
_SERVER_FIELDS = {1: (1, 2, 9), 2: (3, 4, 8), 3: (111, 112, 7), 4: (113, 114, 6)}
class ProtocolError(ValueError):
"""Bounded error without raw device values or secrets."""
def response_fields(raw: bytes) -> dict[str, bytes]:
"""Only complete diagnostic lines; caller scopes bytes to one request."""
return {m[1].decode("ascii"): m[2] for m in _LINE.finditer(raw)}
@dataclass(frozen=True)
class Identity:
model_code: int
device_id: str
imei: str = field(repr=False)
firmware: str
# Preserve vendor SID0/1 verbatim. B2 0.01 has returned 12-digit reports,
# a qualified full MTS ICCID, and a decimal MegaFon SID unlike raw CCID.
# Length alone does not qualify canonical SIM identity; never pad/normalize.
iccid1_reported: str | None = field(repr=False)
iccid2_reported: str | None = field(repr=False)
def parse_identity(fields: dict[str, bytes]) -> Identity:
required = ("DI", "DN", "MN", "SID0", "SID1")
if any(key not in fields for key in required):
raise ProtocolError("identity_response_incomplete")
try:
parts = fields["DI"].decode("ascii").split(";")
if len(parts) not in (3, 4) or any(not re.fullmatch(r"[0-9]{1,5}", p) for p in parts):
raise ProtocolError("invalid_device_version")
if int(parts[0]) != 231:
raise ProtocolError("unsupported_device_model")
imei = fields["MN"].decode("ascii")
device_id = fields["DN"].decode("ascii")
if not re.fullmatch(r"[0-9]{15}", imei):
raise ProtocolError("invalid_imei")
if not re.fullmatch(r"[0-9]{1,10}", device_id):
raise ProtocolError("invalid_device_id")
cards: list[str | None] = []
for key in ("SID0", "SID1"):
value = fields[key].decode("ascii")
if value in ("", "0"):
cards.append(None)
elif re.fullmatch(r"[0-9]{1,22}", value):
cards.append(value)
else:
raise ProtocolError("invalid_sim_identifier")
return Identity(231, device_id, imei, f"{int(parts[1])}.{int(parts[2]):02d}", *cards)
except UnicodeError:
raise ProtocolError("invalid_identity_encoding") from None
@dataclass(frozen=True)
class Setting:
number: int
value: bytes = field(repr=False)
@dataclass(frozen=True)
class Configuration:
"""Ordered raw records, including fields missing from the public UI schema."""
records: tuple[Setting, ...] = field(repr=False)
def value(self, number: int) -> bytes:
for record in self.records:
if record.number == number:
return record.value
raise ProtocolError("required_setting_missing")
def integer(self, number: int, size: int) -> int:
value = self.value(number)
if len(value) != size:
raise ProtocolError("unexpected_integer_width")
return int.from_bytes(value, "big")
def text(self, number: int) -> str:
try:
value = self.value(number)
if value.endswith(b"\x00"):
value = value[:-1]
if b"\x00" in value:
raise ProtocolError("embedded_string_terminator")
return value.decode("ascii")
except UnicodeError:
raise ProtocolError("invalid_setting_text") from None
def replacement_text(self, number: int, value: str) -> bytes:
# Preserve unchanged records exactly. B2 0.01 strips a supplied NUL
# from changed strings in SF readback (observed on the SIM 2 access fields).
return self.value(number) if self.text(number) == value else value.encode("ascii")
def encode(self) -> bytes:
"""Offline serialization only. Does not send or apply anything."""
body = bytearray()
seen = set()
for record in self.records:
if not 1 <= record.number <= 255 or record.number in seen:
raise ProtocolError("invalid_or_duplicate_setting_number")
if len(record.value) > 255:
raise ProtocolError("setting_too_long")
seen.add(record.number)
body.extend(bytes((0x23, record.number, len(record.value))))
body.extend(record.value)
if not body or len(body) > 65535:
raise ProtocolError("invalid_configuration_size")
return (
len(body).to_bytes(2, "big") + binascii.crc_hqx(body, 0xFFFF).to_bytes(2, "big") + body
)
def summary(self) -> dict[str, object]:
"""Explicit allowlist; never expose passwords, phone numbers or tokens."""
servers = []
for slot, (host, port, protocol) in _SERVER_FIELDS.items():
servers.append(
{
"slot": slot,
"host": self.text(host),
"port": self.integer(port, 2),
"protocol_code": self.integer(protocol, 1),
}
)
flags = self.integer(72, 4)
return {
"record_count": len(self.records),
"sha256": hashlib.sha256(self.encode()).hexdigest(),
"servers": servers,
"apn1": self.text(67),
"apn2": self.text(89),
"web_configurator": {
"host": self.text(70),
"port": self.integer(71, 2),
"interval_hours": self.integer(62, 2),
"check_at_start": bool(flags & 1),
},
}
def decode_configuration(raw: bytes) -> Configuration:
if not 7 <= len(raw) <= MAX_CONFIG_BYTES:
raise ProtocolError("invalid_configuration_size")
length, checksum = int.from_bytes(raw[:2], "big"), int.from_bytes(raw[2:4], "big")
if length != len(raw) - 4:
raise ProtocolError("configuration_length_mismatch")
if binascii.crc_hqx(raw[4:], 0xFFFF) != checksum:
raise ProtocolError("configuration_crc_mismatch")
records = []
seen = set()
offset = 4
while offset < len(raw):
if offset + 3 > len(raw):
raise ProtocolError("truncated_setting_header")
marker, number, size = raw[offset : offset + 3]
if marker != 0x23:
raise ProtocolError("unsupported_configuration_record_format")
if number == 0 or number in seen:
raise ProtocolError("invalid_or_duplicate_setting_number")
end = offset + 3 + size
if end > len(raw):
raise ProtocolError("truncated_setting_value")
records.append(Setting(number, raw[offset + 3 : end]))
seen.add(number)
offset = end
return Configuration(tuple(records))
def configuration_response(fields: dict[str, bytes]) -> Configuration:
if "SF" not in fields:
raise ProtocolError("settings_response_incomplete")
encoded = fields["SF"]
if len(encoded) > 2 + ((MAX_CONFIG_BYTES + 2) // 3) * 4:
raise ProtocolError("settings_response_too_large")
try:
value = json.loads(encoded)
if not isinstance(value, str):
raise ProtocolError("invalid_settings_envelope")
raw = base64.b64decode(value, validate=True)
except (ValueError, UnicodeError):
raise ProtocolError("invalid_settings_envelope") from None
return decode_configuration(raw)
def prepare_server_slot(config: Configuration, *, slot: int, host: str, port: int) -> Configuration:
"""Prepare an offline INTERNAL server diff while preserving every other byte.
This is deliberately not a provisioning API: hardware write qualification,
gateway readiness, identity and revision checks belong to the operation owner.
"""
if slot not in _SERVER_FIELDS or type(port) is not int or not 1 <= port <= 65535:
raise ProtocolError("invalid_server_slot_or_port")
if (
len(host) > 49
or not re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?", host)
or any(
not label or label.startswith("-") or label.endswith("-") for label in host.split(".")
)
):
raise ProtocolError("invalid_server_host")
host_field, port_field, protocol_field = _SERVER_FIELDS[slot]
for number in (host_field, port_field, protocol_field):
config.value(number)
values = {
host_field: config.replacement_text(host_field, host),
port_field: port.to_bytes(2, "big"),
protocol_field: b"\x00",
}
return Configuration(
tuple(Setting(r.number, values.get(r.number, r.value)) for r in config.records)
)
@@ -0,0 +1,298 @@
"""Bounded operator-Mac USB bootstrap reader. No configuration-write capability.
Run with --output-dir pointing to private evidence storage. No vendor account,
onboard computer, global Python package or third-party serial driver is needed.
"""
import argparse
import hashlib
import json
import math
import os
import re
import select
import subprocess
import sys
import termios
import time
import uuid
from dataclasses import asdict, dataclass
from datetime import UTC, datetime
from pathlib import Path
from .sim_observation_store import snapshot_details
from .usb_protocol import (
READ_IDENTITY,
READ_SETTINGS,
Configuration,
Identity,
ProtocolError,
configuration_response,
parse_identity,
response_fields,
)
class UsbReadError(RuntimeError):
"""Host/transport failure; message contains no response content."""
@dataclass(frozen=True)
class UsbPort:
path: str
session: str
def parse_ioreg(output: str) -> tuple[UsbPort, ...]:
ports = []
for tree in re.split(r"(?m)(?=^\+-o )", output):
vendor = re.search(r'"idVendor" = (\d+)', tree)
product = re.search(r'"idProduct" = (\d+)', tree)
session = re.search(r'"sessionID" = (\d+)', tree)
if not vendor or not product or not session:
continue
if (int(vendor[1]), int(product[1])) != (0x2E3C, 0x5740):
continue
for path in re.findall(r'"IOCalloutDevice" = "(/dev/cu\.usbmodem[^"\s/]+)"', tree):
ports.append(UsbPort(path, session[1]))
return tuple(dict.fromkeys(ports))
def discover() -> tuple[UsbPort, ...]:
if sys.platform != "darwin":
raise UsbReadError("unsupported_operator_host")
try:
result = subprocess.run(
[
"/usr/sbin/ioreg",
"-p",
"IOService",
"-r",
"-n",
"AT32 Virtual Com Port",
"-l",
"-w",
"0",
],
check=True,
capture_output=True,
text=True,
timeout=5,
)
except (OSError, subprocess.SubprocessError):
raise UsbReadError("usb_discovery_failed") from None
return parse_ioreg(result.stdout)
def _utc() -> str:
return datetime.now(UTC).isoformat()
def _private_file(path: Path, content: bytes) -> None:
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "wb") as output:
output.write(content)
output.flush()
os.fsync(output.fileno())
def read_snapshot(
output_dir: Path, *, port: str | None = None, observe_seconds: float = 2
) -> dict[str, object]:
if not math.isfinite(observe_seconds) or not 2 <= observe_seconds <= 180:
raise UsbReadError("invalid_observation_window")
candidates = discover()
selected = [candidate for candidate in candidates if port is None or candidate.path == port]
if len(selected) != 1:
raise UsbReadError("choose_one_usb_device" if selected else "usb_device_not_found")
candidate = selected[0]
output_dir.mkdir(parents=True, exist_ok=True)
session_dir = output_dir / ("arnavi-read-" + uuid.uuid4().hex)
session_dir.mkdir(mode=0o700)
receipt: dict[str, object] = {
"session_id": session_dir.name,
"started_at_utc": _utc(),
"started_at_monotonic_ns": time.monotonic_ns(),
"usb_before": asdict(candidate),
"commands": [],
"events": [],
"configuration_writes": 0,
"tty_settings_changed": False,
"explicit_modem_controls": False,
"passive_observation_seconds": observe_seconds,
}
commands: list[dict[str, object]] = []
events: list[dict[str, object]] = []
receipt["commands"], receipt["events"] = commands, events
raw = bytearray()
descriptor = None
identity: Identity | None = None
config: Configuration | None = None
summary: dict[str, object] | None = None
failure: Exception | None = None
def receive_until(deadline: float) -> None:
assert descriptor is not None
while time.monotonic() < deadline:
readable, _, _ = select.select(
[descriptor], [], [], min(0.1, max(0, deadline - time.monotonic()))
)
if readable:
try:
chunk = os.read(descriptor, 8192)
except BlockingIOError:
continue
if not chunk:
raise UsbReadError("usb_stream_closed")
if len(raw) + len(chunk) > 1_000_000:
raise UsbReadError("capture_limit_exceeded")
events.append(
{
"offset": len(raw),
"bytes": len(chunk),
"utc": _utc(),
"monotonic_ns": time.monotonic_ns(),
}
)
raw.extend(chunk)
def request(payload: bytes, required: tuple[str, ...]) -> dict[str, bytes]:
assert descriptor is not None
if payload not in (READ_IDENTITY, READ_SETTINGS):
raise UsbReadError("unsupported_read_request")
offset = len(raw)
written = os.write(descriptor, payload)
commands.append(
{
"request_hex": payload.hex(),
"bytes_written": written,
"rx_offset": offset,
"utc": _utc(),
"monotonic_ns": time.monotonic_ns(),
}
)
if written != len(payload):
raise UsbReadError("partial_request_not_retried")
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
receive_until(min(deadline, time.monotonic() + 0.1))
fields = response_fields(bytes(raw[offset:]))
# Reject a clearly wrong model before attempting a configuration read.
if "DI" in fields and fields["DI"].split(b";", 1)[0] != b"231":
raise ProtocolError("unsupported_device_model")
if all(key in fields for key in required):
return fields
raise UsbReadError("usb_read_response_timeout")
try:
# OS flock is a cooperative exclusive lease; the CLI cannot arbitrate
# non-cooperating vendor applications. No line controls are changed.
import fcntl
descriptor = os.open(candidate.path, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
current = termios.tcgetattr(descriptor)
receipt["tty"] = {"ispeed": current[4], "ospeed": current[5], "lflag": current[3]}
if current[3] & (termios.ICANON | termios.ECHO):
raise UsbReadError("unsupported_tty_mode")
receive_until(time.monotonic() + observe_seconds)
identity = parse_identity(request(READ_IDENTITY, ("DI", "DN", "MN", "SID0", "SID1")))
config = configuration_response(request(READ_SETTINGS, ("SF",)))
# Bracket the settings with the same hardware identity; tty names are not identity.
after = parse_identity(request(READ_IDENTITY, ("DI", "DN", "MN", "SID0", "SID1")))
if after != identity:
raise UsbReadError("identity_changed_during_snapshot")
if candidate not in discover():
raise UsbReadError("usb_reenumerated_during_snapshot")
summary = config.summary()
receipt["usb_after"] = asdict(candidate)
receipt["status"] = "settings_read"
except (OSError, ProtocolError, UsbReadError) as exc:
failure = exc
receipt["status"] = "failed"
receipt["error"] = (
str(exc)
if isinstance(exc, (ProtocolError, UsbReadError))
else f"usb_io_error_{exc.errno}"
)
finally:
if descriptor is not None:
os.close(descriptor)
receipt.update(
completed_at_utc=_utc(),
completed_at_monotonic_ns=time.monotonic_ns(),
bytes_read=len(raw),
raw_sha256=hashlib.sha256(raw).hexdigest(),
)
_private_file(session_dir / "response.bin", bytes(raw))
if identity is not None:
_private_file(session_dir / "identity.json", json.dumps(asdict(identity)).encode())
if config is not None:
_private_file(session_dir / "configuration.bin", config.encode())
receipt["configuration_sha256"] = hashlib.sha256(config.encode()).hexdigest()
_private_file(session_dir / "receipt.json", json.dumps(receipt, indent=2).encode())
if failure is not None:
raise UsbReadError(str(receipt["error"])) from None
assert identity is not None and config is not None and summary is not None
return {
# Persist independently of the expiring enrollment candidate, also for
# CLI capture. No identifiers enter portable profiles or public output.
**snapshot_details(session_dir, record=True),
"status": "settings_read",
"model": "Arnavi B2",
"device_id": identity.device_id,
"imei_suffix": identity.imei[-5:],
"firmware": identity.firmware,
"sim1_iccid_reported_suffix": (
identity.iccid1_reported[-5:] if identity.iccid1_reported else None
),
"sim1_iccid_reported_length": len(identity.iccid1_reported or ""),
"sim2_iccid_reported_suffix": (
identity.iccid2_reported[-5:] if identity.iccid2_reported else None
),
"sim2_iccid_reported_length": len(identity.iccid2_reported or ""),
"configuration": summary,
"evidence_directory": str(session_dir),
"provisioned": False,
}
def main() -> None:
parser = argparse.ArgumentParser(
description="Read B2 identity and settings on the operator Mac"
)
parser.add_argument("--list", action="store_true", help="List supported USB interfaces only")
parser.add_argument(
"--port", help="Choose one of the discovered ports when several are attached"
)
parser.add_argument("--output-dir", type=Path, help="Private snapshot storage directory")
parser.add_argument(
"--observe-seconds",
type=float,
default=2,
help="Bounded passive observation before the read (2–180 seconds); no modem commands",
)
args = parser.parse_args()
try:
if args.list:
print(json.dumps([asdict(port) for port in discover()]))
else:
if args.output_dir is None:
parser.error("--output-dir is required for a hardware read")
print(
json.dumps(
read_snapshot(
args.output_dir,
port=args.port,
observe_seconds=args.observe_seconds,
),
ensure_ascii=False,
)
)
except (UsbReadError, ProtocolError) as exc:
print(json.dumps({"status": "failed", "reason": str(exc)}))
raise SystemExit(1) from None
if __name__ == "__main__":
main()
@@ -0,0 +1,312 @@
"""Bounded B2 0.01 configuration transaction, with private durable evidence.
Configurator_251111: 777cc0 envelope, 66fe98 base64, 69b951 SR handler.
Only a validated portable policy can build the target. No arbitrary commands,
firmware, password changes, modem line changes or automatic write retries.
"""
import base64
import hashlib
import json
import os
import re
import select
import termios
import time
import uuid
from collections.abc import Callable
from dataclasses import asdict
from pathlib import Path
from typing import Any, Protocol
from .profiles import prepare
from .usb_protocol import (
READ_IDENTITY,
READ_SETTINGS,
Configuration,
Identity,
ProtocolError,
configuration_response,
decode_configuration,
parse_identity,
response_fields,
)
from .usb_read import UsbReadError, _private_file, _utc, discover
def envelope(original: Configuration, target: Configuration) -> bytes:
password = original.text(5)
if not re.fullmatch(r"[0-9]{6}", password):
raise ProtocolError("unsupported_device_password_format")
if original.value(5) != target.value(5):
raise ProtocolError("password_change_forbidden")
return password.encode("ascii") + b"*CONF*" + base64.b64encode(target.encode()) + b"\r\n"
class Transport(Protocol):
def identity(self) -> Identity: ...
def settings(self) -> Configuration: ...
def write(self, payload: bytes) -> bool: ...
def write_all(fd: int, payload: bytes, progress: Callable[[int], None]) -> None:
"""Complete one frame on a nonblocking tty, never resend accepted bytes."""
offset = 0
deadline = time.monotonic() + 8
while offset < len(payload):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise UsbReadError("usb_write_timeout")
_, writable, _ = select.select([], [fd], [], min(0.1, remaining))
if not writable:
continue
try:
written = os.write(fd, payload[offset:])
except BlockingIOError:
continue
if written <= 0:
raise UsbReadError("usb_write_closed")
offset += written
progress(offset)
def transact(
transport: Transport,
expected: Identity,
before: Configuration,
policy: dict[str, Any],
backup: Callable[[Configuration, Configuration], None],
*,
prepare_target: Callable[[Configuration, dict[str, Any]], Configuration] = prepare,
) -> dict[str, Any]:
if expected.firmware != "0.01" or expected.model_code != 231:
raise ProtocolError("write_firmware_not_qualified")
if transport.identity() != expected:
raise ProtocolError("device_or_sim_changed")
actual = transport.settings()
if actual.encode() != before.encode():
raise ProtocolError("configuration_changed_read_again")
target = prepare_target(actual, policy)
command = envelope(actual, target) # Validate before persisting or sending.
if transport.identity() != expected:
raise ProtocolError("device_or_sim_changed")
changed = [r.number for r in actual.records if r.value != target.value(r.number)]
backup(actual, target) # Durable rollback image must precede the first write.
result: dict[str, Any] = {"changed_fields": changed, "state": "unchanged"}
if not changed:
return result
# Once write starts, an I/O exception means indeterminate, never "not applied".
result["state"] = "uncertain"
try:
result["acknowledged"] = transport.write(command)
readback = transport.settings()
if transport.identity() != expected:
return result
if readback.encode() == target.encode():
result["state"] = "applied"
result["readback_sha256"] = hashlib.sha256(readback.encode()).hexdigest()
return result
if readback.encode() == actual.encode():
result["state"] = "not_applied"
return result
# Same device, confirmed partial/different readback: one bounded rollback.
result["rollback_acknowledged"] = transport.write(envelope(actual, actual))
restored = transport.settings()
if transport.identity() == expected and restored.encode() == actual.encode():
result["state"] = "rolled_back"
except (OSError, UsbReadError, ProtocolError) as exc:
result["error"] = str(exc) if isinstance(exc, UsbReadError) else type(exc).__name__
return result
def apply_policy(
expected_directory: Path, policy: dict[str, Any], output_dir: Path
) -> dict[str, Any]:
return _apply(expected_directory, policy, output_dir, prepare)
def configuration_service_target(before: Configuration, endpoint: dict[str, Any]) -> Configuration:
"""Bootstrap only fields 70/71; retain polling flags and every other raw byte.
The caller must establish the owned endpoint before this explicit operation.
This is separate from portable profiles and ordinary network settings saves.
"""
from .profiles import Endpoint
from .usb_protocol import Setting
checked = Endpoint(host=endpoint["host"], port=endpoint["port"], slot=1)
before.integer(71, 2)
values = {
70: before.replacement_text(70, checked.host),
71: checked.port.to_bytes(2, "big"),
}
return Configuration(
tuple(Setting(r.number, values.get(r.number, r.value)) for r in before.records)
)
def apply_configuration_service(
expected_directory: Path, endpoint: dict[str, Any], output_dir: Path
) -> dict[str, Any]:
return _apply(expected_directory, endpoint, output_dir, configuration_service_target)
def bootstrap_target(before: Configuration, policy: dict[str, Any]) -> Configuration:
"""Initial owner-VPS provisioning, not an ordinary remote profile overlay.
Disable the startup settings pull: on qualified 231/0.01 it can keep the
configuration channel waiting for an unsolicited image after restart.
Explicit owner reads/writes still work. Preserve periodic polling and every
other bit; zero-as-disabled semantics for field 62 have not been qualified.
"""
from .profiles import Policy
from .usb_protocol import Setting, prepare_server_slot
parsed = Policy.model_validate(policy)
if not parsed.endpoint or parsed.endpoint.slot != 1:
raise ProtocolError("initialization_requires_primary_vps")
target = prepare(before, policy)
endpoint = {"host": parsed.endpoint.host, "port": parsed.endpoint.port}
target = prepare_server_slot(target, slot=2, **endpoint)
target = configuration_service_target(target, endpoint)
flags = (target.integer(72, 4) & ~1).to_bytes(4, "big")
return Configuration(
tuple(Setting(r.number, flags if r.number == 72 else r.value) for r in target.records)
)
def apply_bootstrap(
expected_directory: Path, policy: dict[str, Any], output_dir: Path
) -> dict[str, Any]:
return _apply(expected_directory, policy, output_dir, bootstrap_target)
def _apply(
expected_directory: Path,
policy: dict[str, Any],
output_dir: Path,
prepare_target: Callable[[Configuration, dict[str, Any]], Configuration],
) -> dict[str, Any]:
expected = Identity(**json.loads((expected_directory / "identity.json").read_text()))
before = decode_configuration((expected_directory / "configuration.bin").read_bytes())
candidates = discover()
if len(candidates) != 1:
raise UsbReadError("one_usb_device_required")
port = candidates[0]
directory = output_dir / ("arnavi-write-" + uuid.uuid4().hex)
directory.mkdir(mode=0o700, parents=True)
receipt: dict[str, Any] = {
"session_id": directory.name,
"started_at_utc": _utc(),
"started_at_monotonic_ns": time.monotonic_ns(),
"usb": asdict(port),
"state": "not_started",
"commands": [],
"events": [],
}
raw = bytearray()
fd: int | None = None
def capture(deadline: float) -> None:
assert fd is not None
while time.monotonic() < deadline:
ready, _, _ = select.select([fd], [], [], min(0.1, max(0, deadline - time.monotonic())))
if not ready:
continue
try:
chunk = os.read(fd, 8192)
except BlockingIOError:
continue
if not chunk or len(raw) + len(chunk) > 1_000_000:
raise UsbReadError("usb_closed_or_capture_limit")
receipt["events"].append({"offset": len(raw), "bytes": len(chunk), "utc": _utc()})
raw.extend(chunk)
def request(payload: bytes, keys: tuple[str, ...], kind: str) -> dict[str, bytes]:
assert fd is not None
if port not in discover():
raise UsbReadError("usb_session_changed")
offset = len(raw)
# No configuration payload or password enters the receipt/log.
item: dict[str, Any] = {
"kind": kind,
"sha256": hashlib.sha256(payload).hexdigest(),
"utc": _utc(),
"bytes_expected": len(payload),
"bytes_written": 0,
}
receipt["commands"].append(item)
write_all(fd, payload, lambda count: item.update(bytes_written=count))
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
capture(min(deadline, time.monotonic() + 0.1))
fields = response_fields(bytes(raw[offset:]))
if all(k in fields for k in keys):
return fields
if kind == "configuration":
return {} # Missing acknowledgment still requires authoritative readback.
raise UsbReadError("readback_timeout")
class SerialTransport:
def identity(self) -> Identity:
return parse_identity(
request(READ_IDENTITY, ("DI", "DN", "MN", "SID0", "SID1"), "identity")
)
def settings(self) -> Configuration:
return configuration_response(request(READ_SETTINGS, ("SF",), "settings"))
def write(self, payload: bytes) -> bool:
receipt["state"] = "uncertain"
marker = directory / "transmission-started.json"
if not marker.exists():
_private_file(marker, json.dumps({"utc": _utc(), "state": "uncertain"}).encode())
return (
request(payload, ("SR",), "configuration").get("SR", b"").split(b";", 1)[0] == b"1"
)
def backup(original: Configuration, target: Configuration) -> None:
_private_file(directory / "before.bin", original.encode())
_private_file(directory / "target.bin", target.encode())
_private_file(directory / "identity.json", json.dumps(asdict(expected)).encode())
_private_file(directory / "policy.json", json.dumps(policy).encode())
receipt["before_sha256"] = hashlib.sha256(original.encode()).hexdigest()
receipt["target_sha256"] = hashlib.sha256(target.encode()).hexdigest()
_private_file(directory / "prepared.json", json.dumps(receipt).encode())
handle = os.open(directory, os.O_RDONLY)
try:
os.fsync(handle)
finally:
os.close(handle)
try:
import fcntl
fd = os.open(port.path, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
attributes = termios.tcgetattr(fd)
if attributes[3] & (termios.ICANON | termios.ECHO):
raise UsbReadError("unsupported_tty_mode")
capture(time.monotonic() + 2)
receipt.update(
transact(
SerialTransport(), expected, before, policy, backup, prepare_target=prepare_target
)
)
except (OSError, UsbReadError, ProtocolError) as exc:
receipt.update(error=type(exc).__name__)
finally:
if fd is not None:
os.close(fd)
receipt.update(
completed_at_utc=_utc(),
completed_at_monotonic_ns=time.monotonic_ns(),
raw_sha256=hashlib.sha256(raw).hexdigest(),
)
_private_file(directory / "response.bin", bytes(raw))
_private_file(directory / "receipt.json", json.dumps(receipt, indent=2).encode())
return {
k: receipt[k]
for k in ("session_id", "state", "changed_fields", "acknowledged", "readback_sha256")
if k in receipt
}
@@ -0,0 +1,74 @@
"""B2 231/0.01 configuration HTTP payloads, observed 2026-09-26.
The HTTP transport is separate from INTERNAL. Unknown commands and firmware
fail closed. Parsing upload evidence is not proof that a write was applied.
"""
from .usb_protocol import Configuration, ProtocolError, decode_configuration
MAX_BODY = 16384
QUALIFIED_METADATA = bytes.fromhex("0001e7020000")
def decode_request(raw: bytes, *, observe_empty_check: bool = False) -> tuple[str, int, bytes]:
if (
not 20 <= len(raw) <= MAX_BODY
or raw[:2] != b"[\x01"
or raw[-1:] != b"]"
or int.from_bytes(raw[2:4], "big") != len(raw) - 5
or raw[12:18] != QUALIFIED_METADATA
):
raise ProtocolError("unsupported_web_request")
imei = str(int.from_bytes(raw[4:12], "little"))
if len(imei) != 15:
raise ProtocolError("invalid_web_identity")
command, payload = raw[18], raw[19:-1]
if command == 1 and payload == b"":
# The observed reply contains the device's existing numeric ID.
pass
elif command == 2 and payload == b"":
pass
elif command == 5:
decode_configuration(payload)
elif command == 6 and payload == b"\x02":
pass
elif command == 7 and payload == b"":
# Two owner-authorized reference exchanges returned current Unix UTC
# seconds (u32be), 36 seconds apart. No configuration payload.
pass
else:
raise ProtocolError("unqualified_web_command")
return imei, command, payload
def numeric_id_reply(number: int) -> bytes:
if type(number) is not int or not 1 <= number <= 0xFFFFFFFF:
raise ProtocolError("invalid_numeric_device_identity")
return bytes.fromhex("5b00060001") + number.to_bytes(4, "big") + b"]"
def time_reply(unix_seconds: int) -> bytes:
"""Observed opcode-7 clock reply; never reuse a captured timestamp."""
if type(unix_seconds) is not int or not 1 <= unix_seconds <= 0xFFFFFFFF:
raise ProtocolError("invalid_web_time")
return bytes.fromhex("5b00060007") + unix_seconds.to_bytes(4, "big") + b"]"
def settings_reply(configuration: Configuration) -> bytes:
"""Observed manufacturer layout: size:u16be, status=0, command=2, CRC image."""
raw = configuration.encode()
if len(raw) + 6 > MAX_BODY:
raise ProtocolError("web_configuration_too_large")
return b"[" + (len(raw) + 2).to_bytes(2, "big") + b"\x00\x02" + raw + b"]"
def decode_settings_reply(raw: bytes) -> Configuration:
if (
not 13 <= len(raw) <= MAX_BODY
or raw[:1] != b"["
or raw[-1:] != b"]"
or int.from_bytes(raw[1:3], "big") != len(raw) - 4
or raw[3:5] != b"\x00\x02"
):
raise ProtocolError("invalid_web_settings_reply")
return decode_configuration(raw[5:-1])
+101
View File
@@ -0,0 +1,101 @@
"""Offline audits cannot promote schema defaults or disclose device values."""
import json
from k1link.device_plugins.arnavi_b2.configuration_audit import audit
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting
def sample():
raw = Configuration(
tuple(
Setting(n, value)
for n, value in (
(1, b"owner.example"),
(2, (9922).to_bytes(2, "big")),
(3, b"owner.example"),
(4, (9922).to_bytes(2, "big")),
(111, b""),
(112, b"\0\0"),
(113, b""),
(114, b"\0\0"),
(70, b"owner.example"),
(71, (9922).to_bytes(2, "big")),
(5, b"234567"),
(25, b"\0\x0f"),
(52, b"private-phone"),
(72, b"\0\x10\0\0"),
(250, b"unknown-secret"),
)
)
).encode()
metadata = {
"data": {
"settingViewList": [
{"alias": f"231_{n}_1", "defaultValue": "schema-only", "setting": {"number": n}}
for n in (5, 25, 52, 72, 241)
],
"sectionList": [
{
"id": "test",
"subSectionList": [
{"settingViewAliasList": [f"231_{n}_1" for n in (5, 25, 52, 72, 241)]}
],
}
],
}
}
return raw, metadata
def test_audit_separates_presence_overlay_and_unknown_fields_without_values():
raw, metadata = sample()
result = audit(raw, metadata, ("owner.example", 9922))
assert result["record_count"] == 15 and result["portable_scalar_count"] == 1
assert result["portable_noop_exact"] and result["owner_channels_only"]
assert 250 in result["unknown_to_metadata"]
assert 241 in result["portable_catalog_missing"]
section = result["sections"][0]
assert section["portable_scalars"] == [25]
assert section["specialized_records"] == [72]
assert section["preserved_only"] == [5, 52]
assert section["absent_records"] == [241]
for secret in ("234567", "private-phone", "unknown-secret", "owner.example", "schema-only"):
assert secret not in json.dumps(result)
def test_other_optional_destination_prevents_owner_only_claim():
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
raw, metadata = sample()
cfg = decode_configuration(raw)
changed = Configuration(
tuple(
Setting(
r.number,
{
111: b"third-party.example",
112: (1234).to_bytes(2, "big"),
}.get(r.number, r.value),
)
for r in cfg.records
)
).encode()
result = audit(changed, metadata, ("owner.example", 9922))
assert result["channels"]["monitoring_3"] == "other"
assert not result["owner_channels_only"]
assert "third-party.example" not in json.dumps(result)
def test_wrong_width_is_not_synthesized_from_a_schema_default():
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
raw, metadata = sample()
config = decode_configuration(raw)
raw = Configuration(
tuple(Setting(r.number, b"\x0f" if r.number == 25 else r.value) for r in config.records)
).encode()
result = audit(raw, metadata, ("owner.example", 9922))
assert result["portable_scalar_count"] == 0
assert result["portable_catalog_incompatible"] == [25]
assert result["portable_noop_exact"]
+204
View File
@@ -0,0 +1,204 @@
"""Synthetic-only B2 wire fixtures; never commit device dumps or credentials."""
import base64
import binascii
import json
from pathlib import Path
import pytest
from k1link.device_plugins.arnavi_b2.usb_protocol import (
READ_IDENTITY,
READ_SETTINGS,
Configuration,
ProtocolError,
Setting,
configuration_response,
decode_configuration,
parse_identity,
prepare_server_slot,
response_fields,
)
from k1link.device_plugins.arnavi_b2.usb_read import UsbPort, parse_ioreg
def wire(body: bytes) -> bytes:
return len(body).to_bytes(2, "big") + binascii.crc_hqx(body, 0xFFFF).to_bytes(2, "big") + body
def synthetic_config() -> Configuration:
records = [
Setting(1, b"old.example\0"),
Setting(2, b"\x50\x8f"),
Setting(9, b"\0"),
Setting(5, b"SYNTHETIC_SECRET"),
Setting(135, b"\xde\xad\x23\x00"),
]
for host, port, protocol in [(3, 4, 8), (111, 112, 7), (113, 114, 6)]:
records.extend([Setting(host, b""), Setting(port, b"\0\0"), Setting(protocol, b"\0")])
records.extend(
[
Setting(67, b"example.apn\0"),
Setting(89, b""),
Setting(70, b"vendor.example\0"),
Setting(71, (9231).to_bytes(2, "big")),
Setting(72, (2073).to_bytes(4, "big")),
Setting(62, b"\0\x96"),
]
)
return Configuration(tuple(records))
IDENTITY = (
b">DI=231;0;1\r\n>DN=123456\r\n>MN=123456789012345\r\n>SID0=8900000000000000001\r\n>SID1=0\r\n"
)
def test_config_wire_endianness_and_lossless_unknown_records():
original = wire(b"#\x02\x02\x50\x8f#\x87\x04\xde\xad#\x00")
config = decode_configuration(original)
assert config.integer(2, 2) == 20623
assert config.value(135) == b"\xde\xad#\x00"
assert config.encode() == original
@pytest.mark.parametrize(
"body,reason",
[
(b"#\x02\x02\x01", "truncated_setting_value"),
(b"#\x02\x00#\x02\x00", "invalid_or_duplicate_setting_number"),
(b"#\x02\x00#", "truncated_setting_header"),
(b"!\x02\x00", "unsupported_configuration_record_format"),
],
)
def test_invalid_records_fail_closed(body, reason):
with pytest.raises(ProtocolError, match=reason):
decode_configuration(wire(body))
def test_crc_and_length_rejected_before_use():
original = synthetic_config().encode()
damaged = bytearray(original)
damaged[-1] ^= 1
with pytest.raises(ProtocolError, match="crc_mismatch"):
decode_configuration(bytes(damaged))
with pytest.raises(ProtocolError, match="length_mismatch"):
decode_configuration(original + b"\0")
def test_sf_envelope_complete_lines_only_and_secret_redaction():
config = synthetic_config()
sf = b">SF=" + json.dumps(base64.b64encode(config.encode()).decode()).encode()
assert "SF" not in response_fields(sf)
result = configuration_response(response_fields(b"noise\r\n" + sf + b"\r\n"))
assert result.encode() == config.encode()
public = json.dumps(result.summary())
assert "SYNTHETIC_SECRET" not in public
assert "value_hex" not in public
assert result.summary()["web_configurator"]["check_at_start"] is True
def test_identity_and_sim_are_independent_of_usb_port():
result = parse_identity(response_fields(IDENTITY))
assert result.model_code == 231
assert result.imei == "123456789012345"
assert result.firmware == "0.01"
assert result.iccid2_reported is None
assert result.imei not in repr(result)
assert result.iccid1_reported not in repr(result)
partial_sim = parse_identity(
response_fields(IDENTITY.replace(b"8900000000000000001", b"000000000001"))
)
assert partial_sim.iccid1_reported == "000000000001"
with pytest.raises(ProtocolError, match="unsupported_device_model"):
parse_identity(response_fields(IDENTITY.replace(b"231;", b"230;")))
with pytest.raises(ProtocolError, match="identity_response_incomplete"):
parse_identity(response_fields(IDENTITY.split(b">SID0")[0]))
def test_console_prompt_prefix_does_not_hide_complete_identity_lines():
prompted = IDENTITY.replace(b">DI=", b"> >DI=")
assert parse_identity(response_fields(prompted)) == parse_identity(response_fields(IDENTITY))
assert response_fields(b"noise>DI=231;0;1\r\n") == {}
assert response_fields(b"> >DI=231;0;1") == {}
def test_offline_server_patch_changes_only_requested_slot():
original = synthetic_config()
planned = prepare_server_slot(original, slot=2, host="track.example", port=10001)
before = {r.number: r.value for r in original.records}
after = {r.number: r.value for r in decode_configuration(planned.encode()).records}
assert {key for key in before if before[key] != after[key]} == {3, 4}
assert planned.text(1) == "old.example"
assert planned.text(3) == "track.example"
assert planned.integer(4, 2) == 10001
assert planned.value(135) == original.value(135)
assert planned.value(5) == original.value(5)
@pytest.mark.parametrize(
"host,port",
[("https://track.example", 80), ("bad\r\ncmd", 1), ("a..example", 1), ("track.example", 65536)],
)
def test_invalid_server_plan_is_not_serialized(host, port):
with pytest.raises(ProtocolError):
prepare_server_slot(synthetic_config(), slot=2, host=host, port=port)
def test_discovery_filters_usb_profile_and_keeps_instances_separate():
def tree(port, session, vid=11836):
return (
f'+-o AT32 Virtual Com Port@00110000\n "sessionID" = {session}\n'
f' "idVendor" = {vid}\n "idProduct" = 22336\n'
f' "IOCalloutDevice" = "{port}"\n'
)
result = parse_ioreg(
tree("/dev/cu.usbmodemA", 1)
+ tree("/dev/cu.usbmodemB", 2)
+ tree("/dev/cu.usbmodemOther", 3, 999)
)
assert result == (UsbPort("/dev/cu.usbmodemA", "1"), UsbPort("/dev/cu.usbmodemB", "2"))
def test_snapshot_wrong_model_never_sends_settings_request(monkeypatch, tmp_path):
import fcntl
from k1link.device_plugins.arnavi_b2 import usb_read as reader
candidate = UsbPort("/dev/cu.usbmodemSYNTHETIC", "1")
monkeypatch.setattr(reader, "discover", lambda: (candidate,))
original_open, original_write, original_close = reader.os.open, reader.os.write, reader.os.close
monkeypatch.setattr(
reader.os, "open", lambda p, *a: 999 if p == candidate.path else original_open(p, *a)
)
monkeypatch.setattr(reader.os, "close", lambda fd: None if fd == 999 else original_close(fd))
monkeypatch.setattr(fcntl, "flock", lambda *a: None)
monkeypatch.setattr(reader.termios, "tcgetattr", lambda fd: [0, 0, 0, 0, 9600, 9600])
queue, sent = [], []
clock = [0.0]
def tick():
clock[0] += 0.05
return clock[0]
def write(fd, payload):
if fd != 999:
return original_write(fd, payload)
sent.append(payload)
queue.append(b">DI=999;0;1\r\n")
return len(payload)
monkeypatch.setattr(reader.time, "monotonic", tick)
monkeypatch.setattr(reader.os, "write", write)
monkeypatch.setattr(reader.os, "read", lambda fd, size: queue.pop(0))
monkeypatch.setattr(reader.select, "select", lambda *a: ([999] if queue else [], [], []))
with pytest.raises(reader.UsbReadError, match="unsupported_device_model"):
reader.read_snapshot(tmp_path)
assert sent == [READ_IDENTITY]
assert READ_SETTINGS not in sent
receipts = list(tmp_path.glob("*/receipt.json"))
assert len(receipts) == 1
assert json.loads(receipts[0].read_text())["status"] == "failed"
assert receipts[0].stat().st_mode & 0o777 == 0o600
assert Path(receipts[0].parent).stat().st_mode & 0o777 == 0o700
+285
View File
@@ -0,0 +1,285 @@
"""Transaction failure cases with synthetic configurations; no physical USB."""
import base64
from dataclasses import replace
import pytest
from k1link.device_plugins.arnavi_b2.usb_protocol import (
Configuration,
Identity,
ProtocolError,
Setting,
)
from k1link.device_plugins.arnavi_b2.usb_read import UsbReadError
from k1link.device_plugins.arnavi_b2.usb_write import envelope, transact, write_all
IDENTITY = Identity(231, "123456", "123456789012345", "0.01", None, "89000000000000000001")
BEFORE = Configuration((Setting(5, b"123456"), Setting(25, b"\0\x0f"), Setting(135, b"opaque")))
class Fake:
def __init__(self, outcome="apply"):
self.outcome, self.current, self.commands = outcome, BEFORE, []
def identity(self):
return IDENTITY
def settings(self):
return self.current
def write(self, command):
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
self.commands.append(command)
if self.outcome == "lost":
raise OSError("lost")
if self.outcome == "unchanged":
return False
target = decode_configuration(base64.b64decode(command[12:-2]))
self.current = (
Configuration((Setting(5, b"123456"), Setting(25, b"\0\x07"), Setting(135, b"opaque")))
if self.outcome == "partial" and len(self.commands) == 1
else target
)
return self.outcome != "no_ack"
@pytest.mark.parametrize(
"outcome,state,writes",
[
("apply", "applied", 1),
("no_ack", "applied", 1),
("unchanged", "not_applied", 1),
("lost", "uncertain", 1),
("partial", "rolled_back", 2),
],
)
def test_readback_not_ack_is_authoritative_and_writes_are_bounded(outcome, state, writes):
transport = Fake(outcome)
backups = []
def backup(before, target):
assert not transport.commands
backups.append((before, target))
result = transact(transport, IDENTITY, BEFORE, {"parameters": {"25": 30}}, backup)
assert result["state"] == state
assert len(transport.commands) == writes
assert result["changed_fields"] == [25]
assert backups[0][0] == BEFORE
if state == "rolled_back":
assert transport.current == BEFORE
def test_changed_sim_or_settings_or_unsupported_firmware_never_writes():
for expected, before in [
(replace(IDENTITY, iccid2_reported="89000000000000000002"), BEFORE),
(replace(IDENTITY, firmware="0.02"), BEFORE),
(IDENTITY, Configuration((Setting(5, b"123456"),))),
]:
transport = Fake()
with pytest.raises(ProtocolError):
transact(transport, expected, before, {"parameters": {"25": 30}}, lambda *_: None)
assert not transport.commands
def test_backup_failure_prevents_write_and_noop_does_not_rewrite_flash():
transport = Fake()
def fail(*_):
raise OSError("disk full")
with pytest.raises(OSError):
transact(transport, IDENTITY, BEFORE, {"parameters": {"25": 30}}, fail)
assert not transport.commands
assert transact(transport, IDENTITY, BEFORE, {}, lambda *_: None)["state"] == "unchanged"
assert not transport.commands
def test_envelope_has_only_qualified_command_and_rejects_password_change():
assert envelope(BEFORE, BEFORE) == b"123456*CONF*" + base64.b64encode(BEFORE.encode()) + b"\r\n"
with pytest.raises(ProtocolError):
envelope(BEFORE, Configuration((Setting(5, b"654321"),)))
def test_nonblocking_tty_completes_short_write_without_repeating_prefix(monkeypatch):
from k1link.device_plugins.arnavi_b2 import usb_write
payload = bytes(range(256)) * 5 + b"\r\n"
received = bytearray()
calls = []
def send(fd, suffix):
calls.append(suffix)
if len(calls) == 2:
raise BlockingIOError()
count = min(1024, len(suffix))
received.extend(suffix[:count])
return count
monkeypatch.setattr(usb_write.os, "write", send)
monkeypatch.setattr(usb_write.select, "select", lambda *args: ([], [42], []))
progress = []
write_all(42, payload, progress.append)
assert bytes(received) == payload
assert calls == [payload, payload[1024:], payload[1024:]]
assert progress == [1024, len(payload)]
def test_write_deadline_preserves_prefix_and_never_restarts_frame(monkeypatch):
from k1link.device_plugins.arnavi_b2 import usb_write
ticks = iter([0, 0, 9])
calls = []
monkeypatch.setattr(usb_write.time, "monotonic", lambda: next(ticks))
monkeypatch.setattr(usb_write.select, "select", lambda *args: ([], [42], []))
monkeypatch.setattr(usb_write.os, "write", lambda fd, b: calls.append(b) or 2)
progress = []
with pytest.raises(UsbReadError, match="usb_write_timeout"):
write_all(42, b"synthetic-frame\r\n", progress.append)
assert calls == [b"synthetic-frame\r\n"]
assert progress == [2]
def test_mts_readback_is_exact_and_preserves_unmodified_null_terminated_strings():
from k1link.device_plugins.arnavi_b2.profiles import prepare
before = Configuration(
(
Setting(5, b"123456"),
Setting(67, b"internet\0"),
Setting(89, b""),
Setting(90, b""),
Setting(91, b""),
)
)
policy = {
"connectivity": {
"strategy": "operator",
"preset_id": "ru-mts-public-v1",
"sim_slot": 2,
}
}
target = prepare(before, policy)
assert target.value(89) == b"internet.mts.ru"
assert target.value(90) == target.value(91) == b"mts"
assert target.value(67) == before.value(67)
assert prepare(target, policy).encode() == target.encode()
def test_configuration_service_bootstrap_preserves_every_other_record():
from k1link.device_plugins.arnavi_b2.usb_write import configuration_service_target
before = Configuration(
BEFORE.records + (Setting(70, b"vendor.example"), Setting(71, b"\x24\x0f"))
)
target = configuration_service_target(before, {"host": "owner.example", "port": 9922})
assert target.text(70) == "owner.example"
assert target.integer(71, 2) == 9922
assert [(r.number, r.value) for r in target.records if r.number not in (70, 71)] == [
(r.number, r.value) for r in BEFORE.records
]
for value in ("https://owner.example/", "bad\r\ncommand"):
with pytest.raises(ValueError):
configuration_service_target(before, {"host": value, "port": 9922})
def test_initial_provisioning_sets_monitoring_and_configuration_channel_together():
from k1link.device_plugins.arnavi_b2.usb_write import bootstrap_target
before = Configuration(
BEFORE.records
+ tuple(
Setting(n, v)
for n, v in (
(1, b"vendor.example"),
(2, b"\x24\x0f"),
(9, b"\0"),
(3, b""),
(4, b"\0\0"),
(8, b"\0"),
(70, b"vendor.example"),
(71, b"\x24\x0f"),
(72, b"\x80\x00\x08\x19"),
(62, b"\x00\x96"),
)
)
)
policy = {
"endpoint": {"slot": 1, "host": "owner.example", "port": 9922},
"parameters": {"25": 16},
}
target = bootstrap_target(before, policy)
assert all(target.text(n) == "owner.example" for n in (1, 3, 70))
assert all(target.integer(n, 2) == 9922 for n in (2, 4, 71))
assert target.integer(25, 2) == 16
assert target.integer(72, 4) == before.integer(72, 4) & ~1
assert target.value(62) == before.value(62)
assert [r.number for r in target.records if r.value != before.value(r.number)] == [
25,
1,
2,
3,
4,
70,
71,
72,
]
assert target.value(135) == before.value(135) and target.value(5) == before.value(5)
assert bootstrap_target(target, policy).encode() == target.encode()
with pytest.raises(ProtocolError):
bootstrap_target(before, {"parameters": {"25": 16}})
# An absent or malformed bitset must fail before backing up/sending a write.
for value in (None, b"\x01", b"\x00" * 5):
records = tuple(r for r in before.records if r.number != 72)
if value is not None:
records += (Setting(72, value),)
transport = Fake()
transport.current = Configuration(records)
backups = []
with pytest.raises(ProtocolError):
transact(
transport,
IDENTITY,
transport.current,
policy,
lambda *args, backups=backups: backups.append(args),
prepare_target=bootstrap_target,
)
assert not transport.commands and not backups
def test_bootstrap_uses_one_backed_up_verified_usb_transaction():
from k1link.device_plugins.arnavi_b2.usb_write import bootstrap_target
before = Configuration(
BEFORE.records
+ tuple(
Setting(n, v)
for n, v in (
(1, b"vendor.example"),
(2, b"\x24\x0f"),
(9, b"\0"),
(3, b""),
(4, b"\0\0"),
(8, b"\0"),
(70, b"vendor.example"),
(71, b"\x24\x0f"),
(72, b"\x00\x00\x08\x19"),
)
)
)
t = Fake()
t.current = before
backups = []
result = transact(
t,
IDENTITY,
before,
{"endpoint": {"slot": 1, "host": "owner.example", "port": 9922}},
lambda a, b: backups.append((a, b)),
prepare_target=bootstrap_target,
)
assert result["state"] == "applied" and len(t.commands) == len(backups) == 1
assert t.current == backups[0][1] and backups[0][0] == before
+74
View File
@@ -0,0 +1,74 @@
"""Bounded configuration HTTP framing, independent from monitoring packets."""
import pytest
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, ProtocolError, Setting
from k1link.device_plugins.arnavi_b2.web_protocol import (
decode_request,
decode_settings_reply,
settings_reply,
time_reply,
)
def request(command, payload=b""):
body = int("123456789012345").to_bytes(8, "little") + bytes.fromhex("0001e7020000")
body += bytes([command]) + payload
return b"[\x01" + len(body).to_bytes(2, "big") + body + b"]"
def test_upload_preserves_unknown_records_and_read_request_has_no_settings():
config = Configuration((Setting(62, b"\x00\x96"), Setting(222, b"opaque\x00\xff")))
imei, cmd, payload = decode_request(request(5, config.encode()))
assert imei == "123456789012345" and cmd == 5
assert payload == config.encode()
assert decode_request(request(2))[1:] == (2, b"")
assert decode_request(request(6, b"\x02"))[1:] == (6, b"\x02")
reply = settings_reply(config)
assert decode_settings_reply(reply).encode() == config.encode()
assert reply[3:5] == b"\x00\x02"
@pytest.mark.parametrize(
"raw",
[
request(1, b"extra"),
request(2, b"extra"),
request(6, b"\x01"),
request(5, b"no-crc"),
request(2).replace(bytes.fromhex("e702"), bytes.fromhex("e703")),
request(2)[:-1],
request(2) + b"extra",
b"\xff\x23" + b"x" * 18,
],
)
def test_unqualified_requests_fail_closed(raw):
with pytest.raises(ProtocolError):
decode_request(raw)
def test_reply_wrong_size_status_command_and_crc_fail_closed():
raw = settings_reply(Configuration((Setting(62, b"\x00\x96"),)))
for position in (0, 1, 2, 3, 4, 7, 8, 10, len(raw) - 1):
changed = bytearray(raw)
changed[position] ^= 1
with pytest.raises(ProtocolError):
decode_settings_reply(bytes(changed))
def test_engineering_empty_check_admission_never_accepts_images_or_unknown_opcodes():
assert decode_request(request(1), observe_empty_check=True)[1:] == (1, b"")
for raw in (request(1, b"image"), request(3), request(4), request(1) + b"extra"):
with pytest.raises(ProtocolError):
decode_request(raw, observe_empty_check=True)
def test_empty_time_request_and_big_endian_utc_reply():
assert decode_request(request(7))[1:] == (7, b"")
assert time_reply(1700000000) == bytes.fromhex("5b000600076553f1005d")
for raw in (request(7, b"extra"), request(7).replace(b"\xe7\x02", b"\xe7\x03")):
with pytest.raises(ProtocolError):
decode_request(raw)
for value in (True, 0, -1, 2**32, 1700000000.0, "1700000000"):
with pytest.raises(ProtocolError):
time_reply(value)