Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/ci/esp-lte-mtls.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
80 changes: 79 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

108 changes: 100 additions & 8 deletions boards/esp/src/ble/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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<u8, ACCESS_BUFFER_BYTES> {
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<u8, ACCESS_BUFFER_BYTES> {
self.load_access_item(CLIENT_KEYS_KEY, "Client keys").await
}

async fn load_access_item(
&mut self,
key: u8,
what: &str,
) -> heapless::Vec<u8, ACCESS_BUFFER_BYTES> {
let mut data_buffer = [0u8; ACCESS_BUFFER_BYTES];
match map::<u8, _>(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::<u8, _>(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]>,
Expand All @@ -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(())
}

Expand Down
40 changes: 34 additions & 6 deletions boards/esp/src/ble/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand All @@ -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<DefaultPacketPool, BLE_CONNECTIONS_MAX, BLE_L2CAP_CHANNELS_MAX>,
Expand All @@ -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 {
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions boards/esp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {}
}
}
Expand Down
Loading