diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a230a78 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.venv/ +__pycache__/ diff --git a/README.md b/README.md index a19e8dc..f68a7da 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,8 @@ This project uses an **Envelope Pattern** to route messages. 2. **`opencar/cars//v1/*.proto` (The Payload):** Contains the actual, highly-specific state and commands for a given vehicle. These are compiled into raw bytes and placed inside the core envelope. 3. **`opencar/core/v1/transport.toml` (Transport Bindings):** Defines cross-repo transport details that are not protobuf messages themselves but still must stay in sync, such as MQTT topic templates, BLE GATT service/characteristic UUIDs and the BLE message size limit (`ble.payload`) and chunk framing (`ble.fragmentation`, see [`docs/ble-fragmentation.md`](docs/ble-fragmentation.md)). +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). + 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/secure-channel-vectors.json b/docs/secure-channel-vectors.json new file mode 100644 index 0000000..87f33d8 --- /dev/null +++ b/docs/secure-channel-vectors.json @@ -0,0 +1,46 @@ +{ + "description": "Test vectors for docs/secure-channel.md, generated by tools/secure_channel_vectors.py. All byte strings are lowercase hex.", + "protocol": "Noise_IK_25519_ChaChaPoly_BLAKE2s", + "device_static_private": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "device_static_public": "8f40c5adb68f25624ae5b214ea767a6ec94d829d3d7b5e1ad1ba6f3e2138285f", + "device_key_id": "1e1c177be4a37ca2c0ea", + "device_ephemeral_private": "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f", + "client_static_private": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", + "client_static_public": "358072d6365880d1aeea329adf9121383851ed21a28e3b75e965d0d2cd166254", + "client_ephemeral_private": "404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f", + "prologue": "6f70656e6361722f7365637572652f31003165316331373762653461333763613263306561", + "session_id": "a1b2c3d4", + "handshake_init_frame": "01a1b2c3d479a631eede1bf9c98f12032cdeadd0e7a079398fc786b88cc846ec89af85a51a5a5d3ec50c63b0e0156101cf138f46d05427ed87f592c2009bab26f178d726e342e284e9c9aee8bfed050d8af62a83ac94af9655564b601a31f5610e0d528088", + "handshake_response_frame": "02a1b2c3d4675dd574ed7789310b3d2e7681f3790b466c773b1521fecf36577958371ea52f96949c74b5a98cebba1aa6eaf84dc5ff", + "handshake_hash": "9b46ee025aa59134ae661e1f7b2f722f8055c193511f8e777a4ca9267eb0c76a", + "client_to_device": [ + { + "counter": 0, + "plaintext": "636c69656e7420746f206465766963652c206669727374", + "frame": "03a1b2c3d400000000000000007ef8f7df7641390f98cca5e8a3e656f93b83f2a12979b748220134a872b96de1bafc8e3dba52c2" + }, + { + "counter": 1, + "plaintext": "636c69656e7420746f206465766963652c207365636f6e64", + "frame": "03a1b2c3d4000000000000000107ee18b696e6118ecaea61bfc41cc9a4e5412c15853f56bd6b3b5e87c55280914ad2ed3acdaba003" + }, + { + "counter": 5, + "plaintext": "", + "frame": "03a1b2c3d40000000000000005797875d51bf16ac0186d8c7308aceeae" + } + ], + "device_to_client": [ + { + "counter": 0, + "plaintext": "64657669636520746f20636c69656e742c206669727374", + "frame": "03a1b2c3d40000000000000000409a5e301b72ad4c745278dd0c8072051806a06d111e523a5e62dc556b16330553c3c66a4f7909" + }, + { + "counter": 1, + "plaintext": "64657669636520746f20636c69656e742c207365636f6e64", + "frame": "03a1b2c3d400000000000000013ef8f405460040e1af748f0b42d7a5065657f6308601273ecacfa9fb2e0fd84c12cb12c0b1244346" + } + ], + "unknown_session_frame": "05a1b2c3d4" +} diff --git a/docs/secure-channel.md b/docs/secure-channel.md new file mode 100644 index 0000000..96c68a9 --- /dev/null +++ b/docs/secure-channel.md @@ -0,0 +1,84 @@ +# Secure channel + +The secure channel is an end-to-end encrypted, mutually authenticated link between a **client** (the app, later a hub such as Home Assistant) and the **device**. It carries the same `AppToDevice` / `DeviceToApp` messages as BLE. The transports that carry it (LAN direct, an MQTT broker used as a relay, a future custom relay) are dumb pipes: they only move frames, and whatever sits in the middle only sees ciphertext. + +The constants below are in [`transport.toml`](../opencar/core/v1/transport.toml), `[secure_channel]`. Both sides test against [`secure-channel-vectors.json`](secure-channel-vectors.json), generated by [`tools/secure_channel_vectors.py`](../tools/secure_channel_vectors.py) with a reference Noise implementation. + +## Keys and enrollment + +Keys are only exchanged over a bonded BLE link, which is the channel's trust anchor. + +- **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. + +## Protocol + +`Noise_IK_25519_ChaChaPoly_BLAKE2s` ([Noise specification](https://noiseprotocol.org/noise.html), revision 34), the pattern WireGuard uses: + +``` +IK: + <- s + ... + -> e, es, s, ss + <- e, ee, se +``` + +- **Initiator** = the client, which knows the device's static key from BLE. **Responder** = the device, which learns the client's static key from message 1 and looks it up in its registry. +- **Prologue:** the ASCII label `opencar/secure/1`, a `0x00` byte, then the device key ID in ASCII. A handshake meant for another device, or for another version of this protocol, fails. +- **Handshake payloads are empty**, in both messages. Messages only travel in transport frames, after the handshake, where they get forward secrecy and replay protection (a payload in message 1 would have neither). +- One round trip gives mutual authentication and forward secrecy. After message 2 both sides `Split()`: the first cipher state encrypts client → device, the second device → client. Transport messages use empty associated data. + +## Frames + +Every message is one frame, the same bytes on every transport: + +| Bytes | Field | +| --- | --- | +| 0 | Frame type | +| 1–4 | Session ID | +| 5… | Depends on the type | + +| Type | Name | Direction | Rest of the frame | +| --- | --- | --- | --- | +| `1` | Handshake init | client → device | Noise message 1 (96 bytes) | +| `2` | Handshake response | device → client | Noise message 2 (48 bytes) | +| `3` | Transport | both | 8-byte big-endian counter, then the ciphertext (plaintext + 16-byte tag) | +| `4` | Reserved | | The sealed retained state (a later phase) | +| `5` | Unknown session | device → client | Nothing | + +- **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. +- A frame that is too short, has an unknown type, or fails to decrypt is dropped without an answer. + +## Sessions + +The device keeps its sessions in RAM only, keyed by the session ID and the transport connection that carries them. + +- **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). +- **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. +- **Revocation:** a session ends when its client's key is removed from the registry (the phone removed, the bonds cleared or reset, the phone pairing again), and when the transport connection carrying it closes. +- **Device restart:** sessions are lost. A transport frame for a session the device doesn't have on that connection is answered with an **unknown session** frame (type `5`, the session ID, nothing else), at most once per received frame. It is not authenticated, so the client only treats it as a hint: it handshakes again and keeps the old session until the new one is up. A client that gets no answer to a transport frame within its own response timeout handshakes again too. + +## 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. +- **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. + +## 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. + +Regenerate them with: + +```sh +python3 -m venv .venv && .venv/bin/pip install noiseprotocol==0.3.1 +.venv/bin/python -I tools/secure_channel_vectors.py > docs/secure-channel-vectors.json +``` diff --git a/opencar/core/v1/system.proto b/opencar/core/v1/system.proto index 2e4f00f..127bd42 100644 --- a/opencar/core/v1/system.proto +++ b/opencar/core/v1/system.proto @@ -46,6 +46,13 @@ message SystemState { // subscribes. Each update carries every bus the device reports on; a bus // whose driver doesn't report its health is absent. map can_bus_health = 9; + + // The device's identity for the secure channel (docs/secure-channel.md): its + // static public key and key ID. BLE only, never over another transport: the + // app pins it per paired vehicle, so it must come from the bonded link. Sent + // 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; } // This contains a single system command. @@ -98,6 +105,10 @@ message SystemCommand { // Ends the validation session the sending phone started. CancelPhoneValidationCommand cancel_phone_validation = 13; + + // Enrolls a client's public key for the secure channel. BLE only, from a + // validated phone. Answered with SystemCommandResult.device_identity. + EnrollClientKeyCommand enroll_client_key = 14; } } @@ -455,6 +466,13 @@ message PairedPhone { // This is the phone that sent the command. bool is_requester = 3; + + // The phone has a client key enrolled (EnrollClientKeyCommand), so it can + // reach the device over the secure channel (LAN, relay) as well as BLE. + bool remote_key_enrolled = 4; + + // The label the phone enrolled its key with, empty when no key is enrolled. + string remote_key_label = 5; } // The bonded phones. @@ -514,6 +532,11 @@ message SystemCommandResult { // For any phone validation command refused for another reason than a // wrong code. PhoneValidationRefusal validation_refusal = 4; + + // For EnrollClientKeyCommand: the device's identity, which the client pins + // for the secure channel. Lets the app enroll without waiting for a + // SystemState. + DeviceIdentity device_identity = 5; } } @@ -560,3 +583,64 @@ enum CanBusStatus { // The controller went bus-off and is being restarted. CAN_BUS_STATUS_BUS_OFF = 5; } + +// The device's long-term identity for the secure channel (see +// docs/secure-channel.md). The device creates it at first boot and keeps it +// across bond resets and ClearPairedPhonesCommand: it belongs to the device, +// not to its owner. Erasing the device's flash creates a new one, and the app +// must then treat the device as a new one (the phones pair again anyway). +message DeviceIdentity { + // The device's X25519 static public key, 32 bytes. The client pins it per + // paired vehicle and uses it as the responder's static key of the Noise IK + // handshake. + bytes public_key = 1; + + // The device key ID: lowercase hex of the first 10 bytes of the BLAKE2s-256 + // hash of public_key (20 characters). A short, stable name for the device, + // part of the secure channel's prologue. Not a phone's device_id (the `ble:` + // ID of PairedPhone). + string key_id = 2; +} + +// What kind of client a key belongs to. +enum ClientKind { + // Unknown. The device refuses it. + CLIENT_KIND_UNSPECIFIED = 0; + // The sending phone's own key. Its client ID is the phone's device_id (the + // `ble:` ID), so the channel's commands get the same checks as the phone's + // BLE ones. + CLIENT_KIND_PHONE = 1; + // A hub (Home Assistant), enrolled by a validated phone on its behalf. + // Reserved: the device refuses it until hubs are specified. + CLIENT_KIND_HUB = 2; +} + +// Enrolls a client's X25519 static public key, so the client can open the +// secure channel (docs/secure-channel.md) with the device. BLE only: never +// accepted through the secure channel or MQTT, since keys are exchanged over +// a bonded link. Answered with SystemCommandResult.device_identity. +// +// With kind = CLIENT_KIND_PHONE the key belongs to the sending phone, which +// must be validated for the identified car (otherwise +// COMMAND_STATUS_CODE_REJECTED_NOT_VALIDATED). Enrolling again replaces that +// phone's key. Any other kind is refused (COMMAND_STATUS_CODE_FAILED), and so +// is a key that isn't 32 bytes or a label longer than +// secure_channel.max_client_label_bytes (transport.toml). +// +// Revocation: a phone's key goes away with its bond, so it is dropped when the +// phone is removed (RemovePairedPhoneCommand), when every phone is removed +// (ClearPairedPhonesCommand), when the bonds are reset (power-cycle reset) and +// when the phone pairs again. A phone that loses its validation (another car +// approved) keeps its key, but can't send vehicle commands through the channel, +// exactly as over BLE. Its open sessions end when its key is removed. +message EnrollClientKeyCommand { + // The client's X25519 static public key, 32 bytes. + bytes public_key = 1; + + // Whose key it is. + ClientKind kind = 2; + + // Shown in the phone list (PairedPhone.remote_key_label), e.g. the phone's + // model. UTF-8, at most secure_channel.max_client_label_bytes bytes. + string label = 3; +} diff --git a/opencar/core/v1/transport.toml b/opencar/core/v1/transport.toml index a3e96f1..629ec55 100644 --- a/opencar/core/v1/transport.toml +++ b/opencar/core/v1/transport.toml @@ -98,3 +98,49 @@ reassembly_timeout_ms = 2000 pairing = "Recommended before enabling control commands." mtu = "Request ble.payload.att_mtu after connecting. Chunk data size is the negotiated MTU minus 5 bytes (3 ATT + 2 chunk header)." fragmentation = "Every message is sent as chunks with a 2-byte header (LAST flag + 7-bit index, message sequence number) followed by the message and its CRC-32, up to ble.payload.max_message_bytes reassembled. Partial messages are discarded on disconnect, index gap, sequence mismatch, timeout or CRC mismatch. See docs/ble-fragmentation.md." + +[secure_channel] +# The end-to-end encrypted channel between a client (the app) and the device, +# the same on every transport that carries it (LAN, MQTT relay). See +# docs/secure-channel.md and its test vectors, docs/secure-channel-vectors.json. +protocol = "Noise_IK_25519_ChaChaPoly_BLAKE2s" +# The prologue is this label, a 0x00 byte, then the device key ID (ASCII). +prologue_label = "opencar/secure/1" +# The device key ID is the lowercase hex of the first key_id_bytes bytes of the +# BLAKE2s-256 hash of the device's static public key. +key_id_bytes = 10 +# Frame byte 0. 4 is reserved for the sealed retained state. +frame_type_handshake_init = 1 +frame_type_handshake_response = 2 +frame_type_transport = 3 +frame_type_unknown_session = 5 +# Frame bytes 1-4: the session ID, chosen at random by the client. +session_id_bytes = 4 +# Transport frames: an explicit big-endian counter (the Noise nonce) follows +# the session ID. +counter_bytes = 8 +# Transport frames the receiver accepts out of order, behind the highest +# counter it has seen. Anything older, or seen before, is dropped. +replay_window = 64 +# Largest plaintext of one transport frame: one encoded AppToDevice or +# DeviceToApp, the same limit as BLE (ble.payload.max_message_bytes). +max_plaintext_bytes = 4096 +# Stream transports (TCP) prefix each frame with its length, big-endian. +stream_length_prefix_bytes = 2 +# Sessions the device keeps at once, and per client. When full, a new session +# replaces the one idle the longest (the same client's first, see the doc). +max_sessions = 4 +max_sessions_per_client = 2 +# A session with no valid transport frame in either direction for this long +# ends. +idle_timeout_seconds = 300 +# A session ends this long after its handshake, or after this many transport +# frames in one direction, whichever comes first. The client handshakes again +# before reaching either. +max_session_seconds = 3600 +max_session_messages = 1000000 +# How long the client waits for the handshake response before it gives up +# (the device stays silent for a key it doesn't know). +handshake_timeout_ms = 10000 +# Longest EnrollClientKeyCommand.label, in UTF-8 bytes. +max_client_label_bytes = 32 diff --git a/tools/secure_channel_vectors.py b/tools/secure_channel_vectors.py new file mode 100644 index 0000000..6b7813b --- /dev/null +++ b/tools/secure_channel_vectors.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Generates docs/secure-channel-vectors.json, the secure channel's test vectors. + +The vectors are produced with a reference Noise implementation (the +`noiseprotocol` package), from fixed keys, so the firmware and the app can check +their own implementation of docs/secure-channel.md against them. + + python3 -m venv .venv && .venv/bin/pip install noiseprotocol==0.3.1 + .venv/bin/python -I tools/secure_channel_vectors.py > docs/secure-channel-vectors.json + +The output is deterministic: running it again gives the same file. +""" + +import hashlib +import json +import struct +import sys + +import warnings + +from noise.connection import Keypair, NoiseConnection + +# Fixed ephemeral keys are what test vectors are for. +warnings.filterwarnings("ignore", message="One of ephemeral keypairs") + +PROTOCOL = b"Noise_IK_25519_ChaChaPoly_BLAKE2s" +PROLOGUE_LABEL = b"opencar/secure/1" +KEY_ID_BYTES = 10 + +FRAME_HANDSHAKE_INIT = 1 +FRAME_HANDSHAKE_RESPONSE = 2 +FRAME_TRANSPORT = 3 +FRAME_UNKNOWN_SESSION = 5 + +# Fixed private keys (32 bytes each). Never use these anywhere else. +DEVICE_STATIC = bytes(range(0x00, 0x20)) +CLIENT_STATIC = bytes(range(0x20, 0x40)) +CLIENT_EPHEMERAL = bytes(range(0x40, 0x60)) +DEVICE_EPHEMERAL = bytes(range(0x60, 0x80)) +SESSION_ID = bytes.fromhex("a1b2c3d4") + +# Transport payloads. Real ones are encoded AppToDevice / DeviceToApp messages; +# the channel doesn't look inside, so any bytes do. +CLIENT_TO_DEVICE = [ + (0, b"client to device, first"), + (1, b"client to device, second"), + (5, b""), +] +DEVICE_TO_CLIENT = [ + (0, b"device to client, first"), + (1, b"device to client, second"), +] + + +def public_key(private: bytes) -> bytes: + from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey + from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat + + return X25519PrivateKey.from_private_bytes(private).public_key().public_bytes( + Encoding.Raw, PublicFormat.Raw + ) + + +def key_id(public: bytes) -> str: + return hashlib.blake2s(public, digest_size=32).digest()[:KEY_ID_BYTES].hex() + + +def prologue(device_key_id: str) -> bytes: + return PROLOGUE_LABEL + b"\x00" + device_key_id.encode("ascii") + + +def transport_frame(conn: NoiseConnection, counter: int, plaintext: bytes) -> bytes: + conn.noise_protocol.cipher_state_encrypt.n = counter + ciphertext = conn.encrypt(plaintext) + return bytes([FRAME_TRANSPORT]) + SESSION_ID + struct.pack(">Q", counter) + ciphertext + + +def main() -> None: + device_public = public_key(DEVICE_STATIC) + client_public = public_key(CLIENT_STATIC) + device_key_id = key_id(device_public) + pro = prologue(device_key_id) + + client = NoiseConnection.from_name(PROTOCOL) + client.set_as_initiator() + client.set_prologue(pro) + client.set_keypair_from_private_bytes(Keypair.STATIC, CLIENT_STATIC) + client.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC, device_public) + client.set_keypair_from_private_bytes(Keypair.EPHEMERAL, CLIENT_EPHEMERAL) + + device = NoiseConnection.from_name(PROTOCOL) + device.set_as_responder() + device.set_prologue(pro) + device.set_keypair_from_private_bytes(Keypair.STATIC, DEVICE_STATIC) + device.set_keypair_from_private_bytes(Keypair.EPHEMERAL, DEVICE_EPHEMERAL) + + client.start_handshake() + device.start_handshake() + + message1 = client.write_message(b"") + assert device.read_message(message1) == b"" + # The device learns the client's static key from message 1. + assert device.noise_protocol.handshake_state.rs.public_bytes == client_public + message2 = device.write_message(b"") + assert client.read_message(message2) == b"" + assert client.handshake_finished and device.handshake_finished + assert client.get_handshake_hash() == device.get_handshake_hash() + + init_frame = bytes([FRAME_HANDSHAKE_INIT]) + SESSION_ID + message1 + response_frame = bytes([FRAME_HANDSHAKE_RESPONSE]) + SESSION_ID + message2 + + to_device = [] + for counter, plaintext in CLIENT_TO_DEVICE: + frame = transport_frame(client, counter, plaintext) + device.noise_protocol.cipher_state_decrypt.n = counter + assert device.decrypt(frame[13:]) == plaintext + to_device.append( + {"counter": counter, "plaintext": plaintext.hex(), "frame": frame.hex()} + ) + to_client = [] + for counter, plaintext in DEVICE_TO_CLIENT: + frame = transport_frame(device, counter, plaintext) + client.noise_protocol.cipher_state_decrypt.n = counter + assert client.decrypt(frame[13:]) == plaintext + to_client.append( + {"counter": counter, "plaintext": plaintext.hex(), "frame": frame.hex()} + ) + + vectors = { + "description": "Test vectors for docs/secure-channel.md, generated by " + "tools/secure_channel_vectors.py. All byte strings are lowercase hex.", + "protocol": PROTOCOL.decode(), + "device_static_private": DEVICE_STATIC.hex(), + "device_static_public": device_public.hex(), + "device_key_id": device_key_id, + "device_ephemeral_private": DEVICE_EPHEMERAL.hex(), + "client_static_private": CLIENT_STATIC.hex(), + "client_static_public": client_public.hex(), + "client_ephemeral_private": CLIENT_EPHEMERAL.hex(), + "prologue": pro.hex(), + "session_id": SESSION_ID.hex(), + "handshake_init_frame": init_frame.hex(), + "handshake_response_frame": response_frame.hex(), + "handshake_hash": client.get_handshake_hash().hex(), + "client_to_device": to_device, + "device_to_client": to_client, + "unknown_session_frame": (bytes([FRAME_UNKNOWN_SESSION]) + SESSION_ID).hex(), + } + json.dump(vectors, sys.stdout, indent=2) + sys.stdout.write("\n") + + +if __name__ == "__main__": + main()