From 15a063ef1a5f0718f51bd014674a5ee2c5f6f240 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 06:00:10 +0000 Subject: [PATCH] feat(transport): carry the secure channel over any MQTT broker as a relay Per-client topics in both directions, device and app client IDs, relay state throttling and timeouts in [mqtt] of transport.toml, the client key ID in the test vectors, docs/mqtt-relay.md, and deprecate the plaintext topics and SystemState.mqtt_client_id. Closes #48 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiWoJmJsqnYdysAR9wp --- README.md | 2 + docs/lan.md | 2 +- docs/mqtt-relay.md | 73 ++++++++++++++++++++++++++++++++ docs/secure-channel-vectors.json | 1 + docs/secure-channel.md | 5 ++- opencar/core/v1/core.proto | 15 ++++--- opencar/core/v1/system.proto | 19 +++++---- opencar/core/v1/transport.toml | 48 ++++++++++++++++++++- tools/secure_channel_vectors.py | 1 + 9 files changed, 146 insertions(+), 20 deletions(-) create mode 100644 docs/mqtt-relay.md diff --git a/README.md b/README.md index 467a571..1577f0c 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@ This project uses an **Envelope Pattern** to route messages. 5. **[`docs/lan.md`](docs/lan.md) (LAN Direct):** How the app reaches the device on the local network with no server: the TCP connection that carries the secure channel, and discovery by mDNS and a UDP probe (`[lan]` in `transport.toml`). +6. **[`docs/mqtt-relay.md`](docs/mqtt-relay.md) (MQTT Relay):** How the app reaches the device from anywhere through any MQTT broker, used as an untrusted relay for the secure channel: the per-client topics, client IDs, what the relay carries and how often (`[mqtt]` in `transport.toml`), and optional broker hardening. + This allows the core firmware to route messages without needing to understand the contents of the payload, keeping the codebase modular. The `platform_id` allows the final destination (like the mobile app) to know which schema to use for decoding. ## 🛠️ How to Use This Repository diff --git a/docs/lan.md b/docs/lan.md index ddf8a54..75b1a71 100644 --- a/docs/lan.md +++ b/docs/lan.md @@ -76,5 +76,5 @@ reply: 4f434452 01 9b4174fd65e9e12b71a9 127e ## Limits -- The device has one network uplink per build: a build whose uplink is LTE has no LAN. +- The LAN needs WiFi. A device with both WiFi and LTE listens on its WiFi network only, while it is joined to it; a device with LTE alone has no LAN. - Routers with client isolation (common on guest networks) block both discovery and the connection. The app then can't reach the device over the LAN, and falls back to the relay if there is one. diff --git a/docs/mqtt-relay.md b/docs/mqtt-relay.md new file mode 100644 index 0000000..ea3cecf --- /dev/null +++ b/docs/mqtt-relay.md @@ -0,0 +1,73 @@ +# MQTT relay + +The MQTT relay lets the app reach the device from anywhere (LTE, another network) through any MQTT broker the user runs: a Mosquitto container, Home Assistant's Mosquitto add-on, a hosted broker. The broker only moves [secure channel](secure-channel.md) frames between the app and the device. It is **not trusted**: it sees ciphertext, and can't read the state or forge a command. The constants below are in [`transport.toml`](../opencar/core/v1/transport.toml), `[mqtt]`. + +There is no plaintext path: the device accepts nothing from MQTT but secure channel frames, and sends nothing else there. The plaintext topics (`command_topic_template`, `data_topic_template`) and `SystemState.mqtt_client_id` are deprecated. An older app build loses remote access (Bluetooth still works). + +## Topics + +Each MQTT message carries exactly one frame, with no length prefix. Frames are published with QoS 1 (`qos`) and never retained (`retain`). QoS 1 can deliver a frame twice; the channel's replay window drops the copy. + +| Topic | Template | Publisher | Subscriber | +| --- | --- | --- | --- | +| Client → device | `opencar/{device_key_id}/d/{client_key_id}` | the client | the device, with `opencar/{device_key_id}/d/+` | +| Device → client | `opencar/{device_key_id}/c/{client_key_id}` | the device | that client | +| Retained state | `opencar/{device_key_id}/state` | reserved for the sealed retained state (a later phase) | | + +- `{device_key_id}` is the device key ID ([secure-channel.md](secure-channel.md), "Keys and enrollment"). `{client_key_id}` is the client's key ID, derived from the client's static public key the same way: the lowercase hex of the first 10 bytes (`[secure_channel] key_id_bytes`) of its BLAKE2s-256 hash. +- **One topic per client, in both directions.** The device answers on the client topic with the `{client_key_id}` the frame arrived on: the handshake response, transport frames, and the unknown session frame (which it could not route otherwise, since it doesn't know that session's client). Other clients' traffic stays off a phone's mobile data, and a broker ACL can keep each client to its own two topics. +- **Handshake check:** the device drops a handshake init whose client static key doesn't have the key ID of the topic it arrived on, as it drops one for an unknown key. The topic is only routing: the handshake authenticates the client. +- **Sessions** belong to the device's connection to the broker (the transport connection in "Sessions" of [secure-channel.md](secure-channel.md)): when the device reconnects to the broker, its relay sessions end, and the next transport frame from each client gets an unknown session frame, after which the client handshakes again. The app keeps its session across its own broker reconnects: the device still has it. +- **A device with WiFi and LTE** connects to the broker over WiFi while it is joined to its network, and over LTE otherwise. Moving between them is a broker reconnect: the relay sessions end and the clients handshake again. + +## Client IDs + +- The device connects with its device key ID as the MQTT client ID (`device_client_id_template`). +- The app connects with its client key ID, a dash and 4 random bytes in lowercase hex (`app_client_id_template`, `app_client_id_random_bytes`), new for each connection, so two instances of the app (or a reconnect racing the old connection) don't take over each other's broker session. That is 29 characters: MQTT 5 brokers only have to accept 23, but Mosquitto, EMQX, HiveMQ and the Home Assistant add-on accept longer ones. + +## What travels over the relay + +The relay is the **remote tier**, like the LAN ([lan.md](lan.md), "What travels over the LAN"): + +- **Commands:** a validated phone may send basic vehicle commands, with the same checks as over BLE. Advanced vehicle commands are refused (`COMMAND_STATUS_CODE_REJECTED_UNAVAILABLE`, and reported unavailable in the session's command availability). System commands stay BLE-only and are dropped. +- **State:** the basic state only, throttled for mobile data. While the app is in the foreground it sends a heartbeat (`AppToDevice.heartbeat`) through its session every 15 s (`heartbeat_seconds`). A session that had an inbound frame within 35 s (`activity_window_seconds`) is **active**: it gets each basic state update, at most one per 1000 ms (`min_state_interval_ms`, the newest one wins). Otherwise it is **idle** and gets the newest basic state every 30 s (`idle_state_interval_seconds`). When a session starts it gets the system state and the latest basic state at once. +- **System state:** the session's command availability and the device's LAN address, when the session starts, whenever either changes, and at least every 30000 ms (`system_state_repeat_ms`) while unchanged. The app treats its session as lost when nothing arrived for 90000 ms (`receive_timeout_ms`, three repeats) and handshakes again. +- Nothing is sent to a client without a session: with no session open, the device publishes nothing on the relay. + +## The broker + +The broker is a relay, not the security model: the secure channel authenticates both ends and encrypts everything. Broker authentication and TLS are **optional hardening**, against people using your broker for their own traffic and against metadata leaks. Any of these works: + +| Connection | Authentication | +| --- | --- | +| `mqtt://` (TCP, port 1883) | none, or username and password | +| `mqtts://` (TLS, port 8883) | none, username and password, or a client certificate (mTLS) | + +With `mqtt://` a username and password travel in clear text: whoever can see the traffic can use the broker with them, but still can't read or send anything to the car. + +**What the broker (and anyone who can watch plain `mqtt://` traffic) can still see:** which device key IDs and client key IDs talk to each other, when, how often and how much (frame sizes). Not what the frames say. TLS hides this from the network, not from the broker. + +### Mosquitto ACL + +A broker shared with others should keep each client to its own topics. A suggested Mosquitto `acl_file`, with one broker user per device and per phone (the app shows its client key ID and the device key ID in its relay settings; the IDs below are those of the test vectors): + +``` +# The device: username = its device key ID +user 1e1c177be4a37ca2c0ea +topic read opencar/1e1c177be4a37ca2c0ea/d/+ +topic write opencar/1e1c177be4a37ca2c0ea/c/+ +topic write opencar/1e1c177be4a37ca2c0ea/state + +# A phone, with client key ID 6c9a288323521dc27247 +user alice-phone +topic write opencar/1e1c177be4a37ca2c0ea/d/6c9a288323521dc27247 +topic read opencar/1e1c177be4a37ca2c0ea/c/6c9a288323521dc27247 +topic read opencar/1e1c177be4a37ca2c0ea/state +``` + +Without an ACL, another user of the broker can't read or forge anything either, but can flood the device's topics. The device bounds the work that costs it ([secure-channel.md](secure-channel.md), "Handshake rate"). + +## Limits + +- The device must be online to answer. A device that is off, asleep or out of coverage looks the same to the app: its handshake times out (`[secure_channel] handshake_timeout_ms`). A last-known state for that case is a later phase (`state_topic_template`). +- Frames on the relay are at most a transport frame carrying `max_plaintext_bytes`, about 4 KB: within every broker's default message size limit. diff --git a/docs/secure-channel-vectors.json b/docs/secure-channel-vectors.json index 87f33d8..7aa7377 100644 --- a/docs/secure-channel-vectors.json +++ b/docs/secure-channel-vectors.json @@ -7,6 +7,7 @@ "device_ephemeral_private": "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f", "client_static_private": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", "client_static_public": "358072d6365880d1aeea329adf9121383851ed21a28e3b75e965d0d2cd166254", + "client_key_id": "6c9a288323521dc27247", "client_ephemeral_private": "404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f", "prologue": "6f70656e6361722f7365637572652f31003165316331373762653461333763613263306561", "session_id": "a1b2c3d4", diff --git a/docs/secure-channel.md b/docs/secure-channel.md index fe57146..d87b9c5 100644 --- a/docs/secure-channel.md +++ b/docs/secure-channel.md @@ -11,6 +11,7 @@ Keys are only exchanged over a bonded BLE link, which is the channel's trust anc - **Device identity:** the device creates an X25519 static key pair at first boot and keeps it until its flash is erased (bond resets and `ClearPairedPhonesCommand` keep it: it belongs to the device, not to its owner). It reports the public key and its **device key ID** over BLE only, in `SystemState.device_identity` and in the answer to `EnrollClientKeyCommand`. The app pins the key per paired vehicle. A paired vehicle reporting another key was erased or replaced: the app asks the user instead of replacing the pinned key silently. - **Device key ID:** the lowercase hex of the first 10 bytes of the BLAKE2s-256 hash of the device's public key (20 characters). It names the device on transports (MQTT topics, mDNS) without revealing anything secret, and is part of the prologue. - **Client keys:** each client has its own X25519 static key pair. A validated phone enrolls its public key with `EnrollClientKeyCommand` (`CLIENT_KIND_PHONE`, BLE only). The device keeps one key per phone, stored with the phone's `ble:` device ID, and drops it with the phone's bond. `CLIENT_KIND_HUB` is reserved: a hub will be enrolled by a validated phone on its behalf, and the device refuses it until that is specified. The registry must not assume every client is a phone with a BLE bond. +- **Client key ID:** derived from a client's public key like the device key ID (the lowercase hex of the first 10 bytes of its BLAKE2s-256 hash). It names the client's topics on the MQTT relay ([mqtt-relay.md](mqtt-relay.md)). ## Protocol @@ -71,11 +72,11 @@ The device keeps its sessions in RAM only, keyed by the session ID and the trans - After the handshake, the device maps the client's static key to its registry entry. It stamps that client's ID (for a phone, its `ble:` device ID) as `source_device_id` on every `AppToDevice` the session carries, ignoring what the client put there. De-duplication of commands by source and `message_id` therefore works across transports: a command resent over BLE after the channel (or the other way round) is still caught. - Permissions follow the authenticated client, not the transport. A phone's commands get the same checks as over BLE: validated for the identified car, the CAN read-write policy, the dev lock. Through the channel a validated phone may send **basic** vehicle commands only: every transport that carries the channel (the LAN, the relay) is the remote tier, because reaching the device over a network is no proof of being at the car. Advanced vehicle commands need Bluetooth, like system commands, and through the channel they are refused with `COMMAND_STATUS_CODE_REJECTED_UNAVAILABLE` and reported unavailable in the session's command availability. A phone that lost its validation keeps its key but its vehicle commands are refused with `COMMAND_STATUS_CODE_REJECTED_NOT_VALIDATED`, as over BLE. - **System commands stay BLE-only** (pairing, bonds, the approval, the dev lock, validation, restart, key enrollment): they need physical presence. Through the channel they are dropped. -- A session receives the basic state only (no `advanced_state_bytes`), like MQTT. The LAN sends it as it changes; the relay throttles it. +- A session receives the basic state only (no `advanced_state_bytes`). The LAN sends it as it changes; the relay throttles it ([mqtt-relay.md](mqtt-relay.md)). ## Test vectors -[`secure-channel-vectors.json`](secure-channel-vectors.json) holds fixed static and ephemeral keys, the device key ID, the prologue, the two handshake frames and the handshake hash, transport frames in each direction (including an out-of-order counter and an empty keepalive), and an unknown session frame. An implementation passes when, with the fixed ephemeral keys injected, it produces the same frames byte for byte and decrypts the other side's. +[`secure-channel-vectors.json`](secure-channel-vectors.json) holds fixed static and ephemeral keys, the device and client key IDs, the prologue, the two handshake frames and the handshake hash, transport frames in each direction (including an out-of-order counter and an empty keepalive), and an unknown session frame. An implementation passes when, with the fixed ephemeral keys injected, it produces the same frames byte for byte and decrypts the other side's. Regenerate them with: diff --git a/opencar/core/v1/core.proto b/opencar/core/v1/core.proto index eeb60a5..1c3cf48 100644 --- a/opencar/core/v1/core.proto +++ b/opencar/core/v1/core.proto @@ -14,7 +14,8 @@ message AppToDevice { uint32 platform_id = 2; // Stable BLE-device identifier for controller arbitration and lifecycle - // operations. Required for BLE commands; ignored for MQTT. + // operations. Required for BLE commands. Through the secure channel the + // device replaces it with the authenticated client's ID. bytes source_device_id = 6; // The AppToDevice payload, mostly a type of command. @@ -30,9 +31,10 @@ message AppToDevice { // can only be sent from BLE. bytes advanced_command_bytes = 5; - // A heartbeat with no payload. Sent periodically over MQTT to signal that - // a client is active, allowing the vehicle to throttle state updates when - // no clients are connected. + // A heartbeat with no payload. Sent periodically through a secure channel + // session on the MQTT relay while the app is in the foreground, so the + // device sends that session state at the full rate ([mqtt] + // heartbeat_seconds in transport.toml); it throttles idle sessions. bool heartbeat = 7; } } @@ -74,8 +76,9 @@ message DeviceToApp { // This holds the state update data of the device, containing both the system // state and the vehicle specific state. message StateUpdate { - // System state, only transmitted over BLE, except the command availability, - // which MQTT clients get too (see SystemState.command_availability). + // System state, only transmitted over BLE, except the command availability + // and the LAN address, which secure channel clients get too (see + // SystemState). SystemState system_state = 1; // Vehicle specific state. diff --git a/opencar/core/v1/system.proto b/opencar/core/v1/system.proto index 506f9f5..9afe56d 100644 --- a/opencar/core/v1/system.proto +++ b/opencar/core/v1/system.proto @@ -22,10 +22,10 @@ message SystemState { optional CanAccessState can_access = 5; // Which of the vehicle's commands the device accepts right now. Sent over BLE - // and over MQTT (MQTT clients only get the basic commands). Sent whenever it - // changes, repeated while unchanged, and when the app subscribes. The app - // must only trust one received on the current connection: never a cached or - // older one. + // and through the secure channel (which only gets the basic commands). Sent + // whenever it changes, repeated while unchanged, and when the app + // subscribes or a session starts. The app must only trust one received on + // the current connection: never a cached or older one. optional CommandAvailability command_availability = 6; // How far the device trusts the connected phone, and its validation session. @@ -34,10 +34,11 @@ message SystemState { // the app subscribes. optional PhoneAccessState phone_access = 7; - // The device's MQTT client ID: the {client_id} of the topic templates in - // transport.toml, so the topics this device's MQTT clients must use. BLE only. - // Sent with can_access. Unset when the device has no MQTT. - optional string mqtt_client_id = 8; + // Deprecated: the device's MQTT client ID, which named the plaintext MQTT + // topics. The MQTT relay names a device by its device key ID + // (DeviceIdentity.key_id) instead (docs/mqtt-relay.md), and the device no + // longer sends this. + optional string mqtt_client_id = 8 [deprecated = true]; // The health of each CAN bus the device listens on, by bus id (the 0-based // index of the bus in the device's hardware config). BLE only. Sent in a @@ -306,7 +307,7 @@ message CommandAvailability { map basic = 1; // Availability of the advanced commands by field number. BLE only: never - // sent over MQTT. + // sent through the secure channel (LAN, MQTT relay). map advanced = 2; } diff --git a/opencar/core/v1/transport.toml b/opencar/core/v1/transport.toml index 439faa0..96433c8 100644 --- a/opencar/core/v1/transport.toml +++ b/opencar/core/v1/transport.toml @@ -1,6 +1,50 @@ [mqtt] -# {client_id} is the device's MQTT client ID (SystemState.mqtt_client_id), also -# in the topics an app uses: never the app's own client ID. +# The MQTT relay: any MQTT broker carries secure channel frames ([secure_channel]) +# between the app and the device, one frame per MQTT message. The broker is an +# untrusted pipe: it only sees ciphertext. See docs/mqtt-relay.md. +# +# Placeholders: {device_key_id} is the device key ID and {client_key_id} the +# client's key ID, both [secure_channel] key IDs (lowercase hex of the first +# key_id_bytes bytes of the BLAKE2s-256 hash of the public key). +# +# Client -> device frames. Each client publishes to its own topic; the device +# subscribes to device_topic_filter. The device answers on the client topic +# named by the {client_key_id} a frame arrived on, and drops a handshake init +# whose client key doesn't have that key ID. +device_topic_template = "opencar/{device_key_id}/d/{client_key_id}" +device_topic_filter = "opencar/{device_key_id}/d/+" +# Device -> client frames, one topic per client. +client_topic_template = "opencar/{device_key_id}/c/{client_key_id}" +# Reserved for the sealed retained state (a later phase). +state_topic_template = "opencar/{device_key_id}/state" +# QoS of every frame on the device and client topics. Never retained. +qos = 1 +retain = false +# MQTT client IDs. The device uses its key ID. The app uses its client key ID, +# a dash and app_client_id_random_bytes random bytes in lowercase hex, new for +# each connection, so two instances of the app don't take over each other's +# broker session. +device_client_id_template = "{device_key_id}" +app_client_id_template = "{client_key_id}-{random}" +app_client_id_random_bytes = 4 +# While the app is in the foreground it sends a heartbeat (AppToDevice.heartbeat) +# through its session this often. A session with an inbound frame within +# activity_window_seconds is active: it gets each basic state update, at most +# one per min_state_interval_ms. Otherwise it gets the newest one every +# idle_state_interval_seconds. +heartbeat_seconds = 15 +activity_window_seconds = 35 +min_state_interval_ms = 1000 +idle_state_interval_seconds = 30 +# The device sends each session a system state at least this often (ms), even +# when nothing changed. Longer than on the LAN to save mobile data. +system_state_repeat_ms = 30000 +# The app treats its session as lost when it has received no frame for this +# long (ms, three system state repeats) and handshakes again. +receive_timeout_ms = 90000 +# Deprecated: the plaintext topics, before the relay. {client_id} was the +# device's MQTT client ID (SystemState.mqtt_client_id). Not used any more: the +# device accepts nothing but secure channel frames from MQTT. command_topic_template = "opencar/{client_id}/cmd" data_topic_template = "opencar/{client_id}/data" diff --git a/tools/secure_channel_vectors.py b/tools/secure_channel_vectors.py index 6b7813b..f33fb8c 100644 --- a/tools/secure_channel_vectors.py +++ b/tools/secure_channel_vectors.py @@ -136,6 +136,7 @@ def main() -> None: "device_ephemeral_private": DEVICE_EPHEMERAL.hex(), "client_static_private": CLIENT_STATIC.hex(), "client_static_public": client_public.hex(), + "client_key_id": key_id(client_public), "client_ephemeral_private": CLIENT_EPHEMERAL.hex(), "prologue": pro.hex(), "session_id": SESSION_ID.hex(),