diff --git a/Cargo.lock b/Cargo.lock index a47e2dd..9c52b3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,16 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + [[package]] name = "aes" version = "0.8.4" @@ -422,6 +432,30 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.45" @@ -441,6 +475,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common", "inout", + "zeroize", ] [[package]] @@ -550,6 +585,7 @@ version = "0.1.0" dependencies = [ "blake2", "bytes", + "chacha20poly1305", "core-interface", "critical-section", "embassy-executor", @@ -567,6 +603,7 @@ dependencies = [ "sha2", "toml", "x25519-dalek", + "zeroize", ] [[package]] @@ -2554,6 +2591,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "p256" version = "0.13.2" @@ -2587,6 +2630,17 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -3647,6 +3701,16 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "unsafe-libyaml" version = "0.2.11" diff --git a/core-interface/Cargo.toml b/core-interface/Cargo.toml index 14ea270..8364124 100644 --- a/core-interface/Cargo.toml +++ b/core-interface/Cargo.toml @@ -21,6 +21,8 @@ sha2 = { version = "0.10", default-features = false } # and the client keys are X25519, the device key ID a BLAKE2s-256 hash. x25519-dalek = { version = "2.0", default-features = false, features = ["static_secrets", "zeroize"] } blake2 = { version = "0.10", default-features = false } +chacha20poly1305 = { version = "0.10", default-features = false, features = ["alloc"] } +zeroize = { version = "1", default-features = false } [features] # `CommandAuthorization::for_tests`, for vehicle crate tests. Only enable it in @@ -34,6 +36,7 @@ toml = { workspace = true } [dev-dependencies] # Reads the secure channel's test vectors from the contracts. serde_json = "1" +x25519-dalek = { version = "2.0", default-features = false, features = ["static_secrets"] } # The integration tests use the `test-utils` helpers. core-interface = { path = ".", features = ["test-utils"] } critical-section = { workspace = true } diff --git a/core-interface/build.rs b/core-interface/build.rs index 220c9cd..84e9516 100644 --- a/core-interface/build.rs +++ b/core-interface/build.rs @@ -13,6 +13,7 @@ fn main() -> Result<()> { generate_ble_transport_constants()?; generate_phone_validation_constants()?; + generate_secure_channel_constants()?; Ok(()) } @@ -198,3 +199,109 @@ fn parse_uuid(uuid: &str, field: &str) -> u128 { u128::from_str_radix(&hex, 16) .unwrap_or_else(|_| panic!("transport.toml {field} is not valid hex: {uuid}")) } + +/// The secure channel's constants (`[secure_channel]`, docs/secure-channel.md), for +/// `secure_channel.rs`, `identity.rs` and `client_keys.rs`. +fn generate_secure_channel_constants() -> Result<()> { + let toml_str = std::fs::read_to_string("../contracts/opencar/core/v1/transport.toml") + .expect("Failed to read contracts/opencar/core/v1/transport.toml"); + let transport: toml::Value = toml::from_str(&toml_str).expect("Failed to parse transport.toml"); + let section = transport.get("secure_channel").unwrap_or_else(|| { + panic!("transport.toml is missing [secure_channel]; update the contracts submodule") + }); + let int = |key: &str| { + section + .get(key) + .and_then(|v| v.as_integer()) + .unwrap_or_else(|| panic!("transport.toml is missing integer secure_channel.{key}")) + }; + let string = |key: &str| { + section + .get(key) + .and_then(|v| v.as_str()) + .unwrap_or_else(|| panic!("transport.toml is missing string secure_channel.{key}")) + .to_string() + }; + // The wire layout is implemented by hand: a change has to change the code too. + assert_eq!( + string("protocol"), + "Noise_IK_25519_ChaChaPoly_BLAKE2s", + "secure_channel.protocol changed; update core_interface::noise" + ); + assert!( + int("frame_type_handshake_init") == 1 + && int("frame_type_handshake_response") == 2 + && int("frame_type_transport") == 3 + && int("frame_type_unknown_session") == 5 + && int("session_id_bytes") == 4 + && int("counter_bytes") == 8 + && int("stream_length_prefix_bytes") == 2, + "transport.toml secure_channel frame layout changed; update core_interface::secure_channel" + ); + let key_id_bytes = int("key_id_bytes"); + assert!( + (1..=32).contains(&key_id_bytes), + "secure_channel.key_id_bytes out of range" + ); + let replay_window = int("replay_window"); + assert!( + (1..=64).contains(&replay_window), + "secure_channel.replay_window must fit a 64-bit bitmap" + ); + let max_plaintext_bytes = int("max_plaintext_bytes"); + // A frame (13-byte header, 16-byte tag) must fit the 2-byte stream length prefix. + assert!( + max_plaintext_bytes > 0 && max_plaintext_bytes + 29 <= 0xFFFF, + "secure_channel.max_plaintext_bytes out of range" + ); + let max_sessions = int("max_sessions"); + let max_sessions_per_client = int("max_sessions_per_client"); + assert!( + (1..=255).contains(&max_sessions) && (1..=max_sessions).contains(&max_sessions_per_client), + "secure_channel session limits out of range" + ); + let idle_timeout_seconds = int("idle_timeout_seconds"); + let max_session_seconds = int("max_session_seconds"); + let max_session_messages = int("max_session_messages"); + let handshake_timeout_ms = int("handshake_timeout_ms"); + let max_client_label_bytes = int("max_client_label_bytes"); + assert!( + idle_timeout_seconds > 0 + && max_session_seconds > 0 + && max_session_messages > 0 + && handshake_timeout_ms > 0 + && (0..=255).contains(&max_client_label_bytes), + "secure_channel timeouts and limits out of range" + ); + let prologue_label = string("prologue_label"); + + let out_dir = std::env::var("OUT_DIR").unwrap(); + std::fs::write( + std::path::Path::new(&out_dir).join("secure_channel.rs"), + format!( + "// @generated — do not edit. Source: contracts/opencar/core/v1/transport.toml\n\ + /// Start of the prologue, before a 0x00 byte and the device key ID.\n\ + pub const PROLOGUE_LABEL: &[u8] = b{prologue_label:?};\n\ + /// Bytes of the device key ID, before hex.\n\ + pub const DEVICE_KEY_ID_BYTES: usize = {key_id_bytes};\n\ + /// Transport frames accepted behind the highest counter seen.\n\ + pub const REPLAY_WINDOW: u64 = {replay_window};\n\ + /// Largest plaintext of one transport frame.\n\ + pub const MAX_PLAINTEXT_BYTES: usize = {max_plaintext_bytes};\n\ + /// Sessions the device keeps at once.\n\ + pub const MAX_SESSIONS: usize = {max_sessions};\n\ + /// Sessions one client may have at once.\n\ + pub const MAX_SESSIONS_PER_CLIENT: usize = {max_sessions_per_client};\n\ + /// A session without a valid transport frame for this long ends.\n\ + pub const SESSION_IDLE_TIMEOUT_MS: u64 = {idle_timeout_seconds} * 1_000;\n\ + /// A session ends this long after its handshake.\n\ + pub const MAX_SESSION_MS: u64 = {max_session_seconds} * 1_000;\n\ + /// A session ends after this many transport frames in one direction.\n\ + pub const MAX_SESSION_MESSAGES: u64 = {max_session_messages};\n\ + /// How long a client waits for the handshake response.\n\ + pub const HANDSHAKE_TIMEOUT_MS: u64 = {handshake_timeout_ms};\n\ + /// Longest client label, in UTF-8 bytes.\n\ + pub const MAX_CLIENT_LABEL_BYTES: usize = {max_client_label_bytes};\n" + ), + ) +} diff --git a/core-interface/src/client_keys.rs b/core-interface/src/client_keys.rs index 57e1405..3804446 100644 --- a/core-interface/src/client_keys.rs +++ b/core-interface/src/client_keys.rs @@ -24,8 +24,7 @@ use embassy_sync::signal::Signal; use crate::proto; -/// Longest label, in UTF-8 bytes: `secure_channel.max_client_label_bytes` (transport.toml). -pub const MAX_CLIENT_LABEL_BYTES: usize = 32; +pub use crate::secure_channel::MAX_CLIENT_LABEL_BYTES; /// Format version of [`encode_client_keys`]; an unknown one reads as no key. const CLIENT_KEYS_FORMAT_VERSION: u8 = 1; diff --git a/core-interface/src/dedupe.rs b/core-interface/src/dedupe.rs index 7e12358..990c5c7 100644 --- a/core-interface/src/dedupe.rs +++ b/core-interface/src/dedupe.rs @@ -7,9 +7,11 @@ //! transports, without answering it: the app then reports the result as unknown and //! re-reads the state. //! -//! The source is the transport-verified one (the BLE address), never the app's. MQTT -//! has no verified source yet (contracts#8, firmware#16), so its commands are keyed with -//! an empty source and only match other MQTT commands. +//! The source is the transport-verified one, never the app's: the BLE address, or the +//! secure channel client's ID, which for a phone is the same `ble:` ID. So a command +//! resent from BLE to the secure channel (or back) is caught. Plain MQTT has no verified +//! source, so its commands are keyed with an empty source and only match other MQTT +//! commands (plain MQTT commands are refused anyway, see `dispatch.rs`). use alloc::collections::VecDeque; use alloc::vec::Vec; diff --git a/core-interface/src/dispatch.rs b/core-interface/src/dispatch.rs index d0233a3..ed330ec 100644 --- a/core-interface/src/dispatch.rs +++ b/core-interface/src/dispatch.rs @@ -51,9 +51,9 @@ async fn ble_controller_allows(source_device_id: &[u8], now_ms: u64) -> bool { false } -async fn send_not_controller_response(message_id: u64) { +async fn send_not_controller_response(transport: Transport, message_id: u64) { send_to( - Transport::Ble, + transport, proto::DeviceToApp { timestamp_ms: embassy_time::Instant::now().as_millis(), platform_id: crate::PLATFORM_ID.load(Ordering::Relaxed), @@ -338,10 +338,12 @@ fn not_validated_rejection(message_id: u64) -> proto::DeviceToApp { } } -/// The checks a BLE vehicle command passes before it reaches the vehicle, in order: the -/// device is read-write, the phone is validated, the phone holds the controller lease. -/// Returns the command's authorization, or the rejection to answer with. -async fn admit_ble_vehicle_command( +/// The checks a vehicle command from a phone passes before it reaches the vehicle, in +/// order: the device is read-write, the phone is validated, the phone holds the controller +/// lease. The same over BLE and through the secure channel, where `source_device_id` is +/// the client's authenticated ID. Returns the command's authorization, or the rejection +/// to answer with. +async fn admit_vehicle_command( message_id: u64, source_device_id: &[u8], ) -> Result>> { @@ -362,6 +364,49 @@ async fn admit_ble_vehicle_command( )) } +/// Which vehicle command channel a command goes to. +#[derive(Clone, Copy)] +enum VehicleCommand { + Basic, + Advanced, +} + +/// Admits a vehicle command from a phone ([`admit_vehicle_command`]) and hands it to the +/// vehicle, or answers the rejection on `transport`. +async fn dispatch_vehicle_command( + transport: Transport, + kind: VehicleCommand, + message_id: u64, + source_device_id: Vec, + bytes: Vec, +) { + let authorization = match admit_vehicle_command(message_id, &source_device_id).await { + Ok(authorization) => authorization, + Err(Some(rejection)) => { + send_to(transport, *rejection).await; + return; + } + Err(None) => { + send_not_controller_response(transport, message_id).await; + return; + } + }; + let channel = match kind { + VehicleCommand::Basic => &BASIC_CMD_CHANNEL, + VehicleCommand::Advanced => &ADVANCED_CMD_CHANNEL, + }; + channel + .sender() + .send(InboundCommand { + message_id, + transport, + source_device_id, + bytes, + authorization: Some(authorization), + }) + .await; +} + pub async fn reset_ble_controller_lease_for_tests() { let mut lease = BLE_CONTROLLER_LEASE.lock().await; lease.owner_device_id.clear(); @@ -495,52 +540,24 @@ pub async fn handle_ble_message(msg: proto::AppToDevice) { None => {} }, Some(proto::app_to_device::Payload::BasicCommandBytes(bytes)) => { - let authorization = - match admit_ble_vehicle_command(msg.message_id, &source_device_id).await { - Ok(authorization) => authorization, - Err(Some(rejection)) => { - send_to(Transport::Ble, *rejection).await; - return; - } - Err(None) => { - send_not_controller_response(msg.message_id).await; - return; - } - }; - BASIC_CMD_CHANNEL - .sender() - .send(InboundCommand { - message_id: msg.message_id, - transport: Transport::Ble, - source_device_id, - bytes, - authorization: Some(authorization), - }) - .await; + dispatch_vehicle_command( + Transport::Ble, + VehicleCommand::Basic, + msg.message_id, + source_device_id, + bytes, + ) + .await; } Some(proto::app_to_device::Payload::AdvancedCommandBytes(bytes)) => { - let authorization = - match admit_ble_vehicle_command(msg.message_id, &source_device_id).await { - Ok(authorization) => authorization, - Err(Some(rejection)) => { - send_to(Transport::Ble, *rejection).await; - return; - } - Err(None) => { - send_not_controller_response(msg.message_id).await; - return; - } - }; - ADVANCED_CMD_CHANNEL - .sender() - .send(InboundCommand { - message_id: msg.message_id, - transport: Transport::Ble, - source_device_id, - bytes, - authorization: Some(authorization), - }) - .await; + dispatch_vehicle_command( + Transport::Ble, + VehicleCommand::Advanced, + msg.message_id, + source_device_id, + bytes, + ) + .await; } // Heartbeat is an MQTT-only concept — silently ignored on BLE. Some(proto::app_to_device::Payload::Heartbeat(_)) => {} @@ -639,3 +656,44 @@ pub async fn process_mqtt_commands_task() { handle_mqtt_message(receiver.receive().await).await; } } + +// ── Secure channel dispatcher ───────────────────────────────────────────────── + +/// Processes a single `AppToDevice` that a secure channel session carried +/// (`secure_channel.rs`), already stamped with its client's ID as `source_device_id`. +/// Permissions follow the authenticated client, not the transport: +/// - `basic_command_bytes` / `advanced_command_bytes` → the same checks as the same phone +/// over BLE (read-only, validated for this car, controller lease), then +/// `BASIC_CMD_CHANNEL` / `ADVANCED_CMD_CHANNEL` with the command's authorization. The +/// response goes back through the session (`Transport::Secure`). +/// - `system_command` → dropped: system commands need physical presence, so BLE only. +/// - `heartbeat` → nothing (any frame already keeps the session alive). +/// +/// Messages with a mismatched `platform_id` are dropped, and so are commands whose +/// (client, `message_id`) pair was seen recently on any transport (see `dedupe.rs`). +pub async fn handle_secure_message( + session: crate::secure_channel::SessionHandle, + msg: proto::AppToDevice, +) { + if msg.platform_id != crate::PLATFORM_ID.load(Ordering::Relaxed) + || msg.source_device_id.is_empty() + { + return; + } + let transport = Transport::Secure(session); + let kind = match &msg.payload { + Some(proto::app_to_device::Payload::BasicCommandBytes(_)) => VehicleCommand::Basic, + Some(proto::app_to_device::Payload::AdvancedCommandBytes(_)) => VehicleCommand::Advanced, + // BLE only, or nothing to do. + _ => return, + }; + if is_duplicate_command(&msg.source_device_id, msg.message_id) { + return; + } + let bytes = match msg.payload { + Some(proto::app_to_device::Payload::BasicCommandBytes(bytes)) + | Some(proto::app_to_device::Payload::AdvancedCommandBytes(bytes)) => bytes, + _ => return, + }; + dispatch_vehicle_command(transport, kind, msg.message_id, msg.source_device_id, bytes).await; +} diff --git a/core-interface/src/identity.rs b/core-interface/src/identity.rs index b04c187..054761d 100644 --- a/core-interface/src/identity.rs +++ b/core-interface/src/identity.rs @@ -20,8 +20,7 @@ use x25519_dalek::{PublicKey, StaticSecret}; use crate::proto; -/// Bytes of the device key ID, before hex: `secure_channel.key_id_bytes` (transport.toml). -pub const DEVICE_KEY_ID_BYTES: usize = 10; +pub use crate::secure_channel::DEVICE_KEY_ID_BYTES; /// Format version of the stored identity; an unknown one reads as no identity. const IDENTITY_FORMAT_VERSION: u8 = 1; @@ -121,7 +120,6 @@ pub fn device_identity() -> Option { } /// The device's static secret, for the secure channel's handshake. -#[allow(dead_code)] pub(crate) fn device_static_secret() -> Option { IDENTITY.lock(|i| i.borrow().as_ref().map(|i| i.secret.clone())) } diff --git a/core-interface/src/lib.rs b/core-interface/src/lib.rs index 39702d3..403d55f 100644 --- a/core-interface/src/lib.rs +++ b/core-interface/src/lib.rs @@ -20,10 +20,12 @@ mod identity; mod isotp; mod lifecycle; mod mqtt_tls; +mod noise; mod pairing; mod phone_trust; mod requirements; mod routing; +mod secure_channel; #[cfg(debug_assertions)] mod simulation; mod types; @@ -156,6 +158,22 @@ pub use identity::{ encode_device_identity, reset_device_identity_for_tests, restore_device_identity, }; +// Secure channel (sessions over any transport) +pub use noise::NoiseError; +#[cfg(any(test, feature = "test-utils"))] +pub use noise::initiator::{Initiator, InitiatorSession}; +#[cfg(any(test, feature = "test-utils"))] +pub use secure_channel::on_handshake_init_for_tests; +pub use secure_channel::{ + ChannelLink, FRAME_HANDSHAKE_INIT, FRAME_HANDSHAKE_RESPONSE, FRAME_HEADER_BYTES, + FRAME_TRANSPORT, FRAME_UNKNOWN_SESSION, FrameOutcome, HANDSHAKE_TIMEOUT_MS, MAX_FRAME_BYTES, + MAX_PLAINTEXT_BYTES, MAX_SESSION_MESSAGES, MAX_SESSION_MS, MAX_SESSIONS, + MAX_SESSIONS_PER_CLIENT, PROLOGUE_LABEL, REPLAY_WINDOW, SECURE_TX_CHANNEL, SESSION_BYTES, + SESSION_IDLE_TIMEOUT_MS, SessionHandle, TRANSPORT_HEADER_BYTES, close_link, + expire_secure_sessions, is_session_open, on_frame, process_secure_frame, + reset_secure_channel_for_tests, seal, secure_session_count, +}; + // Pairing registry pub use pairing::{ add_paired_phone, ble_max_bonded_phones, clear_paired_phones, is_phone_paired, @@ -191,8 +209,9 @@ pub use dedupe::{ // Dispatch tasks pub use dispatch::{ - handle_ble_message, handle_mqtt_message, process_ble_commands_task, process_mqtt_commands_task, - reset_ble_controller_lease_for_tests, set_ble_controller_lease_ttl_s, + handle_ble_message, handle_mqtt_message, handle_secure_message, process_ble_commands_task, + process_mqtt_commands_task, reset_ble_controller_lease_for_tests, + set_ble_controller_lease_ttl_s, }; // Routing tasks diff --git a/core-interface/src/noise.rs b/core-interface/src/noise.rs new file mode 100644 index 0000000..9c6bf61 --- /dev/null +++ b/core-interface/src/noise.rs @@ -0,0 +1,510 @@ +//! `Noise_IK_25519_ChaChaPoly_BLAKE2s`, as the secure channel uses it (docs/secure-channel.md +//! in the contracts): the IK handshake with empty payloads, then two cipher states with +//! explicit nonces. Written from the Noise specification (revision 34) on `x25519-dalek`, +//! `chacha20poly1305` and `blake2`, and checked against the contracts' test vectors. +//! +//! The device is the responder. The initiator is here for the tests (behind `test-utils`), +//! the app has its own. + +use alloc::vec::Vec; + +use blake2::{Blake2s256, Digest}; +use chacha20poly1305::aead::{Aead, AeadInPlace, KeyInit, Payload}; +use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce}; +use x25519_dalek::{PublicKey, StaticSecret}; +use zeroize::Zeroize; + +pub(crate) const PROTOCOL_NAME: &[u8] = b"Noise_IK_25519_ChaChaPoly_BLAKE2s"; +pub(crate) const DH_LEN: usize = 32; +pub(crate) const TAG_LEN: usize = 16; +const HASH_LEN: usize = 32; +const BLOCK_LEN: usize = 64; + +/// Length of handshake message 1 (e, encrypted s, the empty payload's tag). +pub(crate) const MESSAGE1_LEN: usize = DH_LEN + DH_LEN + TAG_LEN + TAG_LEN; +/// Length of handshake message 2 (e, the empty payload's tag). +pub(crate) const MESSAGE2_LEN: usize = DH_LEN + TAG_LEN; + +/// A handshake or decryption failed. Deliberately says nothing more. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct NoiseError; + +fn hash(parts: &[&[u8]]) -> [u8; HASH_LEN] { + let mut h = Blake2s256::new(); + for p in parts { + h.update(p); + } + h.finalize().into() +} + +fn hmac(key: &[u8; HASH_LEN], parts: &[&[u8]]) -> [u8; HASH_LEN] { + let mut ipad = [0x36u8; BLOCK_LEN]; + let mut opad = [0x5cu8; BLOCK_LEN]; + for (i, k) in key.iter().enumerate() { + ipad[i] ^= k; + opad[i] ^= k; + } + let mut inner = Blake2s256::new(); + inner.update(ipad); + for p in parts { + inner.update(p); + } + let inner: [u8; HASH_LEN] = inner.finalize().into(); + let out = hash(&[&opad, &inner]); + ipad.zeroize(); + opad.zeroize(); + out +} + +/// HKDF with two outputs, as Noise defines it. +fn hkdf2(ck: &[u8; HASH_LEN], ikm: &[u8]) -> ([u8; HASH_LEN], [u8; HASH_LEN]) { + let mut temp = hmac(ck, &[ikm]); + let out1 = hmac(&temp, &[&[1]]); + let out2 = hmac(&temp, &[&out1, &[2]]); + temp.zeroize(); + (out1, out2) +} + +fn nonce(n: u64) -> Nonce { + let mut bytes = [0u8; 12]; + bytes[4..].copy_from_slice(&n.to_le_bytes()); + bytes.into() +} + +/// A cipher state: a key and, for the handshake, its own nonce. Transport messages pass +/// their nonce explicitly (the frame's counter). +pub(crate) struct CipherState { + cipher: ChaCha20Poly1305, +} + +impl CipherState { + fn new(key: &[u8; HASH_LEN]) -> Self { + Self { + cipher: ChaCha20Poly1305::new(Key::from_slice(key)), + } + } + + /// Encrypts `plaintext` with nonce `n` and empty associated data. + #[cfg_attr(not(any(test, feature = "test-utils")), allow(dead_code))] + pub(crate) fn encrypt(&self, n: u64, plaintext: &[u8]) -> Vec { + self.encrypt_with_ad(n, &[], plaintext) + } + + /// Decrypts `ciphertext` with nonce `n` and empty associated data. + #[cfg_attr(not(any(test, feature = "test-utils")), allow(dead_code))] + pub(crate) fn decrypt(&self, n: u64, ciphertext: &[u8]) -> Result, NoiseError> { + self.decrypt_with_ad(n, &[], ciphertext) + } + + /// Encrypts `buffer` in place with nonce `n` and empty associated data, and returns the + /// tag: one buffer for the whole frame, which matters on the ESP's small heap. + pub(crate) fn encrypt_in_place(&self, n: u64, buffer: &mut [u8]) -> [u8; TAG_LEN] { + self.cipher + .encrypt_in_place_detached(&nonce(n), &[], buffer) + .map(Into::into) + // Only fails for inputs far over any frame's size. + .unwrap_or_default() + } + + /// Decrypts `ciphertext` (with its tag) into a single new buffer. + pub(crate) fn decrypt_into_vec( + &self, + n: u64, + ciphertext: &[u8], + ) -> Result, NoiseError> { + let len = ciphertext.len().checked_sub(TAG_LEN).ok_or(NoiseError)?; + let mut out = ciphertext[..len].to_vec(); + let tag = chacha20poly1305::Tag::from_slice(&ciphertext[len..]); + self.cipher + .decrypt_in_place_detached(&nonce(n), &[], &mut out, tag) + .map_err(|_| NoiseError)?; + Ok(out) + } + + fn encrypt_with_ad(&self, n: u64, ad: &[u8], plaintext: &[u8]) -> Vec { + self.cipher + .encrypt( + &nonce(n), + Payload { + msg: plaintext, + aad: ad, + }, + ) + // Only fails for inputs far over any frame's size. + .unwrap_or_default() + } + + fn decrypt_with_ad(&self, n: u64, ad: &[u8], ciphertext: &[u8]) -> Result, NoiseError> { + self.cipher + .decrypt( + &nonce(n), + Payload { + msg: ciphertext, + aad: ad, + }, + ) + .map_err(|_| NoiseError) + } +} + +/// The symmetric state of a handshake. +struct SymmetricState { + ck: [u8; HASH_LEN], + h: [u8; HASH_LEN], + k: Option<(CipherState, u64)>, +} + +impl Drop for SymmetricState { + fn drop(&mut self) { + self.ck.zeroize(); + } +} + +impl SymmetricState { + fn new(prologue: &[u8]) -> Self { + // The protocol name is longer than HASHLEN, so h starts as its hash. + let h = hash(&[PROTOCOL_NAME]); + let mut s = Self { ck: h, h, k: None }; + s.mix_hash(prologue); + s + } + + fn mix_hash(&mut self, data: &[u8]) { + self.h = hash(&[&self.h, data]); + } + + fn mix_key(&mut self, ikm: &[u8]) { + let (ck, mut k) = hkdf2(&self.ck, ikm); + self.ck = ck; + self.k = Some((CipherState::new(&k), 0)); + k.zeroize(); + } + + fn encrypt_and_hash(&mut self, plaintext: &[u8]) -> Vec { + let out = match self.k.as_mut() { + Some((cipher, n)) => { + let out = cipher.encrypt_with_ad(*n, &self.h, plaintext); + *n += 1; + out + } + None => plaintext.to_vec(), + }; + self.mix_hash(&out); + out + } + + fn decrypt_and_hash(&mut self, ciphertext: &[u8]) -> Result, NoiseError> { + let out = match self.k.as_mut() { + Some((cipher, n)) => { + let out = cipher.decrypt_with_ad(*n, &self.h, ciphertext)?; + *n += 1; + out + } + None => ciphertext.to_vec(), + }; + self.mix_hash(ciphertext); + Ok(out) + } + + /// The two transport cipher states: initiator → responder, responder → initiator. + fn split(&self) -> (CipherState, CipherState) { + let (mut k1, mut k2) = hkdf2(&self.ck, &[]); + let out = (CipherState::new(&k1), CipherState::new(&k2)); + k1.zeroize(); + k2.zeroize(); + out + } +} + +fn dh(secret: &StaticSecret, public: &[u8; DH_LEN]) -> Result<[u8; DH_LEN], NoiseError> { + let shared = secret.diffie_hellman(&PublicKey::from(*public)); + // A low-order point gives an all-zero output: refuse it rather than key on it. + if !shared.was_contributory() { + return Err(NoiseError); + } + Ok(*shared.as_bytes()) +} + +/// A finished handshake, on the device's side. +pub(crate) struct ResponderResult { + /// The client's static public key, learned from message 1. + pub(crate) client_static: [u8; DH_LEN], + /// The client's ephemeral public key, to refuse a replayed message 1. + pub(crate) client_ephemeral: [u8; DH_LEN], + /// Message 2, to send back. + pub(crate) message2: Vec, + /// Decrypts client → device. + pub(crate) receive: CipherState, + /// Encrypts device → client. + pub(crate) send: CipherState, + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) handshake_hash: [u8; HASH_LEN], +} + +/// Reads message 1 and writes message 2, as the responder. `accept` sees the client's +/// static key once message 1 is authenticated, and refuses the handshake by returning +/// `false` (an unknown key): message 2 is then never computed. +pub(crate) fn respond( + prologue: &[u8], + device_static: &StaticSecret, + device_ephemeral: &StaticSecret, + message1: &[u8], + accept: impl FnOnce(&[u8; DH_LEN]) -> bool, +) -> Result { + if message1.len() != MESSAGE1_LEN { + return Err(NoiseError); + } + let device_public = PublicKey::from(device_static); + let mut s = SymmetricState::new(prologue); + // Pre-message: <- s + s.mix_hash(device_public.as_bytes()); + // -> e + let re: [u8; DH_LEN] = message1[..DH_LEN].try_into().map_err(|_| NoiseError)?; + s.mix_hash(&re); + // es + s.mix_key(&dh(device_static, &re)?); + // s + let rs: [u8; DH_LEN] = s + .decrypt_and_hash(&message1[DH_LEN..DH_LEN * 2 + TAG_LEN])? + .try_into() + .map_err(|_| NoiseError)?; + // ss + s.mix_key(&dh(device_static, &rs)?); + // payload (empty) + if !s + .decrypt_and_hash(&message1[DH_LEN * 2 + TAG_LEN..])? + .is_empty() + { + return Err(NoiseError); + } + if !accept(&rs) { + return Err(NoiseError); + } + // <- e + let e_public = PublicKey::from(device_ephemeral); + let mut message2 = Vec::with_capacity(MESSAGE2_LEN); + message2.extend_from_slice(e_public.as_bytes()); + s.mix_hash(e_public.as_bytes()); + // ee + s.mix_key(&dh(device_ephemeral, &re)?); + // se + s.mix_key(&dh(device_ephemeral, &rs)?); + // payload (empty) + message2.extend_from_slice(&s.encrypt_and_hash(&[])); + let (receive, send) = s.split(); + Ok(ResponderResult { + client_static: rs, + client_ephemeral: re, + message2, + receive, + send, + handshake_hash: s.h, + }) +} + +/// The client side of the handshake. For tests only: the app has its own. +#[cfg(any(test, feature = "test-utils"))] +pub mod initiator { + use super::*; + + /// A client between message 1 and message 2. + pub struct Initiator { + s: SymmetricState, + e: StaticSecret, + client_static: StaticSecret, + device_static: [u8; DH_LEN], + } + + /// The client's two transport cipher states. + pub struct InitiatorSession { + pub(crate) send: CipherState, + pub(crate) receive: CipherState, + pub handshake_hash: [u8; HASH_LEN], + } + + impl InitiatorSession { + /// Encrypts client → device with nonce `n`. + pub fn encrypt(&self, n: u64, plaintext: &[u8]) -> Vec { + self.send.encrypt(n, plaintext) + } + + /// Decrypts device → client with nonce `n`. + pub fn decrypt(&self, n: u64, ciphertext: &[u8]) -> Result, NoiseError> { + self.receive.decrypt(n, ciphertext) + } + } + + impl Initiator { + /// Writes message 1. + pub fn start( + prologue: &[u8], + client_static: [u8; 32], + client_ephemeral: [u8; 32], + device_static: [u8; DH_LEN], + ) -> Result<(Self, Vec), NoiseError> { + let client_static = StaticSecret::from(client_static); + let e = StaticSecret::from(client_ephemeral); + let mut s = SymmetricState::new(prologue); + s.mix_hash(&device_static); + let e_public = PublicKey::from(&e); + let mut message1 = Vec::with_capacity(MESSAGE1_LEN); + message1.extend_from_slice(e_public.as_bytes()); + s.mix_hash(e_public.as_bytes()); + s.mix_key(&dh(&e, &device_static)?); + let s_public = PublicKey::from(&client_static); + message1.extend_from_slice(&s.encrypt_and_hash(s_public.as_bytes())); + s.mix_key(&dh(&client_static, &device_static)?); + message1.extend_from_slice(&s.encrypt_and_hash(&[])); + Ok(( + Self { + s, + e, + client_static, + device_static, + }, + message1, + )) + } + + /// Reads message 2. + pub fn finish(mut self, message2: &[u8]) -> Result { + let _ = self.device_static; + if message2.len() != MESSAGE2_LEN { + return Err(NoiseError); + } + let re: [u8; DH_LEN] = message2[..DH_LEN].try_into().map_err(|_| NoiseError)?; + self.s.mix_hash(&re); + self.s.mix_key(&dh(&self.e, &re)?); + self.s.mix_key(&dh(&self.client_static, &re)?); + if !self.s.decrypt_and_hash(&message2[DH_LEN..])?.is_empty() { + return Err(NoiseError); + } + let (send, receive) = self.s.split(); + Ok(InitiatorSession { + send, + receive, + handshake_hash: self.s.h, + }) + } + } +} + +#[cfg(test)] +mod tests { + use super::initiator::Initiator; + use super::*; + + fn vectors() -> serde_json::Value { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../contracts/docs/secure-channel-vectors.json" + ); + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() + } + + fn hex(v: &serde_json::Value) -> Vec { + let s = v.as_str().unwrap(); + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() + } + + fn key(v: &serde_json::Value) -> [u8; 32] { + hex(v).try_into().unwrap() + } + + /// Both sides of the handshake and every transport frame of the contracts' vectors, + /// byte for byte. + #[test] + fn matches_the_contract_vectors() { + let v = vectors(); + assert_eq!(v["protocol"].as_str().unwrap().as_bytes(), PROTOCOL_NAME); + let prologue = hex(&v["prologue"]); + let session_id = hex(&v["session_id"]); + let init_frame = hex(&v["handshake_init_frame"]); + let response_frame = hex(&v["handshake_response_frame"]); + assert_eq!(init_frame[0], 1); + assert_eq!(&init_frame[1..5], session_id.as_slice()); + assert_eq!(response_frame[0], 2); + + // The client's side. + let (initiator, message1) = Initiator::start( + &prologue, + key(&v["client_static_private"]), + key(&v["client_ephemeral_private"]), + key(&v["device_static_public"]), + ) + .unwrap(); + assert_eq!(message1, init_frame[5..]); + + // The device's side. + let device_static = StaticSecret::from(key(&v["device_static_private"])); + let device_ephemeral = StaticSecret::from(key(&v["device_ephemeral_private"])); + let mut seen = None; + let device = respond( + &prologue, + &device_static, + &device_ephemeral, + &message1, + |k| { + seen = Some(*k); + true + }, + ) + .unwrap(); + assert_eq!(seen, Some(key(&v["client_static_public"]))); + assert_eq!(device.client_static, key(&v["client_static_public"])); + assert_eq!(device.message2, response_frame[5..]); + assert_eq!(device.handshake_hash.to_vec(), hex(&v["handshake_hash"])); + + let client = initiator.finish(&device.message2).unwrap(); + assert_eq!(client.handshake_hash.to_vec(), hex(&v["handshake_hash"])); + + for f in v["client_to_device"].as_array().unwrap() { + let counter = f["counter"].as_u64().unwrap(); + let plaintext = hex(&f["plaintext"]); + let frame = hex(&f["frame"]); + assert_eq!(frame[0], 3); + assert_eq!(frame[5..13], counter.to_be_bytes()); + assert_eq!(client.encrypt(counter, &plaintext), frame[13..]); + assert_eq!( + device.receive.decrypt(counter, &frame[13..]).unwrap(), + plaintext + ); + } + for f in v["device_to_client"].as_array().unwrap() { + let counter = f["counter"].as_u64().unwrap(); + let plaintext = hex(&f["plaintext"]); + let frame = hex(&f["frame"]); + assert_eq!(device.send.encrypt(counter, &plaintext), frame[13..]); + assert_eq!(client.decrypt(counter, &frame[13..]).unwrap(), plaintext); + } + } + + #[test] + fn a_wrong_prologue_or_device_key_fails_the_handshake() { + let v = vectors(); + let prologue = hex(&v["prologue"]); + let message1 = &hex(&v["handshake_init_frame"])[5..]; + let device_static = StaticSecret::from(key(&v["device_static_private"])); + let ephemeral = StaticSecret::from(key(&v["device_ephemeral_private"])); + assert!( + respond( + b"opencar/secure/2", + &device_static, + &ephemeral, + message1, + |_| true + ) + .is_err() + ); + let other = StaticSecret::from([7u8; 32]); + assert!(respond(&prologue, &other, &ephemeral, message1, |_| true).is_err()); + // Refused by the registry: no message 2. + assert!(respond(&prologue, &device_static, &ephemeral, message1, |_| false).is_err()); + let mut tampered = message1.to_vec(); + tampered[40] ^= 1; + assert!(respond(&prologue, &device_static, &ephemeral, &tampered, |_| true).is_err()); + } +} diff --git a/core-interface/src/routing.rs b/core-interface/src/routing.rs index 9b98b3a..6a41dbc 100644 --- a/core-interface/src/routing.rs +++ b/core-interface/src/routing.rs @@ -69,33 +69,40 @@ static MQTT_LINK: Link = Link { generation: AtomicU32::new(0), }; -fn link(transport: Transport) -> &'static Link { +/// The link of BLE or MQTT. A secure channel session has no link of its own: it is open +/// while the session is (see `secure_channel.rs`). +fn link(transport: Transport) -> Option<&'static Link> { match transport { - Transport::Ble => &BLE_LINK, - Transport::Mqtt => &MQTT_LINK, + Transport::Ble => Some(&BLE_LINK), + Transport::Mqtt => Some(&MQTT_LINK), + Transport::Secure(_) => None, } } fn tx_channel( transport: Transport, -) -> &'static Channel { +) -> Option<&'static Channel> { match transport { - Transport::Ble => &BLE_TX_CHANNEL, - Transport::Mqtt => &MQTT_TX_CHANNEL, + Transport::Ble => Some(&BLE_TX_CHANNEL), + Transport::Mqtt => Some(&MQTT_TX_CHANNEL), + Transport::Secure(_) => None, } } /// Called by the board's transport driver when its link comes up (a phone /// connected, the MQTT session is ready) and when it goes down. Going down clears -/// that transport's TX queue. +/// that transport's TX queue. Ignored for a secure channel session, which opens and ends +/// with the channel. pub fn set_link_up(transport: Transport, up: bool) { - let link = link(transport); + let (Some(link), Some(channel)) = (link(transport), tx_channel(transport)) else { + return; + }; if up { link.up.store(true, Ordering::Relaxed); } else { link.up.store(false, Ordering::Relaxed); link.generation.fetch_add(1, Ordering::Relaxed); - while tx_channel(transport).try_receive().is_ok() {} + while channel.try_receive().is_ok() {} if matches!(transport, Transport::Ble) { crate::phone_trust::set_ble_peer(None); } @@ -104,22 +111,34 @@ pub fn set_link_up(transport: Transport, up: bool) { /// Whether the board reported `transport`'s link as up. pub fn is_link_up(transport: Transport) -> bool { - link(transport).up.load(Ordering::Relaxed) + match (transport, link(transport)) { + (Transport::Secure(session), _) => crate::secure_channel::is_session_open(session), + (_, Some(link)) => link.up.load(Ordering::Relaxed), + (_, None) => false, + } } /// Queues `msg` on `transport`'s TX queue without waiting. Dropped if the link is /// down or the queue is full. Returns whether it was queued. pub(crate) fn try_send_to(transport: Transport, msg: proto::DeviceToApp) -> bool { - is_link_up(transport) && tx_channel(transport).try_send(msg).is_ok() + match (transport, tx_channel(transport)) { + (Transport::Secure(session), _) => crate::secure_channel::try_queue(session, msg), + (_, Some(channel)) => is_link_up(transport) && channel.try_send(msg).is_ok(), + (_, None) => false, + } } /// Queues `msg` on `transport`'s TX queue, waiting for room while the link stays /// up. Dropped if the link is down, or goes down before there is room. Returns /// whether it was queued. A waiting send is woken by any receive, including the /// clear in [`set_link_up`], so it can never outlive the peer it was meant for. +/// +/// A secure channel session never waits: its queue is drained by whichever transport +/// carries it, and a stalled one must not stall the dispatcher (see [`try_send_to`]). pub(crate) async fn send_to(transport: Transport, msg: proto::DeviceToApp) -> bool { - let link = link(transport); - let channel = tx_channel(transport); + let (Some(link), Some(channel)) = (link(transport), tx_channel(transport)) else { + return try_send_to(transport, msg); + }; let generation = link.generation.load(Ordering::Relaxed); let mut msg = Some(msg); core::future::poll_fn(|cx| { diff --git a/core-interface/src/secure_channel.rs b/core-interface/src/secure_channel.rs new file mode 100644 index 0000000..6262587 --- /dev/null +++ b/core-interface/src/secure_channel.rs @@ -0,0 +1,520 @@ +//! The device side of the secure channel (docs/secure-channel.md in the contracts): the +//! end-to-end encrypted, mutually authenticated link between an enrolled client and the +//! device, independent of the transport that carries its frames. +//! +//! Transports stay dumb: they hand every frame they receive to [`process_secure_frame`] +//! (or [`on_frame`] and the dispatcher) with the [`ChannelLink`] it came on, send back the +//! reply it returns on that link, report a closed link with [`close_link`], and send what +//! [`SECURE_TX_CHANNEL`] carries after sealing it with [`seal`]. All the crypto is here. +//! +//! A session is keyed by its session ID and its link. It is RAM-only, ends after +//! [`SESSION_IDLE_TIMEOUT_MS`] idle, [`MAX_SESSION_MS`] or [`MAX_SESSION_MESSAGES`] frames, +//! when its link closes, and when its client's key leaves the registry (`client_keys.rs`). +//! Each message a session carries is stamped with its client's ID as `source_device_id`, +//! so the dispatcher applies the same rules as to that phone over BLE. + +use alloc::vec::Vec; +use core::cell::RefCell; + +use embassy_sync::blocking_mutex::Mutex; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::channel::Channel; +use prost::Message as _; +use x25519_dalek::StaticSecret; + +use crate::noise::{self, CipherState, TAG_LEN}; +use crate::proto; + +include!(concat!(env!("OUT_DIR"), "/secure_channel.rs")); + +/// Frame types (byte 0). +pub const FRAME_HANDSHAKE_INIT: u8 = 1; +pub const FRAME_HANDSHAKE_RESPONSE: u8 = 2; +pub const FRAME_TRANSPORT: u8 = 3; +pub const FRAME_UNKNOWN_SESSION: u8 = 5; +/// Frame type and session ID. +pub const FRAME_HEADER_BYTES: usize = 5; +/// Header of a transport frame: type, session ID and counter. +pub const TRANSPORT_HEADER_BYTES: usize = FRAME_HEADER_BYTES + 8; +/// Largest frame on the wire. +pub const MAX_FRAME_BYTES: usize = TRANSPORT_HEADER_BYTES + MAX_PLAINTEXT_BYTES + TAG_LEN; +/// Handshake inits whose ephemeral key the device remembers, to refuse a replay. +const RECENT_EPHEMERALS: usize = 16; + +/// A transport connection carrying frames: a TCP connection on the LAN, the session with +/// the broker for the relay. The transport picks the number and reports it closed with +/// [`close_link`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChannelLink { + pub connection: u32, +} + +/// An open session, as routing knows it (`Transport::Secure`). Stale once the session +/// ends, even if its slot is reused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SessionHandle { + slot: u8, + generation: u32, +} + +/// Messages for a session (command responses, for now), for the transport carrying it to +/// [`seal`] and send. Never waited on: a message for a session whose transport doesn't +/// drain it in time is dropped, like on a link that is down. +pub static SECURE_TX_CHANNEL: Channel< + CriticalSectionRawMutex, + (SessionHandle, proto::DeviceToApp), + 4, +> = Channel::new(); + +/// The receive side's replay window (as WireGuard's): the highest counter seen and a +/// bitmap of the [`REPLAY_WINDOW`] counters behind it. +#[derive(Default)] +struct ReplayWindow { + highest: Option, + bitmap: u64, +} + +impl ReplayWindow { + fn check(&self, counter: u64) -> bool { + match self.highest { + None => true, + Some(highest) if counter > highest => true, + Some(highest) => { + let behind = highest - counter; + behind < REPLAY_WINDOW && self.bitmap & (1 << behind) == 0 + } + } + } + + /// Records `counter`, which [`Self::check`] accepted and which decrypted. + fn accept(&mut self, counter: u64) { + match self.highest { + Some(highest) if counter <= highest => self.bitmap |= 1 << (highest - counter), + Some(highest) => { + let shift = counter - highest; + self.bitmap = if shift >= 64 { 0 } else { self.bitmap << shift }; + self.bitmap |= 1; + self.highest = Some(counter); + } + None => { + self.bitmap = 1; + self.highest = Some(counter); + } + } + } +} + +struct Session { + generation: u32, + link: ChannelLink, + session_id: [u8; 4], + client_id: Vec, + client_static: [u8; 32], + receive: CipherState, + send: CipherState, + send_counter: u64, + received: u64, + window: ReplayWindow, + created_ms: u64, + last_active_ms: u64, +} + +impl Session { + fn expired(&self, now_ms: u64) -> bool { + now_ms.saturating_sub(self.last_active_ms) >= SESSION_IDLE_TIMEOUT_MS + || now_ms.saturating_sub(self.created_ms) >= MAX_SESSION_MS + || self.received >= MAX_SESSION_MESSAGES + || self.send_counter >= MAX_SESSION_MESSAGES + } + + /// The client's key is still enrolled for the same client. + fn key_still_enrolled(&self) -> bool { + crate::client_keys::client_for_key(&self.client_static) + .is_some_and(|(id, _)| id == self.client_id) + } +} + +struct Sessions { + slots: [Option; MAX_SESSIONS], + next_generation: u32, + recent_ephemerals: [[u8; 32]; RECENT_EPHEMERALS], + next_ephemeral: usize, +} + +static SESSIONS: Mutex> = + Mutex::new(RefCell::new(Sessions { + slots: [const { None }; MAX_SESSIONS], + next_generation: 1, + recent_ephemerals: [[0; 32]; RECENT_EPHEMERALS], + next_ephemeral: 0, + })); + +impl Sessions { + fn find(&self, link: ChannelLink, session_id: &[u8; 4]) -> Option { + self.slots.iter().position(|s| { + s.as_ref() + .is_some_and(|s| s.link == link && &s.session_id == session_id) + }) + } + + fn get(&mut self, handle: SessionHandle) -> Option<&mut Session> { + self.slots + .get_mut(handle.slot as usize)? + .as_mut() + .filter(|s| s.generation == handle.generation) + } + + /// Drops the sessions that expired or whose key left the registry. + fn prune(&mut self, now_ms: u64) { + for slot in self.slots.iter_mut() { + if slot + .as_ref() + .is_some_and(|s| s.expired(now_ms) || !s.key_still_enrolled()) + { + *slot = None; + } + } + } + + /// The slot for a new session of `client_id` on `link` with `session_id`: the same + /// session ID on that link, else a free slot, else the client's session idle the + /// longest if it is at its limit, else the device's session idle the longest. + fn slot_for(&self, link: ChannelLink, session_id: &[u8; 4], client_id: &[u8]) -> usize { + if let Some(i) = self.find(link, session_id) { + return i; + } + let idlest = |only_client: bool| { + self.slots + .iter() + .enumerate() + .filter_map(|(i, s)| s.as_ref().map(|s| (i, s))) + .filter(|(_, s)| !only_client || s.client_id == client_id) + .min_by_key(|(_, s)| s.last_active_ms) + .map(|(i, _)| i) + }; + let client_sessions = self + .slots + .iter() + .flatten() + .filter(|s| s.client_id == client_id) + .count(); + if client_sessions >= MAX_SESSIONS_PER_CLIENT { + return idlest(true).unwrap_or(0); + } + self.slots + .iter() + .position(Option::is_none) + .or_else(|| idlest(false)) + .unwrap_or(0) + } +} + +/// What a received frame leads to. +#[derive(Debug, PartialEq)] +pub enum FrameOutcome { + /// Nothing to answer: a malformed, replayed or unauthenticated frame, an unknown key, + /// or a keepalive. + Drop, + /// Send these bytes back on the link: the handshake response, or an unknown session + /// frame. + Reply(Vec), + /// A message from an authenticated client, stamped with its ID as `source_device_id`, + /// for the dispatcher ([`crate::handle_secure_message`]). + Message(SessionHandle, proto::AppToDevice), +} + +/// The prologue for this device: the label, a 0x00 byte and the device key ID. +fn prologue(key_id: &str) -> Vec { + let mut out = Vec::with_capacity(PROLOGUE_LABEL.len() + 1 + key_id.len()); + out.extend_from_slice(PROLOGUE_LABEL); + out.push(0); + out.extend_from_slice(key_id.as_bytes()); + out +} + +fn unknown_session_frame(session_id: &[u8; 4]) -> Vec { + let mut out = Vec::with_capacity(FRAME_HEADER_BYTES); + out.push(FRAME_UNKNOWN_SESSION); + out.extend_from_slice(session_id); + out +} + +/// Handles one frame received on `link` at `now_ms`. +pub fn on_frame(link: ChannelLink, frame: &[u8], now_ms: u64) -> FrameOutcome { + if frame.len() < FRAME_HEADER_BYTES || frame.len() > MAX_FRAME_BYTES { + return FrameOutcome::Drop; + } + let session_id: [u8; 4] = frame[1..FRAME_HEADER_BYTES].try_into().unwrap_or_default(); + match frame[0] { + FRAME_HANDSHAKE_INIT => { + on_handshake_init(link, session_id, &frame[FRAME_HEADER_BYTES..], now_ms) + } + FRAME_TRANSPORT => on_transport(link, session_id, frame, now_ms), + _ => FrameOutcome::Drop, + } +} + +fn on_handshake_init( + link: ChannelLink, + session_id: [u8; 4], + message1: &[u8], + now_ms: u64, +) -> FrameOutcome { + let Some(ephemeral) = fresh_ephemeral() else { + return FrameOutcome::Drop; + }; + on_handshake_init_with(link, session_id, message1, now_ms, ephemeral) +} + +/// A new ephemeral key from the board's random source. +fn fresh_ephemeral() -> Option { + let fill = crate::validation::random_source()?; + let mut bytes = [0u8; 32]; + fill(&mut bytes); + let secret = StaticSecret::from(bytes); + zeroize::Zeroize::zeroize(&mut bytes); + Some(secret) +} + +fn on_handshake_init_with( + link: ChannelLink, + session_id: [u8; 4], + message1: &[u8], + now_ms: u64, + device_ephemeral: StaticSecret, +) -> FrameOutcome { + let (Some(device_static), Some(identity)) = ( + crate::identity::device_static_secret(), + crate::identity::device_identity(), + ) else { + return FrameOutcome::Drop; + }; + let mut client = None; + let result = noise::respond( + &prologue(&identity.key_id), + &device_static, + &device_ephemeral, + message1, + |client_static| { + client = crate::client_keys::client_for_key(client_static); + // Only phones for now; hubs can't enroll yet. + client + .as_ref() + .is_some_and(|(_, kind)| *kind == proto::ClientKind::Phone) + }, + ); + // An unknown key, or a handshake that failed: no answer, so it doesn't reveal which + // keys are enrolled. + let (Ok(result), Some((client_id, _))) = (result, client) else { + return FrameOutcome::Drop; + }; + SESSIONS.lock(|sessions| { + let mut sessions = sessions.borrow_mut(); + if sessions + .recent_ephemerals + .iter() + .any(|e| e == &result.client_ephemeral) + { + return FrameOutcome::Drop; + } + let i = sessions.next_ephemeral; + sessions.recent_ephemerals[i] = result.client_ephemeral; + sessions.next_ephemeral = (i + 1) % RECENT_EPHEMERALS; + + sessions.prune(now_ms); + let slot = sessions.slot_for(link, &session_id, &client_id); + let generation = sessions.next_generation; + sessions.next_generation = generation.wrapping_add(1).max(1); + sessions.slots[slot] = Some(Session { + generation, + link, + session_id, + client_id, + client_static: result.client_static, + receive: result.receive, + send: result.send, + send_counter: 0, + received: 0, + window: ReplayWindow::default(), + created_ms: now_ms, + last_active_ms: now_ms, + }); + let mut reply = Vec::with_capacity(FRAME_HEADER_BYTES + result.message2.len()); + reply.push(FRAME_HANDSHAKE_RESPONSE); + reply.extend_from_slice(&session_id); + reply.extend_from_slice(&result.message2); + FrameOutcome::Reply(reply) + }) +} + +fn on_transport(link: ChannelLink, session_id: [u8; 4], frame: &[u8], now_ms: u64) -> FrameOutcome { + if frame.len() < TRANSPORT_HEADER_BYTES + TAG_LEN { + return FrameOutcome::Drop; + } + let counter = u64::from_be_bytes( + frame[FRAME_HEADER_BYTES..TRANSPORT_HEADER_BYTES] + .try_into() + .unwrap_or_default(), + ); + let opened = SESSIONS.lock(|sessions| { + let mut sessions = sessions.borrow_mut(); + sessions.prune(now_ms); + let Some(slot) = sessions.find(link, &session_id) else { + return Err(FrameOutcome::Reply(unknown_session_frame(&session_id))); + }; + let session = sessions.slots[slot].as_mut().ok_or(FrameOutcome::Drop)?; + if !session.window.check(counter) { + return Err(FrameOutcome::Drop); + } + let plaintext = session + .receive + .decrypt_into_vec(counter, &frame[TRANSPORT_HEADER_BYTES..]) + .map_err(|_| FrameOutcome::Drop)?; + session.window.accept(counter); + session.received += 1; + session.last_active_ms = now_ms; + let handle = SessionHandle { + slot: slot as u8, + generation: session.generation, + }; + Ok((handle, session.client_id.clone(), plaintext)) + }); + let (handle, client_id, plaintext) = match opened { + Ok(opened) => opened, + Err(outcome) => return outcome, + }; + // An empty plaintext is a keepalive. + if plaintext.is_empty() { + return FrameOutcome::Drop; + } + match proto::AppToDevice::decode(plaintext.as_slice()) { + Ok(mut message) => { + // The client's authenticated identity, never what it put there. + message.source_device_id = client_id; + FrameOutcome::Message(handle, message) + } + Err(_) => FrameOutcome::Drop, + } +} + +/// Seals `message` for `session`: the transport frame and the link to send it on. `None` +/// if the session ended (or its key left the registry), or the message is too large. +pub fn seal( + session: SessionHandle, + message: &proto::DeviceToApp, + now_ms: u64, +) -> Option<(ChannelLink, Vec)> { + let len = message.encoded_len(); + if len > MAX_PLAINTEXT_BYTES { + return None; + } + // One buffer for the whole frame, encrypted in place: the ESP's heap is small. + let mut frame = Vec::with_capacity(TRANSPORT_HEADER_BYTES + len + TAG_LEN); + frame.resize(TRANSPORT_HEADER_BYTES, 0); + message.encode(&mut frame).ok()?; + SESSIONS.lock(|sessions| { + let mut sessions = sessions.borrow_mut(); + sessions.prune(now_ms); + let s = sessions.get(session)?; + let counter = s.send_counter; + s.send_counter += 1; + frame[0] = FRAME_TRANSPORT; + frame[1..FRAME_HEADER_BYTES].copy_from_slice(&s.session_id); + frame[FRAME_HEADER_BYTES..TRANSPORT_HEADER_BYTES].copy_from_slice(&counter.to_be_bytes()); + let tag = s + .send + .encrypt_in_place(counter, &mut frame[TRANSPORT_HEADER_BYTES..]); + frame.extend_from_slice(&tag); + Some((s.link, frame)) + }) +} + +/// Ends every session carried by `link`: the transport connection closed. +pub fn close_link(link: ChannelLink) { + SESSIONS.lock(|sessions| { + for slot in sessions.borrow_mut().slots.iter_mut() { + if slot.as_ref().is_some_and(|s| s.link == link) { + *slot = None; + } + } + }); +} + +/// Ends the sessions that expired, or whose client's key was removed. Frames and [`seal`] +/// do it too; a transport may call it on a timer to free the memory sooner. +pub fn expire_secure_sessions(now_ms: u64) { + SESSIONS.lock(|sessions| sessions.borrow_mut().prune(now_ms)); +} + +/// Whether `session` is still open, for routing. +pub fn is_session_open(session: SessionHandle) -> bool { + let now_ms = embassy_time::Instant::now().as_millis(); + SESSIONS.lock(|sessions| { + sessions + .borrow_mut() + .get(session) + .is_some_and(|s| !s.expired(now_ms) && s.key_still_enrolled()) + }) +} + +/// The number of open sessions (expired ones included until they are pruned). +pub fn secure_session_count() -> usize { + SESSIONS.lock(|sessions| sessions.borrow().slots.iter().flatten().count()) +} + +/// Hands one received frame to the channel and the dispatcher: returns the bytes to send +/// back on `link`, if any. The entry point for transports. +pub async fn process_secure_frame(link: ChannelLink, frame: &[u8]) -> Option> { + let now_ms = embassy_time::Instant::now().as_millis(); + match on_frame(link, frame, now_ms) { + FrameOutcome::Drop => None, + FrameOutcome::Reply(reply) => Some(reply), + FrameOutcome::Message(session, message) => { + crate::dispatch::handle_secure_message(session, message).await; + None + } + } +} + +/// Queues `msg` for `session` on [`SECURE_TX_CHANNEL`] without waiting. Dropped if the +/// session ended or the queue is full. +pub(crate) fn try_queue(session: SessionHandle, msg: proto::DeviceToApp) -> bool { + is_session_open(session) && SECURE_TX_CHANNEL.try_send((session, msg)).is_ok() +} + +/// Handles a handshake init with a given device ephemeral key, for the test vectors. For +/// tests only. +#[cfg(any(test, feature = "test-utils"))] +pub fn on_handshake_init_for_tests( + link: ChannelLink, + frame: &[u8], + now_ms: u64, + device_ephemeral: [u8; 32], +) -> FrameOutcome { + if frame.len() < FRAME_HEADER_BYTES || frame[0] != FRAME_HANDSHAKE_INIT { + return FrameOutcome::Drop; + } + let session_id: [u8; 4] = frame[1..FRAME_HEADER_BYTES].try_into().unwrap_or_default(); + on_handshake_init_with( + link, + session_id, + &frame[FRAME_HEADER_BYTES..], + now_ms, + StaticSecret::from(device_ephemeral), + ) +} + +/// Ends every session and forgets the handshakes seen. For tests only. +pub fn reset_secure_channel_for_tests() { + SESSIONS.lock(|sessions| { + let mut sessions = sessions.borrow_mut(); + sessions.slots = [const { None }; MAX_SESSIONS]; + sessions.recent_ephemerals = [[0; 32]; RECENT_EPHEMERALS]; + sessions.next_ephemeral = 0; + }); + while SECURE_TX_CHANNEL.try_receive().is_ok() {} +} + +/// Bytes of RAM one session takes in the table (its client ID is on the heap, ~10 bytes +/// more). For the heap budget. +pub const SESSION_BYTES: usize = core::mem::size_of::>(); diff --git a/core-interface/src/types.rs b/core-interface/src/types.rs index 2be7c2e..bed243c 100644 --- a/core-interface/src/types.rs +++ b/core-interface/src/types.rs @@ -4,10 +4,13 @@ use alloc::vec::Vec; /// Identifies which transport protocol an inbound command arrived on, allowing /// the vehicle task to route the response back to the same transport. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Transport { Ble, Mqtt, + /// A session of the secure channel, whichever transport carries its frames (see + /// `secure_channel.rs`). Its messages go to `SECURE_TX_CHANNEL`. + Secure(crate::secure_channel::SessionHandle), } /// A decoded inbound command payload forwarded to a vehicle task. @@ -16,7 +19,8 @@ pub struct InboundCommand { pub message_id: u64, /// Which transport delivered this command. pub transport: Transport, - /// Optional transport-level device identifier (BLE source device). + /// The transport-verified sender: the BLE source device, or the secure channel + /// client's ID (a phone's `ble:` ID). Empty over MQTT. pub source_device_id: Vec, /// Raw encoded bytes of the vehicle-specific command proto message. pub bytes: Vec, diff --git a/core-interface/tests/secure_channel.rs b/core-interface/tests/secure_channel.rs new file mode 100644 index 0000000..912bf3f --- /dev/null +++ b/core-interface/tests/secure_channel.rs @@ -0,0 +1,672 @@ +//! The secure channel's device side (docs/architecture.md, "Secure channel"): handshakes +//! with enrolled clients only, frames, the replay window, sessions and their expiry, and +//! messages authorized like the same phone over BLE. + +use core_interface::{ + ADVANCED_CMD_CHANNEL, BASIC_CMD_CHANNEL, BLE_TX_CHANNEL, ChannelLink, FrameOutcome, Initiator, + InitiatorSession, MAX_SESSIONS, MAX_SESSIONS_PER_CLIENT, REPLAY_WINDOW, SECURE_TX_CHANNEL, + SESSION_IDLE_TIMEOUT_MS, SYSTEM_COMMAND_CHANNEL, SessionHandle, Transport, add_paired_phone, + approve_can_read_write, clear_paired_phones, close_link, confirm_car_fingerprint, + confirm_car_identity, device_identity, handle_ble_message, handle_secure_message, init, + on_frame, on_handshake_init_for_tests, proto, remove_paired_phone, reset_can_access_for_tests, + reset_client_keys_for_tests, reset_device_identity_for_tests, reset_phone_trust_for_tests, + reset_phone_validation_for_tests, reset_secure_channel_for_tests, restore_device_identity, + revoke_car_identity, seal, secure_session_count, set_can_dev_write_unlocked, set_can_read_only, + set_random_source, validate_phone_for_tests, +}; +use prost::Message as _; +use proto::app_to_device::Payload; + +const PLATFORM_ID: u32 = 0xDEAD_BEEF; +const CAR_A: &[u8] = b"KNAC381AAP5000001"; +const CAR_B: &[u8] = b"KNAC381AAP5000002"; +const OWNER: &[u8] = b"ble:\x01\x02\x03\x04\x05\x06"; +const SECOND: &[u8] = b"ble:\x0A\x0B\x0C\x0D\x0E\x0F"; +const OWNER_STATIC: [u8; 32] = [0x41; 32]; +const SECOND_STATIC: [u8; 32] = [0x42; 32]; +const LAN: ChannelLink = ChannelLink { connection: 1 }; +const RELAY: ChannelLink = ChannelLink { connection: 2 }; + +fn counting_random(buf: &mut [u8]) { + static NEXT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(1); + for b in buf { + *b = NEXT.fetch_add(7, std::sync::atomic::Ordering::Relaxed); + } +} + +fn public(secret: [u8; 32]) -> [u8; 32] { + x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(secret)).to_bytes() +} + +fn next_id() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +fn ephemeral() -> [u8; 32] { + let mut e = [0u8; 32]; + // Clamping clears the low bits of byte 0, so keep the counter out of it. + e[1..9].copy_from_slice(&next_id().to_le_bytes()); + e[31] = 0x55; + e +} + +fn drain() { + while BLE_TX_CHANNEL.try_receive().is_ok() {} + while SECURE_TX_CHANNEL.try_receive().is_ok() {} + while BASIC_CMD_CHANNEL.try_receive().is_ok() {} + while ADVANCED_CMD_CHANNEL.try_receive().is_ok() {} + while SYSTEM_COMMAND_CHANNEL.try_receive().is_ok() {} +} + +fn enroll(phone: &[u8], client_static: [u8; 32]) { + let msg = proto::AppToDevice { + message_id: next_id(), + platform_id: PLATFORM_ID, + source_device_id: phone.to_vec(), + payload: Some(Payload::SystemCommand(proto::SystemCommand { + action: Some(proto::system_command::Action::EnrollClientKey( + proto::EnrollClientKeyCommand { + public_key: public(client_static).to_vec(), + kind: proto::ClientKind::Phone as i32, + label: "test".into(), + }, + )), + })), + }; + embassy_futures::block_on(handle_ble_message(msg)); + let resp = BLE_TX_CHANNEL.try_receive().unwrap(); + let Some(proto::device_to_app::Payload::CommandResponse(resp)) = resp.payload else { + panic!("no response"); + }; + assert!(resp.success, "{}", resp.error_message); +} + +/// Car A identified, approved and read-write, both phones bonded, the owner validated and +/// both enrolled. +fn boot() { + init(PLATFORM_ID); + revoke_car_identity(); + reset_can_access_for_tests(); + embassy_futures::block_on(clear_paired_phones()); + reset_phone_trust_for_tests(); + reset_phone_validation_for_tests(); + reset_client_keys_for_tests(); + reset_device_identity_for_tests(); + reset_secure_channel_for_tests(); + set_random_source(counting_random); + assert!(restore_device_identity(&[]).is_some()); + core_interface::set_link_up(Transport::Ble, true); + core_interface::reset_recent_commands_for_tests(); + embassy_futures::block_on(core_interface::reset_ble_controller_lease_for_tests()); + drain(); + for phone in [OWNER, SECOND] { + embassy_futures::block_on(add_paired_phone(phone)); + } + confirm_car_identity(); + assert!(confirm_car_fingerprint(CAR_A)); + approve_can_read_write().unwrap(); + set_can_dev_write_unlocked(true).unwrap(); + assert!(!set_can_read_only(false)); + assert!(validate_phone_for_tests(OWNER)); + assert!(validate_phone_for_tests(SECOND)); + enroll(OWNER, OWNER_STATIC); + enroll(SECOND, SECOND_STATIC); + // Approving another car ends every validation but keeps the keys. Back in car A, only + // the owner validates again: the second phone has a key but no validation. + assert!(confirm_car_fingerprint(CAR_B)); + approve_can_read_write().unwrap(); + assert!(confirm_car_fingerprint(CAR_A)); + approve_can_read_write().unwrap(); + assert!(!set_can_read_only(false)); + assert!(validate_phone_for_tests(OWNER)); + drain(); +} + +fn prologue() -> Vec { + let mut p = b"opencar/secure/1\0".to_vec(); + p.extend_from_slice(device_identity().unwrap().key_id.as_bytes()); + p +} + +struct Client { + session: InitiatorSession, + session_id: [u8; 4], + link: ChannelLink, + counter: u64, +} + +fn init_frame(client_static: [u8; 32], session_id: [u8; 4]) -> (Initiator, Vec) { + let device_key: [u8; 32] = device_identity().unwrap().public_key.try_into().unwrap(); + let (initiator, message1) = + Initiator::start(&prologue(), client_static, ephemeral(), device_key).unwrap(); + let mut frame = vec![1]; + frame.extend_from_slice(&session_id); + frame.extend_from_slice(&message1); + (initiator, frame) +} + +fn connect_at(client_static: [u8; 32], link: ChannelLink, now_ms: u64) -> Client { + let session_id = (next_id() as u32).to_be_bytes(); + let (initiator, frame) = init_frame(client_static, session_id); + let FrameOutcome::Reply(reply) = on_frame(link, &frame, now_ms) else { + panic!("no handshake response"); + }; + assert_eq!(reply[0], 2); + assert_eq!(reply[1..5], session_id); + Client { + session: initiator.finish(&reply[5..]).unwrap(), + session_id, + link, + counter: 0, + } +} + +fn connect(client_static: [u8; 32], link: ChannelLink) -> Client { + connect_at(client_static, link, 0) +} + +impl Client { + fn frame_at(&self, counter: u64, plaintext: &[u8]) -> Vec { + let mut frame = vec![3]; + frame.extend_from_slice(&self.session_id); + frame.extend_from_slice(&counter.to_be_bytes()); + frame.extend_from_slice(&self.session.encrypt(counter, plaintext)); + frame + } + + fn frame(&mut self, msg: &proto::AppToDevice) -> Vec { + let frame = self.frame_at(self.counter, &msg.encode_to_vec()); + self.counter += 1; + frame + } + + fn send_at(&mut self, msg: &proto::AppToDevice, now_ms: u64) -> FrameOutcome { + let frame = self.frame(msg); + on_frame(self.link, &frame, now_ms) + } + + fn send(&mut self, msg: &proto::AppToDevice) -> FrameOutcome { + self.send_at(msg, 1) + } + + fn open(&self, frame: &[u8]) -> proto::DeviceToApp { + assert_eq!(frame[0], 3); + assert_eq!(frame[1..5], self.session_id); + let counter = u64::from_be_bytes(frame[5..13].try_into().unwrap()); + let plaintext = self.session.decrypt(counter, &frame[13..]).unwrap(); + proto::DeviceToApp::decode(plaintext.as_slice()).unwrap() + } +} + +fn basic(source: &[u8]) -> proto::AppToDevice { + proto::AppToDevice { + message_id: next_id(), + platform_id: PLATFORM_ID, + source_device_id: source.to_vec(), + payload: Some(Payload::BasicCommandBytes(vec![0x08, 0x01])), + } +} + +fn message(outcome: FrameOutcome) -> (SessionHandle, proto::AppToDevice) { + match outcome { + FrameOutcome::Message(session, msg) => (session, msg), + other => panic!("expected a message, got {other:?}"), + } +} + +/// The response the dispatcher queued for the session, opened by the client. +fn secure_response(client: &Client) -> proto::CommandResponse { + let (session, msg) = SECURE_TX_CHANNEL.try_receive().expect("no response queued"); + let (link, frame) = seal(session, &msg, 2).expect("session closed"); + assert_eq!(link, client.link); + match client.open(&frame).payload { + Some(proto::device_to_app::Payload::CommandResponse(r)) => r, + other => panic!("not a response: {other:?}"), + } +} + +// ── Handshake ───────────────────────────────────────────────────────────────── + +#[test] +fn the_device_handshake_matches_the_contract_vectors() { + boot(); + let v: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../contracts/docs/secure-channel-vectors.json" + )) + .unwrap(), + ) + .unwrap(); + let hex = |k: &str| -> Vec { + let s = v[k].as_str().unwrap(); + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() + }; + let mut stored = vec![1]; + stored.extend(hex("device_static_private")); + assert_eq!(restore_device_identity(&stored), None); + assert_eq!( + device_identity().unwrap().key_id, + v["device_key_id"].as_str().unwrap() + ); + let client_static: [u8; 32] = hex("client_static_private").try_into().unwrap(); + enroll(OWNER, client_static); + let outcome = on_handshake_init_for_tests( + LAN, + &hex("handshake_init_frame"), + 0, + hex("device_ephemeral_private").try_into().unwrap(), + ); + assert_eq!( + outcome, + FrameOutcome::Reply(hex("handshake_response_frame")) + ); + // A transport frame of the vectors decrypts (it isn't an AppToDevice, so it is dropped + // after decryption), and the unknown session frame matches. + let frame = hex("unknown_session_frame"); + let mut transport = vec![3]; + transport.extend_from_slice(&frame[1..5]); + transport.extend_from_slice(&[0; 8]); + transport.extend_from_slice(&[0; 16]); + assert_eq!(on_frame(RELAY, &transport, 0), FrameOutcome::Reply(frame)); +} + +#[test] +fn an_unknown_client_key_gets_no_answer() { + boot(); + let (_, frame) = init_frame([0x77; 32], [1, 2, 3, 4]); + assert_eq!(on_frame(LAN, &frame, 0), FrameOutcome::Drop); + assert_eq!(secure_session_count(), 0); +} + +#[test] +fn a_replayed_handshake_init_is_refused() { + boot(); + let (_, frame) = init_frame(OWNER_STATIC, [1, 2, 3, 4]); + assert!(matches!(on_frame(LAN, &frame, 0), FrameOutcome::Reply(_))); + assert_eq!(on_frame(LAN, &frame, 0), FrameOutcome::Drop); + assert_eq!(on_frame(RELAY, &frame, 0), FrameOutcome::Drop); + assert_eq!(secure_session_count(), 1); +} + +#[test] +fn malformed_frames_are_dropped() { + boot(); + let mut client = connect(OWNER_STATIC, LAN); + for frame in [vec![], vec![3, 0, 0], vec![9; 40], vec![2; 53], vec![4; 40]] { + assert_eq!(on_frame(LAN, &frame, 1), FrameOutcome::Drop, "{frame:?}"); + } + let mut tampered = client.frame(&basic(OWNER)); + *tampered.last_mut().unwrap() ^= 1; + assert_eq!(on_frame(LAN, &tampered, 1), FrameOutcome::Drop); +} + +// ── Messages and authorization ──────────────────────────────────────────────── + +#[test] +fn a_validated_phone_command_reaches_the_vehicle_stamped_and_authorized() { + boot(); + let mut client = connect(OWNER_STATIC, LAN); + // Whatever the client claims, the session's client is the source. + let msg = basic(SECOND); + let (session, stamped) = message(client.send(&msg)); + assert_eq!(stamped.source_device_id, OWNER); + embassy_futures::block_on(handle_secure_message(session, stamped)); + let cmd = BASIC_CMD_CHANNEL + .try_receive() + .expect("command not dispatched"); + assert_eq!(cmd.source_device_id, OWNER); + assert_eq!(cmd.message_id, msg.message_id); + assert_eq!(cmd.transport, Transport::Secure(session)); + assert!(cmd.authorization.is_some()); +} + +#[test] +fn advanced_commands_are_allowed_through_a_session() { + boot(); + let mut client = connect(OWNER_STATIC, RELAY); + let mut msg = basic(OWNER); + msg.payload = Some(Payload::AdvancedCommandBytes(vec![0x08, 0x02])); + let (session, stamped) = message(client.send(&msg)); + embassy_futures::block_on(handle_secure_message(session, stamped)); + assert!(ADVANCED_CMD_CHANNEL.try_receive().is_ok()); +} + +#[test] +fn a_phone_that_is_not_validated_is_refused_through_the_session() { + boot(); + assert!(!core_interface::is_phone_validated(SECOND)); + let mut client = connect(SECOND_STATIC, LAN); + let (session, stamped) = message(client.send(&basic(SECOND))); + embassy_futures::block_on(handle_secure_message(session, stamped)); + assert!(BASIC_CMD_CHANNEL.try_receive().is_err()); + let resp = secure_response(&client); + assert_eq!( + resp.status_code, + proto::CommandStatusCode::RejectedNotValidated as i32 + ); +} + +#[test] +fn a_read_only_device_refuses_with_the_reason() { + boot(); + set_can_dev_write_unlocked(false).unwrap(); + let mut client = connect(OWNER_STATIC, LAN); + let (session, stamped) = message(client.send(&basic(OWNER))); + embassy_futures::block_on(handle_secure_message(session, stamped)); + assert!(BASIC_CMD_CHANNEL.try_receive().is_err()); + let resp = secure_response(&client); + assert_eq!( + resp.status_code, + proto::CommandStatusCode::RejectedUnavailable as i32 + ); +} + +#[test] +fn system_commands_are_dropped() { + boot(); + let mut client = connect(OWNER_STATIC, LAN); + for action in [ + proto::system_command::Action::RestartCommand(Default::default()), + proto::system_command::Action::ClearPairedPhones(Default::default()), + proto::system_command::Action::SetCanReadWriteApproval( + proto::SetCanReadWriteApprovalCommand { approved: false }, + ), + proto::system_command::Action::EnrollClientKey(Default::default()), + ] { + let mut msg = basic(OWNER); + msg.payload = Some(Payload::SystemCommand(proto::SystemCommand { + action: Some(action), + })); + let (session, stamped) = message(client.send(&msg)); + embassy_futures::block_on(handle_secure_message(session, stamped)); + } + assert!(SYSTEM_COMMAND_CHANNEL.try_receive().is_err()); + assert!(SECURE_TX_CHANNEL.try_receive().is_err()); + assert_eq!( + embassy_futures::block_on(core_interface::paired_phone_count()), + 2 + ); + assert!(!core_interface::is_can_read_only()); +} + +#[test] +fn a_command_resent_on_ble_after_the_channel_is_a_duplicate() { + boot(); + let mut client = connect(OWNER_STATIC, LAN); + let msg = basic(OWNER); + let (session, stamped) = message(client.send(&msg)); + embassy_futures::block_on(handle_secure_message(session, stamped)); + assert!(BASIC_CMD_CHANNEL.try_receive().is_ok()); + embassy_futures::block_on(handle_ble_message(msg)); + assert!(BASIC_CMD_CHANNEL.try_receive().is_err()); + assert!(BLE_TX_CHANNEL.try_receive().is_err()); +} + +#[test] +fn responses_are_sealed_for_the_session_only() { + boot(); + let mut client = connect(OWNER_STATIC, LAN); + let (session, _) = message(client.send(&basic(OWNER))); + let msg = proto::DeviceToApp { + timestamp_ms: 7, + platform_id: PLATFORM_ID, + payload: None, + }; + let (link, first) = seal(session, &msg, 2).unwrap(); + assert_eq!(link, LAN); + let (_, second) = seal(session, &msg, 2).unwrap(); + // Each frame has its own counter. + assert_eq!(first[5..13], 0u64.to_be_bytes()); + assert_eq!(second[5..13], 1u64.to_be_bytes()); + assert_eq!(client.open(&first), msg); + assert_eq!(client.open(&second), msg); + // Another client's session can't read it. + let other = connect(SECOND_STATIC, RELAY); + let counter = u64::from_be_bytes(first[5..13].try_into().unwrap()); + assert!(other.session.decrypt(counter, &first[13..]).is_err()); + // Too large for one frame. + let huge = proto::DeviceToApp { + timestamp_ms: 0, + platform_id: PLATFORM_ID, + payload: Some(proto::device_to_app::Payload::CommandResponse( + proto::CommandResponse { + error_message: "x".repeat(core_interface::MAX_PLAINTEXT_BYTES), + ..Default::default() + }, + )), + }; + assert_eq!(seal(session, &huge, 2), None); +} + +// ── Replay window ───────────────────────────────────────────────────────────── + +#[test] +fn duplicated_and_old_frames_are_dropped() { + boot(); + let client = connect(OWNER_STATIC, LAN); + let msg = |id| proto::AppToDevice { + message_id: id, + platform_id: PLATFORM_ID, + source_device_id: vec![], + payload: Some(Payload::Heartbeat(Default::default())), + }; + let frame5 = client.frame_at(5, &msg(5).encode_to_vec()); + assert!(matches!( + on_frame(LAN, &frame5, 1), + FrameOutcome::Message(..) + )); + assert_eq!(on_frame(LAN, &frame5, 1), FrameOutcome::Drop, "duplicate"); + // Out of order within the window: accepted once. + let frame2 = client.frame_at(2, &msg(2).encode_to_vec()); + assert!(matches!( + on_frame(LAN, &frame2, 1), + FrameOutcome::Message(..) + )); + assert_eq!(on_frame(LAN, &frame2, 1), FrameOutcome::Drop); + // Far ahead, then one that falls outside the window behind it. + let far = 5 + REPLAY_WINDOW + 10; + let frame_far = client.frame_at(far, &msg(far).encode_to_vec()); + assert!(matches!( + on_frame(LAN, &frame_far, 1), + FrameOutcome::Message(..) + )); + let frame6 = client.frame_at(6, &msg(6).encode_to_vec()); + assert_eq!( + on_frame(LAN, &frame6, 1), + FrameOutcome::Drop, + "outside the window" + ); + let inside = far - REPLAY_WINDOW + 1; + let frame_inside = client.frame_at(inside, &msg(inside).encode_to_vec()); + assert!(matches!( + on_frame(LAN, &frame_inside, 1), + FrameOutcome::Message(..) + )); +} + +#[test] +fn an_empty_plaintext_is_a_keepalive() { + boot(); + let client = connect(OWNER_STATIC, LAN); + let keepalive = client.frame_at(0, &[]); + assert_eq!( + on_frame(LAN, &keepalive, SESSION_IDLE_TIMEOUT_MS - 1), + FrameOutcome::Drop + ); + // It kept the session alive past the first idle timeout. + let late = client.frame_at(1, &basic(OWNER).encode_to_vec()); + assert!(matches!( + on_frame(LAN, &late, 2 * SESSION_IDLE_TIMEOUT_MS - 2), + FrameOutcome::Message(..) + )); +} + +// ── Sessions ────────────────────────────────────────────────────────────────── + +fn unknown_session(client: &Client) -> FrameOutcome { + let mut frame = vec![5]; + frame.extend_from_slice(&client.session_id); + FrameOutcome::Reply(frame) +} + +#[test] +fn a_frame_for_an_unknown_session_is_answered_with_unknown_session() { + boot(); + let mut client = connect(OWNER_STATIC, LAN); + // The session belongs to its link. + let frame = client.frame(&basic(OWNER)); + assert_eq!(on_frame(RELAY, &frame, 1), unknown_session(&client)); + // The device restarted. + reset_secure_channel_for_tests(); + assert_eq!(client.send(&basic(OWNER)), unknown_session(&client)); +} + +#[test] +fn an_idle_session_expires() { + boot(); + let mut client = connect(OWNER_STATIC, LAN); + assert!(matches!( + client.send_at(&basic(OWNER), SESSION_IDLE_TIMEOUT_MS - 1), + FrameOutcome::Message(..) + )); + assert_eq!( + client.send_at(&basic(OWNER), 2 * SESSION_IDLE_TIMEOUT_MS), + unknown_session(&client) + ); +} + +#[test] +fn a_session_ends_after_its_lifetime() { + boot(); + let mut client = connect(OWNER_STATIC, LAN); + let mut now = 0; + while now + SESSION_IDLE_TIMEOUT_MS / 2 < core_interface::MAX_SESSION_MS { + now += SESSION_IDLE_TIMEOUT_MS / 2; + assert!(matches!( + client.send_at(&basic(OWNER), now), + FrameOutcome::Message(..) + )); + } + assert_eq!( + client.send_at(&basic(OWNER), core_interface::MAX_SESSION_MS), + unknown_session(&client) + ); +} + +#[test] +fn removing_the_key_ends_the_session() { + boot(); + let mut client = connect(OWNER_STATIC, LAN); + let (session, _) = message(client.send(&basic(OWNER))); + assert!(core_interface::is_session_open(session)); + embassy_futures::block_on(remove_paired_phone(OWNER)); + assert!(!core_interface::is_session_open(session)); + assert_eq!(client.send(&basic(OWNER)), unknown_session(&client)); + assert_eq!(seal(session, &Default::default(), 1), None); + // And it can't handshake again. + let (_, frame) = init_frame(OWNER_STATIC, [9, 9, 9, 9]); + assert_eq!(on_frame(LAN, &frame, 1), FrameOutcome::Drop); +} + +#[test] +fn closing_the_link_ends_its_sessions() { + boot(); + let mut lan = connect(OWNER_STATIC, LAN); + let mut relay = connect(OWNER_STATIC, RELAY); + close_link(LAN); + assert_eq!(lan.send(&basic(OWNER)), unknown_session(&lan)); + assert!(matches!( + relay.send(&basic(OWNER)), + FrameOutcome::Message(..) + )); +} + +#[test] +fn a_client_at_its_limit_replaces_its_idlest_session() { + boot(); + let mut first = connect_at(OWNER_STATIC, LAN, 0); + let mut second = connect_at(OWNER_STATIC, RELAY, 10); + let other = connect_at(SECOND_STATIC, LAN, 20); + assert_eq!(MAX_SESSIONS_PER_CLIENT, 2); + let mut third = connect_at(OWNER_STATIC, ChannelLink { connection: 3 }, 30); + assert_eq!(first.send_at(&basic(OWNER), 31), unknown_session(&first)); + assert!(matches!( + second.send_at(&basic(OWNER), 31), + FrameOutcome::Message(..) + )); + assert!(matches!( + third.send_at(&basic(OWNER), 31), + FrameOutcome::Message(..) + )); + assert_eq!(secure_session_count(), 3); + let _ = other; +} + +#[test] +fn a_full_table_replaces_the_idlest_session() { + boot(); + assert_eq!(MAX_SESSIONS, 4); + let mut clients = vec![ + connect_at(OWNER_STATIC, ChannelLink { connection: 10 }, 0), + connect_at(SECOND_STATIC, ChannelLink { connection: 11 }, 1), + connect_at(OWNER_STATIC, ChannelLink { connection: 12 }, 2), + connect_at(SECOND_STATIC, ChannelLink { connection: 13 }, 3), + ]; + // The first one is the idlest unless used: use it. + assert!(matches!( + clients[0].send_at(&basic(OWNER), 4), + FrameOutcome::Message(..) + )); + // The owner is at its limit: its idlest (connection 12) is replaced. + let _new = connect_at(OWNER_STATIC, ChannelLink { connection: 14 }, 5); + assert_eq!( + clients[2].send_at(&basic(OWNER), 6), + unknown_session(&clients[2]) + ); + assert!(matches!( + clients[0].send_at(&basic(OWNER), 6), + FrameOutcome::Message(..) + )); + assert!(matches!( + clients[1].send_at(&basic(SECOND), 6), + FrameOutcome::Message(..) + )); + assert_eq!(secure_session_count(), 4); +} + +#[test] +fn the_same_session_id_on_a_link_is_replaced() { + boot(); + let a = connect(OWNER_STATIC, LAN); + let (initiator, frame) = init_frame(OWNER_STATIC, a.session_id); + let FrameOutcome::Reply(reply) = on_frame(LAN, &frame, 1) else { + panic!() + }; + let mut b = Client { + session: initiator.finish(&reply[5..]).unwrap(), + session_id: a.session_id, + link: LAN, + counter: 0, + }; + assert_eq!(secure_session_count(), 1); + assert!(matches!(b.send(&basic(OWNER)), FrameOutcome::Message(..))); + let old = a.frame_at(0, &basic(OWNER).encode_to_vec()); + assert_eq!( + on_frame(LAN, &old, 1), + FrameOutcome::Drop, + "the old keys no longer work" + ); +} + +#[test] +fn a_session_and_a_handshake_fit_the_esp_heap() { + // A session's table entry; its client ID adds ~10 bytes on the heap. Printed for the + // heap budget (docs/architecture.md). + println!("session: {} bytes", core_interface::SESSION_BYTES); + assert!(core_interface::SESSION_BYTES <= 512); +} diff --git a/docs/architecture.md b/docs/architecture.md index 9ad2f2b..e4f425c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -65,9 +65,10 @@ The actual binary entry point. Generated fresh by `xtask` before every build fro | `MQTT_TX_CHANNEL` | core → board | `DeviceToApp` | Responses and system state to the MQTT driver; only filled while the session is up | | `MQTT_STATE_TX` | core → board | `DeviceToApp` | Newest vehicle state for MQTT, basic only and throttled (a `Signal`); sent after `MQTT_TX_CHANNEL` | | `SYSTEM_COMMAND_CHANNEL` | core → board | `SystemCommand` | BLE only; board handles restart (already answered by core, see [BLE](ble.md#restart)) and phone removal (the CAN read-write commands, `ListPairedPhones` and phone validation are handled in core) | -| `BASIC_CMD_CHANNEL` | core → vehicle | `InboundCommand` | From BLE (MQTT is rejected until authenticated) | -| `ADVANCED_CMD_CHANNEL` | core → vehicle | `InboundCommand` | BLE only | +| `BASIC_CMD_CHANNEL` | core → vehicle | `InboundCommand` | From BLE and the secure channel (plain MQTT is rejected) | +| `ADVANCED_CMD_CHANNEL` | core → vehicle | `InboundCommand` | From BLE and the secure channel | | `CMD_RESP_CHANNEL` | vehicle → core | `(Transport, CommandResponse)` | Transport tag routes response back | +| `SECURE_TX_CHANNEL` | core → transport | `(SessionHandle, DeviceToApp)` | Responses for a [secure channel](#secure-channel) session, for the transport carrying it to `seal`; never waited on | | `VEHICLE_STATE_CHANNEL` | vehicle → core | `VehicleStatePayload` | BLE gets full; MQTT gets basic only | | `CAN_RX_CHANNEL` | board → vehicle | `CanFrame` | Hardware-received CAN frame | | `CAN_TX_CHANNELS[bus_id]` | vehicle → board | `CanTxFrame` | Frame to transmit on that CAN bus, with its TX class (one queue per bus; see [CAN bus](can.md#tx-classes)) | @@ -85,14 +86,26 @@ A response goes back on the transport its command came in on. If that transport * A response the vehicle is still working on when its phone leaves isn't tied to that connection: if another phone connects before it is sent, that phone gets it. `CMD_RESP_CHANNEL` only carries the `Transport`. ### Duplicate commands -The app may resend a command with the same `message_id` after switching transport or reconnecting, and the broker redelivers an MQTT QoS 1 message it didn't see acknowledged. Both dispatchers drop a command whose (source, `message_id`) pair they saw in the last `DEDUPE_WINDOW_MS` (5 min, at most `DEDUPE_CAPACITY` = 16 entries, oldest forgotten first), without answering it (`dedupe.rs`). Heartbeats aren't commands and aren't remembered; `message_id` 0 (the proto default) never counts as a duplicate. The source is the transport-verified one (the BLE address). MQTT has none until its commands are authenticated (contracts#8, firmware#16), so MQTT commands are keyed by `message_id` alone and only match each other: a resend from BLE to MQTT isn't caught yet. +The app may resend a command with the same `message_id` after switching transport or reconnecting, and the broker redelivers an MQTT QoS 1 message it didn't see acknowledged. Both dispatchers drop a command whose (source, `message_id`) pair they saw in the last `DEDUPE_WINDOW_MS` (5 min, at most `DEDUPE_CAPACITY` = 16 entries, oldest forgotten first), without answering it (`dedupe.rs`). Heartbeats aren't commands and aren't remembered; `message_id` 0 (the proto default) never counts as a duplicate. The source is the transport-verified one: the BLE address, or a secure channel session's client ID, which for a phone is the same `ble:` ID, so a resend from BLE to the secure channel (or back) is caught. Plain MQTT has none, so its commands are keyed by `message_id` alone and only match each other. **`platform_id`** is a CRC32 of the proto package name (e.g. `0xF7544D7E` for `opencar.cars.virtual_car.v1`), pre-computed and stored in `contracts/.../meta.toml`. xtask injects it as a compile-time constant into `.app_build/src/main.rs`. `core_interface::init(platform_id)` stores it in an `AtomicU32`; the dispatcher tasks validate every inbound message against it and silently drop mismatches. **Read-only devices:** while the device is CAN read-only, both dispatchers answer `BasicCommandBytes` and `AdvancedCommandBytes` with a failed `CommandResponse` giving the reason instead of routing them (see [CAN](can.md#read-write-policy)). Over BLE they are then refused from a phone that isn't validated in the car (`REJECTED_NOT_VALIDATED`, see [BLE](ble.md#phone-trust)). +**Secure channel:** see [Secure channel](#secure-channel): vehicle commands get the same checks as over BLE for the session's client, and system commands are dropped. + **MQTT restrictions:** `SystemCommand` and `AdvancedCommandBytes` are restricted to BLE and silently dropped from MQTT. `BasicCommandBytes` are **rejected for now** as well: MQTT commands aren't authenticated (anyone the broker lets publish to the command topic, with credentials or a certificate that ship in the app, could send or replay one; TLS protects the link, not the commands), so `handle_mqtt_message` answers them with a failed `CommandResponse` saying so and never queues them to `BASIC_CMD_CHANNEL`. The gate is the `MQTT_COMMANDS_AUTHENTICATED` constant in `dispatch.rs`; remove it once MQTT commands are authenticated (contracts#8, firmware#16). State updates and heartbeats over MQTT are unaffected. +### Secure channel +The device side of the end-to-end encrypted channel ([contracts `docs/secure-channel.md`](https://github.com/OpenCarControls/contracts/blob/main/docs/secure-channel.md)): `Noise_IK_25519_ChaChaPoly_BLAKE2s` between an enrolled client and the device, the same on every transport that carries its frames. `noise.rs` implements the handshake (the device is the responder) and the cipher states from the Noise specification on `x25519-dalek`, `chacha20poly1305` and `blake2`, and its tests pass the contracts' `secure-channel-vectors.json` byte for byte. (`clatter`, a `no_std` Noise crate, was considered; the IK pattern alone is short, and doing it directly gives the explicit nonces and the fixed ephemeral keys the vectors need without its generic layers.) Its constants come from `[secure_channel]` in `transport.toml`, generated by the build script. + +* **Transports stay dumb.** A transport hands each received frame to `process_secure_frame(link, bytes)` with the `ChannelLink` (a connection number it picks) it came on, sends back the reply it returns on that link, reports a closed connection with `close_link`, and drains `SECURE_TX_CHANNEL`, sealing each message with `seal(session, msg)` (which also gives the link). All the crypto is in `core-interface`. No transport uses it yet: the LAN (firmware#120) and MQTT (firmware#122) transports plug into it. +* **Handshake.** A valid handshake init from a key in the registry (`client_for_key`, [BLE](ble.md#client-keys)) creates a session and is answered with the handshake response. An unknown key, or a failed handshake, gets no answer, and an init whose ephemeral key was seen recently is refused (a replay). The ephemeral key comes from the board's random source; without it, or without a device identity, the channel is off. +* **Sessions** (`secure_channel.rs`) are RAM-only, keyed by session ID and link, at most `MAX_SESSIONS` (4) and `MAX_SESSIONS_PER_CLIENT` (2); a new one replaces the client's idlest session at its limit, else the idlest one. A session ends after `SESSION_IDLE_TIMEOUT_MS` without a valid frame, `MAX_SESSION_MS` after its handshake, after `MAX_SESSION_MESSAGES` frames one way, when its link closes, and when its client's key leaves the registry (checked on every frame and seal). A transport frame for a session the device doesn't have on that link is answered with an unknown session frame. +* **Frames.** Transport frames carry an explicit counter (the nonce); a 64-wide replay window drops duplicates and counters too far behind, and is only updated once a frame decrypts. An empty plaintext is a keepalive. +* **Identity and authorization.** Each `AppToDevice` a session carries is stamped with its client's ID (a phone's `ble:` ID) as `source_device_id`, whatever the client put there, and goes to `handle_secure_message`: basic and advanced vehicle commands get the same checks as that phone over BLE (read-only, validated for this car, controller lease) and a `CommandAuthorization`, and their response comes back through the session (`Transport::Secure(SessionHandle)`, routed to `SECURE_TX_CHANNEL`). System commands are dropped: they stay BLE-only. The `MQTT_COMMANDS_AUTHENTICATED` gate only applies to plain MQTT, until MQTT carries only channel frames (firmware#122). +* **Memory.** A session's table entry is about 200 bytes (`SESSION_BYTES`, in a static, not the heap). A handshake only allocates a few small buffers. `seal` builds a frame in one buffer, encrypted in place, and an inbound frame is decrypted into one buffer, so a message costs about its own size on the heap (up to 4 KB for the largest). + ### Channel flow ``` diff --git a/docs/ble.md b/docs/ble.md index 4427e07..88d5dd5 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -74,7 +74,7 @@ Pairing is Just Works, so bonding during a pairing window doesn't prove the phon | Approved | device + car (`CarDigest`) | The platform's own frames that don't act on the car ([TX classes](can.md#tx-classes)) | The owner's CAN read-write approval, given once at first setup | | Validated | phone + car | Vehicle commands (every basic and advanced command) | An in-car action the vehicle defines | -A vehicle command needs all three, plus the dev lock in development builds. The dispatcher refuses a command from a phone that isn't validated with `COMMAND_STATUS_CODE_REJECTED_NOT_VALIDATED`, after the read-only check, and hands the command it lets through a `CommandAuthorization` for its phone. The board's TX check reads the validation again when the command's frames are sent ([TX classes](can.md#tx-classes)). MQTT has no phone identity and never gets an authorization; when MQTT commands are authenticated (contracts#8), a phone will have to be validated in the car first. +A vehicle command needs all three, plus the dev lock in development builds. The dispatcher refuses a command from a phone that isn't validated with `COMMAND_STATUS_CODE_REJECTED_NOT_VALIDATED`, after the read-only check, and hands the command it lets through a `CommandAuthorization` for its phone. The board's TX check reads the validation again when the command's frames are sent ([TX classes](can.md#tx-classes)). Plain MQTT has no phone identity and never gets an authorization. Through the [secure channel](architecture.md#secure-channel), a phone's commands carry its `ble:` ID and get exactly these checks and an authorization. **Validation session** (`validation.rs`), run by `core-interface` with methods from the vehicle: diff --git a/docs/testing.md b/docs/testing.md index 3a95280..a26aba1 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -7,7 +7,7 @@ The README has the quick-start commands; this page covers how the suites are org | Crate | Covers | Command | |---|---|---| -| `core-interface` | `passes_filter`, BLE/MQTT dispatch (platform_id gating, routing, `source_device_id` stamping, empty-source rejection), response routing, state publish split, CAN read-only flag and its change notifications, the CAN read-write policy (each condition blocking read-write, approval bound to one car, surviving a reboot and phone changes, relock conditions, bonded-phone-only BLE commands, MQTT never approving or unlocking, release builds without the dev lock, vehicle commands refused with the reason while read-only, the access state repeated while unchanged), the command requirements check (gate order, freshness, requirements, rejection responses that never block), the repeat limit (per command, from the last admitted run, after the requirements, not affecting availability), command availability (nothing before a report, read-only and old reports held back, publish on change, repeat and resend, MQTT basic commands only at the MQTT rate), per-bus CAN TX channels, SavvyCAN logging (GVRET parsing and encoding, session lifecycle, forced read-only), phone trust (vehicle commands and command frames needing a validated phone, validation sessions with code entry, in-car actions, attempts, cooldown and timeouts, validations bound to one car, who can change the approval or remove a validated phone, persistence and pruning to the bonds, the connected phone's access state), the secure channel's keys (the device identity made once and kept, its key ID against the contracts' test vectors, client key enrollment from a validated phone over BLE only, replaced on re-enrollment, dropped with the bond but kept when the validation ends, the store encoding), the deprecated CAN debug commands being ignored, BLE chunking and reassembly (chunk headers, CRC, MTU limits, gaps, duplicates, sequence mismatches, timeouts, oversize messages) | `cargo test -p core-interface -- --test-threads=1` | +| `core-interface` | `passes_filter`, BLE/MQTT dispatch (platform_id gating, routing, `source_device_id` stamping, empty-source rejection), response routing, state publish split, CAN read-only flag and its change notifications, the CAN read-write policy (each condition blocking read-write, approval bound to one car, surviving a reboot and phone changes, relock conditions, bonded-phone-only BLE commands, MQTT never approving or unlocking, release builds without the dev lock, vehicle commands refused with the reason while read-only, the access state repeated while unchanged), the command requirements check (gate order, freshness, requirements, rejection responses that never block), the repeat limit (per command, from the last admitted run, after the requirements, not affecting availability), command availability (nothing before a report, read-only and old reports held back, publish on change, repeat and resend, MQTT basic commands only at the MQTT rate), per-bus CAN TX channels, SavvyCAN logging (GVRET parsing and encoding, session lifecycle, forced read-only), phone trust (vehicle commands and command frames needing a validated phone, validation sessions with code entry, in-car actions, attempts, cooldown and timeouts, validations bound to one car, who can change the approval or remove a validated phone, persistence and pruning to the bonds, the connected phone's access state), the secure channel's keys (the device identity made once and kept, its key ID against the contracts' test vectors, client key enrollment from a validated phone over BLE only, replaced on re-enrollment, dropped with the bond but kept when the validation ends, the store encoding), the secure channel (the Noise handshake and transport frames against the contracts' test vectors, unknown keys and replayed handshakes unanswered, the replay window, keepalives, session expiry, limits and replacement, key removal and link close ending sessions, messages stamped with the client's ID and authorized like BLE, system commands dropped, refusals sealed back to the session, de-duplication across BLE and the channel), the deprecated CAN debug commands being ignored, BLE chunking and reassembly (chunk headers, CRC, MTU limits, gaps, duplicates, sequence mismatches, timeouts, oversize messages) | `cargo test -p core-interface -- --test-threads=1` | | `virtual-car-controller` | `encode_state` proto encoding, worst-case state update fits the BLE message limit, CAN frame → state updates, `process_basic_command`, `tick_simulation` (initial defaults, ramp-up, park phase, odometer increment, door-lock preservation, cycle wraparound), the door lock refused while the simulated car drives and when pressed again inside its interval and sending a command frame for its phone, the simulated validation methods (button, cluster code), command availability and ids pinned to the wire | `cargo test -p virtual-car-controller -- --test-threads=1` | | `egmp-controller` | New state publishes no invented values, worst-case state update fits the BLE message limit, decoding of real CAN frames (charge port, windows, hazards), charge port state through AC and DC sessions, battery power, range, charging times, charge limits, climate state, temperatures in both units, preconditioning states, battery temperatures and 12 V voltage, distance unit, regen mode and level, tire pressures, command requirements and availability from fixture states, command ids pinned to the wire | `cargo test -p egmp-controller -- --test-threads=1` | | `board-pc` | `socketcan_to_core_frame` / `core_to_socketcan_frame` round-trips, the CAN read-write approval and phone validations file formats, BLE helpers | `cargo test -p board-pc -- --test-threads=1` |