From 93893375f3195b4ee3f43fdedd22ff4bf67e73f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 01:22:55 +0000 Subject: [PATCH 1/4] chore(contracts): bump to the device identity and secure channel contracts Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiWM4SEVB1xBTaoykRa --- contracts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts b/contracts index 1faf470..4ce23a0 160000 --- a/contracts +++ b/contracts @@ -1 +1 @@ -Subproject commit 1faf470ab2490fdb73bd65da092798396a26bef8 +Subproject commit 4ce23a07186da9982f43183a3e208ea1819893a3 From 765697ea05c7d268335578ceafd847326bef414a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 01:30:05 +0000 Subject: [PATCH 2/4] feat(secure): add the device identity key and the client key registry The trust anchor of the secure channel (contracts#44, phase 1): - core-interface: the device's X25519 identity, made once from the board's random source and restored at boot, reported with its key ID in SystemState over BLE; the client key registry, filled by EnrollClientKeyCommand from a validated phone over BLE only, dropped with the phone's bond, kept when its validation ends, persisted like the validations. ListPairedPhones reports remote_key_enrolled and the label. - ESP: identity and client keys in the access range of the flash, the identity made once the BLE controller (and so the true RNG) is up. - PC: device_identity_file and client_keys_file under [hardware.pc]. Closes #118 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiWM4SEVB1xBTaoykRa --- .github/ci/esp-lte-mtls.toml | 5 + Cargo.lock | 80 +++++- boards/esp/src/ble/store.rs | 108 +++++++- boards/esp/src/ble/transport.rs | 40 ++- boards/esp/src/lib.rs | 1 + boards/pc/main.template.rs | 2 + boards/pc/src/lib.rs | 6 +- boards/pc/src/restart.rs | 1 + boards/pc/src/secure_keys.rs | 100 +++++++ boards/pc/xtask_builder.rs | 19 ++ config.toml.example | 5 + core-interface/Cargo.toml | 6 + core-interface/src/can_access.rs | 4 +- core-interface/src/client_keys.rs | 292 ++++++++++++++++++++ core-interface/src/dispatch.rs | 26 ++ core-interface/src/identity.rs | 132 +++++++++ core-interface/src/lib.rs | 13 + core-interface/src/pairing.rs | 5 +- core-interface/src/phone_trust.rs | 14 +- core-interface/src/validation.rs | 6 + core-interface/tests/client_keys.rs | 402 ++++++++++++++++++++++++++++ docs/architecture.md | 2 +- docs/ble.md | 21 +- docs/testing.md | 2 +- 24 files changed, 1263 insertions(+), 29 deletions(-) create mode 100644 boards/pc/src/secure_keys.rs create mode 100644 core-interface/src/client_keys.rs create mode 100644 core-interface/src/identity.rs create mode 100644 core-interface/tests/client_keys.rs diff --git a/.github/ci/esp-lte-mtls.toml b/.github/ci/esp-lte-mtls.toml index d5bd639..aaeef9c 100644 --- a/.github/ci/esp-lte-mtls.toml +++ b/.github/ci/esp-lte-mtls.toml @@ -52,6 +52,11 @@ rx_pin = 6 # can_rw_approval_file = "/tmp/opencar-can-rw-approval.txt" # Where the phones validated in the car are kept (the ESP keeps them in flash). # phone_validations_file = "/tmp/opencar-phone-validations.txt" +# Where the device identity key of the secure channel is kept (the ESP keeps it in flash). +# Deleting it gives the device a new identity: phones pair again. +# device_identity_file = "/tmp/opencar-device-identity.txt" +# Where the clients' enrolled keys are kept (the ESP keeps them in flash). +# client_keys_file = "/tmp/opencar-client-keys.txt" [hardware.pc.ble] device_name = "OpenCar" diff --git a/Cargo.lock b/Cargo.lock index 9a2b5d6..a47e2dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -192,6 +192,15 @@ dependencies = [ "wyz", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -539,6 +548,7 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" name = "core-interface" version = "0.1.0" dependencies = [ + "blake2", "bytes", "core-interface", "critical-section", @@ -553,8 +563,10 @@ dependencies = [ "portable-atomic", "prost", "prost-build", + "serde_json", "sha2", "toml", + "x25519-dalek", ] [[package]] @@ -619,6 +631,32 @@ dependencies = [ "typenum", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "cvt" version = "0.1.2" @@ -1693,6 +1731,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "filetime" version = "0.2.29" @@ -2911,6 +2955,15 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "0.38.44" @@ -2921,7 +2974,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3924,6 +3977,17 @@ dependencies = [ "tap", ] +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core 0.6.4", + "zeroize", +] + [[package]] name = "xtask" version = "0.1.0" @@ -3989,6 +4053,20 @@ name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] name = "zmij" diff --git a/boards/esp/src/ble/store.rs b/boards/esp/src/ble/store.rs index b6ab879..beb3c25 100644 --- a/boards/esp/src/ble/store.rs +++ b/boards/esp/src/ble/store.rs @@ -5,9 +5,10 @@ //! back to the `trouble-host` stack so paired phones can re-encrypt without //! triggering a full re-pairing procedure. //! -//! The same flash also holds the owner's CAN read-write approval (see docs/can.md) -//! and the phones validated in the car (see docs/ble.md, "Phone trust"), in a separate -//! range, since the BLE task owns the flash and both arrive over BLE. +//! The same flash also holds the owner's CAN read-write approval (see docs/can.md), +//! the phones validated in the car (see docs/ble.md, "Phone trust"), the device identity +//! key and the clients' enrolled keys (docs/ble.md, "Device identity" and "Client keys"), +//! in a separate range, since the BLE task owns the flash and they arrive over BLE. //! //! It also holds the count of short boots for the bond reset by power-cycling //! (`power_cycle.rs`), which has to be written before the bonds are loaded. @@ -132,11 +133,15 @@ mod hardware { use super::{StoredApproval, StoredBond}; - /// The approval and the validations are the only items in their range. + /// The approval, the validations, the device identity and the client keys are the + /// only items in their range (the "access range"). const APPROVAL_KEY: u8 = 0; const VALIDATIONS_KEY: u8 = 1; - /// Large enough for the validations of 8 phones (`encode_phone_validations`). - const ACCESS_BUFFER_BYTES: usize = 256; + const IDENTITY_KEY: u8 = 2; + const CLIENT_KEYS_KEY: u8 = 3; + /// Large enough for the client keys of 8 phones (`encode_client_keys`, about 620 + /// bytes), the largest item in the range. + const ACCESS_BUFFER_BYTES: usize = 768; /// So is the short-boot count in its own. const SHORT_BOOTS_KEY: u8 = 0; @@ -276,8 +281,87 @@ mod hardware { self.rewrite_access_range(approval, validations).await } - /// Erases the range of the approval and the validations, then writes both: the - /// range holds nothing else. + /// Persist the clients' enrolled keys (`core_interface::encode_client_keys`, empty + /// to erase them). Like the approval, a failed write erases the range and writes + /// everything again. + pub(in crate::ble) async fn store_client_keys(&mut self, keys: &[u8]) -> Result<(), ()> { + if self.write_access_item(CLIENT_KEYS_KEY, keys).await.is_ok() { + return Ok(()); + } + log::warn!("Client keys store: write failed, erasing its range and retrying"); + let approval = self.load_can_rw_approval().await; + self.rewrite_access_range(approval, &core_interface::encode_phone_validations()) + .await + } + + /// Persist the device identity (`core_interface::restore_device_identity` returns + /// it when it created one). Like the approval, a failed write erases the range and + /// writes everything again. + pub(in crate::ble) async fn store_device_identity( + &mut self, + identity: &[u8], + ) -> Result<(), ()> { + if self.write_access_item(IDENTITY_KEY, identity).await.is_ok() { + return Ok(()); + } + log::warn!("Device identity store: write failed, erasing its range and retrying"); + let approval = self.load_can_rw_approval().await; + self.rewrite_access_range(approval, &core_interface::encode_phone_validations()) + .await + } + + /// Load the device identity, as `core_interface::restore_device_identity` takes it. + /// Empty if there is none, or on any flash error (a new identity is then made). + pub(in crate::ble) async fn load_device_identity( + &mut self, + ) -> heapless::Vec { + self.load_access_item(IDENTITY_KEY, "Device identity").await + } + + /// Load the clients' enrolled keys, as `core_interface::restore_client_keys` takes + /// them. Empty if there are none, or on any flash error: the phones enroll again. + pub(in crate::ble) async fn load_client_keys( + &mut self, + ) -> heapless::Vec { + self.load_access_item(CLIENT_KEYS_KEY, "Client keys").await + } + + async fn load_access_item( + &mut self, + key: u8, + what: &str, + ) -> heapless::Vec { + let mut data_buffer = [0u8; ACCESS_BUFFER_BYTES]; + match map::(self.storage, self.approval_range.clone()) + .fetch_item::<&[u8]>(&mut data_buffer, &key) + .await + { + Ok(Some(bytes)) => heapless::Vec::from_slice(bytes).unwrap_or_default(), + Ok(None) => heapless::Vec::new(), + Err(e) => { + log::warn!("{} store: load failed ({:?}), none", what, e); + heapless::Vec::new() + } + } + } + + /// Writes `bytes` under `key` in the access range, or removes it when empty. + async fn write_access_item(&mut self, key: u8, bytes: &[u8]) -> Result<(), ()> { + let mut data_buffer = [0u8; ACCESS_BUFFER_BYTES]; + let mut map = map::(self.storage, self.approval_range.clone()); + let result = if bytes.is_empty() { + map.remove_item(&mut data_buffer, &key).await + } else { + map.store_item(&mut data_buffer, &key, &bytes).await + }; + result.map_err(|e| { + log::error!("Access store: write of item {} failed: {:?}", key, e); + }) + } + + /// Erases the access range, then writes the approval, the validations, and the + /// device identity and client keys `core-interface` holds now: the range holds + /// nothing else. async fn rewrite_access_range( &mut self, approval: Option<[u8; 32]>, @@ -297,6 +381,14 @@ mod hardware { if !validations.is_empty() { self.write_phone_validations(validations).await?; } + // The identity first: losing it makes the app see another device. + if let Some(identity) = core_interface::encode_device_identity() { + self.write_access_item(IDENTITY_KEY, &identity).await?; + } + let keys = core_interface::encode_client_keys(); + if !keys.is_empty() { + self.write_access_item(CLIENT_KEYS_KEY, &keys).await?; + } Ok(()) } diff --git a/boards/esp/src/ble/transport.rs b/boards/esp/src/ble/transport.rs index f433518..0ea5c7b 100644 --- a/boards/esp/src/ble/transport.rs +++ b/boards/esp/src/ble/transport.rs @@ -256,6 +256,10 @@ mod hardware { if core_interface::restore_phone_validations(&validations) { log::info!("Phone validations: restored from flash"); } + let client_keys = bond_store.load_client_keys().await; + if core_interface::restore_client_keys(&client_keys) { + log::info!("Client keys: restored from flash"); + } let loaded_bonds = bond_store.load_bonds().await; crate::ble::boot_pairing::BONDS_LOADED.signal(loaded_bonds.len()); @@ -269,6 +273,18 @@ mod hardware { } }; + // The hardware RNG is a true random source once the radio runs, so a new identity + // is only made from here on. + let stored_identity = bond_store.load_device_identity().await; + if let Some(created) = core_interface::restore_device_identity(&stored_identity) { + log::info!("Device identity: created"); + let _ = bond_store.store_device_identity(&created).await; + } + match core_interface::device_identity() { + Some(identity) => log::info!("Device identity: key ID {}", identity.key_id), + None => log::error!("Device identity: none, the secure channel is off"), + } + let controller: ExternalController<_, 20> = ExternalController::new(connector); static HOST_RESOURCES: StaticCell< HostResources, @@ -295,7 +311,8 @@ mod hardware { core_interface::add_paired_phone(&phone_device_id(&bond.identity.bd_addr.0)).await; } } - // A validation never outlives its phone's bond (a bond reset cleared them all). + // A validation, or a client key, never outlives its phone's bond (a bond reset + // cleared them all). core_interface::prune_phone_validations().await; let Host { @@ -340,6 +357,9 @@ mod hardware { { let _ = bond_store.store_phone_validations(&validations).await; } + if let Some(keys) = core_interface::try_take_client_keys_to_store() { + let _ = bond_store.store_client_keys(&keys).await; + } let pairing_open = core_interface::is_pairing_window_open(); @@ -638,6 +658,9 @@ mod hardware { if let Some(validations) = core_interface::try_take_phone_validations_to_store() { let _ = bond_store.store_phone_validations(&validations).await; } + if let Some(keys) = core_interface::try_take_client_keys_to_store() { + let _ = bond_store.store_client_keys(&keys).await; + } log::warn!("SYSTEM: restarting"); // Lets the BLE runner send a pending disconnect and the log drain. embassy_time::Timer::after(embassy_time::Duration::from_millis(100)).await; @@ -782,9 +805,10 @@ mod hardware { conn.next(), BOND_OPS.receive(), select(encryption_poll, wait_until(short_boot.clear_at)), - select( + select3( core_interface::can_read_write_approval_to_store(), core_interface::phone_validations_to_store(), + core_interface::client_keys_to_store(), ), ) .await @@ -796,16 +820,20 @@ mod hardware { short_boot.clear(bond_store).await; continue; } - // Approvals and validations arrive over this connection, so persist them - // while it lasts. - Either4::Fourth(Either::First(approval)) => { + // Approvals, validations and client keys arrive over this connection, so + // persist them while it lasts. + Either4::Fourth(Either3::First(approval)) => { let _ = bond_store.store_can_rw_approval(approval).await; continue; } - Either4::Fourth(Either::Second(validations)) => { + Either4::Fourth(Either3::Second(validations)) => { let _ = bond_store.store_phone_validations(&validations).await; continue; } + Either4::Fourth(Either3::Third(keys)) => { + let _ = bond_store.store_client_keys(&keys).await; + continue; + } Either4::Second(op) => { if op == BondOp::Restart { // The phone sees the link end at once instead of waiting for the diff --git a/boards/esp/src/lib.rs b/boards/esp/src/lib.rs index 35b031b..02b245f 100644 --- a/boards/esp/src/lib.rs +++ b/boards/esp/src/lib.rs @@ -129,6 +129,7 @@ mod hardware { | Some(core_interface::proto::system_command::Action::StartPhoneValidation(_)) | Some(core_interface::proto::system_command::Action::SubmitPhoneValidationCode(_)) | Some(core_interface::proto::system_command::Action::CancelPhoneValidation(_)) + | Some(core_interface::proto::system_command::Action::EnrollClientKey(_)) | None => {} } } diff --git a/boards/pc/main.template.rs b/boards/pc/main.template.rs index 185c317..3ebee86 100644 --- a/boards/pc/main.template.rs +++ b/boards/pc/main.template.rs @@ -14,6 +14,8 @@ async fn main(spawner: Spawner) { board_pc::set_ble_paired_store_path(BLE_PAIRED_PHONES_FILE); core_interface::set_ble_max_bonded_phones(BLE_MAX_BONDED_PHONES); board_pc::start(&spawner); + // After `start`, which sets the random source a new identity is made from. + board_pc::restore_secure_keys(DEVICE_IDENTITY_FILE, CLIENT_KEYS_FILE); {CAN_SPAWNS}{BLE_HTTP_SPAWN}{MQTT_DRIVER_SPAWN}{CAN_LOGGER_SPAWN} spawner.spawn({VEHICLE_CRATE_IDENT}::handle_basic_commands_task().unwrap()); spawner.spawn({VEHICLE_CRATE_IDENT}::handle_advanced_commands_task().unwrap()); spawner.spawn({VEHICLE_CRATE_IDENT}::state_update_task().unwrap()); diff --git a/boards/pc/src/lib.rs b/boards/pc/src/lib.rs index 788d934..60859a7 100644 --- a/boards/pc/src/lib.rs +++ b/boards/pc/src/lib.rs @@ -5,6 +5,7 @@ mod can_logger; mod network; mod phone_validations; mod restart; +mod secure_keys; use core_interface::SYSTEM_COMMAND_CHANNEL; @@ -14,6 +15,7 @@ pub use can_approval::{can_rw_approval_store_task, restore_can_rw_approval}; pub use can_logger::can_logger_task; pub use network::mqtt_driver_task; pub use phone_validations::{phone_validations_store_task, restore_phone_validations}; +pub use secure_keys::{client_keys_store_task, restore_secure_keys}; pub fn start(spawner: &embassy_executor::Spawner) { spawner.spawn(core_interface::process_ble_commands_task().unwrap()); @@ -25,6 +27,7 @@ pub fn start(spawner: &embassy_executor::Spawner) { spawner.spawn(core_interface::publish_can_bus_health_task().unwrap()); spawner.spawn(can_rw_approval_store_task().unwrap()); spawner.spawn(phone_validations_store_task().unwrap()); + spawner.spawn(client_keys_store_task().unwrap()); core_interface::set_random_source(fill_random); spawner.spawn(system_command_task().unwrap()); } @@ -53,7 +56,7 @@ pub async fn system_command_task() { path ); } - // A validation never outlives its phone's bond. + // A validation, or a client key, never outlives its phone's bond. core_interface::prune_phone_validations().await; loop { @@ -126,6 +129,7 @@ pub async fn system_command_task() { | Some(core_interface::proto::system_command::Action::StartPhoneValidation(_)) | Some(core_interface::proto::system_command::Action::SubmitPhoneValidationCode(_)) | Some(core_interface::proto::system_command::Action::CancelPhoneValidation(_)) + | Some(core_interface::proto::system_command::Action::EnrollClientKey(_)) | None => {} } } diff --git a/boards/pc/src/restart.rs b/boards/pc/src/restart.rs index ccf68b9..b73ea71 100644 --- a/boards/pc/src/restart.rs +++ b/boards/pc/src/restart.rs @@ -6,6 +6,7 @@ pub(crate) fn flush_and_restart() { crate::can_approval::flush_pending_approval(); crate::phone_validations::flush_pending_validations(); + crate::secure_keys::flush_pending_client_keys(); let exe = match std::env::current_exe() { Ok(exe) => exe, Err(e) => { diff --git a/boards/pc/src/secure_keys.rs b/boards/pc/src/secure_keys.rs new file mode 100644 index 0000000..d308252 --- /dev/null +++ b/boards/pc/src/secure_keys.rs @@ -0,0 +1,100 @@ +//! File-backed stores for the secure channel's keys (see docs/ble.md, "Device identity" +//! and "Client keys"): the device identity key and the clients' enrolled keys. +//! +//! Both files hold the bytes `core-interface` hands over, as hex, like the validations +//! file. A missing or malformed identity file makes a new identity (the app then sees +//! another device); a missing or malformed client keys file means no enrolled key. + +use std::sync::OnceLock; + +use crate::phone_validations::{format_validations as format_hex, parse_validations as parse_hex}; + +static CLIENT_KEYS_PATH: OnceLock<&'static str> = OnceLock::new(); + +fn read_hex(path: &str, what: &str) -> Option> { + match std::fs::read_to_string(path) { + Ok(content) => { + let bytes = parse_hex(&content); + if bytes.is_none() { + log::warn!("{}: '{}' is malformed, ignoring it", what, path); + } + bytes + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => { + log::warn!("{}: failed to read '{}': {:?}", what, path, e); + None + } + } +} + +/// Loads the device identity and the client keys into `core-interface`, creating the +/// identity (and writing it to `identity_path`) on the first boot. Called once from +/// `main`, after `start` set the random source and before any task runs; the system +/// command task prunes the keys to the bonded phones once it has restored those. +pub fn restore_secure_keys(identity_path: &'static str, client_keys_path: &'static str) { + let stored = read_hex(identity_path, "Device identity").unwrap_or_default(); + if let Some(created) = core_interface::restore_device_identity(&stored) { + match std::fs::write(identity_path, format_hex(&created)) { + Ok(()) => log::info!("Device identity: created and saved to '{}'", identity_path), + Err(e) => log::error!( + "Device identity: failed to save '{}', it will change on restart: {:?}", + identity_path, + e + ), + } + } + match core_interface::device_identity() { + Some(identity) => log::info!("Device identity: key ID {}", identity.key_id), + None => log::error!("Device identity: none, the secure channel is off"), + } + + let _ = CLIENT_KEYS_PATH.set(client_keys_path); + let keys = read_hex(client_keys_path, "Client keys").unwrap_or_default(); + log::info!( + "Client keys: {}", + if core_interface::restore_client_keys(&keys) { + "restored from file" + } else { + "none enrolled" + } + ); +} + +/// Writes each change of the client keys to the file set by [`restore_secure_keys`]. +#[embassy_executor::task] +pub async fn client_keys_store_task() { + let Some(path) = CLIENT_KEYS_PATH.get().copied() else { + log::error!("Client keys: no file set, keys won't survive a restart"); + return; + }; + loop { + let bytes = core_interface::client_keys_to_store().await; + write_client_keys(path, &bytes); + } +} + +/// Writes a change of the client keys that the store task hasn't taken yet. Called before +/// a restart. +pub(crate) fn flush_pending_client_keys() { + if let (Some(path), Some(bytes)) = ( + CLIENT_KEYS_PATH.get().copied(), + core_interface::try_take_client_keys_to_store(), + ) { + write_client_keys(path, &bytes); + } +} + +fn write_client_keys(path: &str, bytes: &[u8]) { + let result = if bytes.is_empty() { + match std::fs::remove_file(path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + other => other, + } + } else { + std::fs::write(path, format_hex(bytes)) + }; + if let Err(e) = result { + log::error!("Client keys: failed to update '{}': {:?}", path, e); + } +} diff --git a/boards/pc/xtask_builder.rs b/boards/pc/xtask_builder.rs index 138793c..5eb6446 100644 --- a/boards/pc/xtask_builder.rs +++ b/boards/pc/xtask_builder.rs @@ -66,6 +66,13 @@ struct PcHardwareConfig { /// Where the phones validated in the car are kept (the ESP keeps them in flash). #[serde(default = "default_phone_validations_file")] phone_validations_file: String, + /// Where the device identity key of the secure channel is kept (the ESP keeps it in + /// flash). Deleting it gives the device a new identity: phones pair again. + #[serde(default = "default_device_identity_file")] + device_identity_file: String, + /// Where the clients' enrolled keys are kept (the ESP keeps them in flash). + #[serde(default = "default_client_keys_file")] + client_keys_file: String, } fn default_can_rw_approval_file() -> String { @@ -76,6 +83,14 @@ fn default_phone_validations_file() -> String { "/tmp/opencar-phone-validations.txt".to_string() } +fn default_device_identity_file() -> String { + "/tmp/opencar-device-identity.txt".to_string() +} + +fn default_client_keys_file() -> String { + "/tmp/opencar-client-keys.txt".to_string() +} + pub struct Builder; impl Builder { @@ -242,6 +257,8 @@ impl TargetBuilder for Builder { const BLE_PAIRED_PHONES_FILE: &str = \"{store_path}\";\n\ const CAN_RW_APPROVAL_FILE: &str = \"{approval_path}\";\n\ const PHONE_VALIDATIONS_FILE: &str = \"{validations_path}\";\n\ + const DEVICE_IDENTITY_FILE: &str = \"{identity_path}\";\n\ + const CLIENT_KEYS_FILE: &str = \"{client_keys_path}\";\n\ const MQTT_CLIENT_ID: &str = \"{cid}\";\n\ const MQTT_CMD_TOPIC: &str = \"{cmd_topic}\";\n\ const MQTT_DATA_TOPIC: &str = \"{data_topic}\";\n\ @@ -257,6 +274,8 @@ impl TargetBuilder for Builder { store_path = paired_phones_file, approval_path = escape_rust_string(&pc_hw.can_rw_approval_file), validations_path = escape_rust_string(&pc_hw.phone_validations_file), + identity_path = escape_rust_string(&pc_hw.device_identity_file), + client_keys_path = escape_rust_string(&pc_hw.client_keys_file), cid = client_id, cmd_topic = mqtt_cmd_topic, data_topic = mqtt_data_topic, diff --git a/config.toml.example b/config.toml.example index ccd6c87..63e7dc4 100644 --- a/config.toml.example +++ b/config.toml.example @@ -51,6 +51,11 @@ controller_lease_ttl_s = 15 # can_rw_approval_file = "/tmp/opencar-can-rw-approval.txt" # Where the phones validated in the car are kept (the ESP keeps them in flash). # phone_validations_file = "/tmp/opencar-phone-validations.txt" +# Where the device identity key of the secure channel is kept (the ESP keeps it in flash). +# Deleting it gives the device a new identity: phones pair again. +# device_identity_file = "/tmp/opencar-device-identity.txt" +# Where the clients' enrolled keys are kept (the ESP keeps them in flash). +# client_keys_file = "/tmp/opencar-client-keys.txt" [hardware.pc.ble] device_name = "OpenCar" diff --git a/core-interface/Cargo.toml b/core-interface/Cargo.toml index aa4207a..14ea270 100644 --- a/core-interface/Cargo.toml +++ b/core-interface/Cargo.toml @@ -17,6 +17,10 @@ bytes = { workspace = true } portable-atomic = { workspace = true } # Hashes the car fingerprint for the read-write approval (no VIN stored in flash). sha2 = { version = "0.10", default-features = false } +# The secure channel (docs/secure-channel.md in the contracts): the device identity key +# 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 } [features] # `CommandAuthorization::for_tests`, for vehicle crate tests. Only enable it in @@ -28,6 +32,8 @@ prost-build = { workspace = true } toml = { workspace = true } [dev-dependencies] +# Reads the secure channel's test vectors from the contracts. +serde_json = "1" # The integration tests use the `test-utils` helpers. core-interface = { path = ".", features = ["test-utils"] } critical-section = { workspace = true } diff --git a/core-interface/src/can_access.rs b/core-interface/src/can_access.rs index 7e8b0f6..389f0b2 100644 --- a/core-interface/src/can_access.rs +++ b/core-interface/src/can_access.rs @@ -289,7 +289,8 @@ pub fn can_access_state() -> proto::CanAccessState { } /// A BLE state update carrying only the system state with [`can_access_state`], the -/// connected phone's [`crate::phone_access_state`] and the device's MQTT client ID. +/// connected phone's [`crate::phone_access_state`], the device's MQTT client ID and its +/// identity for the secure channel (`identity.rs`). pub fn can_access_state_update(timestamp_ms: u64) -> proto::DeviceToApp { proto::DeviceToApp { timestamp_ms, @@ -300,6 +301,7 @@ pub fn can_access_state_update(timestamp_ms: u64) -> proto::DeviceToApp { can_access: Some(can_access_state()), phone_access: crate::phone_trust::phone_access_state(timestamp_ms), mqtt_client_id: crate::mqtt_client_id().map(Into::into), + device_identity: crate::identity::device_identity(), ..Default::default() }), vehicle_state: None, diff --git a/core-interface/src/client_keys.rs b/core-interface/src/client_keys.rs new file mode 100644 index 0000000..57e1405 --- /dev/null +++ b/core-interface/src/client_keys.rs @@ -0,0 +1,292 @@ +//! The client key registry: the X25519 static public keys clients enrolled for the secure +//! channel (see docs/secure-channel.md in the contracts, and docs/ble.md, "Client keys"). +//! +//! A validated phone enrolls its own key over BLE (`EnrollClientKeyCommand`, handled by the +//! dispatcher). The registry keeps one key per phone, under the phone's `ble:` device ID, +//! which the channel stamps as `source_device_id` on what the phone sends through it. +//! +//! A phone's key goes away with its bond: when the phone is removed or pairs again +//! ([`crate::forget_phone_validation`]), when every phone is removed +//! ([`crate::clear_paired_phones`]) and when the bonds are reset (pruned at boot by +//! [`crate::prune_phone_validations`]). A phone that loses its validation (another car +//! approved) keeps its key: it just can't send vehicle commands, as over BLE. +//! +//! The registry stores a client kind so hubs (Home Assistant) can be enrolled later +//! without a BLE bond of their own. They are refused for now. + +use alloc::string::String; +use alloc::vec::Vec; +use core::cell::RefCell; + +use embassy_sync::blocking_mutex::Mutex; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +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; + +/// Format version of [`encode_client_keys`]; an unknown one reads as no key. +const CLIENT_KEYS_FORMAT_VERSION: u8 = 1; + +/// One enrolled client. +#[derive(Clone)] +struct ClientKey { + /// The client's ID: a phone's `ble:` device ID. + client_id: Vec, + kind: proto::ClientKind, + public_key: [u8; 32], + label: String, +} + +static CLIENT_KEYS: Mutex>> = + Mutex::new(RefCell::new(Vec::new())); + +/// The keys the board has to persist, encoded ([`encode_client_keys`]); empty to erase +/// them. Only the latest value matters. +static CLIENT_KEYS_TO_STORE: Signal> = Signal::new(); + +fn store_client_keys() { + CLIENT_KEYS_TO_STORE.signal(encode_client_keys()); +} + +/// Why an enrollment was refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum EnrollError { + NotValidated, + UnsupportedKind, + BadKey, + LabelTooLong, + KeyInUse, + NoIdentity, +} + +impl EnrollError { + pub(crate) fn message(self) -> &'static str { + match self { + Self::NotValidated => { + "command rejected: only a phone validated in this car can enroll its key" + } + Self::UnsupportedKind => "command rejected: only a phone can enroll its own key", + Self::BadKey => "command rejected: the key must be a 32-byte X25519 public key", + Self::LabelTooLong => "command rejected: the label is too long", + Self::KeyInUse => "command rejected: this key is enrolled for another client", + Self::NoIdentity => "command rejected: the device has no identity key", + } + } +} + +/// Enrolls `cmd`'s key for the sending phone, `source_device_id` (the one the BLE transport +/// stamped). Answers with the device identity. Replaces the phone's previous key. +pub(crate) fn enroll_client_key( + source_device_id: &[u8], + cmd: &proto::EnrollClientKeyCommand, +) -> Result { + if !crate::phone_trust::is_phone_validated(source_device_id) { + return Err(EnrollError::NotValidated); + } + if cmd.kind != proto::ClientKind::Phone as i32 { + return Err(EnrollError::UnsupportedKind); + } + let public_key: [u8; 32] = cmd + .public_key + .as_slice() + .try_into() + .map_err(|_| EnrollError::BadKey)?; + // An all-zero key (or another low-order point) would make every DH output zero. + if public_key == [0; 32] { + return Err(EnrollError::BadKey); + } + if cmd.label.len() > MAX_CLIENT_LABEL_BYTES { + return Err(EnrollError::LabelTooLong); + } + let identity = crate::identity::device_identity().ok_or(EnrollError::NoIdentity)?; + let entry = ClientKey { + client_id: source_device_id.to_vec(), + kind: proto::ClientKind::Phone, + public_key, + label: cmd.label.clone(), + }; + CLIENT_KEYS.lock(|keys| { + let mut keys = keys.borrow_mut(); + // A key belongs to one client: the channel maps it back to that client. + if keys + .iter() + .any(|k| k.public_key == entry.public_key && k.client_id != entry.client_id) + { + return Err(EnrollError::KeyInUse); + } + keys.retain(|k| k.client_id != entry.client_id); + keys.push(entry); + Ok(()) + })?; + store_client_keys(); + crate::phone_trust::notify_phone_access_changed(); + Ok(identity) +} + +// ── Queries ─────────────────────────────────────────────────────────────────── + +/// `true` while `client_id` has a key enrolled. +pub fn is_client_key_enrolled(client_id: &[u8]) -> bool { + CLIENT_KEYS.lock(|keys| keys.borrow().iter().any(|k| k.client_id == client_id)) +} + +/// The label `client_id` enrolled its key with, empty when it has none. +pub fn client_key_label(client_id: &[u8]) -> String { + CLIENT_KEYS.lock(|keys| { + keys.borrow() + .iter() + .find(|k| k.client_id == client_id) + .map(|k| k.label.clone()) + .unwrap_or_default() + }) +} + +/// The client a static public key belongs to: its ID and kind. For the secure channel's +/// handshake, and on every frame of a session (a removed key ends its sessions). +pub fn client_for_key(public_key: &[u8; 32]) -> Option<(Vec, proto::ClientKind)> { + CLIENT_KEYS.lock(|keys| { + keys.borrow() + .iter() + .find(|k| &k.public_key == public_key) + .map(|k| (k.client_id.clone(), k.kind)) + }) +} + +// ── Revocation ──────────────────────────────────────────────────────────────── + +/// Drops `client_id`'s key. Called with its validation when a phone's bond goes away. +pub(crate) fn forget_client_key(client_id: &[u8]) { + let changed = CLIENT_KEYS.lock(|keys| { + let mut keys = keys.borrow_mut(); + let before = keys.len(); + keys.retain(|k| k.client_id != client_id); + keys.len() != before + }); + if changed { + store_client_keys(); + } +} + +/// Drops every phone's key (every bond removed). +pub(crate) fn clear_phone_client_keys() { + let changed = CLIENT_KEYS.lock(|keys| { + let mut keys = keys.borrow_mut(); + let before = keys.len(); + keys.retain(|k| k.kind != proto::ClientKind::Phone); + keys.len() != before + }); + if changed { + store_client_keys(); + } +} + +/// Drops the keys of phones that are no longer bonded (a bond reset, or bonds lost). +pub(crate) fn prune_client_keys() { + let changed = CLIENT_KEYS.lock(|keys| { + let mut keys = keys.borrow_mut(); + let before = keys.len(); + keys.retain(|k| { + k.kind != proto::ClientKind::Phone || crate::pairing::is_paired(&k.client_id) + }); + keys.len() != before + }); + if changed { + store_client_keys(); + } +} + +// ── Persistence ─────────────────────────────────────────────────────────────── + +/// The keys in the format the board stores: version, count, then for each client its +/// kind, its ID with its length, its key, and its label with its length. Empty when there +/// is none. +pub fn encode_client_keys() -> Vec { + CLIENT_KEYS.lock(|keys| { + let keys = keys.borrow(); + if keys.is_empty() { + return Vec::new(); + } + let mut out = Vec::with_capacity(2 + keys.len() * 80); + out.push(CLIENT_KEYS_FORMAT_VERSION); + out.push(keys.len() as u8); + for k in keys.iter() { + out.push(k.kind as i32 as u8); + out.push(k.client_id.len() as u8); + out.extend_from_slice(&k.client_id); + out.extend_from_slice(&k.public_key); + out.push(k.label.len() as u8); + out.extend_from_slice(k.label.as_bytes()); + } + out + }) +} + +fn take<'a>(rest: &mut &'a [u8], len: usize) -> Option<&'a [u8]> { + if rest.len() < len { + return None; + } + let (head, tail) = rest.split_at(len); + *rest = tail; + Some(head) +} + +fn decode_client_keys(bytes: &[u8]) -> Option> { + let mut rest = bytes; + let header = take(&mut rest, 2)?; + if header[0] != CLIENT_KEYS_FORMAT_VERSION { + return None; + } + let count = header[1] as usize; + let mut keys = Vec::with_capacity(count); + for _ in 0..count { + let kind = proto::ClientKind::try_from(take(&mut rest, 1)?[0] as i32).ok()?; + let id_len = take(&mut rest, 1)?[0] as usize; + if id_len == 0 { + return None; + } + let client_id = take(&mut rest, id_len)?.to_vec(); + let public_key: [u8; 32] = take(&mut rest, 32)?.try_into().ok()?; + let label_len = take(&mut rest, 1)?[0] as usize; + let label = core::str::from_utf8(take(&mut rest, label_len)?) + .ok()? + .into(); + keys.push(ClientKey { + client_id, + kind, + public_key, + label, + }); + } + (rest.is_empty() && !keys.is_empty()).then_some(keys) +} + +/// Loads the keys the board persisted ([`encode_client_keys`]). Called once at boot, +/// before the transports start; [`crate::prune_phone_validations`] then drops those of +/// phones no longer bonded. Anything malformed reads as no key: the phones enroll again. +/// Returns whether any key was restored. +pub fn restore_client_keys(bytes: &[u8]) -> bool { + let keys = decode_client_keys(bytes).unwrap_or_default(); + let restored = !keys.is_empty(); + CLIENT_KEYS.lock(|k| *k.borrow_mut() = keys); + restored +} + +/// Waits for the next change the board has to persist: the encoded keys, empty to erase +/// them. +pub async fn client_keys_to_store() -> Vec { + CLIENT_KEYS_TO_STORE.wait().await +} + +/// Non-blocking [`client_keys_to_store`]: `None` if nothing is pending. +pub fn try_take_client_keys_to_store() -> Option> { + CLIENT_KEYS_TO_STORE.try_take() +} + +/// Clears the registry and any pending store. For tests only. +pub fn reset_client_keys_for_tests() { + CLIENT_KEYS.lock(|k| k.borrow_mut().clear()); + CLIENT_KEYS_TO_STORE.reset(); +} diff --git a/core-interface/src/dispatch.rs b/core-interface/src/dispatch.rs index ccee615..d0233a3 100644 --- a/core-interface/src/dispatch.rs +++ b/core-interface/src/dispatch.rs @@ -223,6 +223,8 @@ fn paired_phones_answer(source_device_id: &[u8], phones: Vec>) -> System .map(|device_id| proto::PairedPhone { trust: crate::phone_trust::phone_trust_level(&device_id) as i32, is_requester: device_id.as_slice() == source_device_id, + remote_key_enrolled: crate::client_keys::is_client_key_enrolled(&device_id), + remote_key_label: crate::client_keys::client_key_label(&device_id), device_id, }) .collect(), @@ -230,6 +232,24 @@ fn paired_phones_answer(source_device_id: &[u8], phones: Vec>) -> System ))) } +// ── Client keys ─────────────────────────────────────────────────────────────── + +/// Enrolls the sending phone's key for the secure channel (`client_keys.rs`). BLE only, from +/// a validated phone; answered with the device identity. +fn handle_enroll_client_key( + source_device_id: &[u8], + cmd: &proto::EnrollClientKeyCommand, +) -> SystemAnswer { + use crate::client_keys::EnrollError; + match crate::client_keys::enroll_client_key(source_device_id, cmd) { + Ok(identity) => Ok(Some(proto::system_command_result::Result::DeviceIdentity( + identity, + ))), + Err(e @ EnrollError::NotValidated) => Err(Refusal::not_validated(e.message())), + Err(e) => Err(Refusal::failed(e.message())), + } +} + fn validation_refusal((error, data): crate::validation::Refused) -> Refusal { Refusal { status: proto::CommandStatusCode::Failed, @@ -363,6 +383,8 @@ pub async fn reset_ble_controller_lease_for_tests() { /// a phone is validated for this car), and answered with a `CommandResponse` /// - `list_paired_phones` and the phone validation commands → handled here and answered /// with a `CommandResponse` carrying a `SystemCommandResult` +/// - `enroll_client_key` → handled here (`client_keys.rs`), from a validated phone only +/// (`REJECTED_NOT_VALIDATED` otherwise), answered with the device identity /// - `remove_paired_phone` / `clear_paired_phones` → `SYSTEM_COMMAND_CHANNEL`, unless /// they would remove a validated phone and the sender isn't validated (answered with a /// `REJECTED_NOT_VALIDATED` response) @@ -466,6 +488,10 @@ pub async fn handle_ble_message(msg: proto::AppToDevice) { let result = handle_phone_validation(&source_device_id, action).await; send_system_command_response(msg.message_id, result).await; } + Some(proto::system_command::Action::EnrollClientKey(cmd)) => { + let result = handle_enroll_client_key(&source_device_id, &cmd); + send_system_command_response(msg.message_id, result).await; + } None => {} }, Some(proto::app_to_device::Payload::BasicCommandBytes(bytes)) => { diff --git a/core-interface/src/identity.rs b/core-interface/src/identity.rs new file mode 100644 index 0000000..b04c187 --- /dev/null +++ b/core-interface/src/identity.rs @@ -0,0 +1,132 @@ +//! The device identity: the X25519 static key pair of the secure channel (see +//! docs/secure-channel.md in the contracts, and docs/ble.md, "Device identity"). +//! +//! The device creates it once, from the board's random source, and keeps it until its +//! flash is erased: bond resets and `ClearPairedPhones` keep it, since it belongs to the +//! device, not to its owner. The app pins its public key over BLE, so a new key makes the +//! app treat the device as another one. +//! +//! The board persists it: it hands what it stored to [`restore_device_identity`] at boot, +//! and stores what that returns, if anything (a key created on the first boot). + +use alloc::string::String; +use alloc::vec::Vec; +use core::cell::RefCell; + +use blake2::{Blake2s256, Digest}; +use embassy_sync::blocking_mutex::Mutex; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +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; + +/// Format version of the stored identity; an unknown one reads as no identity. +const IDENTITY_FORMAT_VERSION: u8 = 1; + +/// Length of the stored identity: the version and the private key. +pub const DEVICE_IDENTITY_STORED_BYTES: usize = 33; + +struct Identity { + secret: StaticSecret, + public: PublicKey, + key_id: String, +} + +static IDENTITY: Mutex>> = + Mutex::new(RefCell::new(None)); + +/// The device key ID of `public_key`: the lowercase hex of the first +/// [`DEVICE_KEY_ID_BYTES`] bytes of its BLAKE2s-256 hash. +pub fn device_key_id(public_key: &[u8; 32]) -> String { + let hash = Blake2s256::digest(public_key); + let mut out = String::with_capacity(DEVICE_KEY_ID_BYTES * 2); + for b in &hash[..DEVICE_KEY_ID_BYTES] { + use core::fmt::Write as _; + let _ = write!(out, "{b:02x}"); + } + out +} + +fn identity_from_secret(bytes: [u8; 32]) -> Identity { + let secret = StaticSecret::from(bytes); + let public = PublicKey::from(&secret); + let key_id = device_key_id(public.as_bytes()); + Identity { + secret, + public, + key_id, + } +} + +fn decode_identity(bytes: &[u8]) -> Option<[u8; 32]> { + let (&version, key) = bytes.split_first()?; + if version != IDENTITY_FORMAT_VERSION { + return None; + } + key.try_into().ok() +} + +fn encode_identity(secret: &[u8; 32]) -> Vec { + let mut out = Vec::with_capacity(DEVICE_IDENTITY_STORED_BYTES); + out.push(IDENTITY_FORMAT_VERSION); + out.extend_from_slice(secret); + out +} + +/// Loads the identity the board stored (empty if none), or creates one from the board's +/// random source when there is none or it is malformed. Returns the encoded identity the +/// board must store when it created one, `None` otherwise. Without a random source the +/// device has no identity (and the secure channel is off) rather than a guessable key: +/// call it after `set_random_source`, and on the ESP once the radio runs. +pub fn restore_device_identity(stored: &[u8]) -> Option> { + if let Some(secret) = decode_identity(stored) { + IDENTITY.lock(|i| *i.borrow_mut() = Some(identity_from_secret(secret))); + crate::phone_trust::notify_phone_access_changed(); + return None; + } + let Some(fill) = crate::validation::random_source() else { + IDENTITY.lock(|i| *i.borrow_mut() = None); + return None; + }; + let mut secret = [0u8; 32]; + fill(&mut secret); + let identity = identity_from_secret(secret); + let encoded = encode_identity(&identity.secret.to_bytes()); + IDENTITY.lock(|i| *i.borrow_mut() = Some(identity)); + crate::phone_trust::notify_phone_access_changed(); + Some(encoded) +} + +/// The encoded identity, as [`restore_device_identity`] returns it, for a board that +/// rewrites its storage. `None` while the device has no identity. +pub fn encode_device_identity() -> Option> { + IDENTITY.lock(|i| { + i.borrow() + .as_ref() + .map(|i| encode_identity(&i.secret.to_bytes())) + }) +} + +/// The device's identity as the app sees it, `None` while it has none. +pub fn device_identity() -> Option { + IDENTITY.lock(|i| { + i.borrow().as_ref().map(|i| proto::DeviceIdentity { + public_key: i.public.as_bytes().to_vec(), + key_id: i.key_id.clone(), + }) + }) +} + +/// 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())) +} + +/// Forgets the identity. For tests only. +pub fn reset_device_identity_for_tests() { + IDENTITY.lock(|i| *i.borrow_mut() = None); +} diff --git a/core-interface/src/lib.rs b/core-interface/src/lib.rs index 0550b8e..39702d3 100644 --- a/core-interface/src/lib.rs +++ b/core-interface/src/lib.rs @@ -13,8 +13,10 @@ mod can_log; mod can_probe; mod can_tx; mod channels; +mod client_keys; mod dedupe; mod dispatch; +mod identity; mod isotp; mod lifecycle; mod mqtt_tls; @@ -143,6 +145,17 @@ pub use requirements::{ Snapshot, rejection_response, respond_to_command, try_send_response, }; +// Secure channel keys (the device identity, the clients' keys) +pub use client_keys::{ + MAX_CLIENT_LABEL_BYTES, client_for_key, client_key_label, client_keys_to_store, + encode_client_keys, is_client_key_enrolled, reset_client_keys_for_tests, restore_client_keys, + try_take_client_keys_to_store, +}; +pub use identity::{ + DEVICE_IDENTITY_STORED_BYTES, DEVICE_KEY_ID_BYTES, device_identity, device_key_id, + encode_device_identity, reset_device_identity_for_tests, restore_device_identity, +}; + // Pairing registry pub use pairing::{ add_paired_phone, ble_max_bonded_phones, clear_paired_phones, is_phone_paired, diff --git a/core-interface/src/pairing.rs b/core-interface/src/pairing.rs index e23bc98..3a18c36 100644 --- a/core-interface/src/pairing.rs +++ b/core-interface/src/pairing.rs @@ -57,7 +57,7 @@ pub async fn add_paired_phone(device_id: &[u8]) -> bool { added } -/// Removes the phone and its validation: a validation never outlives its bond. +/// Removes the phone, its validation and its client key: neither outlives its bond. pub async fn remove_paired_phone(device_id: &[u8]) -> bool { let removed = PAIRED_PHONES.lock(|phones| { let mut phones = phones.borrow_mut(); @@ -73,7 +73,7 @@ pub async fn remove_paired_phone(device_id: &[u8]) -> bool { removed } -/// Removes every phone and every validation. +/// Removes every phone, every validation and every phone's client key. pub async fn clear_paired_phones() -> usize { let count = PAIRED_PHONES.lock(|phones| { let mut phones = phones.borrow_mut(); @@ -82,5 +82,6 @@ pub async fn clear_paired_phones() -> usize { count }); crate::phone_trust::clear_phone_validations(); + crate::client_keys::clear_phone_client_keys(); count } diff --git a/core-interface/src/phone_trust.rs b/core-interface/src/phone_trust.rs index 8d6d189..1770519 100644 --- a/core-interface/src/phone_trust.rs +++ b/core-interface/src/phone_trust.rs @@ -117,9 +117,11 @@ pub(crate) fn add_phone_validation(car: CarDigest, device_id: &[u8]) { store_validations(); } -/// Ends `device_id`'s validation. Called when its bond is removed, and by the board when -/// the phone pairs again: new keys can belong to another phone claiming its address. +/// Ends `device_id`'s validation and drops its client key (`client_keys.rs`). Called when +/// its bond is removed, and by the board when the phone pairs again: new keys can belong +/// to another phone claiming its address. pub fn forget_phone_validation(device_id: &[u8]) { + crate::client_keys::forget_client_key(device_id); let changed = VALIDATIONS.lock(|v| { let mut v = v.borrow_mut(); let Some(validations) = v.as_mut() else { @@ -155,10 +157,12 @@ pub(crate) fn on_car_approved(car: CarDigest) { } } -/// Drops the validations of phones that are no longer bonded. The board calls it once -/// at boot, after restoring the validations and the bonds, so a bond reset (or bonds -/// lost from flash) also ends their validations. +/// Drops the validations and the client keys of phones that are no longer bonded. The +/// board calls it once at boot, after restoring the validations, the client keys and the +/// bonds, so a bond reset (or bonds lost from flash) also ends their validations and +/// drops their keys. pub async fn prune_phone_validations() { + crate::client_keys::prune_client_keys(); let changed = VALIDATIONS.lock(|v| { let mut v = v.borrow_mut(); let Some(validations) = v.as_mut() else { diff --git a/core-interface/src/validation.rs b/core-interface/src/validation.rs index ddcc7f3..216b377 100644 --- a/core-interface/src/validation.rs +++ b/core-interface/src/validation.rs @@ -194,6 +194,12 @@ pub fn set_random_source(fill: fn(&mut [u8])) { STATE.lock(|s| s.borrow_mut().random = Some(fill)); } +/// The board's random source, also used for the device identity key (`identity.rs`) and +/// the secure channel's ephemeral keys. +pub(crate) fn random_source() -> Option { + STATE.lock(|s| s.borrow().random) +} + /// A receiver for the running challenge: `changed()` resolves when a session starts or /// ends. At most two (the vehicle, and a test). pub fn validation_challenge_receiver() diff --git a/core-interface/tests/client_keys.rs b/core-interface/tests/client_keys.rs new file mode 100644 index 0000000..6932edf --- /dev/null +++ b/core-interface/tests/client_keys.rs @@ -0,0 +1,402 @@ +//! The secure channel's keys (docs/ble.md, "Device identity" and "Client keys"): the +//! device identity is created once and kept, a validated phone enrolls its key over BLE +//! only, and the key goes away with the phone's bond but not with its validation. + +use core_interface::{ + BLE_TX_CHANNEL, MQTT_TX_CHANNEL, add_paired_phone, approve_can_read_write, clear_paired_phones, + client_for_key, client_key_label, confirm_car_fingerprint, confirm_car_identity, + device_identity, device_key_id, encode_client_keys, encode_device_identity, + forget_phone_validation, handle_ble_message, handle_mqtt_message, init, is_client_key_enrolled, + proto, prune_phone_validations, 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, restore_client_keys, restore_device_identity, + revoke_car_identity, set_random_source, try_take_client_keys_to_store, + validate_phone_for_tests, +}; +use proto::app_to_device::Payload; +use proto::system_command::Action; +use proto::system_command_result::Result as Data; + +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_KEY: [u8; 32] = [0x11; 32]; +const SECOND_KEY: [u8; 32] = [0x22; 32]; + +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(1, std::sync::atomic::Ordering::Relaxed); + } +} + +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(s: &str) -> Vec { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() +} + +/// Car A identified, the owner validated in it and the second phone only bonded, and a +/// device identity. +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(); + set_random_source(counting_random); + assert!(restore_device_identity(&[]).is_some()); + core_interface::set_link_up(core_interface::Transport::Ble, true); + core_interface::set_link_up(core_interface::Transport::Mqtt, true); + core_interface::reset_recent_commands_for_tests(); + while BLE_TX_CHANNEL.try_receive().is_ok() {} + while MQTT_TX_CHANNEL.try_receive().is_ok() {} + for phone in [OWNER, SECOND] { + embassy_futures::block_on(add_paired_phone(phone)); + } + confirm_car_identity(); + assert!(confirm_car_fingerprint(CAR_A)); + assert!(validate_phone_for_tests(OWNER)); +} + +fn next_message_id() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +fn system_message(source: &[u8], action: Action) -> proto::AppToDevice { + proto::AppToDevice { + message_id: next_message_id(), + platform_id: PLATFORM_ID, + source_device_id: source.to_vec(), + payload: Some(Payload::SystemCommand(proto::SystemCommand { + action: Some(action), + })), + } +} + +fn system(source: &[u8], action: Action) -> proto::CommandResponse { + embassy_futures::block_on(handle_ble_message(system_message(source, action))); + loop { + let msg = BLE_TX_CHANNEL.try_receive().expect("no BLE response"); + if let Some(proto::device_to_app::Payload::CommandResponse(resp)) = msg.payload { + return resp; + } + } +} + +fn enroll_cmd(key: &[u8], kind: proto::ClientKind, label: &str) -> Action { + Action::EnrollClientKey(proto::EnrollClientKeyCommand { + public_key: key.to_vec(), + kind: kind as i32, + label: label.into(), + }) +} + +fn enroll(source: &[u8], key: [u8; 32], label: &str) -> proto::CommandResponse { + system(source, enroll_cmd(&key, proto::ClientKind::Phone, label)) +} + +fn result(resp: &proto::CommandResponse) -> Option<&Data> { + match &resp.response_data { + Some(proto::command_response::ResponseData::SystemResult(r)) => r.result.as_ref(), + _ => None, + } +} + +fn listed(source: &[u8]) -> Vec { + let resp = system(source, Action::ListPairedPhones(Default::default())); + match result(&resp) { + Some(Data::PairedPhones(p)) => p.phones.clone(), + _ => panic!("no paired phones"), + } +} + +// ── Device identity ─────────────────────────────────────────────────────────── + +#[test] +fn key_id_matches_the_contract_vectors() { + let v = vectors(); + let public: [u8; 32] = hex(v["device_static_public"].as_str().unwrap()) + .try_into() + .unwrap(); + assert_eq!(device_key_id(&public), v["device_key_id"].as_str().unwrap()); +} + +#[test] +fn a_stored_identity_is_restored_and_reported() { + boot(); + let v = vectors(); + let mut stored = vec![1u8]; + stored.extend(hex(v["device_static_private"].as_str().unwrap())); + assert_eq!( + restore_device_identity(&stored), + None, + "nothing new to store" + ); + let identity = device_identity().unwrap(); + assert_eq!( + identity.public_key, + hex(v["device_static_public"].as_str().unwrap()) + ); + assert_eq!(identity.key_id, v["device_key_id"].as_str().unwrap()); + assert_eq!(encode_device_identity().unwrap(), stored); + + // Reported over BLE with the access state. + let update = core_interface::can_access_state_update(0); + let Some(proto::device_to_app::Payload::StateUpdate(state)) = update.payload else { + panic!("no state update"); + }; + assert_eq!(state.system_state.unwrap().device_identity, Some(identity)); +} + +#[test] +fn a_missing_or_malformed_identity_is_created_once() { + boot(); + reset_device_identity_for_tests(); + let created = restore_device_identity(&[]).expect("a new identity to store"); + assert_eq!(created.len(), 33); + let identity = device_identity().unwrap(); + // After a restart, the stored one is used. + reset_device_identity_for_tests(); + assert_eq!(restore_device_identity(&created), None); + assert_eq!(device_identity().unwrap(), identity); + // An unknown format reads as none, and a new key replaces it. + let mut unknown = created.clone(); + unknown[0] = 9; + assert!(restore_device_identity(&unknown).is_some()); + assert_ne!(device_identity().unwrap(), identity); +} + +#[test] +fn no_identity_without_a_random_source() { + boot(); + reset_device_identity_for_tests(); + reset_phone_validation_for_tests(); // forgets the random source + assert_eq!(restore_device_identity(&[]), None); + assert_eq!(device_identity(), None); + set_random_source(counting_random); + assert!(validate_phone_for_tests(OWNER)); + let resp = enroll(OWNER, OWNER_KEY, "Pixel"); + assert!(!resp.success); + assert!(!is_client_key_enrolled(OWNER)); +} + +#[test] +fn the_identity_survives_clearing_the_phones() { + boot(); + let identity = device_identity().unwrap(); + embassy_futures::block_on(clear_paired_phones()); + assert_eq!(device_identity().unwrap(), identity); +} + +// ── Enrollment ──────────────────────────────────────────────────────────────── + +#[test] +fn a_validated_phone_enrolls_its_key_and_gets_the_device_identity() { + boot(); + let resp = enroll(OWNER, OWNER_KEY, "Pixel 9"); + assert!(resp.success, "{}", resp.error_message); + assert_eq!( + result(&resp), + Some(&Data::DeviceIdentity(device_identity().unwrap())) + ); + assert!(is_client_key_enrolled(OWNER)); + assert_eq!( + client_for_key(&OWNER_KEY), + Some((OWNER.to_vec(), proto::ClientKind::Phone)) + ); + let phones = listed(OWNER); + let owner = phones.iter().find(|p| p.device_id == OWNER).unwrap(); + assert!(owner.remote_key_enrolled); + assert_eq!(owner.remote_key_label, "Pixel 9"); + let second = phones.iter().find(|p| p.device_id == SECOND).unwrap(); + assert!(!second.remote_key_enrolled); + assert_eq!(second.remote_key_label, ""); +} + +#[test] +fn a_bonded_but_not_validated_phone_cannot_enroll() { + boot(); + let resp = enroll(SECOND, SECOND_KEY, "Other"); + assert!(!resp.success); + assert_eq!( + resp.status_code, + proto::CommandStatusCode::RejectedNotValidated as i32 + ); + assert!(!is_client_key_enrolled(SECOND)); + assert_eq!(client_for_key(&SECOND_KEY), None); +} + +#[test] +fn enrollment_over_mqtt_is_ignored() { + boot(); + embassy_futures::block_on(handle_mqtt_message(system_message( + OWNER, + enroll_cmd(&OWNER_KEY, proto::ClientKind::Phone, "Pixel"), + ))); + assert!(!is_client_key_enrolled(OWNER)); + assert!( + MQTT_TX_CHANNEL.try_receive().is_err(), + "no answer over MQTT" + ); +} + +#[test] +fn enrolling_again_replaces_the_key() { + boot(); + assert!(enroll(OWNER, OWNER_KEY, "Old").success); + let new_key = [0x33; 32]; + assert!(enroll(OWNER, new_key, "New").success); + assert_eq!(client_for_key(&OWNER_KEY), None); + assert_eq!( + client_for_key(&new_key), + Some((OWNER.to_vec(), proto::ClientKind::Phone)) + ); + assert_eq!(client_key_label(OWNER), "New"); +} + +#[test] +fn hubs_bad_keys_long_labels_and_other_clients_keys_are_refused() { + boot(); + let refused = |action: Action| { + let resp = system(OWNER, action); + assert!(!resp.success); + assert_eq!(resp.status_code, proto::CommandStatusCode::Failed as i32); + }; + refused(enroll_cmd( + &OWNER_KEY, + proto::ClientKind::Hub, + "Home Assistant", + )); + refused(enroll_cmd(&OWNER_KEY, proto::ClientKind::Unspecified, "")); + refused(enroll_cmd(&OWNER_KEY[..31], proto::ClientKind::Phone, "")); + refused(enroll_cmd(&[0; 32], proto::ClientKind::Phone, "")); + refused(enroll_cmd( + &OWNER_KEY, + proto::ClientKind::Phone, + &"x".repeat(core_interface::MAX_CLIENT_LABEL_BYTES + 1), + )); + assert!(!is_client_key_enrolled(OWNER)); + + // A key enrolled by another phone stays that phone's. + assert!(validate_phone_for_tests(SECOND)); + assert!(enroll(SECOND, SECOND_KEY, "Second").success); + refused(enroll_cmd(&SECOND_KEY, proto::ClientKind::Phone, "")); + assert_eq!(client_for_key(&SECOND_KEY).unwrap().0, SECOND); +} + +// ── Revocation ──────────────────────────────────────────────────────────────── + +#[test] +fn the_key_goes_away_with_the_bond() { + boot(); + assert!(enroll(OWNER, OWNER_KEY, "Pixel").success); + embassy_futures::block_on(remove_paired_phone(OWNER)); + assert!(!is_client_key_enrolled(OWNER)); + assert_eq!(client_for_key(&OWNER_KEY), None); +} + +#[test] +fn the_key_goes_away_when_the_phone_pairs_again() { + boot(); + assert!(enroll(OWNER, OWNER_KEY, "Pixel").success); + forget_phone_validation(OWNER); + assert!(!is_client_key_enrolled(OWNER)); +} + +#[test] +fn every_phone_key_goes_away_when_the_phones_are_cleared() { + boot(); + assert!(validate_phone_for_tests(SECOND)); + assert!(enroll(OWNER, OWNER_KEY, "Pixel").success); + assert!(enroll(SECOND, SECOND_KEY, "Second").success); + embassy_futures::block_on(clear_paired_phones()); + assert!(!is_client_key_enrolled(OWNER)); + assert!(!is_client_key_enrolled(SECOND)); + assert!(encode_client_keys().is_empty()); +} + +#[test] +fn keys_of_phones_no_longer_bonded_are_pruned_at_boot() { + boot(); + assert!(validate_phone_for_tests(SECOND)); + assert!(enroll(OWNER, OWNER_KEY, "Pixel").success); + assert!(enroll(SECOND, SECOND_KEY, "Second").success); + let stored = encode_client_keys(); + + // A bond reset: only the owner's bond is restored. + embassy_futures::block_on(clear_paired_phones()); + reset_client_keys_for_tests(); + assert!(restore_client_keys(&stored)); + embassy_futures::block_on(add_paired_phone(OWNER)); + embassy_futures::block_on(prune_phone_validations()); + assert!(is_client_key_enrolled(OWNER)); + assert!(!is_client_key_enrolled(SECOND)); + let persisted = try_take_client_keys_to_store().expect("the pruned keys to store"); + assert_eq!(persisted, encode_client_keys()); +} + +#[test] +fn the_key_stays_when_the_validation_ends() { + boot(); + assert!(enroll(OWNER, OWNER_KEY, "Pixel").success); + approve_can_read_write().unwrap(); + // Moved to another car and approved there: every validation ends. + assert!(confirm_car_fingerprint(CAR_B)); + approve_can_read_write().unwrap(); + assert!(!core_interface::is_phone_validated(OWNER)); + assert!(is_client_key_enrolled(OWNER)); + assert_eq!(client_for_key(&OWNER_KEY).unwrap().0, OWNER); +} + +// ── Persistence ─────────────────────────────────────────────────────────────── + +#[test] +fn keys_round_trip_through_the_store_encoding() { + boot(); + assert!(validate_phone_for_tests(SECOND)); + assert!(enroll(OWNER, OWNER_KEY, "Pixel 9 Pro").success); + assert!(enroll(SECOND, SECOND_KEY, "").success); + let stored = try_take_client_keys_to_store().expect("a change to store"); + assert_eq!(stored, encode_client_keys()); + + reset_client_keys_for_tests(); + assert!(!is_client_key_enrolled(OWNER)); + assert!(restore_client_keys(&stored)); + assert_eq!(client_for_key(&OWNER_KEY).unwrap().0, OWNER); + assert_eq!(client_for_key(&SECOND_KEY).unwrap().0, SECOND); + assert_eq!(client_key_label(OWNER), "Pixel 9 Pro"); + assert_eq!(encode_client_keys(), stored); +} + +#[test] +fn malformed_stored_keys_read_as_none() { + boot(); + assert!(enroll(OWNER, OWNER_KEY, "Pixel").success); + let stored = encode_client_keys(); + for bad in [ + vec![], + vec![2, 0], + stored[..stored.len() - 1].to_vec(), + [stored.as_slice(), &[0]].concat(), + ] { + reset_client_keys_for_tests(); + assert!(!restore_client_keys(&bad), "{bad:?}"); + assert!(!is_client_key_enrolled(OWNER)); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index b3451f8..9ad2f2b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,7 +12,7 @@ The intermediary between transport layers (BLE/MQTT) and vehicle logic. Knows no * Defines 12 static `Channel`s as the inter-crate contract (see [Channels](#channels)). * Defines shared types: `Transport`, `InboundCommand`, `VehicleStatePayload`, `CanLogFrame`. * Defines pure-logic `#[embassy_executor::task]` functions: `process_ble_commands_task`, `process_mqtt_commands_task`, `route_responses_task`, `publish_state_task`, `publish_can_access_task`, `publish_command_availability_task`, `publish_can_bus_health_task`. -* Exposes `pub fn passes_filter()`, `pub fn is_can_read_only()`, `pub fn set_can_read_only(bool)`, the CAN read-write policy (car identity, owner approval, dev lock; see [CAN](can.md#read-write-policy)), the CAN TX classes (`CanTxFrame`, `CommandAuthorization`; see [CAN](can.md#tx-classes)), phone trust and validation sessions (see [BLE](ble.md#phone-trust)), and the SavvyCAN logging API (`is_can_logging`, `log_can_frame`, `run_can_log_session`). +* Exposes `pub fn passes_filter()`, `pub fn is_can_read_only()`, `pub fn set_can_read_only(bool)`, the CAN read-write policy (car identity, owner approval, dev lock; see [CAN](can.md#read-write-policy)), the CAN TX classes (`CanTxFrame`, `CommandAuthorization`; see [CAN](can.md#tx-classes)), phone trust and validation sessions (see [BLE](ble.md#phone-trust)), the secure channel's keys (the device identity and the client key registry, see [BLE](ble.md#device-identity)), and the SavvyCAN logging API (`is_can_logging`, `log_can_frame`, `run_can_log_session`). * Has 4 inner async helpers (`handle_ble_message`, `handle_mqtt_message`, `route_single_response`, `publish_single_state`) extracted from the task loops so they can be unit-tested without running an executor. * **`publish_single_state` is intentionally non-blocking:** state updates don't go through the TX queues. Each transport has a single-value slot (`BLE_STATE_TX`, `MQTT_STATE_TX`, embassy `Signal`s) that the newest update overwrites. This guarantees `publish_state_task` never stalls, keeping `VEHICLE_STATE_CHANNEL` always drainable and preventing a deadlock cascade through `state_update_task` and command-handler tasks, and a state update can never push a command response out of a queue. * Uses `#![cfg_attr(not(test), no_std)]` so host tests compile without a `no_std` target. diff --git a/docs/ble.md b/docs/ble.md index ee484bc..4427e07 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -60,7 +60,7 @@ Encryption is checked via a per-connection `tx_auth: AtomicBool` (initialized `f trouble-host's `notify` sends nothing to a peer that hasn't enabled notifications (and still returns `Ok`), and the app subscribes only after the link is encrypted, so the first state update after connecting would otherwise be lost. `publish_single_state` keeps the last BLE state message in `core_interface::latest_ble_state()` (unlike `BLE_STATE_TX`, it isn't emptied when sent). When the app writes the TX characteristic's CCCD with notifications enabled, `gatt_event_task` signals `ble_tx_notify_task`, which sends that cached state (full state, original timestamp) through the normal path, `SUBSCRIBE_RESEND_DELAY_MS` (500 ms) later: a notification sent right as the CCCD write is accepted was lost on Android, before the app's notification stream was listening. It is still held until the link is encrypted. Nothing is sent if the vehicle hasn't published a state since boot. The CAN access state (`SystemState.can_access`, sent with the connected phone's `SystemState.phone_access`, see [Phone trust](#phone-trust)) the command availability (`SystemState.command_availability`) and the CAN bus health (`SystemState.can_bus_health`) are sent again too (`resend_can_access_state()`, `resend_command_availability()`, `resend_can_bus_health()`), and all three are repeated every few seconds anyway (see [CAN](can.md#read-write-policy), [Vehicle commands](commands.md#command-availability) and [Bus health](can.md#bus-health)). A message the app was already subscribed for may arrive twice; state updates are idempotent. ## MQTT client ID -The access state update also carries `SystemState.mqtt_client_id`, the `network.mqtt.client_id` this device's topics are built from, and it is unset in a build without MQTT. The app can't know it otherwise, and needs it to use this device's topics. So give each device its own `client_id`. +The access state update also carries the [device identity](#device-identity) and `SystemState.mqtt_client_id`, the `network.mqtt.client_id` this device's topics are built from, and it is unset in a build without MQTT. The app can't know it otherwise, and needs it to use this device's topics. So give each device its own `client_id`. ## CAN read-write commands `SetCanReadWriteApprovalCommand` and `SetCanDevWriteUnlockCommand` are handled in `core-interface`'s dispatcher, not forwarded to the board: only from a phone in the paired-phone registry (checked against the stamped `source_device_id`), and answered with a `CommandResponse`. Once a phone is validated for the identified car, the approval needs a validated phone (see [Phone trust](#phone-trust)). Unlike phone management they don't need the pairing window. See [CAN](can.md#read-write-policy) for the policy. @@ -94,10 +94,25 @@ A vehicle command needs all three, plus the dev lock in development builds. The The platform-specific methods are added per vehicle (E-GMP: a [code shown on the cluster](can.md#e-gmp-cluster-code), in Ready with media playing); a vehicle that declares none can't validate a phone, so none of its commands run. virtual-car's simulated methods are described in [CAN](can.md#car-identity). +## Device identity +The device's identity for the [secure channel](https://github.com/OpenCarControls/contracts/blob/main/docs/secure-channel.md) is an X25519 static key pair (`identity.rs`). It is made once, from the board's random source (`set_random_source`), and kept until the flash is erased: bond resets and `ClearPairedPhones` keep it, since it belongs to the device and not to its owner. There is no factory reset that rotates it short of erasing the flash; the phones pair again then anyway. Without a random source there is no identity and the secure channel is off, rather than a guessable key. The ESP only makes one once the BLE controller is up, since its RNG is only a true random source while the radio runs. + +The board hands what it stored to `restore_device_identity()` at boot and stores what that returns, if anything (a key made on the first boot). The public key and its **device key ID** (the lowercase hex of the first 10 bytes of its BLAKE2s-256 hash) are reported in `SystemState.device_identity`, sent with the access state over BLE only, and in the answer to `EnrollClientKeyCommand`. The app pins the key per paired vehicle. + +## Client keys +A client (the app) reaches the device over the secure channel with its own X25519 static key, which it enrolls over BLE (`EnrollClientKeyCommand`, handled by the dispatcher, `client_keys.rs`): + +* Only from a phone validated for the identified car (`REJECTED_NOT_VALIDATED` otherwise), and only over BLE (the MQTT dispatcher drops every system command). The key belongs to the sending phone (`CLIENT_KIND_PHONE`): it is stored under the phone's stamped `ble:` device ID, which the channel will stamp as `source_device_id` on what the phone sends through it. Enrolling again replaces the phone's key. Hubs (`CLIENT_KIND_HUB`), a key that isn't 32 bytes or is all zeros, a label over 32 bytes and a key enrolled by another client are refused. +* It is answered with the device identity. `ListPairedPhones` reports which phones have a key (`remote_key_enrolled`) and its label. +* A phone's key goes away with its bond: removing the phone or pairing it again (`forget_phone_validation`), clearing the phones (`clear_paired_phones`), and a bond reset (`prune_phone_validations` at boot drops the keys of phones no longer bonded). A phone that loses its validation, when another car is approved, keeps its key: its vehicle commands are refused like over BLE. +* `client_for_key()` maps a static public key to its client's ID and kind, for the channel's handshake. + +The keys are persisted like the validations: `encode_client_keys()` (a format version, then each client's kind, ID, key and label), `client_keys_to_store()` / `try_take_client_keys_to_store()` for the board, `restore_client_keys()` at boot before pruning. + ## Removing phones `RemovePairedPhone` / `ClearPairedPhones` (only accepted while the pairing window is open) queue a `BondOp` for the BLE task, which owns the bonds. Removing a validated phone, or clearing them while one is validated, needs a validated phone; the dispatcher answers a refused one with `REJECTED_NOT_VALIDATED` and doesn't forward it. It removes each bond from the stack, the `BondStore` flash, the controller's filter accept and resolving lists, and the paired-phone registry in `core-interface`, and disconnects the phone if it is connected. A removed phone can no longer reconnect. The `device_id` is `ble:` followed by the phone's 6-byte address (the same stamp as `source_device_id`). -The registry only mirrors the bonds (restored from flash at startup, updated on pairing and removal), so `ListPairedPhones` reports real bonds; `core-interface` answers it with each phone's trust level. Removing a phone from the registry also ends its validation. `UpsertPairedPhone` is ignored on ESP: phones enter by pairing. +The registry only mirrors the bonds (restored from flash at startup, updated on pairing and removal), so `ListPairedPhones` reports real bonds; `core-interface` answers it with each phone's trust level. Removing a phone from the registry also ends its validation and drops its [client key](#client-keys). `UpsertPairedPhone` is ignored on ESP: phones enter by pairing. ## Restart `RestartCommand` is checked and answered by `core-interface`'s dispatcher, then forwarded to the board. It needs a bonded phone, and a validated one once a phone is validated for the identified car (see [Phone trust](#phone-trust)): a restart ends what the device is doing for the owner, such as a battery preconditioning session, and unlocks nothing. A refusal is answered like the approval's and never reaches the board. It doesn't need the pairing window. MQTT drops it, like every system command. @@ -145,7 +160,7 @@ Paired-phone data is persisted in flash using `esp-storage` (single sector, chec LTKs (`BondInformation`) are persisted by `BondStore` (`sequential-storage` map keyed by the phone's address) in the last two flash sectors. On startup the BLE task loads the bonds and feeds them back via `stack.add_bond_information()` before `stack.build()`, so the phone can re-encrypt without re-pairing after a power cycle. -The two sectors before them hold the owner's CAN read-write approval (`StoredApproval`: a format version and the approved car's digest, see [CAN](can.md#read-write-policy)) and, under a second key, the validated phones (the bytes of `encode_phone_validations()`: a format version, the car digest and the device IDs, see [Phone trust](#phone-trust)). The BLE task owns the flash, so it restores both before the stack starts (pruning the validations once the bonds are loaded) and writes each change `core-interface` hands it (`can_read_write_approval_to_store()`, `phone_validations_to_store()`), from the advertise loop or, during a connection, from `gatt_event_task`. If the range can't be written it is erased and both items are written again from their current values. Erasing the flash clears the bonds, the approval and the validations. The PC board keeps the validations in the file `[hardware.pc] phone_validations_file`. +The two sectors before them (the "access range") hold the owner's CAN read-write approval (`StoredApproval`: a format version and the approved car's digest, see [CAN](can.md#read-write-policy)) and, under their own keys, the validated phones (the bytes of `encode_phone_validations()`: a format version, the car digest and the device IDs, see [Phone trust](#phone-trust)), the [device identity](#device-identity) (a format version and the private key) and the [client keys](#client-keys) (`encode_client_keys()`). The BLE task owns the flash, so it restores them before the stack starts (pruning the validations and the client keys once the bonds are loaded; the identity once the BLE controller is up, making it on the first boot) and writes each change `core-interface` hands it (`can_read_write_approval_to_store()`, `phone_validations_to_store()`, `client_keys_to_store()`), from the advertise loop or, during a connection, from `gatt_event_task`. If the range can't be written it is erased and every item is written again from its current value, the identity first. Erasing the flash clears the bonds, the approval, the validations, the identity and the client keys. The PC board keeps the validations, the identity and the client keys in the files `[hardware.pc] phone_validations_file`, `device_identity_file` and `client_keys_file`. The two sectors before the approval hold the count of short boots for the [bond reset by power-cycling](#bond-reset-by-power-cycling) (a single `u8`). It has its own range so that a write failing on it (which erases that range) can never touch the bonds or the approval. diff --git a/docs/testing.md b/docs/testing.md index 9be40ba..3a95280 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 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 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` | From 16d52848575e194e31df16b20b16835a0a1a94a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 01:37:59 +0000 Subject: [PATCH 3/4] feat(secure): run the secure channel in core-interface The device side of the secure channel (contracts#44, phase 1), independent of the transport that carries its frames: - noise.rs: Noise_IK_25519_ChaChaPoly_BLAKE2s (responder, plus a test initiator), written on x25519-dalek, chacha20poly1305 and blake2; passes the contracts' test vectors byte for byte. - secure_channel.rs: frames, the 64-wide replay window, a session table (4 sessions, 2 per client) with idle, lifetime and message-count expiry, sessions ended by a closed link or a removed key, silent drops for unknown keys and replayed handshakes, unknown session replies, seal() for outbound messages and SECURE_TX_CHANNEL for responses. - dispatch: handle_secure_message stamps the client's ID and applies the same checks as BLE to basic and advanced commands; system commands are dropped. Transport::Secure routes responses back through the session. - Constants from [secure_channel] in transport.toml. Closes #119 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiWM4SEVB1xBTaoykRa --- Cargo.lock | 64 +++ core-interface/Cargo.toml | 3 + core-interface/build.rs | 107 ++++ core-interface/src/client_keys.rs | 3 +- core-interface/src/dedupe.rs | 8 +- core-interface/src/dispatch.rs | 158 ++++-- core-interface/src/identity.rs | 4 +- core-interface/src/lib.rs | 23 +- core-interface/src/noise.rs | 510 +++++++++++++++++++ core-interface/src/routing.rs | 45 +- core-interface/src/secure_channel.rs | 520 +++++++++++++++++++ core-interface/src/types.rs | 8 +- core-interface/tests/secure_channel.rs | 672 +++++++++++++++++++++++++ docs/architecture.md | 19 +- docs/ble.md | 2 +- docs/testing.md | 2 +- 16 files changed, 2068 insertions(+), 80 deletions(-) create mode 100644 core-interface/src/noise.rs create mode 100644 core-interface/src/secure_channel.rs create mode 100644 core-interface/tests/secure_channel.rs 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` | From c6179b316137d87c83a3f58d0bac99f9f5cf490e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 18:15:50 +0000 Subject: [PATCH 4/4] chore(contracts): pin to contracts main after the secure channel merge Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkZEiWM4SEVB1xBTaoykRa --- contracts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts b/contracts index 4ce23a0..d825689 160000 --- a/contracts +++ b/contracts @@ -1 +1 @@ -Subproject commit 4ce23a07186da9982f43183a3e208ea1819893a3 +Subproject commit d825689a2436f0f34fdb3b9dfe7b52a0467c3a8e