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
14 changes: 14 additions & 0 deletions docs/machine.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,20 @@ Re-registering rotates the secret and resets the counter, so a listener that
restarts just registers again. See
[`warpedpinball.origin`](api-reference.md) for the frame layout.

Listening to several boards at once means choosing a secret before you can
check the signature. `peek()` reads the unverified body so you can route on
the `machine_id` it claims:

```python
claimed = origin.peek(datagram).get("machine_id")
event = origin.unpack(secrets[claimed], datagram) # this is the trust step
```

Identify boards this way rather than by the datagram's source address: NAT
between a board and the listener rewrites the address, and the signature is
what actually establishes who sent it. Treat everything `peek()` returns as
attacker-controlled until `unpack()` has returned.

## The raw escape hatch

Every firmware route is reachable even without a wrapper:
Expand Down
29 changes: 29 additions & 0 deletions tests/test_origin.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,32 @@ def test_non_json_and_non_object_bodies_are_rejected():
packet = origin._mac(secret, body).encode() + body
with pytest.raises(origin.OriginAuthError):
origin.unpack(secret, packet)


def test_peek_reads_the_body_without_a_secret():
body = {"machine_id": "a1b2c3d4", "type": "game_state", "n": 3}
packet = origin.pack(origin.new_secret(), body)

# Routing to a secret has to happen before the secret is known.
assert origin.peek(packet) == body


def test_peek_does_not_authenticate():
# A forged datagram peeks fine -- that is the point of the warning in the
# docstring. unpack() is the step that establishes trust.
forged = origin.pack("not-the-real-secret", {"machine_id": "a1b2c3d4", "n": 1})

assert origin.peek(forged)["machine_id"] == "a1b2c3d4"
with pytest.raises(origin.OriginAuthError):
origin.unpack("the-real-secret", forged)


@pytest.mark.parametrize("packet", [b"", b"short", b"0" * origin.MAC_LEN])
def test_peek_rejects_malformed_frames(packet):
with pytest.raises(origin.OriginAuthError):
origin.peek(packet)


def test_peek_rejects_a_body_that_is_not_a_json_object():
with pytest.raises(origin.OriginAuthError):
origin.peek(b"0" * origin.MAC_LEN + b"[1, 2]")
2 changes: 1 addition & 1 deletion warpedpinball/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
from .origin import OriginAuthError
from .transports.http import HttpTransport

__version__ = "0.3.1"
__version__ = "0.4.0"

__all__ = [
"connect",
Expand Down
41 changes: 35 additions & 6 deletions warpedpinball/origin.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,18 +73,47 @@ def pack(secret: str, body: Dict[str, Any]) -> bytes:
return _mac(secret, encoded).encode("ascii") + encoded


def unpack(secret: str, packet: bytes) -> Dict[str, Any]:
"""Verify and decode a datagram; raises :class:`OriginAuthError` if it
was not signed with ``secret`` or is not a well-formed frame."""
def _split(packet: bytes) -> tuple[bytes, bytes]:
"""Signature and body halves of a frame, or raise on a malformed one."""
if len(packet) <= MAC_LEN:
raise OriginAuthError("Origin datagram too short to carry a signature")
received, body = packet[:MAC_LEN], packet[MAC_LEN:]
if not hmac.compare_digest(received.decode("ascii", "replace"), _mac(secret, body)):
raise OriginAuthError("Origin datagram signature does not match")
return packet[:MAC_LEN], packet[MAC_LEN:]


def _decode(body: bytes) -> Dict[str, Any]:
try:
decoded = json.loads(body)
except ValueError as exc:
raise OriginAuthError(f"Origin datagram body is not valid JSON: {exc}") from None
if not isinstance(decoded, dict):
raise OriginAuthError("Origin datagram body is not a JSON object")
return decoded


def peek(packet: bytes) -> Dict[str, Any]:
"""Decode a datagram's body **without verifying its signature**.

A listener holding secrets for many boards has a chicken-and-egg problem:
it must know which board is claiming to have sent a datagram before it can
choose the secret to check it against. This answers that question, and
nothing else -- everything it returns is unverified and, on an open
network, attacker-controlled.

Use it only to route::

machine_id = origin.peek(packet).get("machine_id")
body = origin.unpack(secrets[machine_id], packet) # now it's trusted

Nothing from :func:`peek` should reach storage, a decision, or a log line
that implies it is true.
"""
return _decode(_split(packet)[1])


def unpack(secret: str, packet: bytes) -> Dict[str, Any]:
"""Verify and decode a datagram; raises :class:`OriginAuthError` if it
was not signed with ``secret`` or is not a well-formed frame."""
received, body = _split(packet)
if not hmac.compare_digest(received.decode("ascii", "replace"), _mac(secret, body)):
raise OriginAuthError("Origin datagram signature does not match")
return _decode(body)