git clone https://garage44.eu/jeroen/pinnacle.gitcartopolis-agent · 2026-11-30T15:10:23Z
feat(bt): recognise a paired device that moves to a private address Pairing now hands over identities (Vol 3 Part H 3.6.4): once the link is encrypted each side sends its identity resolving key and the address that does not change, the responder first. A bond keeps the peer's IRK, and the host resolves every address it hears or connects from against the IRKs kept: a phone that moved to a new resolvable private address is found and connected by its identity, and its link encrypted with the key kept, with no new pairing. Found entries keep the address last heard (air), which a connection goes to. Bonds on disk grow to 40 bytes when they hold an IRK, flagged in the byte after the key; 24-byte bonds kept before still read. The simulated air lets a controller move to a private address (Controller::move_to), and the address hash is checked against the spec's sample (Appendix D.7).
bt/src/host.rs | 202 ++++++++++++++++++++++++++++++++++++++++++++------------
bt/src/lib.rs | 4 +-
bt/src/sim.rs | 40 ++++++++---
bt/src/smp.rs | 192 ++++++++++++++++++++++++++++++++++++++++++++++++-----
bt/src/tests.rs | 163 +++++++++++++++++++++++++++++++++++++++++++--
5 files changed, 527 insertions(+), 74 deletions(-)
diff --git a/bt/src/host.rs b/bt/src/host.rs
index 397a851..fdb323d 100644
--- a/bt/src/host.rs
+++ b/bt/src/host.rs
@@ -108,9 +108,11 @@ pub enum Event {
}
/// A device paired with: what encrypts the link to it again without
-/// pairing anew.
+/// pairing anew, and knows it by whatever address it uses.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Bond {
+ /// Its identity address where it gave one, else the address it paired
+ /// from.
pub address: Address,
/// Its address type (0 public, 1 random).
pub kind: u8,
@@ -119,35 +121,60 @@ pub struct Bond {
/// Whether the pairing compared numbers (a device in the middle would
/// have shown a different one); not, for a device without a display.
pub compared: bool,
+ /// Its identity resolving key: the private addresses it moves to are
+ /// known by it ([`smp::resolves`]).
+ pub irk: Option<[u8; 16]>,
}
+/// In a kept bond's last byte besides "compared": an IRK follows.
+const HAS_IRK: u8 = 0x02;
+
impl Bond {
- pub const SIZE: usize = 24;
-
- /// Address, type, key, compared: for keeping it on disk.
- pub fn to_bytes(&self) -> [u8; Bond::SIZE] {
- let mut b = [0u8; Bond::SIZE];
- b[..6].copy_from_slice(&self.address.0);
- b[6] = self.kind;
- b[7..23].copy_from_slice(&self.key);
- b[23] = u8::from(self.compared);
+ /// Address, type, key, compared, and the IRK where there is one: for
+ /// keeping it on disk. 24 bytes without one, as bonds were kept before
+ /// identities, or 40 with.
+ pub fn to_bytes(&self) -> Vec<u8> {
+ let mut b = self.address.0.to_vec();
+ b.push(self.kind);
+ b.extend_from_slice(&self.key);
+ b.push(u8::from(self.compared) | if self.irk.is_some() { HAS_IRK } else { 0 });
+ if let Some(irk) = self.irk {
+ b.extend_from_slice(&irk);
+ }
b
}
- pub fn from_bytes(b: &[u8]) -> Option<Bond> {
- (b.len() == Bond::SIZE).then(|| Bond {
+ /// The bond at the start of `b`, and how many bytes it took.
+ pub fn from_bytes(b: &[u8]) -> Option<(Bond, usize)> {
+ let flags = *b.get(23)?;
+ let irk = match flags & HAS_IRK {
+ 0 => None,
+ _ => Some(b.get(24..40)?.try_into().unwrap()),
+ };
+ let bond = Bond {
address: Address(b[..6].try_into().unwrap()),
kind: b[6],
key: b[7..23].try_into().unwrap(),
- compared: b[23] != 0,
- })
+ compared: flags & 1 != 0,
+ irk,
+ };
+ Some((bond, if irk.is_some() { 40 } else { 24 }))
+ }
+
+ /// Whether `address` is this device's: its own, or one it moved to.
+ pub fn knows(&self, address: Address) -> bool {
+ address == self.address || self.irk.is_some_and(|irk| smp::resolves(&irk, &address.0))
}
}
/// A device seen while scanning.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Found {
+ /// Its address, or a paired device's identity whatever address it
+ /// advertised from.
pub address: Address,
+ /// The address it was last heard from, which a connection goes to.
+ pub air: Address,
pub name: Option<String>,
pub rssi: i8,
/// When it was last heard (ms, the caller's clock).
@@ -167,7 +194,10 @@ enum Request {
struct Connection {
handle: u16,
+ /// The peer, by its identity once known ([`Bond::address`]).
peer: Address,
+ /// The address it connected from, which pairing's functions take.
+ air: Address,
central: bool,
mtu: usize,
/// An L2CAP frame being put together from ACL fragments, and its
@@ -239,6 +269,9 @@ pub struct Host {
io: u8,
/// Where pairing's secrets come from; none, and pairing is refused.
random: Option<Random>,
+ /// This device's identity resolving key, handed to every device it
+ /// pairs with.
+ irk: Option<[u8; 16]>,
}
/// Secret bytes for pairings: HMAC-SHA-256 of a seed over a count.
@@ -295,6 +328,7 @@ impl Host {
bonds: Vec::new(),
io: smp::NO_INPUT_NO_OUTPUT,
random: None,
+ irk: None,
};
host.command(hci::RESET, &[]);
host
@@ -331,6 +365,15 @@ impl Host {
self.io = io;
}
+ /// This device's identity resolving key, kept by whoever runs the host
+ /// (it must stay the same across starts): handed with this device's
+ /// address to each device it pairs with, so a peer that keeps it knows
+ /// this device by it. Without one, peers get no identity of ours, and
+ /// theirs is still asked for.
+ pub fn set_identity(&mut self, irk: [u8; 16]) {
+ self.irk = Some(irk);
+ }
+
/// The devices paired with, kept by whoever runs the host and given
/// back to it at start ([`Host::remember`]).
pub fn bonds(&self) -> &[Bond] {
@@ -340,12 +383,37 @@ impl Host {
pub fn remember(&mut self, bond: Bond) {
self.bonds.retain(|b| b.address != bond.address);
self.bonds.push(bond);
+ // Heard before it was known: now by its identity, once.
+ for f in &mut self.found {
+ if bond.knows(f.air) {
+ f.address = bond.address;
+ }
+ }
+ let mut seen = Vec::new();
+ self.found.retain(|f| {
+ let first = !seen.contains(&f.address);
+ seen.push(f.address);
+ first
+ });
+ }
+
+ /// The identity of a paired device `air` is, or `air` itself.
+ fn resolve(&self, air: Address) -> Address {
+ self.bonds
+ .iter()
+ .find(|b| b.knows(air))
+ .map_or(air, |b| b.address)
}
/// Forgets a pairing: the next connection is in the open until paired
/// again. A link to it now is dropped.
pub fn forget(&mut self, address: Address) {
self.bonds.retain(|b| b.address != address);
+ for f in &mut self.found {
+ if f.address == address {
+ f.address = f.air;
+ }
+ }
let connected: Vec<u16> = self
.connections
.iter()
@@ -369,7 +437,7 @@ impl Host {
let c = self.connections.iter().find(|c| c.handle == connection)?;
Some((
smp::address_bytes(self.address.0, 0),
- smp::address_bytes(c.peer.0, c.peer_kind),
+ smp::address_bytes(c.air.0, c.peer_kind),
))
}
@@ -402,12 +470,12 @@ impl Host {
let Some((own, peer_bytes)) = self.addresses(connection) else {
return;
};
- let (io, now) = (self.io, self.now);
+ let (io, irk, now) = (self.io, self.irk, self.now);
let Some(random) = self.random.as_mut() else {
return;
};
let (pairing, out) =
- smp::Pairing::start(io, own, peer_bytes, &mut |b: &mut [u8]| random.fill(b), now);
+ smp::Pairing::start(io, own, peer_bytes, irk, &mut |b: &mut [u8]| random.fill(b), now);
if let Some(c) = self.connection(connection) {
c.pairing = Some(pairing);
}
@@ -465,11 +533,44 @@ impl Host {
self.start_encryption(connection, &key);
}
}
- smp::Output::Failed(reason) => self.events.push_back(Event::PairingFailed {
- connection,
- peer,
- reason,
- }),
+ smp::Output::Keys(identity) => {
+ let Some(c) = self.connection(connection) else {
+ continue;
+ };
+ let Some((key, compared)) = c.paired.take() else {
+ continue;
+ };
+ let bond = match identity {
+ Some(id) => Bond {
+ address: Address(id.address),
+ kind: id.kind,
+ key,
+ compared,
+ irk: Some(id.irk),
+ },
+ None => Bond {
+ address: c.air,
+ kind: c.peer_kind,
+ key,
+ compared,
+ irk: None,
+ },
+ };
+ // Known by its identity from here on.
+ c.peer = bond.address;
+ self.remember(bond);
+ self.events.push_back(Event::Paired { connection, bond });
+ }
+ smp::Output::Failed(reason) => {
+ if let Some(c) = self.connection(connection) {
+ c.paired = None;
+ }
+ self.events.push_back(Event::PairingFailed {
+ connection,
+ peer,
+ reason,
+ })
+ }
}
}
}
@@ -600,11 +701,17 @@ impl Host {
self.command(hci::LE_SET_ADVERTISE_ENABLE, &[u8::from(on)]);
}
- /// Connects to a device heard while scanning (scanning stops for it).
+ /// Connects to a device heard while scanning (scanning stops for it),
+ /// at the address it was last heard from.
pub fn connect(&mut self, peer: Address) {
if self.connecting.is_some() || self.connections.iter().any(|c| c.peer == peer) {
return;
}
+ let peer = self
+ .found
+ .iter()
+ .find(|f| f.address == peer)
+ .map_or(peer, |f| f.air);
if self.scanning {
self.command(hci::LE_SET_SCAN_ENABLE, &[0x00, 0x00]);
}
@@ -812,11 +919,13 @@ impl Host {
}
let handle = u16::from_le_bytes([p[2], p[3]]);
let central = p[4] == 0;
- let peer = Address(p[6..12].try_into().unwrap());
+ let air = Address(p[6..12].try_into().unwrap());
+ let peer = self.resolve(air);
let peer_kind = p[5];
self.connections.push(Connection {
handle,
peer,
+ air,
central,
mtu: att::DEFAULT_MTU,
rx: Vec::new(),
@@ -884,12 +993,15 @@ impl Host {
hci::EVT_ENCRYPTION_CHANGE if p.len() >= 4 => {
let handle = u16::from_le_bytes([p[1], p[2]]);
let (status, on) = (p[0], p[3] != 0);
+ let now = self.now;
let Some(c) = self.connection(handle) else { return };
let peer = c.peer;
- let kind = c.peer_kind;
if status != hci::SUCCESS || !on {
c.encrypted = false;
let pairing = c.paired.take().is_some();
+ if pairing {
+ c.pairing = None;
+ }
self.events.push_back(if pairing {
Event::PairingFailed {
connection: handle,
@@ -906,19 +1018,14 @@ impl Host {
return;
}
c.encrypted = true;
- if let Some((key, compared)) = c.paired.take() {
- let bond = Bond {
- address: peer,
- kind,
- key,
- compared,
- };
- self.remember(bond);
- self.events.push_back(Event::Paired {
- connection: handle,
- bond,
- });
- }
+ // A pairing's key: the identities are handed over now, and
+ // the bond kept once they are ([`smp::Output::Keys`]).
+ let out = match (c.paired.is_some(), c.pairing.as_mut()) {
+ (true, Some(pairing)) => pairing.encrypted(now),
+ _ => Vec::new(),
+ };
+ self.smp_outputs(handle, out);
+ let peer = self.connection(handle).map_or(peer, |c| c.peer);
self.events.push_back(Event::Encrypted {
connection: handle,
peer,
@@ -996,7 +1103,9 @@ impl Host {
if p.len() < 9 {
return;
}
- let address = Address(p[2..8].try_into().unwrap());
+ let air = Address(p[2..8].try_into().unwrap());
+ // A paired device that moved address is still the one known.
+ let address = self.resolve(air);
let len = p[8] as usize;
if p.len() < 9 + len + 1 {
return;
@@ -1008,6 +1117,7 @@ impl Host {
let seen = self.now;
let tell = match self.found.iter_mut().find(|f| f.address == address) {
Some(f) => {
+ f.air = air;
f.rssi = rssi;
f.seen = seen;
let learnt = name.is_some() && f.name != name;
@@ -1022,6 +1132,7 @@ impl Host {
0,
Found {
address,
+ air,
name: name.clone(),
rssi,
seen,
@@ -1092,13 +1203,20 @@ impl Host {
let Some((own, peer_bytes)) = self.addresses(connection) else {
return;
};
- let io = self.io;
+ let (io, irk) = (self.io, self.irk);
let Some(random) = self.random.as_mut() else {
self.send_smp(connection, &[smp::PAIRING_FAILED, smp::NOT_SUPPORTED]);
return;
};
- let (pairing, out) =
- smp::Pairing::answer(io, own, peer_bytes, p, &mut |b: &mut [u8]| random.fill(b), now);
+ let (pairing, out) = smp::Pairing::answer(
+ io,
+ own,
+ peer_bytes,
+ irk,
+ p,
+ &mut |b: &mut [u8]| random.fill(b),
+ now,
+ );
if let Some(c) = self.connection(connection) {
c.pairing = Some(pairing);
}
diff --git a/bt/src/lib.rs b/bt/src/lib.rs
index 2e2ba6a..879e44c 100644
--- a/bt/src/lib.rs
+++ b/bt/src/lib.rs
@@ -15,7 +15,9 @@
//! Secure Connections ([`smp`]: a six-digit number compared on both
//! screens, or "just works" with a device that has none), after which the
//! controllers encrypt the link, and a bonded device's link is encrypted
-//! again on every connection with the key kept ([`Bond`]).
+//! again on every connection with the key kept ([`Bond`]); the two hand
+//! each other their identity as they pair, so a paired device that moves to
+//! a new private address is still known.
#![no_std]
diff --git a/bt/src/sim.rs b/bt/src/sim.rs
index ef7c318..7e3d8f8 100644
--- a/bt/src/sim.rs
+++ b/bt/src/sim.rs
@@ -10,6 +10,8 @@
//! from that key, a counter a direction for the nonce, a 4-byte check), and
//! [`Air::heard`] keeps what a listener would have picked up. The session
//! key's derivation and the nonce are the sim's own, not the link layer's.
+//! A controller may move to a private address ([`Controller::move_to`]), as
+//! a phone does for privacy.
use crate::hci::{self, Address, Framer, Packet};
use alloc::collections::VecDeque;
@@ -39,6 +41,8 @@ struct Link {
pub struct Controller {
address: Address,
+ /// The private address it moved to, which the air hears instead.
+ private: Option<Address>,
framer: Framer,
out: VecDeque<Vec<u8>>,
advertising: bool,
@@ -69,6 +73,7 @@ impl Controller {
pub fn new(address: Address) -> Controller {
Controller {
address,
+ private: None,
framer: Framer::default(),
out: VecDeque::new(),
advertising: false,
@@ -91,6 +96,23 @@ impl Controller {
self.address
}
+ /// Moves to a private address, as a phone or a watch does every few
+ /// minutes for privacy (a resolvable one, from its IRK: [`crate::smp::private_address`]):
+ /// from now on it advertises and connects from that, of the random
+ /// type, and no longer answers at the old one. Its host is not told,
+ /// as a controller resolving addresses itself would not tell it.
+ pub fn move_to(&mut self, address: Address) {
+ self.private = Some(address);
+ }
+
+ /// The address the air hears, and its type (0 public, 1 random).
+ fn on_air(&self) -> (Address, u8) {
+ match self.private {
+ Some(a) => (a, 1),
+ None => (self.address, 0),
+ }
+ }
+
/// The next bytes for the host.
pub fn transmit(&mut self) -> Option<Vec<u8>> {
self.out.pop_front()
@@ -211,11 +233,11 @@ impl Controller {
}
}
- fn connection_complete(&mut self, handle: u16, central: bool, peer: Address) {
+ fn connection_complete(&mut self, handle: u16, central: bool, (peer, kind): (Address, u8)) {
let mut p = alloc::vec![hci::LE_CONNECTION_COMPLETE, hci::SUCCESS];
p.extend_from_slice(&handle.to_le_bytes());
p.push(u8::from(!central));
- p.push(0);
+ p.push(kind);
p.extend_from_slice(&peer.0);
p.extend_from_slice(&[0x18, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00]);
self.event(hci::EVT_LE_META, p);
@@ -242,8 +264,8 @@ impl Controller {
self.event(hci::EVT_LE_META, p);
}
- fn advertising_report(&mut self, from: Address, data: &[u8], rssi: i8) {
- let mut p = alloc::vec![hci::LE_ADVERTISING_REPORT, 1, 0x00, 0x00];
+ fn advertising_report(&mut self, (from, kind): (Address, u8), data: &[u8], rssi: i8) {
+ let mut p = alloc::vec![hci::LE_ADVERTISING_REPORT, 1, 0x00, kind];
p.extend_from_slice(&from.0);
p.push(data.len() as u8);
p.extend_from_slice(data);
@@ -308,14 +330,14 @@ impl Air {
continue;
}
let (from, data) = (
- self.controllers[i].address,
+ self.controllers[i].on_air(),
self.controllers[i].advertising_data.clone(),
);
for (j, scanner) in self.controllers.iter_mut().enumerate() {
- if i == j || !scanner.scanning || scanner.reported.contains(&from) {
+ if i == j || !scanner.scanning || scanner.reported.contains(&from.0) {
continue;
}
- scanner.reported.push(from);
+ scanner.reported.push(from.0);
let rssi = -40 - (i as i8 + j as i8) * 7;
scanner.advertising_report(from, &data, rssi);
}
@@ -328,7 +350,7 @@ impl Air {
let Some(j) = self
.controllers
.iter()
- .position(|c| c.address == peer && c.advertising)
+ .position(|c| c.on_air().0 == peer && c.advertising)
else {
continue;
};
@@ -356,7 +378,7 @@ impl Air {
sent: 0,
received: 0,
});
- let (ai, aj) = (self.controllers[i].address, self.controllers[j].address);
+ let (ai, aj) = (self.controllers[i].on_air(), self.controllers[j].on_air());
self.controllers[i].connection_complete(hi, true, aj);
self.controllers[j].connection_complete(hj, false, ai);
}
diff --git a/bt/src/smp.rs b/bt/src/smp.rs
index 3dfde3a..38d9914 100644
--- a/bt/src/smp.rs
+++ b/bt/src/smp.rs
@@ -7,11 +7,16 @@
//! fake; with none on one side the pairing is "just works", private from
//! listeners but not proof against a device in the middle.
//!
+//! Once the link is encrypted the two hand each other their identity
+//! (Vol 3 Part H 3.6.4): an identity resolving key (IRK) and the address
+//! that does not change. A phone or a watch moves to a new resolvable
+//! private address every few minutes, made from its IRK ([`ah`]), so a
+//! listener cannot follow it; whoever holds the IRK knows it still
+//! ([`resolves`]).
+//!
//! What is not here: legacy pairing (before Bluetooth 4.2: its key is
//! found from a recorded pairing, so it is refused), a passkey typed on
-//! one side (a keyboard pairing), out-of-band data, and the keys a pairing
-//! may hand over afterwards (identity and signing keys): none is asked for
-//! or given, so a device that changes its address is not recognised.
+//! one side (a keyboard pairing), out-of-band data, and signing keys.
//!
//! Bytes are as they go over the air, least significant first, the
//! functions too (Linux's convention): `cmac` turns them round for AES.
@@ -28,6 +33,8 @@ pub const PAIRING_FAILED: u8 = 0x05;
pub const SECURITY_REQUEST: u8 = 0x0b;
pub const PAIRING_PUBLIC_KEY: u8 = 0x0c;
pub const PAIRING_DHKEY_CHECK: u8 = 0x0d;
+pub const IDENTITY_INFORMATION: u8 = 0x08;
+pub const IDENTITY_ADDRESS_INFORMATION: u8 = 0x09;
// Why a pairing failed.
pub const AUTHENTICATION_REQUIREMENTS: u8 = 0x03;
@@ -52,6 +59,10 @@ const BONDING: u8 = 0x01;
const MITM: u8 = 0x04;
const SECURE_CONNECTIONS: u8 = 0x08;
+// The keys handed over after pairing: only the identity is asked for or
+// given (Secure Connections agrees the link's key, so none is sent).
+const ID_KEY: u8 = 0x02;
+
/// How long a pairing may wait for the other side, or for its person.
pub const TIMEOUT_MS: u64 = 30_000;
@@ -137,6 +148,33 @@ pub fn g2(u: &[u8; 32], v: &[u8; 32], x: &[u8; 16], y: &[u8; 16]) -> u32 {
u32::from_le_bytes(t[..4].try_into().unwrap()) % 1_000_000
}
+/// The random address hash: ah(k, r) = e(k, 0¹⁰⁴ ‖ r) mod 2²⁴, the IRK
+/// and the three bytes as over the air.
+pub fn ah(irk: &[u8; 16], prand: &[u8; 3]) -> [u8; 3] {
+ let mut key = *irk;
+ key.reverse();
+ let mut block = [0u8; 16];
+ block[13] = prand[2];
+ block[14] = prand[1];
+ block[15] = prand[0];
+ aes::Aes::new(&key).unwrap().encrypt_blocks(&mut block);
+ [block[15], block[14], block[13]]
+}
+
+/// A resolvable private address from an IRK and 22 random bits: the hash
+/// in the low three bytes, `prand` in the high ones, its top bits 0b01.
+pub fn private_address(irk: &[u8; 16], prand: [u8; 3]) -> [u8; 6] {
+ let mut prand = prand;
+ prand[2] = (prand[2] & 0x3f) | 0x40;
+ let hash = ah(irk, &prand);
+ [hash[0], hash[1], hash[2], prand[0], prand[1], prand[2]]
+}
+
+/// Whether `address` is a resolvable private address made from `irk`.
+pub fn resolves(irk: &[u8; 16], address: &[u8; 6]) -> bool {
+ address[5] & 0xc0 == 0x40 && ah(irk, &[address[3], address[4], address[5]]) == address[..3]
+}
+
/// What the machine wants done.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Output {
@@ -146,15 +184,30 @@ pub enum Output {
/// (numeric comparison), or, with `None`, may it pair at all (just
/// works, the peer asking). [`Pairing::confirm`] answers.
Ask(Option<u32>),
- /// Paired: the link's long-term key, and whether the person compared
- /// numbers (proof against a device in the middle).
+ /// Agreed: the link's long-term key, and whether the person compared
+ /// numbers (proof against a device in the middle). The link is to be
+ /// encrypted with it, then [`Pairing::encrypted`] called.
Done {
key: [u8; 16],
compared: bool,
},
+ /// The keys are handed over and the pairing over: the peer's identity,
+ /// if it gave one.
+ Keys(Option<Identity>),
Failed(u8),
}
+/// A device's identity: what it is known by whatever address it uses.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct Identity {
+ /// Its identity resolving key, as over the air.
+ pub irk: [u8; 16],
+ /// The address that does not change, and its type (0 public, 1 static
+ /// random).
+ pub address: [u8; 6],
+ pub kind: u8,
+}
+
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum State {
Response,
@@ -164,6 +217,10 @@ enum State {
/// The person is asked; the peer's check may arrive meanwhile.
Person,
Check,
+ /// The key agreed; the link not yet encrypted with it.
+ Encrypting,
+ /// Encrypted: the keys handed over.
+ Keys,
Over,
}
@@ -190,6 +247,14 @@ pub struct Pairing {
key: [u8; 16],
asked: bool,
peer_check: Option<[u8; 16]>,
+ /// This device's IRK, its identity handed over with its own address.
+ irk: Option<[u8; 16]>,
+ /// The keys agreed: those this device sends, those the peer does.
+ send_keys: u8,
+ take_keys: u8,
+ keys_sent: bool,
+ peer_irk: Option<[u8; 16]>,
+ peer_identity: Option<Identity>,
/// The last time something happened.
pub at: u64,
}
@@ -208,11 +273,14 @@ pub fn address_bytes(address: [u8; 6], kind: u8) -> [u8; 7] {
impl Pairing {
/// `random` gives fresh secret bytes; `own` and `peer` are this
- /// device's and the peer's address bytes ([`address_bytes`]).
+ /// device's and the peer's address bytes ([`address_bytes`]); `irk`
+ /// this device's identity resolving key, handed over with `own` as its
+ /// identity address (so `own` must be one: public or static).
fn new(
initiator: bool,
own: [u8; 7],
peer: [u8; 7],
+ irk: Option<[u8; 16]>,
random: &mut dyn FnMut(&mut [u8]),
now: u64,
) -> Pairing {
@@ -253,16 +321,35 @@ impl Pairing {
key: [0; 16],
asked: false,
peer_check: None,
+ irk,
+ send_keys: 0,
+ take_keys: 0,
+ keys_sent: false,
+ peer_irk: None,
+ peer_identity: None,
at: now,
}
}
/// The request or response this device sends: its IO, no OOB, bonding,
- /// MITM where it can compare, Secure Connections, 16-byte keys, no keys
- /// handed over afterwards.
- fn features(code: u8, io: u8) -> [u8; 7] {
+ /// MITM where it can compare, Secure Connections, 16-byte keys, and the
+ /// keys to hand over afterwards: the initiator's, then the responder's.
+ fn features(code: u8, io: u8, initiator_keys: u8, responder_keys: u8) -> [u8; 7] {
let mitm = if io == NO_INPUT_NO_OUTPUT { 0 } else { MITM };
- [code, io, 0, BONDING | mitm | SECURE_CONNECTIONS, 16, 0, 0]
+ [
+ code,
+ io,
+ 0,
+ BONDING | mitm | SECURE_CONNECTIONS,
+ 16,
+ initiator_keys,
+ responder_keys,
+ ]
+ }
+
+ /// The identity key bit, where this device has one to give.
+ fn own_keys(&self) -> u8 {
+ if self.irk.is_some() { ID_KEY } else { 0 }
}
/// Starts pairing as the central: the request to send.
@@ -270,11 +357,13 @@ impl Pairing {
io: u8,
own: [u8; 7],
peer: [u8; 7],
+ irk: Option<[u8; 16]>,
random: &mut dyn FnMut(&mut [u8]),
now: u64,
) -> (Pairing, Vec<Output>) {
- let mut p = Pairing::new(true, own, peer, random, now);
- p.request = Self::features(PAIRING_REQUEST, io);
+ let mut p = Pairing::new(true, own, peer, irk, random, now);
+ // Ours if we have one; the peer's always asked for.
+ p.request = Self::features(PAIRING_REQUEST, io, p.own_keys(), ID_KEY);
let out = alloc::vec![Output::Send(p.request.to_vec())];
(p, out)
}
@@ -284,11 +373,12 @@ impl Pairing {
io: u8,
own: [u8; 7],
peer: [u8; 7],
+ irk: Option<[u8; 16]>,
request: &[u8],
random: &mut dyn FnMut(&mut [u8]),
now: u64,
) -> (Pairing, Vec<Output>) {
- let mut p = Pairing::new(false, own, peer, random, now);
+ let mut p = Pairing::new(false, own, peer, irk, random, now);
let Ok(request) = <[u8; 7]>::try_from(request) else {
let out = p.failed(INVALID_PARAMETERS);
return (p, out);
@@ -302,7 +392,10 @@ impl Pairing {
let out = p.failed(INVALID_PARAMETERS);
return (p, out);
}
- p.response = Self::features(PAIRING_RESPONSE, io);
+ // Of the keys asked for, only identities: theirs taken, ours given.
+ p.take_keys = request[5] & ID_KEY;
+ p.send_keys = request[6] & p.own_keys();
+ p.response = Self::features(PAIRING_RESPONSE, io, p.take_keys, p.send_keys);
match method(&p.request, &p.response) {
Some(numeric) => p.numeric = numeric,
None => {
@@ -364,9 +457,15 @@ impl Pairing {
if response[3] & SECURE_CONNECTIONS == 0 {
return self.failed(AUTHENTICATION_REQUIREMENTS);
}
- if response[4] < 16 || response[5] != 0 || response[6] != 0 {
+ // The keys to hand over: at most those asked for.
+ if response[4] < 16
+ || response[5] & !self.request[5] != 0
+ || response[6] & !self.request[6] != 0
+ {
return self.failed(INVALID_PARAMETERS);
}
+ self.send_keys = response[5];
+ self.take_keys = response[6];
match method(&self.request, &self.response) {
Some(numeric) => self.numeric = numeric,
None => return self.failed(NOT_SUPPORTED),
@@ -436,6 +535,27 @@ impl Pairing {
let check: [u8; 16] = body.try_into().unwrap();
self.finish(check)
}
+ // The peer's identity: its IRK, then its address. It may come
+ // before this side's controller says the link is encrypted.
+ (State::Encrypting | State::Keys, IDENTITY_INFORMATION, _)
+ if body.len() == 16 && self.take_keys & ID_KEY != 0 && self.peer_irk.is_none() =>
+ {
+ self.peer_irk = Some(body.try_into().unwrap());
+ Vec::new()
+ }
+ (State::Encrypting | State::Keys, IDENTITY_ADDRESS_INFORMATION, _)
+ if body.len() == 7 && self.peer_identity.is_none() =>
+ {
+ let Some(irk) = self.peer_irk else {
+ return self.failed(UNSPECIFIED);
+ };
+ self.peer_identity = Some(Identity {
+ irk,
+ address: body[1..].try_into().unwrap(),
+ kind: body[0],
+ });
+ self.hand_over()
+ }
_ => self.failed(UNSPECIFIED),
}
}
@@ -495,7 +615,7 @@ impl Pairing {
if !self.initiator {
out.push(Output::Send(self.check_pdu()));
}
- self.state = State::Over;
+ self.state = State::Encrypting;
self.private = [0; 32];
out.push(Output::Done {
key: self.key,
@@ -504,6 +624,46 @@ impl Pairing {
out
}
+ /// The link is encrypted with the key agreed: the keys are handed over,
+ /// the responder's first, and [`Output::Keys`] ends the pairing.
+ pub fn encrypted(&mut self, now: u64) -> Vec<Output> {
+ if self.state != State::Encrypting {
+ return Vec::new();
+ }
+ self.at = now;
+ self.state = State::Keys;
+ self.hand_over()
+ }
+
+ /// Sends this side's keys once it is its turn, and ends the pairing
+ /// once both sides' are across.
+ fn hand_over(&mut self) -> Vec<Output> {
+ let mut out = Vec::new();
+ if self.state != State::Keys {
+ return out;
+ }
+ let peer_done = self.take_keys & ID_KEY == 0 || self.peer_identity.is_some();
+ if !self.keys_sent && (!self.initiator || peer_done) {
+ self.keys_sent = true;
+ if self.send_keys & ID_KEY != 0
+ && let Some(irk) = self.irk
+ {
+ let own = if self.initiator { self.a } else { self.b };
+ let mut info = alloc::vec![IDENTITY_INFORMATION];
+ info.extend_from_slice(&irk);
+ let mut address = alloc::vec![IDENTITY_ADDRESS_INFORMATION, own[6]];
+ address.extend_from_slice(&own[..6]);
+ out.push(Output::Send(info));
+ out.push(Output::Send(address));
+ }
+ }
+ if self.keys_sent && peer_done {
+ self.state = State::Over;
+ out.push(Output::Keys(self.peer_identity));
+ }
+ out
+ }
+
/// (Na, Nb): the initiator's nonce and the responder's.
fn nonces(&self) -> ([u8; 16], [u8; 16]) {
if self.initiator {
diff --git a/bt/src/tests.rs b/bt/src/tests.rs
index 8ec3649..60a187c 100644
--- a/bt/src/tests.rs
+++ b/bt/src/tests.rs
@@ -397,14 +397,27 @@ const A: Address = Address([1, 0, 0, 0, 0, 0xc0]);
const B: Address = Address([2, 0, 0, 0, 0, 0xc0]);
/// Two hosts that may pair, `io` what each can show; B advertises a
-/// writable characteristic.
+/// writable characteristic. Each has an identity ([`irk`]) to hand over.
fn pairing_world(io: [u8; 2]) -> World {
+ pairing_world_with(io, [true; 2])
+}
+
+/// The identity resolving key of the `i`th host.
+fn irk(i: usize) -> [u8; 16] {
+ [0xa0 + i as u8; 16]
+}
+
+/// As [`pairing_world`], an identity only where `identities` says.
+fn pairing_world_with(io: [u8; 2], identities: [bool; 2]) -> World {
let mut hosts = alloc::vec![
Host::new("Ada's phone", Vec::new()),
Host::new("Bo's phone", alloc::vec![card_service(b"bo-card")]),
];
for (i, host) in hosts.iter_mut().enumerate() {
host.enable_pairing([i as u8 + 0x51; 32], io[i]);
+ if identities[i] {
+ host.set_identity(irk(i));
+ }
}
let mut w = World::new(hosts);
w.hosts[1].advertise(true);
@@ -567,6 +580,144 @@ fn a_bonded_device_is_private_again_on_reconnecting() {
assert!(!w.hosts[0].encrypted(ca));
}
+/// The spec's sample for the address hash (Vol 3 Part H, Appendix D.7),
+/// over-the-air order; an address made from an IRK resolves by it alone.
+#[test]
+fn private_addresses_resolve_by_their_irk() {
+ let k = bytes::<16>("9b7d390aa610103405adc857a33402ec");
+ assert_eq!(smp::ah(&k, &[0x94, 0x81, 0x70]), [0xaa, 0xfb, 0x0d]);
+ let a = smp::private_address(&k, [0x12, 0x34, 0xff]);
+ assert_eq!(a[5] >> 6, 0b01, "a resolvable one's top bits");
+ assert!(smp::resolves(&k, &a));
+ assert!(!smp::resolves(&irk(0), &a));
+ assert!(!smp::resolves(&k, &B.0));
+}
+
+/// Pairs A and B on a connection, both people saying yes.
+fn pair(w: &mut World, ca: u16, cb: u16) {
+ w.hosts[0].pair(ca);
+ w.settle();
+ w.events(0);
+ w.events(1);
+ w.hosts[1].confirm(cb, true);
+ w.hosts[0].confirm(ca, true);
+ w.settle();
+}
+
+/// A phone or a watch moves to a new private address every few minutes.
+/// Paired, it is still known: found by its identity, as its bond is kept,
+/// and private again on connecting, with no number to compare.
+#[test]
+fn a_paired_device_that_moves_address_is_still_known() {
+ let mut w = pairing_world([smp::DISPLAY_YES_NO; 2]);
+ let (ca, cb) = connect(&mut w);
+ pair(&mut w, ca, cb);
+ let (ea, eb) = (w.events(0), w.events(1));
+ // Each kept the other's identity.
+ assert!(
+ has(
+ &ea,
+ |e| matches!(e, Event::Paired { bond, .. } if bond.address == B && bond.irk == Some(irk(1)))
+ ),
+ "{ea:?}"
+ );
+ assert!(
+ has(
+ &eb,
+ |e| matches!(e, Event::Paired { bond, .. } if bond.address == A && bond.irk == Some(irk(0)))
+ ),
+ "{eb:?}"
+ );
+ disconnect(&mut w, ca);
+
+ let moved = Address(smp::private_address(&irk(1), [0x12, 0x34, 0x56]));
+ w.air.controllers[1].move_to(moved);
+ w.hosts[0].start_scan();
+ w.settle();
+ // Heard at its new address, it is the paired B.
+ let found = w.hosts[0]
+ .found()
+ .iter()
+ .find(|f| f.air == moved)
+ .expect("heard at its new address");
+ assert_eq!(found.address, B);
+ assert!(w.hosts[0].bonds().iter().any(|b| b.address == found.address));
+ assert!(has(
+ &w.events(0),
+ |e| matches!(e, Event::Found { address, .. } if *address == B)
+ ));
+
+ // Connected by its identity: private at once, nothing asked.
+ let (ca, cb, ea, eb) = connect_seeing(&mut w);
+ assert!(has(
+ &ea,
+ |e| matches!(e, Event::Connected { peer, .. } if *peer == B)
+ ));
+ for events in [&ea, &eb] {
+ assert!(
+ has(events, |e| matches!(e, Event::Encrypted { .. })),
+ "{events:?}"
+ );
+ assert!(!has(events, |e| matches!(
+ e,
+ Event::Confirm { .. } | Event::Paired { .. }
+ )));
+ }
+ assert!(w.hosts[0].encrypted(ca) && w.hosts[1].encrypted(cb));
+ w.hosts[0].write(ca, 0x0003, b"moved-and-private");
+ w.settle();
+ assert!(!heard(&w, b"moved-and-private"));
+}
+
+/// A device that gives no identity is known only at the address it paired
+/// from: moved, it is a stranger again, and nothing is encrypted.
+#[test]
+fn a_device_without_an_identity_is_not_followed() {
+ let mut w = pairing_world_with([smp::DISPLAY_YES_NO; 2], [true, false]);
+ let (ca, cb) = connect(&mut w);
+ pair(&mut w, ca, cb);
+ let ea = w.events(0);
+ assert!(
+ has(
+ &ea,
+ |e| matches!(e, Event::Paired { bond, .. } if bond.address == B && bond.irk.is_none())
+ ),
+ "{ea:?}"
+ );
+ disconnect(&mut w, ca);
+ let moved = Address(smp::private_address(&[0x77; 16], [1, 2, 3]));
+ w.air.controllers[1].move_to(moved);
+ w.hosts[0].start_scan();
+ w.settle();
+ let found = w.hosts[0].found().iter().find(|f| f.air == moved).unwrap();
+ assert_eq!(found.address, moved);
+}
+
+/// Bonds kept before identities (24 bytes) still read; one with an IRK
+/// round-trips.
+#[test]
+fn bonds_keep_their_identity_on_disk() {
+ use crate::Bond;
+ let old = Bond {
+ address: B,
+ kind: 0,
+ key: [7; 16],
+ compared: true,
+ irk: None,
+ };
+ let bytes = old.to_bytes();
+ assert_eq!(bytes.len(), 24);
+ assert_eq!(Bond::from_bytes(&bytes), Some((old, 24)));
+ let new = Bond {
+ irk: Some(irk(1)),
+ ..old
+ };
+ let mut bytes = new.to_bytes();
+ bytes.push(0x42);
+ assert_eq!(Bond::from_bytes(&bytes), Some((new, 40)));
+ assert_eq!(Bond::from_bytes(&bytes[..30]), None);
+}
+
#[test]
fn just_works_with_a_device_that_has_no_display() {
let mut w = pairing_world([smp::DISPLAY_YES_NO, smp::NO_INPUT_NO_OUTPUT]);
@@ -717,17 +868,17 @@ fn a_device_in_the_middle_shows_different_numbers() {
);
let io = smp::DISPLAY_YES_NO;
// A pairs with the middle (thinking it B); the middle with B.
- let (mut alice, start_a) = smp::Pairing::start(io, a, m, &mut counter(1), 0);
+ let (mut alice, start_a) = smp::Pairing::start(io, a, m, None, &mut counter(1), 0);
let smp::Output::Send(request) = &start_a[0] else {
panic!()
};
- let (mut middle_to_a, out) = smp::Pairing::answer(io, m, a, request, &mut counter(2), 0);
+ let (mut middle_to_a, out) = smp::Pairing::answer(io, m, a, None, request, &mut counter(2), 0);
let (alice_saw, _) = pump(&mut alice, &mut middle_to_a, Vec::new(), out);
- let (mut middle_to_b, start_b) = smp::Pairing::start(io, m, b, &mut counter(3), 0);
+ let (mut middle_to_b, start_b) = smp::Pairing::start(io, m, b, None, &mut counter(3), 0);
let smp::Output::Send(request) = &start_b[0] else {
panic!()
};
- let (mut bob, out) = smp::Pairing::answer(io, b, m, request, &mut counter(4), 0);
+ let (mut bob, out) = smp::Pairing::answer(io, b, m, None, request, &mut counter(4), 0);
let (_, bob_saw) = pump(&mut middle_to_b, &mut bob, Vec::new(), out);
let (Some(x), Some(y)) = (asked(&alice_saw), asked(&bob_saw)) else {
panic!("both asked: {alice_saw:?} {bob_saw:?}");
@@ -736,6 +887,6 @@ fn a_device_in_the_middle_shows_different_numbers() {
// A legacy request (no Secure Connections bit) is refused outright.
let mut legacy = request.clone();
legacy[3] &= !0x08;
- let (_, out) = smp::Pairing::answer(io, b, m, &legacy, &mut counter(5), 0);
+ let (_, out) = smp::Pairing::answer(io, b, m, None, &legacy, &mut counter(5), 0);
assert!(out.contains(&smp::Output::Failed(smp::AUTHENTICATION_REQUIREMENTS)));
}