Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 29 additions & 8 deletions docs/device-info.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,27 @@ against the device public key recovered during onboarding and checks that the
body DID matches the URL DID. Only unambiguous reports with one value per field
are persisted. Query parameters do not supply or override metadata.

This handler accepts exactly these six fields, nonempty metadata values of
1–128 ASCII letters, digits, dots, underscores or hyphens, decimal `featureset`,
and hexadecimal `newfeatureset`. These conservative limits match the observed
reports; authentic firmware variants outside them are acknowledged and logged as
unsupported without writing. They require further evidence before expanding the
accepted contract.
The Saros 20 Flow (`roborock.vacuum.a307`) uses a V2 form instead. It sends the
five metadata fields as `multipart/form-data` parts, without a `signature` part.
Four headers carry the signature: `v` is `v2`, `n` is a nonce, `t` is a Unix
timestamp and `s` is the base64 signature. The device signs the form above,
followed by the nonce and the timestamp, with PKCS#1 v1.5 and SHA-384:

```text
did=<numeric DID>&featureset=<decimal flags>&newfeatureset=<hex flags>&pid=<model>&sn=<serial>:<n>:<t>
```

The server rebuilds this text in the field order above, whatever the order of
the parts. It verifies the signature with the same device public key and applies
the same checks. An upload of the five fields counts as malformed if a header is
missing or `v` is not `v2`.

This handler accepts exactly the fields of either form, nonempty metadata
values of 1–128 ASCII letters, digits, dots, underscores or hyphens, decimal
`featureset`, and hexadecimal `newfeatureset`. These conservative limits match
the observed reports; authentic firmware variants outside them are acknowledged
and logged as unsupported without writing. They require further evidence before
expanding the accepted contract.

For an existing inventory device matched by DID, or by its runtime DID-to-DUID
link, verified reports update `sn`, `featureSet`, and `newFeatureSet` in
Expand All @@ -45,8 +60,10 @@ acknowledgement behavior. Responses retain the previous fallback body, including
The inspected G10S firmware ignores that body; preserving it avoids changing the
response contract for other models whose callback has not been audited.

There is no nonce or timestamp in this form. A valid recorded report can be
replayed; signature verification establishes its origin, not its freshness.
The form with a `signature` field has no nonce or timestamp. The V2 form has
both, but the server does not check them for freshness or reuse. A valid
recorded report of either form can be replayed; signature verification
establishes its origin, not its freshness.
No replayed report can change identity or credentials through this handler.

The server logs the DID, an outcome (`stored`, `unchanged`, `unmatched`,
Expand Down Expand Up @@ -90,3 +107,7 @@ acknowledgement for other contracts and refuses metadata writes when verificatio
fails. A cloud response capture is unnecessary
for the inspected G10S callback, but would be needed to describe the cloud's exact
response body or another model's response parser.

One a307 upload was verified with its recovered RSA public key against the V2
form and its PKCS#1 v1.5/SHA-384 contract. No raw signatures, serial numbers,
nonces or keys are included here.
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"""Acknowledge signed firmware metadata uploads and update known devices.

The G10S rriot_rr upload callback accepts HTTP 200/201 and ignores the response
body. Its form is RSA PKCS#1 v1.5/SHA-256 signed in the field order below. See
docs/device-info.md for firmware evidence and the limits of this contract.
body. Its form is RSA PKCS#1 v1.5/SHA-256 signed in the field order below. The
a307 omits the signature field and sends a V2 header signature instead: SHA-384
over the same fields, followed by the nonce and timestamp headers. See
docs/device-info.md for firmware evidence and the limits of these contracts.
"""

from __future__ import annotations
Expand All @@ -17,6 +19,7 @@
from cryptography.hazmat.primitives.asymmetric import padding

from shared.context import ServerContext
from shared.http_helpers import route_header
from shared.inventory_io import WEB_API_INVENTORY_FILE, inventory_transaction, load_inventory, write_inventory

from .catchall import build as _build_catchall
Expand All @@ -31,13 +34,33 @@ def match(path: str, method: str = "POST") -> bool:
return method.upper() == "POST" and _PATH.fullmatch(path) is not None


def _signature_contract(
query_params: dict[str, list[str]], params: dict[str, list[str]]
) -> tuple[str, str, hashes.HashAlgorithm] | None:
"""Pick the signature form of an upload, or None if the form is unknown.

The result is the base64 signature, the text that follows the canonical
fields in the signed message, and the hash algorithm.
"""
if set(params) == {*_FIELDS, "signature"}:
return params["signature"][0], "", hashes.SHA256()
if set(params) != set(_FIELDS) or route_header(query_params, "v") != "v2":
return None
nonce, timestamp, signature = (route_header(query_params, name) for name in ("n", "t", "s"))
if not (nonce and timestamp and signature):
return None
return signature, f":{nonce}:{timestamp}", hashes.SHA384()


def _verified_report(
ctx: ServerContext, params: dict[str, list[str]], did: str
ctx: ServerContext, query_params: dict[str, list[str]], params: dict[str, list[str]], did: str
) -> tuple[dict[str, str] | None, str]:
# Duplicates and extra fields would make reconstructing the signed message
# ambiguous. Unsupported forms retain the acknowledgement but cannot write.
if set(params) != {*_FIELDS, "signature"} or any(len(v) != 1 for v in params.values()):
contract = _signature_contract(query_params, params)
if contract is None or any(len(v) != 1 for v in params.values()):
return None, "malformed_fields"
signature_b64, suffix, algorithm = contract
fields = {name: params[name][0] for name in _FIELDS}
if fields["did"] != did:
return None, "did_mismatch"
Expand All @@ -50,23 +73,23 @@ def _verified_report(
return None, "missing_key"
canonical = "&".join(f"{name}={fields[name]}" for name in _FIELDS)
try:
signature = base64.b64decode(params["signature"][0], validate=True)
key.verify(signature, canonical.encode("ascii"), padding.PKCS1v15(), hashes.SHA256())
signature = base64.b64decode(signature_b64, validate=True)
key.verify(signature, (canonical + suffix).encode("ascii"), padding.PKCS1v15(), algorithm)
except (InvalidSignature, ValueError, TypeError):
return None, "invalid_signature"
return fields, "verified"


def build(
ctx: ServerContext,
_query_params: dict[str, list[str]],
query_params: dict[str, list[str]],
body_params: dict[str, list[str]],
clean_path: str,
) -> dict[str, Any]:
path_match = _PATH.fullmatch(clean_path)
assert path_match is not None # Route matcher already checked the path.
did = path_match.group(1)
report, outcome = _verified_report(ctx, body_params, did)
report, outcome = _verified_report(ctx, query_params, body_params, did)
updated_count = 0
if report is not None:
identities = {did}
Expand Down Expand Up @@ -106,7 +129,9 @@ def build(
outcome = "stored"
else:
outcome, updated_count = "write_failed", 0
_LOGGER.info("Device info did=%s outcome=%s updated=%d", did, outcome, updated_count)
# A module logger has no handler, so INFO would be dropped. The context
# loggers write to the server log files and stdout.
ctx.loggers.get("api", _LOGGER).info("Device info did=%s outcome=%s updated=%d", did, outcome, updated_count)
# No response data is consumed by the verified firmware. Continue accepting
# unsupported/unverifiable reports without allowing them to alter inventory.
return _build_catchall(ctx, _query_params, body_params, clean_path)
return _build_catchall(ctx, query_params, body_params, clean_path)
30 changes: 29 additions & 1 deletion src/roborock_local_server/bundled_backend/shared/http_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from typing import Any
from typing import Any, Mapping


def classify_host(host: str) -> str:
Expand Down Expand Up @@ -34,6 +34,34 @@ def pick_first(values: list[str]) -> str:
return ""


# Route builders receive no request headers. These headers reach them as
# "__header_<name>" query pseudo-params, like "__host". The a307 sends these
# four names with its device info upload. The key capture in server.py also
# tries aliases like "sign", "nonce" and "ts", but no device info upload is
# known to use them.
_ROUTE_HEADERS = ("v", "n", "t", "s")
_ROUTE_HEADER_PREFIX = "__header_"


def with_route_headers(query_params: dict[str, list[str]], headers: Mapping[str, str]) -> dict[str, list[str]]:
"""Return query_params with the route headers added as pseudo-params.

A query cannot supply them: pseudo-params from the query are dropped.
"""
params = {key: values for key, values in query_params.items() if not key.startswith(_ROUTE_HEADER_PREFIX)}
for name in _ROUTE_HEADERS:
value = str(headers.get(name) or "").strip()
if value:
params[f"{_ROUTE_HEADER_PREFIX}{name}"] = [value]
return params


def route_header(query_params: dict[str, list[str]], name: str) -> str:
"""Return a header that with_route_headers added, or "" if it was absent."""
values = query_params.get(f"{_ROUTE_HEADER_PREFIX}{name}") or [""]
return values[0]


def wrap_response(data: Any) -> dict[str, Any]:
return {
"success": True,
Expand Down
3 changes: 2 additions & 1 deletion src/roborock_local_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
start_broker,
strip_roborock_prefix,
)
from shared.http_helpers import with_route_headers
from shared.inventory_io import atomic_write_inventory, inventory_transaction
from shared.protocol_auth import ProtocolAuthStore
from shared.schedule_runner import ScheduleRunner
Expand Down Expand Up @@ -1364,7 +1365,7 @@ async def _handle_roborock_request(self, request: Request) -> Response:
rules=self.endpoint_rules,
context=self.context,
clean_path=clean_path,
query_params=query_params,
query_params=with_route_headers(query_params, request_headers),
body_params=body_params,
method=request.method,
)
Expand Down
Loading