//! A simulated controller, and the air between several: what the host //! stack is tested against, and what `cargo xtask` puts behind a QEMU's //! serial port so the system finds devices, connects and talks GATT with //! no radio. A controller takes H4 from its host ([`Controller::receive`]) //! and answers with events and ACL data ([`Controller::transmit`]); the //! [`Air`] carries advertising to scanners, makes connections, and passes //! ACL data between connected controllers. A link is encrypted as a //! controller does it: once both sides' hosts hand over the same long-term //! key, every ACL packet crosses the air sealed with AES-CCM (a session key //! 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; use alloc::vec::Vec; use pinnacle_crypto::aes::{Aes, Ccm}; /// How many packets [`Air::heard`] keeps, the latest. const HEARD: usize = 512; /// What a controller holds of ACL data: packets at once, bytes each. const ACL_PACKETS: u8 = 8; const ACL_LEN: u16 = 251; #[derive(Clone, Copy, PartialEq, Eq, Debug)] struct Link { handle: u16, /// The other controller, by index in the air. peer: usize, peer_handle: u16, /// This side asked for the connection. central: bool, /// The session key, once encrypted; packets sent and received under it. key: Option<[u8; 16]>, sent: u64, received: u64, } pub struct Controller { address: Address, /// The private address it moved to, which the air hears instead. private: Option
, framer: Framer, out: VecDeque>, advertising: bool, advertising_data: Vec, scanning: bool, /// A connection asked for: the peer's address. connecting: Option
, links: Vec, next_handle: u16, /// Addresses reported since scanning started (duplicates are filtered). reported: Vec
, /// Disconnections the air must carry out: (handle, reason). disconnects: Vec<(u16, u8)>, /// ACL data for the air to carry: (handle, continuing, data). acl_out: Vec<(u16, bool, Vec)>, /// Whether the host asked for a reset (the air then drops its links). reset: bool, /// Encryption the host asked for: (handle, long-term key). encrypting: Vec<(u16, [u8; 16])>, /// The host's answers to a key request: (handle, its key or none). keys_given: Vec<(u16, Option<[u8; 16]>)>, /// Key requests put to this host: (handle, the central's index, its /// handle, the key it asked with). keys_asked: Vec<(u16, usize, u16, [u8; 16])>, } impl Controller { pub fn new(address: Address) -> Controller { Controller { address, private: None, framer: Framer::default(), out: VecDeque::new(), advertising: false, advertising_data: Vec::new(), scanning: false, connecting: None, links: Vec::new(), next_handle: 0x40, reported: Vec::new(), disconnects: Vec::new(), acl_out: Vec::new(), reset: false, encrypting: Vec::new(), keys_given: Vec::new(), keys_asked: Vec::new(), } } pub fn address(&self) -> Address { 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> { self.out.pop_front() } fn event(&mut self, code: u8, parameters: Vec) { self.out.push_back(Packet::Event { code, parameters }.to_h4()); } fn command_complete(&mut self, opcode: u16, status: u8, ret: &[u8]) { let mut p = alloc::vec![1]; p.extend_from_slice(&opcode.to_le_bytes()); p.push(status); p.extend_from_slice(ret); self.event(hci::EVT_COMMAND_COMPLETE, p); } fn command_status(&mut self, opcode: u16, status: u8) { let mut p = alloc::vec![status, 1]; p.extend_from_slice(&opcode.to_le_bytes()); self.event(hci::EVT_COMMAND_STATUS, p); } /// Bytes from the host. pub fn receive(&mut self, bytes: &[u8]) { self.framer.push(bytes); while let Some(packet) = self.framer.packet() { match packet { Packet::Command { opcode, parameters } => self.command(opcode, ¶meters), Packet::Acl { handle, continuing, data, } => { if self.links.iter().any(|l| l.handle == handle) { self.acl_out.push((handle, continuing, data)); // Buffers come back as soon as the air took the data. let mut p = alloc::vec![1]; p.extend_from_slice(&handle.to_le_bytes()); p.extend_from_slice(&1u16.to_le_bytes()); self.event(hci::EVT_NUMBER_OF_COMPLETED_PACKETS, p); } } Packet::Event { .. } => {} } } } fn command(&mut self, opcode: u16, p: &[u8]) { match opcode { hci::RESET => { self.advertising = false; self.scanning = false; self.connecting = None; self.reset = true; self.command_complete(opcode, hci::SUCCESS, &[]); } hci::READ_BD_ADDR => { let address = self.address.0; self.command_complete(opcode, hci::SUCCESS, &address); } hci::LE_READ_BUFFER_SIZE => { let mut ret = ACL_LEN.to_le_bytes().to_vec(); ret.push(ACL_PACKETS); self.command_complete(opcode, hci::SUCCESS, &ret); } hci::LE_SET_ADVERTISING_DATA => { let len = p.first().copied().unwrap_or(0) as usize; self.advertising_data = p.get(1..1 + len).unwrap_or(&[]).to_vec(); self.command_complete(opcode, hci::SUCCESS, &[]); } hci::LE_SET_ADVERTISE_ENABLE => { self.advertising = p.first() == Some(&1); self.command_complete(opcode, hci::SUCCESS, &[]); } hci::LE_SET_SCAN_ENABLE => { let on = p.first() == Some(&1); if on && !self.scanning { self.reported.clear(); } self.scanning = on; self.command_complete(opcode, hci::SUCCESS, &[]); } hci::LE_CREATE_CONNECTION if p.len() >= 12 => { self.connecting = Some(Address(p[6..12].try_into().unwrap())); self.command_status(opcode, hci::SUCCESS); } hci::LE_CREATE_CONNECTION_CANCEL => { self.connecting = None; self.command_complete(opcode, hci::SUCCESS, &[]); } hci::DISCONNECT if p.len() >= 3 => { let handle = u16::from_le_bytes([p[0], p[1]]); self.disconnects.push((handle, p[2])); self.command_status(opcode, hci::SUCCESS); } hci::LE_START_ENCRYPTION if p.len() >= 28 => { let handle = u16::from_le_bytes([p[0], p[1]]); self.encrypting.push((handle, p[12..28].try_into().unwrap())); self.command_status(opcode, hci::SUCCESS); } hci::LE_LONG_TERM_KEY_REQUEST_REPLY if p.len() >= 18 => { self.keys_given.push(( u16::from_le_bytes([p[0], p[1]]), Some(p[2..18].try_into().unwrap()), )); self.command_complete(opcode, hci::SUCCESS, &p[..2]); } hci::LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY if p.len() >= 2 => { self.keys_given.push((u16::from_le_bytes([p[0], p[1]]), None)); self.command_complete(opcode, hci::SUCCESS, &p[..2]); } hci::SET_EVENT_MASK | hci::LE_SET_EVENT_MASK | hci::LE_SET_ADVERTISING_PARAMETERS | hci::LE_SET_SCAN_PARAMETERS => self.command_complete(opcode, hci::SUCCESS, &[]), _ => self.command_complete(opcode, 0x01, &[]), } } 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(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); } fn disconnection_complete(&mut self, handle: u16, reason: u8) { let mut p = alloc::vec![hci::SUCCESS]; p.extend_from_slice(&handle.to_le_bytes()); p.push(reason); self.event(hci::EVT_DISCONNECTION_COMPLETE, p); } fn encryption_change(&mut self, handle: u16, status: u8, on: bool) { let mut p = alloc::vec![status]; p.extend_from_slice(&handle.to_le_bytes()); p.push(u8::from(on)); self.event(hci::EVT_ENCRYPTION_CHANGE, p); } fn key_request(&mut self, handle: u16) { let mut p = alloc::vec![hci::LE_LONG_TERM_KEY_REQUEST]; p.extend_from_slice(&handle.to_le_bytes()); p.extend_from_slice(&[0; 10]); self.event(hci::EVT_LE_META, p); } 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); p.push(rssi as u8); self.event(hci::EVT_LE_META, p); } } /// The air: every controller in range of every other. #[derive(Default)] pub struct Air { pub controllers: Vec, /// What went over the air between connected devices, as a listener /// hears it: ACL packets, sealed on an encrypted link. The latest /// [`HEARD`]. pub heard: VecDeque>, /// Session keys made so far, for the next one's derivation. sessions: u64, } /// The CCM nonce for a link's `count`th packet one way: the count, the /// direction (1 from the central), zeros. fn nonce(count: u64, from_central: bool) -> [u8; 13] { let mut n = [0u8; 13]; n[..8].copy_from_slice(&count.to_le_bytes()); n[8] = u8::from(from_central); n } impl Air { fn hear(&mut self, packet: Vec) { if self.heard.len() == HEARD { self.heard.pop_front(); } self.heard.push_back(packet); } /// Adds a controller with `address`; returns its index. pub fn add(&mut self, address: Address) -> usize { self.controllers.push(Controller::new(address)); self.controllers.len() - 1 } /// Carries what happened since the last step: advertising to the /// scanners, connections asked for, ACL data, disconnections. pub fn step(&mut self) { let n = self.controllers.len(); // A reset drops a controller's links, on both sides. for i in 0..n { if self.controllers[i].reset { self.controllers[i].reset = false; for link in core::mem::take(&mut self.controllers[i].links) { let peer = &mut self.controllers[link.peer]; peer.links.retain(|l| l.handle != link.peer_handle); peer.disconnection_complete(link.peer_handle, hci::REASON_REMOTE_USER); } } } // Advertising reaches every scanner, once per address per scan. for i in 0..n { if !self.controllers[i].advertising { continue; } let (from, data) = ( 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.0) { continue; } scanner.reported.push(from.0); let rssi = -40 - (i as i8 + j as i8) * 7; scanner.advertising_report(from, &data, rssi); } } // Connections: an advertiser answers whoever asked for it. for i in 0..n { let Some(peer) = self.controllers[i].connecting else { continue; }; let Some(j) = self .controllers .iter() .position(|c| c.on_air().0 == peer && c.advertising) else { continue; }; self.controllers[i].connecting = None; self.controllers[i].scanning = false; self.controllers[j].advertising = false; let (hi, hj) = (self.controllers[i].next_handle, self.controllers[j].next_handle); self.controllers[i].next_handle += 1; self.controllers[j].next_handle += 1; self.controllers[i].links.push(Link { handle: hi, peer: j, peer_handle: hj, central: true, key: None, sent: 0, received: 0, }); self.controllers[j].links.push(Link { handle: hj, peer: i, peer_handle: hi, central: false, key: None, sent: 0, received: 0, }); 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); } // Encryption asked by a central: the peer's host is asked its key. for i in 0..n { for (handle, key) in core::mem::take(&mut self.controllers[i].encrypting) { let Some(link) = self.controllers[i] .links .iter() .find(|l| l.handle == handle) .copied() else { continue; }; let peer = &mut self.controllers[link.peer]; peer.keys_asked.push((link.peer_handle, i, handle, key)); peer.key_request(link.peer_handle); } } // Its answer: the same key encrypts both sides; none, and the // central hears the key is missing; another, and the first sealed // packet would fail its check, so the link drops. for j in 0..n { for (handle, given) in core::mem::take(&mut self.controllers[j].keys_given) { let Some(at) = self.controllers[j].keys_asked.iter().position(|k| k.0 == handle) else { continue; }; let (_, i, central_handle, key) = self.controllers[j].keys_asked.remove(at); match given { None => self.controllers[i].encryption_change(central_handle, hci::KEY_MISSING, false), Some(given) if given == key => { self.sessions += 1; let mut session = [0u8; 16]; session[..8].copy_from_slice(&self.sessions.to_le_bytes()); Aes::new(&key).unwrap().encrypt_blocks(&mut session); for (c, h) in [(i, central_handle), (j, handle)] { if let Some(l) = self.controllers[c].links.iter_mut().find(|l| l.handle == h) { l.key = Some(session); l.sent = 0; l.received = 0; } self.controllers[c].encryption_change(h, hci::SUCCESS, true); } } Some(_) => self.controllers[i] .disconnects .push((central_handle, hci::REASON_MIC_FAILURE)), } } } // ACL data crosses to the peer's handle, sealed on an encrypted link. for i in 0..n { for (handle, continuing, mut data) in core::mem::take(&mut self.controllers[i].acl_out) { let Some(at) = self.controllers[i].links.iter().position(|l| l.handle == handle) else { continue; }; let link = self.controllers[i].links[at]; let from_central = link.central; if let Some(key) = link.key { let ccm = Ccm::new(&key, 4).unwrap(); let tag = ccm.seal( &nonce(link.sent, from_central), &[u8::from(continuing)], &mut data, ); self.controllers[i].links[at].sent += 1; let mut on_air = data.clone(); on_air.extend_from_slice(&tag[..4]); self.hear(on_air); let peer = &mut self.controllers[link.peer]; let Some(pl) = peer.links.iter_mut().find(|l| l.handle == link.peer_handle) else { continue; }; let opened = ccm.open( &nonce(pl.received, from_central), &[u8::from(continuing)], &mut data, &tag[..4], ); pl.received += 1; if !opened { self.controllers[i] .disconnects .push((handle, hci::REASON_MIC_FAILURE)); continue; } } else { self.hear(data.clone()); } self.controllers[link.peer].out.push_back( Packet::Acl { handle: link.peer_handle, continuing, data, } .to_h4(), ); } } // Disconnections, on both sides. for i in 0..n { for (handle, reason) in core::mem::take(&mut self.controllers[i].disconnects) { let Some(pos) = self.controllers[i].links.iter().position(|l| l.handle == handle) else { continue; }; let link = self.controllers[i].links.remove(pos); self.controllers[i].disconnection_complete(handle, reason); let peer = &mut self.controllers[link.peer]; peer.links.retain(|l| l.handle != link.peer_handle); peer.disconnection_complete(link.peer_handle, hci::REASON_REMOTE_USER); } } } }