diff --git a/README.md b/README.md index f68a7da..467a571 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,8 @@ This project uses an **Envelope Pattern** to route messages. 4. **[`docs/secure-channel.md`](docs/secure-channel.md) (Secure Channel):** The end-to-end encrypted channel (Noise `IK`) that carries the same messages over the LAN and an MQTT relay, the device identity and client keys it uses (exchanged over BLE with `EnrollClientKeyCommand`), and its [test vectors](docs/secure-channel-vectors.json). +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`). + 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 new file mode 100644 index 0000000..ddf8a54 --- /dev/null +++ b/docs/lan.md @@ -0,0 +1,80 @@ +# LAN direct + +LAN direct lets the app talk to the device on the local network (home WiFi) with no server in between. The app connects to the device over TCP and runs the [secure channel](secure-channel.md) on that connection, so the network only sees ciphertext. The constants below are in [`transport.toml`](../opencar/core/v1/transport.toml), `[lan]`. + +## Connection + +- The device listens on TCP port 4734 (`tcp_port`) while it has an address on the network. +- Every frame on the connection is a secure channel frame prefixed with its length, a 2-byte big-endian integer (`[secure_channel] stream_length_prefix_bytes`). A length of 0 or longer than the largest frame (a transport frame carrying `max_plaintext_bytes`) closes the connection. +- The device accepts 2 connections at once (`max_clients`). When a new connection arrives and all are taken, it closes a connection that has no session yet if there is one, otherwise it refuses the new connection. It closes a connection that hasn't completed a handshake within `handshake_timeout_ms`, and one whose sessions have all ended (idle, expired or revoked). +- The app gives up on a TCP connection after 3000 ms (`connect_timeout_ms`) and tries the next address. +- A session belongs to the connection it was made on (see "Sessions" in [secure-channel.md](secure-channel.md)): closing the connection ends it. +- The app sends a keepalive (an empty transport frame) when it has sent nothing on its session for 60 s (`keepalive_seconds`), well within the session's idle timeout. +- The device sends each session a system state at least every 5000 ms (`system_state_repeat_ms`), even when nothing changed. The app treats a connection that has received no frame for 15000 ms (`receive_timeout_ms`, three repeats) as dropped: it closes it and looks for the device again. A device that restarted, or left the network, is noticed within that time instead of at the next keepalive. + +## What travels over the LAN + +The LAN is the **remote tier**, like MQTT and the relay: being on the same network as the car is no proof of being at the car, so only Bluetooth gets the proximity (advanced) tier. + +- **State:** the basic state only (no `advanced_state_bytes`), not throttled: when a session starts the device sends the system state and the latest basic state, then each basic state update as it comes. +- **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), and system commands stay BLE-only and are dropped (see "Identity and authorization" in [secure-channel.md](secure-channel.md)). +- **`SystemState.lan_address`:** the device's `ip:port`, sent over BLE and through the secure channel (on every transport) when the app subscribes or a session starts, and whenever it changes. The app saves it per vehicle as the last known address. + +## Discovery + +The app needs the device's address. When the user entered one for the vehicle (for a network where discovery is blocked), the app connects to that address only: no discovery, and no fallback to the others, so a wrong address stays wrong rather than being hidden. Otherwise it tries these in order (`discovery_order`) and stops at the first address where the secure channel handshake with the paired vehicle's pinned device key succeeds: + +1. **mDNS** (DNS-SD), for 3000 ms (`[lan.mdns] browse_timeout_ms`). +2. **UDP probe**, for networks that filter multicast. +3. **The last known address** (`SystemState.lan_address` or the last successful discovery). + +An address from any of these is only a hint. A wrong host, or someone answering for the device, fails the handshake because the device key is pinned. The app doesn't look for the device while the phone isn't on WiFi. + +### mDNS + +The device announces the service `_opencar._tcp` on `tcp_port`, with its BLE name as the instance name and two TXT keys: + +| Key | Value | +| --- | --- | +| `id` | The device key ID (20 lowercase hex characters) | +| `v` | `protocol_version` in decimal (`1`) | + +The app matches on `id`, never on the instance name, and skips a `v` it doesn't know. Nothing else is announced, so the network doesn't learn which car the device is in. The device announces again when its address changes. + +### UDP probe + +The app broadcasts a probe to UDP port 4735 (`[lan.udp_discovery] port`), to the limited broadcast address (`255.255.255.255`) and to the subnet's broadcast address. A device answers the sender (its source address and port) with a reply. Both are raw bytes, not protobuf, so the device answers without decoding. + +**Probe**, 15 bytes (`probe_bytes`): + +| Bytes | Field | +| --- | --- | +| 0–3 | `OCDQ` in ASCII (`probe_magic`) | +| 4 | `protocol_version` (`1`) | +| 5–14 | The wanted device key ID as its 10 raw bytes (`[secure_channel] key_id_bytes`), or all zero for any device | + +**Reply**, 17 bytes (`reply_bytes`): + +| Bytes | Field | +| --- | --- | +| 0–3 | `OCDR` in ASCII (`reply_magic`) | +| 4 | `protocol_version` (`1`) | +| 5–14 | The device's key ID as its 10 raw bytes | +| 15–16 | `tcp_port`, big-endian | + +- The device ignores a probe of any other length, magic or version, and one that asks for another device's key ID. +- It sends at most 4 replies per second (`max_replies_per_second`), all senders together, and ignores the probes beyond that. The probe is nearly as long as the reply, so the responder can't amplify traffic. +- The app sends 3 probes 500 ms apart (`probe_count`, `probe_interval_ms`), and waits 1000 ms after the last one (`reply_timeout_ms`). It connects to the address the reply came from, on the reply's port, and ignores replies for other key IDs. + +Test vector, for the device key ID `9b4174fd65e9e12b71a9` and `tcp_port` 4734: + +``` +probe (that device): 4f434451 01 9b4174fd65e9e12b71a9 +probe (any device): 4f434451 01 00000000000000000000 +reply: 4f434452 01 9b4174fd65e9e12b71a9 127e +``` + +## Limits + +- The device has one network uplink per build: a build whose uplink is LTE 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/secure-channel.md b/docs/secure-channel.md index 96c68a9..fe57146 100644 --- a/docs/secure-channel.md +++ b/docs/secure-channel.md @@ -50,7 +50,7 @@ Every message is one frame, the same bytes on every transport: - **Session ID:** 4 random bytes the client picks for each handshake. The device echoes it in its response and uses it on every frame of the session. It only routes frames; it is not secret and not authenticated by itself. - **Counter:** the Noise nonce of the transport message, explicit because message transports (MQTT QoS 1) can duplicate and, rarely, reorder frames. Each direction counts from 0 and increments by one per frame. The receiver keeps a sliding window of 64 (`replay_window`, as in WireGuard): it accepts a counter ahead of the highest it has seen, or behind it within the window and not seen before, and drops anything else. It only updates the window once the frame decrypts. - **Plaintext:** one encoded `AppToDevice` (client → device) or `DeviceToApp` (device → client), at most 4096 bytes (`max_plaintext_bytes`, the same limit as BLE so a message fits every transport). An empty plaintext is a keepalive: it keeps the session from idling and carries no message. -- **Stream transports** (TCP on the LAN) prefix each frame with its length as a 2-byte big-endian integer. Message transports (MQTT) carry one frame per message. +- **Stream transports** (TCP on the LAN, see [lan.md](lan.md)) prefix each frame with its length as a 2-byte big-endian integer. Message transports (MQTT) carry one frame per message. - A frame that is too short, has an unknown type, or fails to decrypt is dropped without an answer. ## Sessions @@ -59,6 +59,7 @@ The device keeps its sessions in RAM only, keyed by the session ID and the trans - **Handshake:** a valid handshake init from an enrolled client creates a session on the connection it arrived on, and the device answers with the handshake response. A session ID already in use on that connection is replaced. The client sends no transport frame before it has the response. - **Unknown client key:** the device drops the handshake without answering, so it doesn't reveal which keys are enrolled. The same goes for a handshake that fails (another device's key, a wrong prologue). The client gives up after `handshake_timeout_ms` (10 s) and tells the user to connect over Bluetooth (its phone was removed, or the device was erased). +- **Handshake rate:** the device processes at most 8 handshake inits per second (`max_handshake_inits_per_second`), all transports together, and drops the rest unanswered, as for an unknown key. Each init costs X25519 work, and anyone who can reach a transport (the LAN, the relay's broker) can send them. A client whose init was dropped retries after its handshake timeout. - **Replayed handshakes:** the device refuses an init whose ephemeral key it has seen recently for that client. A replayed init can't produce a usable session anyway (the attacker lacks the client's ephemeral private key), but would take a slot. - **Limits:** at most 4 sessions (`max_sessions`) and 2 per client (`max_sessions_per_client`, a phone on the LAN and the relay at once). When a new session doesn't fit, it replaces the same client's session idle the longest if the client is at its limit, otherwise the device's session idle the longest. - **Expiry:** a session ends after 300 s without a valid transport frame in either direction (`idle_timeout_seconds`), 3600 s after its handshake (`max_session_seconds`), or after 1,000,000 transport frames in one direction (`max_session_messages`). The client handshakes again before the lifetime or count limit, with a new session ID, and keeps using the old session until the new one is up. There is no rekeying inside a session. @@ -68,9 +69,9 @@ The device keeps its sessions in RAM only, keyed by the session ID and the trans ## Identity and authorization - 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. A validated phone may send basic and advanced vehicle commands through the channel. 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. +- 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. -- What state a session receives depends on the transport: the LAN gets the full state like BLE, the relay the basic, throttled state. +- A session receives the basic state only (no `advanced_state_bytes`), like MQTT. The LAN sends it as it changes; the relay throttles it. ## Test vectors diff --git a/opencar/core/v1/system.proto b/opencar/core/v1/system.proto index 127bd42..506f9f5 100644 --- a/opencar/core/v1/system.proto +++ b/opencar/core/v1/system.proto @@ -53,6 +53,15 @@ message SystemState { // with can_access. Unset on a firmware without the secure channel, or while // the device has no random source to create its key. optional DeviceIdentity device_identity = 10; + + // The device's address on its local network, as "ip:port" (IPv4 for now), + // where it accepts LAN connections (docs/lan.md). Set while the device has a + // LAN listener and an address, unset otherwise. Sent over BLE and through the + // secure channel, when the app subscribes or a session starts and whenever it + // changes, so the app keeps its last known address fresh. Only a hint for + // finding the device: the handshake against the pinned device key is what + // authenticates it. + optional string lan_address = 11; } // This contains a single system command. diff --git a/opencar/core/v1/transport.toml b/opencar/core/v1/transport.toml index 629ec55..439faa0 100644 --- a/opencar/core/v1/transport.toml +++ b/opencar/core/v1/transport.toml @@ -4,6 +4,69 @@ command_topic_template = "opencar/{client_id}/cmd" data_topic_template = "opencar/{client_id}/data" +[lan] +# LAN direct: the app connects straight to the device on the local network +# over TCP and talks to it through the secure channel ([secure_channel]), with +# no server. See docs/lan.md. +# TCP port the device listens on. Frames use the stream framing of +# [secure_channel] (a 2-byte big-endian length before each frame). +tcp_port = 4734 +# LAN connections the device accepts at once. +max_clients = 2 +# Version of the LAN discovery formats and of the secure channel they lead to: +# the mDNS "v" TXT value and the version byte of the UDP probe and reply. +protocol_version = 1 +# How long (ms) the app waits for a TCP connection before trying the next +# address. +connect_timeout_ms = 3000 +# The app sends an empty transport frame (a keepalive) when it has sent nothing +# on its session for this long, so the session doesn't idle out. +keepalive_seconds = 60 +# The device sends each session a system state at least this often (ms), even +# when nothing changed. +system_state_repeat_ms = 5000 +# The app treats a connection that has received no frame for this long (ms) as +# dropped, closes it and looks for the device again: three system state repeats. +receive_timeout_ms = 15000 +# The order the app tries to find the device. It stops at the first address +# where the handshake with the pinned device key succeeds. An address the user +# entered replaces the whole list: the app tries it alone. +discovery_order = ["mdns", "udp_probe", "last_known_address"] + +[lan.mdns] +# DNS-SD service type the device announces. The instance name is the device's +# BLE name; the app matches on the "id" TXT value, never on the name. +service = "_opencar._tcp" +# TXT keys: "id" is the device key ID ([secure_channel] key_id_bytes, hex), +# "v" is protocol_version in decimal. Nothing else (no car platform). +txt_key_device_id = "id" +txt_key_version = "v" +# How long (ms) the app browses before moving on to the UDP probe. +browse_timeout_ms = 3000 + +[lan.udp_discovery] +# For networks that filter multicast. The app broadcasts a probe to this UDP +# port; a device answers the sender with a reply. Raw bytes, not protobuf, so +# the device answers without decoding: see docs/lan.md. +port = 4735 +# Probe: probe_magic (ASCII), protocol_version (1 byte), then the wanted device +# key ID (the key_id_bytes raw bytes, not hex), all zero for "any device". +# Always probe_bytes long; anything else is ignored. +probe_magic = "OCDQ" +probe_bytes = 15 +# Reply: reply_magic (ASCII), protocol_version (1 byte), the device key ID (raw +# bytes), then tcp_port (2 bytes, big-endian). +reply_magic = "OCDR" +reply_bytes = 17 +# Replies the device sends per second at most, all senders together; probes +# beyond that are ignored. +max_replies_per_second = 4 +# The app sends probe_count probes, probe_interval_ms apart, and waits +# reply_timeout_ms after the last one. +probe_count = 3 +probe_interval_ms = 500 +reply_timeout_ms = 1000 + [ble.service] name = "Open Car Control" uuid = "1acff001-229b-4d38-a5d2-9af1d9b11f00" @@ -144,3 +207,7 @@ max_session_messages = 1000000 handshake_timeout_ms = 10000 # Longest EnrollClientKeyCommand.label, in UTF-8 bytes. max_client_label_bytes = 32 +# Handshake inits the device processes per second at most, all transports +# together; the rest are dropped unanswered. Bounds the X25519 work anyone who +# can reach a transport (the LAN, the relay's broker) can make it do. +max_handshake_inits_per_second = 8