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/contracts b/contracts index 1faf470..4ce23a0 160000 --- a/contracts +++ b/contracts @@ -1 +1 @@ -Subproject commit 1faf470ab2490fdb73bd65da092798396a26bef8 +Subproject commit 4ce23a07186da9982f43183a3e208ea1819893a3 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` |