From dcf9c2a2ca930fbb26dccbd9efcd3a90554f530e Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:28:02 +0000 Subject: [PATCH] feat(wifi): run an RTL8852CE's station data under hardware CCMP with host packet numbers in the TX descriptor, its group key, its port and host-side PMF, where the handshake stopped at the first key --- .../src/wifi/realtek/ax/h2c.rs | 27 +- .../src/wifi/realtek/ax/h2c/tests.rs | 24 + .../src/wifi/realtek/ax/keys.rs | 3 +- .../src/wifi/realtek/ax/live.rs | 144 +++- .../src/wifi/realtek/ax/live/tests/chip.rs | 194 ++++- .../src/wifi/realtek/ax/pci.rs | 30 + .../src/wifi/realtek/ax/station.rs | 753 +++++++++++++++--- .../src/wifi/realtek/ax/station/chip.rs | 9 +- .../src/wifi/realtek/ax/station/tests.rs | 737 ++++++++++++++++- .../src/wifi/realtek/ax/txd.rs | 51 +- .../src/wifi/realtek/ax/txd/tests.rs | 65 ++ 11 files changed, 1828 insertions(+), 209 deletions(-) diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/h2c.rs b/crates/stela-driver-net/src/wifi/realtek/ax/h2c.rs index 0ea8dabcc7..72b1fb9cf9 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/h2c.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/h2c.rs @@ -21,7 +21,8 @@ //! `rtw89_fw_h2c_set_bcn_fltr_cfg` (`fw.c:5397-5470`) and //! `rtw89_fw_h2c_set_edca` (`fw.c:5241-5276`). For the keys (M3 spec S12): //! `rtw89_cam_send_sec_key_cmd`'s SEC_UPD (`cam.c:11-99`) and -//! `rtw89_fw_h2c_dctl_sec_cam_v1` (`fw.c:2346-2382`). +//! `rtw89_fw_h2c_dctl_sec_cam_v1` (`fw.c:2346-2382`). For a flush with drop: +//! `rtw89_fw_h2c_pkt_drop` (`fw.c:10621-10676`). //! //! Each of those is fixed to the one station interface of milestone 2c's //! spec: wifi role STATION, self role CLIENT, MAC 0, PHY 0, address CAM 0 @@ -84,6 +85,8 @@ pub(super) const H2C_FUNC_USR_EDCA: u8 = 0xF; pub(super) const H2C_FUNC_ADD_SCANOFLD_CH: u8 = 0x16; pub(super) const H2C_FUNC_SCANOFLD: u8 = 0x17; pub(super) const H2C_FUNC_CFG_BCNFLTR: u8 = 0x1E; +/// `H2C_FUNC_PKT_DROP` (`fw.h:4776`), a FW_OFLD func too. +pub(super) const H2C_FUNC_PKT_DROP: u8 = 0x1B; /// `H2C_CL_BA_CAM` / `H2C_FUNC_MAC_BA_CAM` (`fw.h:4808-4809`). pub(super) const H2C_CL_BA_CAM: u8 = 0xC; pub(super) const H2C_FUNC_MAC_BA_CAM: u8 = 0; @@ -272,6 +275,28 @@ impl H2c { ) } + /// `rtw89_fw_h2c_pkt_drop` (`fw.c:10621-10676`) as + /// `rtw89_mac_pkt_drop_sta` (`mac.c:7255-7278`) sends it for a station + /// of the vif on `port`: MAC / FW_OFLD / PKT_DROP, rack 0, dack 0, + /// `H2C_PKT_DROP_LEN` 24 bytes (`fw.c:10620`). w0 = `sel` [7:0] | + /// `macid` [15:8] | band (`mac_idx` 0) [23:16] | `port` [31:24]; w1 = + /// mbssid 0 [7:0] | tf_trs [15:8], the vif's `trigger`, 0 without an HE + /// association (`core.c:5718-5722`); w2-w5 = `macid_band_sel` 0 + /// (`fw.h:2110-2158`). + pub fn pkt_drop(&mut self, sel: u8, macid: u8, port: u8) -> (u8, Vec) { + let w0 = field(u32::from(sel), 7, 0) + | field(u32::from(macid), 15, 8) + | field(0, 23, 16) + | field(u32::from(port), 31, 24); + self.packet( + H2C_CAT_MAC, + H2C_CL_MAC_FW_OFLD, + H2C_FUNC_PKT_DROP, + false, + &le_words(&[w0, 0, 0, 0, 0, 0]), + ) + } + /// `rtw89_fw_h2c_rf_reg`: one page of stored RF register words for /// `path`, as OUTSRC / RF_REG_A (path A) or RF_REG_B (any other path, /// as Linux's ternary has it) with func `page`, rack 0 and dack 0. The diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/h2c/tests.rs b/crates/stela-driver-net/src/wifi/realtek/ax/h2c/tests.rs index 0921598dd4..05157b7194 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/h2c/tests.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/h2c/tests.rs @@ -776,3 +776,27 @@ fn security_cam_class_and_func_constants_are_linuxs() { assert_eq!((H2C_CL_MAC_FR_EXCHG, H2C_FUNC_MAC_DCTLINFO_UD_V1), (5, 9)); assert_eq!((SEC_CAM_LEN, SEC_KEY_TYPE_CCMP128), (20, 6)); } + +#[test] +fn pkt_drop_is_byte_exact() { + // rtw89_fw_h2c_pkt_drop (fw.c:10621-10676) for rtw89_mac_pkt_drop_sta's + // station (mac.c:7255-7278): MAC / FW_OFLD / PKT_DROP (0x1b), rack 0, + // dack 0, H2C_PKT_DROP_LEN 24: w0 = sel [7:0] | macid [15:8] | band 0 + // [23:16] | port [31:24]; w1 = mbssid 0 [7:0] | tf_trs 0 [15:8] (no HE + // association, core.c:5718-5722); w2..w5 = macid_band_sel 0 + // (fw.h:2110-2158). + for (sel, seq) in [(0u8, 17u8), (1, 18), (2, 19), (3, 20)] { + let (got, p) = H2c::at(seq).pkt_drop(sel, 0, 0); + assert_eq!(got, seq); + let (len, b) = body(&p); + assert_eq!(len, 32); + // REC_ACK only by the every-fourth-sequence rule. + let rack = if seq % 4 == 0 { 0x40 } else { 0 }; + assert_eq!(&b[..8], &[0x25, 0x1B, 0x00, seq, 0x20, rack, 0x00, 0x00]); + let mut payload = [0u8; 24]; + payload[0] = sel; + assert_eq!(&b[8..], &payload[..]); + } + let (_, p) = H2c::at(1).pkt_drop(3, 0x7F, 2); + assert_eq!(word(&body(&p).1[8..], 0), 0x0200_7F03); +} diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/keys.rs b/crates/stela-driver-net/src/wifi/realtek/ax/keys.rs index 47a32bfb71..3b32bda714 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/keys.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/keys.rs @@ -36,7 +36,8 @@ //! second SEC_UPD), a BIP key (the IGTK stays on the host, spec S1.2), an //! AP's or a TDLS peer's own address CAM, MLO, WoWLAN's IV words, the //! DISABLE_KEY flushes of `rtw89_ops_set_key` (`rtw89_hci_flush_queues` and -//! `rtw89_mac_flush_txq`, `mac80211.c:1010-1013`, M3 Task 15), its BTC +//! `rtw89_mac_flush_txq`, `mac80211.c:1010-1015`, which the station runs +//! through `Live::flush` before each delete), its BTC //! EAPOL_END notify and RX statistics reset, and any key on the air: a //! frame goes under a key only as its TX descriptor names the entry. use super::assoc::{AddrCam, CamKeys}; diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/live.rs b/crates/stela-driver-net/src/wifi/realtek/ax/live.rs index 82c9db456d..5ac74cd59b 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/live.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/live.rs @@ -100,12 +100,18 @@ //! from [`keys`]): [`Live::add_key`] installs one in the security CAM and //! points the address CAM at it, waiting for the firmware's receipt and //! acknowledgement, and [`Live::remove_key`] deletes one; [`Live::leave`] -//! deletes what is left first. A refused key leaves the chip on. +//! deletes what is left first. A refused key leaves the chip on. A data +//! frame goes under a key as its TX descriptor names the key's CAM entry, +//! key ID and host PN ([`Live::queue_data`]), only an entry +//! [`Live::add_key`] installed ([`Chip::transmit_data`]). [`Live::flush`] +//! is `rtw89_ops_flush`: the TX rings' wait, then with drop the PKT_DROP +//! H2Cs for the AP's station, without it the wait for the MAC's TX queues. //! -//! This module sends no frame under a key yet (M3 Task 15: -//! [`Chip::transmit_data`] refuses a keyed frame), and grants no TX status -//! beyond RPQ's: a report says the MAC is done with a frame, acknowledged or -//! not, nothing more. It runs no IQK, DPK, TSSI, watchdog, interrupts, probe +//! This module grants no TX status beyond RPQ's: a report says the MAC is +//! done with a frame, acknowledged or not, nothing more; a flush grants no +//! empty queue either, as Linux's waits only log their timeouts. It +//! encrypts no management frame (a robust one is sealed on the host, spec +//! S1.2). It runs no IQK, DPK, TSSI, watchdog, interrupts, probe //! request or idle power save, and processes no beacon filter report (M3 //! Task 18). It has no `Drop`: a live chip that is dropped keeps running, //! its rings and pools quarantined, as rtw88's `Hardware` keeps running for @@ -121,7 +127,7 @@ use super::core_tail; use super::dm::Dig; use super::efuse::RxGain; use super::h2c::{H2c, ScanChannel}; -use super::io::{AxError, AxIo}; +use super::io::{AxError, AxIo, poll32}; use super::keys::{self, KeyCam}; use super::pci::{Rings, TX_DONE, TxChannel, TxPools, WD_HEAD_BYTES, releases}; use super::receive::{Event, MAX_PENDING, Mode, Received, Tag}; @@ -130,7 +136,7 @@ use super::scan::{self, EdccaBak, ScanEnd, ScanError, hw_band, wifi_band}; use super::station::chip::{ self, Association, Chip, Data, HardwareKey, Incoming, Management, Token, }; -use super::txd::{self, RateCaps}; +use super::txd::{self, RateCaps, TxSec}; use super::txpwr_tables::TxPowerTables; use super::vif; use crate::Mac; @@ -168,10 +174,26 @@ pub const CONNECTED: AxError = /// ([`Live::held_dropped`]). const MAX_HELD: usize = MAX_PENDING; -/// What every keyed frame gets until encrypted data is sent (M3 Task 15), -/// and what the station's key calls got in M3a (spec S14.5). +/// What the station's key calls got in M3a (spec S14.5), which the host +/// check's M3a verdict still reads; nothing returns it since M3 Task 15. pub const KEYS_BEFORE_M3B: &str = "keys before M3b"; +/// What [`Chip::transmit_data`] gets for a frame naming a security CAM +/// entry that holds no key [`Live::add_key`] installed. +pub const KEY_NOT_IN_CAM: &str = "a key not in the security CAM"; + +/// `R_AX_DLE_EMPTY0` (`reg.h:631`), and the queues `dle_is_txq_empty` +/// wants empty in it (`mac.c:2393-2405`, bits `reg.h:632-651`). +const R_AX_DLE_EMPTY0: u32 = 0x8430; +const DLE_TXQ_EMPTY: u32 = 0x07FF_079F; +/// `rtw89_mac_flush_txq`'s `read_poll_timeout`: every 10 ms for up to +/// 200 ms (`mac.c:6360-6361`). +const FLUSH_TXQ_STEP_US: u64 = 10_000; +const FLUSH_TXQ_WAIT_US: u64 = 200_000; +/// `rtw89_mac_pkt_drop_sta`'s selections (`mac.c:7259-7264`), +/// `RTW89_PKT_DROP_SEL_MACID_BE_ONCE` to `_VO_ONCE` (`core.h:6485-6488`). +const PKT_DROP_SELS: [u8; 4] = [0, 1, 2, 3]; + /// The data and management channels, in the order the reclaim reads them. const TX_CHANNELS: [TxChannel; 5] = [ TxChannel::Ach0, @@ -1186,6 +1208,65 @@ impl Live { done.and_then(|done| done) } + /// `rtw89_ops_flush` (`mac80211.c:1122-1136`), as mac80211's + /// `ieee80211_flush_queues` and `rtw89_ops_set_key`'s DISABLE_KEY + /// (`mac80211.c:1010-1013`) call it: no LPS to leave, then + /// `rtw89_hci_flush_queues`, the TX rings' wait of [`Rings::flush_tx`]; + /// then with `drop`, as the 8852C's firmware lacks `NO_PACKET_DROP` + /// (`fw.c:870`), `__rtw89_drop_packets` (`mac80211.c:1109-1120`): for + /// the AP's station, which exists while a BSSID is set (mac80211 adds it + /// before authentication and iterates it as uploaded), the four + /// PKT_DROP H2Cs of `rtw89_mac_pkt_drop_sta` (`mac.c:7255-7278`), BE, BK, + /// VI then VO once for macid 0, each sent without a wait and its failure + /// passed over as Linux ignores it; without `drop`, + /// `rtw89_mac_flush_txq` (`mac.c:6352-6363`): `R_AX_DLE_EMPTY0` sampled + /// every 10 ms for up to 200 ms until `dle_is_txq_empty`'s queues are + /// all empty (`mac.c:2388-2412`), a timeout passed over as Linux only + /// logs it. Frames drained meanwhile are held for the next + /// [`Live::drain`]. Refused before any I/O on a chip off + /// ([`POWERED_OFF`]) and while a scan has not been ended + /// ([`SCAN_NOT_ENDED`]); a failed register read is returned, the chip + /// left on, as is the first PKT_DROP that could not be sent. + /// + /// # Safety + /// [`start`]'s contract, still holding for this chip. + pub unsafe fn flush(&mut self, drop: bool) -> Result<(), AxError> { + self.idle()?; + self.rings.flush_tx(&mut self.io)?; + if !drop { + return match poll32( + &mut self.io, + R_AX_DLE_EMPTY0, + DLE_TXQ_EMPTY, + DLE_TXQ_EMPTY, + FLUSH_TXQ_STEP_US, + FLUSH_TXQ_WAIT_US, + ) { + Ok(()) | Err(AxError::Timeout { .. }) => Ok(()), + Err(error) => Err(error), + }; + } + if self.bssid.is_none() { + return Ok(()); + } + let mut held = core::mem::take(&mut self.held); + let sent = self.session(|io, session| { + let mut first = Ok(()); + for sel in PKT_DROP_SELS { + let packet = session.h2c.pkt_drop(sel, vif::MAC_ID, vif::PORT); + // SAFETY: the caller's contract is `start`'s, which `send`'s + // is, for the live chip's own window and rings. + let result = unsafe { session.send(io, packet, &mut |e| held.keep(e)) }; + if first.is_ok() { + first = result.map(|_| ()); + } + } + first + }); + self.held = held; + sent.and_then(|sent| sent) + } + /// The channel context released after the station left (mac80211's /// `ieee80211_link_release_channel` at the end of /// `ieee80211_set_disassoc` and `ieee80211_destroy_auth_data`): @@ -1236,11 +1317,14 @@ impl Live { unsafe { self.submit(ch, &head, bytes) } } - /// Queue a data frame without a key, as [`Live::queue_management`] - /// queues a management frame: the WD head of [`txd::data`] for the - /// queue of `tid`, `eapol`, the tuned band, the peer's `supported` - /// rates and, once associated, the STBC and LDPC its RA H2C took - /// (`rtwsta_link->ra`, `core.c:1144-1145`; neither before). + /// Queue a data frame, as [`Live::queue_management`] queues a + /// management frame: the WD head of [`txd::data`] for the queue of + /// `tid`, `eapol`, the tuned band, the peer's `supported` rates, once + /// associated the STBC and LDPC its RA H2C took (`rtwsta_link->ra`, + /// `core.c:1145-1146`; neither before), and `sec`, the hardware key a + /// Protected frame goes under (`rtw89_core_tx_update_sec_key`), whose + /// CCMP header [`txd::strip_ccmp`] removed. The key's CAM entry is the + /// caller's to have installed ([`Chip::transmit_data`] checks it). /// /// # Safety /// [`start`]'s contract, still holding for this chip. @@ -1250,6 +1334,7 @@ impl Live { tid: u8, eapol: bool, supported: u16, + sec: Option, ) -> Result, AxError> { if self.off { return Err(POWERED_OFF); @@ -1270,7 +1355,7 @@ impl Live { ldpc: false, }, }; - let (ch, head) = txd::data(bytes, tid, eapol, self.chan.band, supported, caps, None)?; + let (ch, head) = txd::data(bytes, tid, eapol, self.chan.band, supported, caps, sec)?; // SAFETY: the caller's contract is `submit`'s, word for word. unsafe { self.submit(ch, &head, bytes) } } @@ -1547,16 +1632,29 @@ impl Chip for Live { unsafe { self.queue_management(frame.bytes, frame.basic_rates) }.map_err(|e| e.to_string()) } - /// [`Live::queue_data`]; a frame with a key is refused until M3b. + /// [`Live::queue_data`], a frame's key as its CAM entry, key ID and PN + /// ([`TxSec`]). A frame naming an entry that holds no key + /// [`Live::add_key`] installed and nothing deleted since is refused + /// with [`KEY_NOT_IN_CAM`] before any access: the hardware would + /// encrypt it under whatever that entry held, or under nothing. fn transmit_data(&mut self, frame: &Data<'_>) -> Result, String> { if self.off { return Err(POWERED_OFF.to_string()); } - if frame.key.is_some() { - return Err(KEYS_BEFORE_M3B.into()); - } + let sec = match frame.key { + Some((cam, _, _)) if !self.key_installed(cam) => return Err(KEY_NOT_IN_CAM.into()), + Some((cam, keyid, pn)) => Some(TxSec { keyid, cam, pn }), + None => None, + }; + let Data { + bytes, + tid, + eapol, + supported_rates, + .. + } = *frame; // SAFETY: `start`'s contract holds for the live chip's every use. - unsafe { self.queue_data(frame.bytes, frame.tid, frame.eapol, frame.supported_rates) } + unsafe { self.queue_data(bytes, tid, eapol, supported_rates, sec) } .map_err(|e| e.to_string()) } @@ -1619,6 +1717,12 @@ impl Chip for Live { unsafe { Live::remove_key(self, cam) }.map_err(|e| e.to_string()) } + /// [`Live::flush`]. + fn flush(&mut self, drop: bool) -> Result<(), String> { + // SAFETY: `start`'s contract holds for the live chip's every use. + unsafe { Live::flush(self, drop) }.map_err(|e| e.to_string()) + } + /// Accepted without the BA CAM until M3b, with no access. fn start_rx_block_ack(&mut self, _tid: u8, _ssn: u16) -> Result<(), String> { if self.off { diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/live/tests/chip.rs b/crates/stela-driver-net/src/wifi/realtek/ax/live/tests/chip.rs index e6a21bdc67..17712716ae 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/live/tests/chip.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/live/tests/chip.rs @@ -10,7 +10,7 @@ use crate::wifi::realtek::ax::station::chip::{ Association, Chip, Data, HardwareKey, Incoming, Management, Received as Heard, Token, }; use crate::wifi::realtek::ax::tests::firmware::{Air, Sent, rx_buffer}; -use crate::wifi::realtek::ax::txd::{self, RateCaps}; +use crate::wifi::realtek::ax::txd::{self, RateCaps, TxSec}; use crate::wifi::{Band, Channel}; use alloc::string::{String, ToString}; @@ -65,6 +65,22 @@ fn data_frame(seq: u16, n: u8) -> Vec { f } +/// [`data_frame`] as QoS data of `tid`, its QoS control after the header. +fn qos_frame(seq: u16, tid: u8, n: u8) -> Vec { + let mut f = data_frame(seq, n); + f[0] = 0x88; + f.splice(24..24, [tid, 0]); + f +} + +/// [`qos_frame`] as the CCMP strip leaves a frame under a key: Protected, +/// no CCMP header. +fn protected_frame(seq: u16, tid: u8, n: u8) -> Vec { + let mut f = qos_frame(seq, tid, n); + f[1] |= 0x40; + f +} + fn data(bytes: &[u8], tid: u8) -> Data<'_> { Data { bytes, @@ -185,7 +201,7 @@ fn transmit_management_kicks_ch8_and_reports_the_ack() { fn transmit_data_maps_tid_to_its_channel() { let (mut live, _m, air) = on_air(&|_| {}); for (tid, ch, idx) in [(0, TxChannel::Ach0, 0x1058), (7, TxChannel::Ach3, 0x1064)] { - let frame = data_frame(u16::from(tid), tid); + let frame = qos_frame(u16::from(tid), tid, tid); let before = live.io().trace.len(); let sent = Chip::transmit_data(&mut live, &data(&frame, tid)); assert_eq!(sent, Ok(Some(token(ch, 0)))); @@ -193,7 +209,7 @@ fn transmit_data_maps_tid_to_its_channel() { } // EAPOL goes with BK on the queue of its TID, the unassociated peer // with neither STBC nor LDPC. - let eapol = data_frame(9, 0x88); + let eapol = qos_frame(9, 7, 0x88); let frame = Data { eapol: true, ..data(&eapol, 7) @@ -839,7 +855,7 @@ fn silent_rpq_runs_the_pages_out_without_reusing_one() { air.silent_rpq(); let mut tokens = Vec::new(); for n in 0..40u16 { - let frame = data_frame(n, n as u8); + let frame = qos_frame(n, 5, n as u8); if let Some(token) = Chip::transmit_data(&mut live, &data(&frame, 5)).unwrap() { tokens.push(token); } @@ -859,7 +875,7 @@ fn silent_rpq_runs_the_pages_out_without_reusing_one() { ); air.ack_all(); assert_eq!(poll(&mut live).len(), 16); - let frame = data_frame(40, 40); + let frame = qos_frame(40, 5, 40); assert!( Chip::transmit_data(&mut live, &data(&frame, 5)) .unwrap() @@ -932,23 +948,175 @@ fn the_chip_installs_and_removes_keys() { } #[test] -fn keyed_data_and_block_ack_wait_for_later_tasks() { - let (mut live, _m, _air) = on_air(&|_| {}); - let before = live.io().trace.len(); - let m3b = Err(String::from("keys before M3b")); - let frame = data_frame(1, 1); +fn keyed_data_goes_under_its_cam_entry_and_pn() { + let (mut live, _m, air) = on_air(&|_| {}); + let material: [u8; 16] = core::array::from_fn(|i| i as u8); + let ch1 = channel(HwBand::G2, 1); + Chip::set_bssid(&mut live, Mac(AP)).unwrap(); + Chip::associate(&mut live, &joined(ch1, 0xFFF, None)).unwrap(); + let ptk = HardwareKey { + pairwise: true, + index: 0, + material: &material, + }; + assert_eq!(Chip::add_key(&mut live, &ptk), Ok(0)); + // rtw89_core_tx_update_sec_key: the frame names CAM entry 0, key ID 0 + // and its PN in BODY4/5 (spec S5.3). + let frame = protected_frame(5, 0, 0x5A); let keyed = Data { - key: Some((0, 0, 1)), + key: Some((0, 0, 0x0605_0403_0201)), ..data(&frame, 0) }; - assert_eq!(Chip::transmit_data(&mut live, &keyed), m3b.map(|()| None)); + assert_eq!( + Chip::transmit_data(&mut live, &keyed), + Ok(Some(token(TxChannel::Ach0, 0))) + ); + poll(&mut live); + let sent = air.sent(); + let caps = RateCaps { + stbc: false, + ldpc: false, + }; + let sec = TxSec { + keyid: 0, + cam: 0, + pn: 0x0605_0403_0201, + }; + let (_, head) = txd::data(&frame, 0, false, HwBand::G2, 0xFFF, caps, Some(sec)).unwrap(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].head, head); + assert_eq!(sent[0].bytes, frame); + // A key the security CAM does not hold is refused before any access: + // entry 1 holds nothing, and entry 0 is gone once removed. + let before = live.io().trace.len(); + let unheld = Err(String::from("a key not in the security CAM")); + let other = Data { + key: Some((1, 0, 1)), + ..data(&frame, 0) + }; + assert_eq!(Chip::transmit_data(&mut live, &other), unheld.clone()); + assert_eq!(live.io().trace.len(), before); + Chip::remove_key(&mut live, 0).unwrap(); + assert_eq!(Chip::transmit_data(&mut live, &keyed), unheld); // RX Block Ack is accepted without the BA CAM (Task 16). + let before = live.io().trace.len(); assert_eq!(Chip::start_rx_block_ack(&mut live, 0, 0x123), Ok(())); assert_eq!(Chip::stop_rx_block_ack(&mut live, 0), Ok(())); assert_eq!(live.io().trace.len(), before); assert_eq!(Chip::mac(&live), Mac(MAC)); } +/// The TX rings `rtw89_pci_ops_flush_queues` waits on: every one but CH12, +/// ACH0-7, CH8, CH9, CH10 and CH11 (`pci.h:556-569`), in ring order. +const FLUSHED: [u32; 12] = [ + 0x1058, 0x105C, 0x1060, 0x1064, 0x1068, 0x106C, 0x1070, 0x1074, 0x1078, 0x107C, 0x11D0, 0x11D4, +]; +/// `R_AX_DLE_EMPTY0` and the queues `dle_is_txq_empty` wants empty +/// (`mac.c:2388-2412`, `reg.h:631-651`). +const DLE_EMPTY0: u32 = 0x8430; +const TXQ_EMPTY: u32 = 0x07FF_079F; + +/// The 32-bit reads of a trace. +fn reads32(t: &[Op]) -> Vec { + t.iter() + .filter_map(|o| match o { + Op::R32(r) => Some(*r), + _ => None, + }) + .collect() +} + +#[test] +fn a_flush_without_drop_waits_on_the_rings_then_the_mac() { + let (mut live, _m, _air) = on_air(&|_| {}); + live.io_mut().set32(DLE_EMPTY0, TXQ_EMPTY); + let before = live.io().trace.len(); + assert_eq!(Chip::flush(&mut live, false), Ok(())); + let t = &live.io().trace[before..]; + // __pci_flush_txch: each ring's index already at its host's, so one + // read each; then rtw89_mac_flush_txq's first sample, already empty. + let mut want = FLUSHED.to_vec(); + want.push(DLE_EMPTY0); + assert_eq!(reads32(t), want); + assert_eq!(delays(t), 0); + assert_eq!(kicks(t), 0); + // The MAC's queues never empty: read_poll_timeout every 10 ms for + // 200 ms, one last sample after it, and the flush ends without error + // as Linux's only logs. + live.io_mut().set32(DLE_EMPTY0, TXQ_EMPTY & !1); + let before = live.io().trace.len(); + assert_eq!(Chip::flush(&mut live, false), Ok(())); + let t = &live.io().trace[before..]; + let samples = reads32(t).iter().filter(|&&r| r == DLE_EMPTY0).count(); + assert!((21..=22).contains(&samples), "{samples}"); + assert!((200_000..=210_000).contains(&delays(t)), "{}", delays(t)); +} + +#[test] +fn a_flush_waits_60_us_on_a_ring_the_dma_engine_left() { + // No Air: nothing reads the TXBD, so ACH0's hardware index stays 0 + // behind its host index of 1. + let (mut live, _m) = live_hearing(&|_| {}); + live.io_mut().set32(DLE_EMPTY0, TXQ_EMPTY); + let frame = qos_frame(1, 0, 1); + assert!(matches!( + Chip::transmit_data(&mut live, &data(&frame, 0)), + Ok(Some(_)) + )); + let before = live.io().trace.len(); + assert_eq!(Chip::flush(&mut live, true), Ok(())); + let t = &live.io().trace[before..]; + let reads = reads32(t); + assert_eq!(reads.iter().filter(|&&r| r == 0x1058).count(), 60); + assert!(FLUSHED[1..].iter().all(|r| reads.contains(r))); + // 60 waits of 1 us between them, then on (pci.c:1401-1407). + let ach0: u64 = t + .iter() + .filter_map(|o| match o { + Op::Delay(us) => Some(*us), + _ => None, + }) + .take(60) + .sum(); + assert_eq!(ach0, 60); + // With drop and no AP's station, no PKT_DROP and no MAC wait. + assert_eq!(kicks(t), 0); + assert!(!reads.contains(&DLE_EMPTY0)); +} + +#[test] +fn a_flush_with_drop_drops_the_stations_four_queues() { + let (mut live, m, _air) = on_air(&|_| {}); + let ch1 = channel(HwBand::G2, 1); + Chip::set_bssid(&mut live, Mac(AP)).unwrap(); + Chip::associate(&mut live, &joined(ch1, 0xFFF, None)).unwrap(); + let seq = live.h2c(); + let before = live.io().trace.len(); + assert_eq!(Chip::flush(&mut live, true), Ok(())); + let t = &live.io().trace[before..]; + // __rtw89_drop_packets for the AP's station: PKT_DROP of BE, BK, VI + // and VO once for macid 0 (rtw89_mac_pkt_drop_sta, mac.c:7255-7278), + // as the 8852C's firmware lacks NO_PACKET_DROP (fw.c:870); no wait for + // the MAC's queues (mac80211.c:1132-1135). + assert_eq!(kicks(t), 4); + for sel in 0..4u8 { + let mut h2c = seq; + for _ in 0..sel { + h2c.pkt_drop(0, 0, 0); + } + let (at, want) = h2c.pkt_drop(sel, 0, 0); + assert_eq!(h2c_of(&m, 1, 9, 0x1B, at), want); + } + assert!(!reads32(t).contains(&DLE_EMPTY0)); + // A flush is refused while a scan has not ended, and on a chip off. + Chip::disassociate(&mut live).unwrap(); + Chip::begin_scan(&mut live, &[ch1]).unwrap(); + assert_eq!( + Chip::flush(&mut live, false), + Err(SCAN_NOT_ENDED.to_string()) + ); +} + #[test] fn a_powered_off_chip_refuses_every_call() { let (mut live, _m, _air) = on_air(&|_| {}); @@ -989,6 +1157,8 @@ fn a_powered_off_chip_refuses_every_call() { }; assert_eq!(Chip::add_key(&mut live, &key), Err(dead.clone())); assert_eq!(Chip::remove_key(&mut live, 0), Err(dead.clone())); + assert_eq!(Chip::flush(&mut live, true), Err(dead.clone())); + assert_eq!(Chip::flush(&mut live, false), Err(dead.clone())); assert_eq!(Chip::start_rx_block_ack(&mut live, 0, 0), Err(dead.clone())); assert_eq!(Chip::stop_rx_block_ack(&mut live, 0), Err(dead)); assert_eq!(live.io().trace.len(), off); diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/pci.rs b/crates/stela-driver-net/src/wifi/realtek/ax/pci.rs index 0146ba881f..13da43c334 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/pci.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/pci.rs @@ -90,6 +90,8 @@ const RTW89_PCI_TXBD_OPT_LS: u16 = 1 << 14; const BD_OPT_DMA_HI_SHIFT: u32 = 6; /// `TXBD_HW_IDX_MASK` (`pci.h:558`): the hardware read index of a TX ring. const TXBD_HW_IDX_MASK: u32 = 0x0FFF_0000; +/// `__pci_flush_txch`'s reads of one ring (`pci.c:1401`). +const FLUSH_TRIES: usize = 60; /// `enum rtw89_cv` (`core.h:201`). const CHIP_CAV: u8 = 0; @@ -458,6 +460,34 @@ impl Rings { } } + /// `rtw89_pci_ops_flush_queues` (`pci.c:1432-1436`): for every TX ring + /// but CH12, which `__rtw89_pci_ops_flush_txchs` skips (`pci.c:1414-1430`; + /// the 8852CE masks no other, `tx_dma_ch_mask` 0, `rtw8852ce.c:63`), in + /// ring order, `__pci_flush_txch` (`pci.c:1388-1410`): up to 60 reads of + /// the ring's IDX, each not yet showing the hardware index ([27:16]) at + /// the host's (`bd_ring->wp`: a data or management channel's, 0 for a + /// ring nothing is queued on) followed by a 1 us delay. A ring still + /// behind after them is passed over, as Linux only logs it. Nothing is + /// written and no TXBD is taken back; only a failed read is an error. + pub fn flush_tx(&self, io: &mut I) -> Result<(), AxError> { + for (ring, entry) in TX_TABLE.iter().enumerate().take(CH12) { + let wp = match ring { + 0..=3 => self.data_host[ring].get(), + 8 => self.data_host[TxChannel::Ch8.slot()].get(), + _ => 0, + }; + for _ in 0..FLUSH_TRIES { + let value = io.read32(entry.idx)?; + let rp = (value & TXBD_HW_IDX_MASK) >> TXBD_HW_IDX_MASK.trailing_zeros(); + if rp == u32::from(wp) { + break; + } + io.delay_us(1); + } + } + Ok(()) + } + /// The RPQ ring, read by polling as RXQ is. `pre_init` must have /// succeeded first. pub fn rpq(&mut self) -> Rpq<'_> { diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/station.rs b/crates/stela-driver-net/src/wifi/realtek/ax/station.rs index ec0889a7fb..05a5a96b78 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/station.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/station.rs @@ -20,27 +20,55 @@ //! - The association programs the chip with the negotiated peer as //! `BSS_CHANGED_ASSOC` does (spec S10), on the channel the join switched //! to. -//! - EAPOL runs over the data queues, without a key; data frames wait in -//! `held` while the chip has no room, management frames in the outbox. +//! - EAPOL runs over the data queues; data frames wait in `held` while the +//! chip has no room, management frames in the outbox. +//! - The handshake's keys go to the chip's security CAM (`rtw89_ops_set_key`, +//! spec S12), CCMP-128 only (spec S1.2): the PTK with a host packet +//! number, the GTK receive-only; a key of an index already held replaces +//! it as `ieee80211_key_replace` does, the old one deleted first, and an +//! identical one is not installed again (`ieee80211_key_identical`). The +//! port opens on both, and under PMF on the IGTK too, which stays on the +//! host (`BipKey`); a rekey while it is open authorizes it again on the +//! keys then held, as mac80211's station stays authorized across one. +//! - Data under the PTK leaves as `Protection::HostIv` plans it: the +//! station reserves its PN and writes its CCMP header, which +//! [`super::txd::strip_ccmp`] checks against the reservation and removes; +//! the chip puts the PN in the TX descriptor and the hardware encrypts +//! (`hw_sec_hdr`, spec S5.4). A reservation is spent whether the frame +//! leaves, waits or is dropped, so PNs only increase. Robust management +//! frames are sealed on the host under the PTK (`realtek::ccmp`), as +//! rtw88 seals them, and leave without a hardware key. +//! - Received data the hardware decrypted (its CCMP header and MIC kept, +//! spec S7.3) is taken under the key its key ID names, through the +//! station's replay and port checks, fragments reassembled and A-MSDUs +//! split as rtw88 takes them; protected management frames are opened on +//! the host when the hardware left them sealed. //! - A departure leaves through the chip (spec S11), which releases its -//! channel. +//! channel. From an association, mac80211's `ieee80211_set_disassoc` +//! flushes first ([`chip::Chip::flush`] with drop, then without it after +//! a deauthentication of the station's own); each key is deleted after a +//! flush without drop, as `rtw89_ops_set_key`'s DISABLE_KEY flushes, the +//! PTK first, then the group keys, before the chip disassociates. //! //! The radio polls (spec S1.4): it never signals, and the keeper services //! it from `carrier()` and `receive()`. Its diagnostic is the progress line //! of spec S14.6, which names no address, then the chip's own counts. //! -//! This module does not grant (M3a): keys (`install_key` refuses with -//! "keys before M3b", so the port never opens), encrypted or protected -//! frames, the IGTK, SAE, RX Block Ack and reordering, fragments and -//! A-MSDUs received, beacon loss, A-MSDU or aggregated TX, power save, -//! templates, the watchdog, or following the AP's beacons and channel -//! switches. Nor the chip half of mac80211's TX flush before a -//! deauthentication (`rtw89_ops_flush`'s ring wait and PKT_DROP H2Cs). +//! This module does not grant: any cipher but CCMP-128 (TKIP, GCMP, +//! CCMP-256, WEP), hardware-encrypted management frames +//! (`hw_mgmt_tx_encrypt`), SAE, RX Block Ack and reordering, beacon loss, +//! A-MSDU or aggregated TX, power save, templates, the watchdog, SA Query +//! requests of its own, or following the AP's beacons and channel +//! switches. The GTK is deleted before the chip disassociates, where Linux +//! deletes a station's group key (a vif key in station mode, cfg.c's +//! `ieee80211_add_key` without an address) only after cfg80211's +//! disconnect (`__cfg80211_disconnected`'s `rdev_del_key` loop, +//! `net/wireless/sme.c:1375-1391`); either way the chip ends keyless. pub mod chip; -use self::chip::{Association, Chip, Data, Incoming, Management, Received, Token}; +use self::chip::{Association, Chip, Data, HardwareKey, Incoming, Management, Received, Token}; use super::assoc::HtPeer; -use super::live::KEYS_BEFORE_M3B; +use super::txd; use crate::{ Clock, Link, LinkError, Mac, wifi::{ @@ -48,17 +76,22 @@ use crate::{ connection::keeper::{self, Advertisement, Keeper, Peer, Radio, Stage}, frame::Mpdu, network::Network, + realtek::ccmp, regulatory::{channel::DISABLED, database::Country}, scan::{self, Outcome, Retirement, Scanner, result::Bss}, security::{ - self, Cipher, Integrity, KeyIdentity, KeySlot, PacketNumber, ReplaySeed, - SecurityStatus, management as protection, + self, Cipher, InstallOutcome, Integrity, KeyIdentity, KeyScope, KeySlot, PacketNumber, + ReplaySeed, SecurityStatus, + aggregate::{OrderedGroup, Shape}, + management::{self as protection, BipKey, ManagementCipher}, + tx::TransmitSeed, }, station::{ Action, AssociationContext, Completion, Failure, Join, NativeBssObservation, Phase as Peering, RegulatoryPolicy, Station, Ticket, data::{self, Ingress, Protection, Qos, SequenceOwner, TxClass}, external, + fragments::Fragments, multi_link::Affiliation, phy::{Capabilities, McsMaps, Role}, wire::six_ghz::Selection, @@ -68,6 +101,7 @@ use crate::{ use alloc::{collections::VecDeque, format, string::String, sync::Arc, vec::Vec}; use core::fmt; use stela_driver_base::entropy::Entropy; +use zeroize::Zeroizing; /// How long the radio may take from its start to carrier (M3 spec S1.5): /// one scan's budget, `SAE_BUDGET_US` and `HANDSHAKE_TIMEOUT_US`, 28.98 s, @@ -77,8 +111,15 @@ pub const WIFI_CARRIER_WAIT_US: u64 = 30_000_000; const BSS_EXPIRY_US: u64 = 30_000_000; /// The data frames that wait for room, the oldest dropped past it. const MAX_HELD: usize = 256; -/// The EAPOL frames whose release reports the progress line awaits. +/// The EAPOL frames, and the ticketed management frames the station no +/// longer awaits, whose release reports the progress line still counts. const MAX_EAPOL_REPORTS: usize = 64; +/// What a key the chip cannot take gets (spec S1.2). +const CCMP_128_ONLY: &str = "a key other than CCMP-128 on an RTL8852C"; +/// `IEEE80211_CCMP_HDR_LEN`, and a management frame's header, before which +/// a sealed frame's CCMP header goes. +const CCMP_HEADER: usize = 8; +const MANAGEMENT_HEADER: usize = 24; /// What SAE gets in M3a (M3 Task 17). const SAE_BEFORE_M3B: &str = "SAE before M3b"; /// `ieee80211_add_wmm_info_ie`, without U-APSD. @@ -125,22 +166,40 @@ impl fmt::Display for Error { } } -/// The keeper's handle on the IGTK the host would hold (M3b). +/// The keeper's handle on the IGTK the host holds. pub struct ManagementKey; +/// One key the chip's security CAM holds: its slot, kind, key ID, entry +/// and material (for the host's sealing and opening under the PTK). +struct Key { + slot: KeySlot, + pairwise: bool, + index: u8, + cam: u8, + material: Zeroizing>, +} + +/// Whether `a` and `b` are the same key material, compared in time that +/// does not depend on where they differ. +fn same_material(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0u8, |d, (a, b)| d | (a ^ b)) == 0 +} + /// A BSS and when it was last heard, a `cfg80211_internal_bss`. struct Heard { observation: Arc, at: u64, } -/// A data frame waiting for room: its MPDU, the queue's TID, whether it is -/// EAPOL, and the peer's rates. +/// A data frame waiting for room: its MPDU (without its CCMP header when +/// it goes under a key), the queue's TID, whether it is EAPOL, the peer's +/// rates, and the key it goes under: CAM entry, key ID and its reserved PN. struct Held { bytes: Vec, tid: u8, eapol: bool, supported: u16, + key: Option<(u8, u8, u64)>, } /// What a management frame is to the progress line. @@ -345,8 +404,20 @@ pub struct Rtl8852c { peer: Option, /// The ticketed management frame whose report the station awaits. reporting: Option<(Token, Kind)>, + /// Ticketed management frames the chip took before the one the station + /// awaits, until their reports: counted, not the station's. + earlier: VecDeque<(Token, Kind)>, /// The EAPOL frames the chip took, until their reports. eapol_reports: VecDeque, + /// The keys the chip's security CAM holds. + keys: Vec, + /// The next `KeySlot` number: each key gets its own. + next_slot: u16, + /// The join's management cipher, and the IGTK the host checks group + /// frames under. + management_cipher: Option, + integrity: Option, + fragments: Fragments, port_open: bool, departing: Option, left: bool, @@ -379,7 +450,13 @@ impl Rtl8852c { context: None, peer: None, reporting: None, + earlier: VecDeque::new(), eapol_reports: VecDeque::new(), + keys: Vec::new(), + next_slot: 0, + management_cipher: None, + integrity: None, + fragments: Fragments::default(), port_open: false, departing: None, left: false, @@ -426,9 +503,7 @@ impl Rtl8852c { fn act(&mut self, action: Action) { match action { - Action::Transmit { ticket, bytes, .. } => { - self.outbox.push_back((Some(ticket), bytes)); - } + Action::Transmit { ticket, bytes, .. } => self.queue_management(Some(ticket), bytes), Action::Configure { ticket, context: Some(context), @@ -445,8 +520,32 @@ impl Rtl8852c { } } - /// The station left: nothing it queued leaves after it. + /// `bytes` to the outbox, a protected frame sealed first: mac80211 + /// encrypts a frame as it enters its TX path. One that cannot be sealed + /// (no PTK) is dropped, reported once. + fn queue_management(&mut self, ticket: Option, bytes: Vec) { + if bytes.get(1).is_some_and(|fc| fc & 0x40 != 0) { + match self.seal(&bytes) { + Ok(sealed) => self.outbox.push_back((ticket, sealed)), + Err(_) => self.unsupported("a protected management frame without its key"), + } + } else { + self.outbox.push_back((ticket, bytes)); + } + } + + /// The station left of the AP's doing or its own: an association's + /// `ieee80211_set_disassoc` without a frame of its own flushes with + /// drop first, its failure passed over as Linux's is. fn depart(&mut self, ticket: Ticket) { + if self.context.is_some() { + let _ = self.chip.flush(true); + } + self.leave(ticket); + } + + /// The station left: nothing it queued leaves after it. + fn leave(&mut self, ticket: Ticket) { self.departing = Some(ticket); self.left = true; self.port_open = false; @@ -455,17 +554,32 @@ impl Rtl8852c { self.held.clear(); } - /// The station's state gone after its retirement. + /// The station's state gone after its retirement, the keys with it. A + /// report still awaited is counted when it comes. fn clear(&mut self) { self.context = None; self.peer = None; self.admitted = None; self.departing = None; self.left = false; - self.reporting = None; + if let Some(report) = self.reporting.take() { + self.keep_earlier(report); + } self.port_open = false; self.outbox.clear(); self.held.clear(); + self.keys.clear(); + self.management_cipher = None; + self.integrity = None; + self.fragments.clear(); + } + + /// A report the station no longer awaits, kept for the progress line. + fn keep_earlier(&mut self, report: (Token, Kind)) { + if self.earlier.len() >= MAX_EAPOL_REPORTS { + self.earlier.pop_front(); + } + self.earlier.push_back(report); } fn observed(&self, handle: usize) -> Result, Error> { @@ -484,16 +598,11 @@ impl Rtl8852c { /// rtw88's `send_management` (`station.rs:889`): the outbox, oldest /// first, while the chip has room; a ticketed frame's token is kept - /// for its report. + /// for its report, the token it replaces among the earlier ones. A + /// protected frame was sealed as it was queued. fn send_management(&mut self) -> Result<(), Error> { let basic_rates = self.basic_rates(); while let Some((_, bytes)) = self.outbox.front() { - // A protected frame needs the PTK the host would seal it under. - if bytes[1] & 0x40 != 0 { - self.outbox.pop_front(); - self.unsupported("a protected management frame before M3b"); - continue; - } let frame = Management { bytes, basic_rates }; let Some(token) = Self::chip(self.chip.transmit_management(&frame))? else { return Ok(()); @@ -508,7 +617,9 @@ impl Rtl8852c { Kind::Other => {} } if let Some(ticket) = ticket { - self.reporting = Some((token, kind)); + if let Some(earlier) = self.reporting.replace((token, kind)) { + self.keep_earlier(earlier); + } self.station.submitted(ticket).map_err(Error::Station)?; } } @@ -524,7 +635,7 @@ impl Rtl8852c { tid: held.tid, eapol: held.eapol, supported_rates: held.supported, - key: None, + key: held.key, }; let Some(token) = Self::chip(self.chip.transmit_data(&frame))? else { return Ok(()); @@ -542,10 +653,44 @@ impl Rtl8852c { Ok(()) } - /// rtw88's `send` (`station.rs:1121`, spec S13.1) without A-MSDU, TX - /// Block Ack or keys: the MSDU as the station prepares it, held, then - /// sent while the chip has room, as mac80211 hands a frame to the - /// driver at once. + /// rtw88's `seal` (`station.rs:918`), `IEEE80211_KEY_FLAG_SW_MGMT_TX`'s + /// host half: `bytes`, a robust management frame, sealed under the PTK + /// at the next PN of its slot, which data shares, as one key's + /// `tx_pn` counts both in Linux. + fn seal(&mut self, bytes: &[u8]) -> Result, Error> { + let key = self + .keys + .iter_mut() + .find(|key| key.pairwise) + .ok_or(Error::Refused("no pairwise key"))?; + let identity = key.slot.installed().ok_or(Error::Refused("no key"))?; + if bytes.len() < MANAGEMENT_HEADER { + return Err(Error::Refused("a management frame shorter than its header")); + } + let nonce = key + .slot + .reserve_host_tx_nonce(identity) + .map_err(Error::Key)?; + let pn = nonce.packet_number(); + let header: [u8; CCMP_HEADER] = nonce.into_header(); + let material: &[u8; 16] = key.material[..] + .try_into() + .map_err(|_| Error::Unsupported(CCMP_128_ONLY))?; + Ok(ccmp::seal( + material, + &bytes[..MANAGEMENT_HEADER], + &header, + pn, + &bytes[MANAGEMENT_HEADER..], + )) + } + + /// rtw88's `send` (`station.rs:1121`, spec S13.1) without A-MSDU or TX + /// Block Ack: the MSDU as the station prepares it under the keys held, + /// a `HostIv` frame's CCMP header checked against its reservation and + /// removed (spec S5.4), held, then sent while the chip has room, as + /// mac80211 hands a frame to the driver at once. A frame the strip + /// refuses is dropped, its PN spent. fn send(&mut self, ethernet: &[u8], class: TxClass) -> Result<(), Error> { let epoch = self .station @@ -554,7 +699,7 @@ impl Rtl8852c { let context = self.context.clone().ok_or(Error::Refused("no context"))?; let tid = data::data_tid(&context, None, None, ethernet); let mut policy = Admitted(&self.channels); - let mut keys: Vec<&mut KeySlot> = Vec::new(); + let mut keys: Vec<&mut KeySlot> = self.keys.iter_mut().map(|key| &mut key.slot).collect(); let plan = match tid { Some(tid) => self.station.prepare_qos_msdu_refs( epoch, @@ -577,12 +722,22 @@ impl Rtl8852c { ), } .map_err(Error::Data)?; - let (_, _, mpdu, protection, _, _) = plan.into_parts(); - match protection { - Protection::None => {} - Protection::HostIv { .. } => return Err(Error::Unsupported(KEYS_BEFORE_M3B)), + let (_, _, mut mpdu, protection, _, _) = plan.into_parts(); + let key = match protection { + Protection::None => None, + Protection::HostIv { key, pn } => { + let cam = self + .keys + .iter() + .find(|held| held.slot.installed() == Some(key)) + .map(|held| held.cam) + .ok_or(Error::Refused("a key the chip does not hold"))?; + txd::strip_ccmp(&mut mpdu, pn.value(), key.index()) + .map_err(|error| Error::Chip(format!("{error}")))?; + Some((cam, key.index(), pn.value())) + } Protection::Firmware { .. } => return Err(Error::Refused("a firmware key")), - } + }; if self.held.len() >= MAX_HELD { self.held.pop_front(); } @@ -591,6 +746,7 @@ impl Rtl8852c { tid: tid.unwrap_or(0), eapol: class != TxClass::Data, supported: context.negotiated().legacy.supported, + key, }); self.send_data() } @@ -631,25 +787,23 @@ impl Rtl8852c { /// A frame's release report: the ticketed management frame's goes to /// the station as its TX status (rtw88's `Report::Transmitted`, - /// `station.rs:1275-1288`, spec S1.10); an EAPOL frame's is counted. + /// `station.rs:1275-1288`, spec S1.10), and is counted; one the station + /// no longer awaits, and an EAPOL frame's, is counted only. fn transmitted(&mut self, token: Token, acknowledged: bool, now: u64) -> Result<(), Error> { if let Some((_, kind)) = self.reporting.filter(|&(awaited, _)| awaited == token) { self.reporting = None; - if acknowledged { - let exchange = match kind { - Kind::Authentication => self.progress.auth.as_mut(), - Kind::Association => self.progress.assoc.as_mut(), - Kind::Other => None, - }; - if let Some(exchange) = exchange { - bump(&mut exchange.acked); - } - } + self.count_ack(kind, acknowledged); return self .station .management_status(acknowledged, now) .map_err(Error::Station); } + if let Some(at) = self.earlier.iter().position(|&(sent, _)| sent == token) { + if let Some((_, kind)) = self.earlier.remove(at) { + self.count_ack(kind, acknowledged); + } + return Ok(()); + } if let Some(at) = self.eapol_reports.iter().position(|&sent| sent == token) { self.eapol_reports.remove(at); if acknowledged && let Some(eapol) = &mut self.progress.eapol { @@ -659,6 +813,18 @@ impl Rtl8852c { Ok(()) } + /// An acknowledged authentication or association, counted. + fn count_ack(&mut self, kind: Kind, acknowledged: bool) { + let exchange = match kind { + Kind::Authentication => self.progress.auth.as_mut(), + Kind::Association => self.progress.assoc.as_mut(), + Kind::Other => None, + }; + if acknowledged && let Some(exchange) = exchange { + bump(&mut exchange.acked); + } + } + /// The scan ended (spec S8.2): its ticket completed, the chip restored /// (`rtw89_hw_scan_complete`, spec S8.3), and the scan left for the /// keeper to retire, even when the restore failed, which powered the @@ -711,12 +877,15 @@ impl Rtl8852c { Some(mpdu) } - /// rtw88's `frame` (`station.rs:1344`) without keys: a scan's beacons - /// and probe responses to the scanner, management frames to - /// [`Self::management_frame`], unprotected whole MSDUs to the station. - /// A protected frame has no key to be taken under in M3a, and - /// fragments and A-MSDUs are M3b's (spec S13.3). - fn frame(&mut self, frame: Mpdu, now: u64) -> Result<(), Error> { + /// rtw88's `frame` (`station.rs:1344`) without TKIP or Block Ack + /// reordering (spec S13.3): a scan's beacons and probe responses to the + /// scanner, management frames to [`Self::management_frame`], and data + /// with a body to the station, a protected frame under the key its key + /// ID names (pairwise for unicast, a group key for a group address), + /// dropped without one, failing its ICV, or left encrypted by the + /// hardware (mac80211 would decrypt it in software; no Stela station + /// does). Fragments are reassembled. + fn frame(&mut self, mut frame: Mpdu, now: u64) -> Result<(), Error> { let header = *frame.header(); if let Some(ticket) = self.scanning && matches!(header.control & 0xfc, 0x80 | 0x50) @@ -730,32 +899,93 @@ impl Rtl8852c { if header.control & 12 == 0 { return self.management_frame(frame, now); } - if header.control & 12 != 8 - || !header.data_present() - || header.protected() - || header.fragmented() - || header.amsdu - { + if header.control & 12 != 8 || !header.data_present() { return Ok(()); } - self.deliver(&frame); + if header.protected() { + let multicast = header.receiver.is_multicast(); + let index = frame.bytes().get(header.length + 3).map(|byte| byte >> 6); + let Some(key) = self + .keys + .iter() + .find(|key| key.pairwise != multicast && Some(key.index) == index) + .and_then(|key| key.slot.installed()) + else { + return Ok(()); + }; + if frame.security.icv_error || !frame.security.decrypted { + return Ok(()); + } + frame.security.key = Some(key); + } + if header.fragmented() { + self.reassemble(&frame, now); + return Ok(()); + } + self.deliver(frame); Ok(()) } - /// rtw88's `deliver` (`station.rs:1451`) of one MSDU: mac80211 drops - /// what its port check refuses. EAPOL goes to the keeper. - fn deliver(&mut self, frame: &Mpdu) { - let Some(epoch) = self.station.association_epoch() else { - return; + /// rtw88's `reassemble` (`station.rs:1415`): `frame`, one fragment; + /// the station has the MSDU with the last of them. + fn reassemble(&mut self, frame: &Mpdu, now: u64) { + let key = frame.security.key; + let slot = self + .keys + .iter_mut() + .map(|key| &mut key.slot) + .find(|slot| key.is_some() && slot.installed() == key); + if let Some(whole) = self.fragments.add(frame, slot, now) { + self.deliver(whole); + } + } + + /// rtw88's `deliver` (`station.rs:1451`): `frame`, an MSDU or an + /// A-MSDU, to the station; mac80211 drops what its replay and port + /// checks refuse. EAPOL goes to the keeper. + fn deliver(&mut self, frame: Mpdu) { + let ingress = if frame.header().amsdu { + let Some(context) = self.context.clone() else { + return; + }; + let key = frame.security.key; + // SAFETY: an A-MSDU is one record here, delivered as received + // (no reorder buffer holds it), and `clear` drops what an + // older association left. + let group = + unsafe { OrderedGroup::new(context, alloc::vec![frame], Shape::WholeMpdu, ()) }; + let slot = self + .keys + .iter_mut() + .map(|key| &mut key.slot) + .find(|slot| key.is_some() && slot.installed() == key); + let Ok(received) = self.station.receive_ordered_group(&group, slot) else { + return; + }; + let keys: Vec<&KeySlot> = self.keys.iter().map(|key| &key.slot).collect(); + match self.station.receive_group_refs(&received, &keys) { + Ok(ingress) => ingress, + Err(_) => return, + } + } else { + let Some(epoch) = self.station.association_epoch() else { + return; + }; + let mut keys: Vec<&mut KeySlot> = + self.keys.iter_mut().map(|key| &mut key.slot).collect(); + match self.station.receive_msdu_refs(epoch, &frame, &mut keys) { + Ok(ingress) => alloc::vec![ingress], + Err(_) => return, + } }; - let mut keys: Vec<&mut KeySlot> = Vec::new(); - match self.station.receive_msdu_refs(epoch, frame, &mut keys) { - Ok(Ingress::Data(ethernet)) => self.received.push_back(ethernet), - Ok(Ingress::ControlPort { ethernet, .. }) => { - bump(&mut self.progress.eapol.get_or_insert_default().received); - self.events.push_back(keeper::Event::Eapol(ethernet)); + for ingress in ingress { + match ingress { + Ingress::Data(ethernet) => self.received.push_back(ethernet), + Ingress::ControlPort { ethernet, .. } => { + bump(&mut self.progress.eapol.get_or_insert_default().received); + self.events.push_back(keeper::Event::Eapol(ethernet)); + } } - Err(_) => {} } } @@ -777,29 +1007,50 @@ impl Rtl8852c { } } - /// rtw88's `management_frame` (`station.rs:1514`) of M3a: what the - /// station's authentication and association take, and the AP's - /// departures. Beacons and probe responses outside a scan, action - /// frames (Block Ack is M3 Task 16's; channel switches are not - /// followed), protected frames, and, under PMF, robust frames to - /// everyone (BIP is M3b's) are dropped, as is everything before a join. + /// rtw88's `management_frame` (`station.rs:1514`): what the station's + /// authentication and association take, and the AP's departures; a + /// protected frame to [`Self::protected_management`]. Under PMF a + /// robust frame to everyone must carry its IGTK's MIC (BIP on the host) + /// and a departure to the station alone must come protected once keys + /// are installed (`ieee80211_drop_unencrypted_mgmt`). Beacons and + /// probe responses outside a scan and unprotected action frames (Block + /// Ack is M3 Task 16's; channel switches are not followed) are dropped, + /// as is everything before a join. fn management_frame(&mut self, frame: Mpdu, now: u64) -> Result<(), Error> { let header = *frame.header(); let subtype = header.control & 0xfc; - if matches!(subtype, 0x80 | 0x50 | 0xd0) || header.protected() { + if matches!(subtype, 0x80 | 0x50) { return Ok(()); } - if self.station.phase() == Peering::ExternalAuthenticating { + if header.protected() { + return self.protected_management(frame); + } + if subtype == 0xd0 || self.station.phase() == Peering::ExternalAuthenticating { return Ok(()); } let Some(epoch) = self.station.association_epoch() else { return Ok(()); }; - // `ieee80211_drop_unencrypted_mgmt` of an MFP station. - if self.station.requires_protected_management() - && header.receiver.is_multicast() - && protection::robust(&frame) - { + let pmf = self.station.requires_protected_management(); + if pmf && header.receiver.is_multicast() && protection::robust(&frame) { + let Some(integrity) = &mut self.integrity else { + return Ok(()); + }; + let Ok(authenticated) = integrity.authenticate(&frame) else { + return Ok(()); + }; + if matches!(subtype, 0xa0 | 0xc0) { + let body = authenticated.body(); + let action = self + .station + .receive_protected_departure(epoch, &frame, body) + .map_err(Error::Station)?; + self.events.push_back(keeper::Event::ConnectionLost); + self.act(action); + } + return Ok(()); + } + if pmf && matches!(subtype, 0xa0 | 0xc0) && !self.keys.is_empty() { return Ok(()); } let before = self.station.phase(); @@ -816,6 +1067,73 @@ impl Rtl8852c { Ok(()) } + /// rtw88's `protected_management` (`station.rs:1598`) without Block + /// Ack (M3 Task 16) or channel switches: a frame under the PTK, opened + /// on the host when the hardware left it sealed, taken once under its + /// packet number (`ieee80211_crypto_ccmp_decrypt` keeps management's + /// apart from data's); a departure ends the association, and an SA + /// Query request is answered, sealed in turn. + fn protected_management(&mut self, mut frame: Mpdu) -> Result<(), Error> { + let local = self.address; + let Some(epoch) = self.station.association_epoch() else { + return Ok(()); + }; + let header = *frame.header(); + let Some(key) = self.keys.iter_mut().find(|key| key.pairwise) else { + return Ok(()); + }; + if frame.security.icv_error { + return Ok(()); + } + if !frame.security.decrypted { + let number = frame + .bytes() + .get(header.length..) + .and_then(|iv| PacketNumber::from_header(iv).ok()); + let material: Option<&[u8; 16]> = key.material[..].try_into().ok(); + let (Some((number, _)), Some(material)) = (number, material) else { + return Ok(()); + }; + let Some(opened) = ccmp::open(material, frame.bytes(), number) else { + return Ok(()); + }; + let security = SecurityStatus { + decrypted: true, + integrity: Integrity::Verified, + ..SecurityStatus::default() + }; + let Ok(clear) = Mpdu::new(opened, frame.radio.clone(), security) else { + return Ok(()); + }; + frame = clear; + } + frame.security.key = key.slot.installed(); + let Ok(authenticated) = key.slot.authorize_unicast_management(&frame, local) else { + return Ok(()); + }; + let body = authenticated.body(); + match header.control & 0xfc { + 0xa0 | 0xc0 => { + let action = self + .station + .receive_protected_departure(epoch, &frame, body) + .map_err(Error::Station)?; + self.events.push_back(keeper::Event::ConnectionLost); + self.act(action); + } + 0xd0 if body.len() >= 4 && body[..2] == [8, 0] => { + let response = [8, 1, body[2], body[3]]; + let Some(ap) = header.transmitter else { + return Ok(()); + }; + let bytes = management(local, ap, 0xd0, true, &response); + self.queue_management(None, bytes); + } + _ => {} + } + Ok(()) + } + /// The AP's answer `action` came of, for the progress line: whether it /// accepted the authentication. fn answered(&mut self, before: Peering, subtype: u16, action: &Action) -> bool { @@ -971,6 +1289,7 @@ impl Rtl8852c { Self::chip(self.chip.tune(bss.channel))?; Self::chip(self.chip.set_bssid(bss.bssid))?; self.peer = Some(peer); + self.management_cipher = join.request.pmf().map(|pmf| pmf.management()); self.progress.auth.get_or_insert_default(); let now = self.clock.now_us(); let mut policy = Admitted(&self.channels); @@ -1014,37 +1333,217 @@ impl Rtl8852c { /// rtw88's `deauthenticate` (`station.rs:2296`): the deauthentication /// after what the outbox holds, then the station's departure, even when - /// the chip refused the frame. Held data never leaves after it: - /// mac80211 flushes with drop first (`ieee80211_set_disassoc`), and - /// the departure drops what the chip has not taken. + /// the chip refused the frame. Held data never leaves after it. From an + /// association, as `ieee80211_set_disassoc` sends it: a flush with drop + /// first (mac80211 purges its queues, the chip drops what it holds), + /// the frame, then a flush without drop so it leaves (`mlme.c:4594-4604` + /// at the donor's mac80211); `ieee80211_mgd_deauth` flushes neither + /// during an authentication or association. A flush's failure is passed + /// over, as Linux's is. fn deauthenticate_with(&mut self, reason: u16) -> Result<(), Error> { if self.left || self.station.phase() == Peering::Idle { return Ok(()); } + let associated = self.context.is_some(); + if associated { + self.held.clear(); + let _ = self.chip.flush(true); + } if let Ok((local, ap)) = self.station.addresses() { let protected = self.station.protected_port_authorized(); let bytes = management(local, ap, 0xc0, protected, &reason.to_le_bytes()); - self.outbox.push_back((None, bytes)); + self.queue_management(None, bytes); } let sent = self.send_management(); - let action = self.station.disconnect().map_err(Error::Station)?; - self.act(action); + if associated { + let _ = self.chip.flush(false); + } + match self.station.disconnect().map_err(Error::Station)? { + Action::Remove { ticket, .. } => self.leave(ticket), + action => self.act(action), + } sent } - /// rtw88's `retire_peer` (`station.rs:2311`), the chip first: its - /// disassociation (spec S11) releases the channel, then the removal is - /// accepted. A failed disassociation powered the chip off, which holds - /// no association either. + /// rtw88's `retire_peer` (`station.rs:2311`) on rtw89 (spec S14.5): + /// `sta_info_flush`'s key deletes first, the PTK, then the group keys by + /// key ID, each as `rtw89_ops_set_key`'s DISABLE_KEY runs it, a flush + /// without drop, then the CAM delete (`mac80211.c:1010-1015`); then the + /// chip's disassociation (spec S11), which releases the channel; then + /// the removal is accepted. Every step runs whatever an earlier one + /// returned, as mac80211 goes on past a driver's failures, and the + /// first error is returned. A failed disassociation powered the chip + /// off, which holds no association either. fn retire(&mut self) -> Result<(), Error> { + let mut keys = core::mem::take(&mut self.keys); + keys.sort_by_key(|key| (!key.pairwise, key.index)); + let mut first = Ok(()); + for key in &keys { + let _ = self.chip.flush(false); + let removed = Self::chip(self.chip.remove_key(key.cam)); + if first.is_ok() { + first = removed; + } + } + drop(keys); let left = Self::chip(self.chip.disassociate()); + if first.is_ok() { + first = left; + } if let Some(ticket) = self.departing.take() { self.station .complete_removal(ticket, Completion::Accepted) .map_err(Error::Station)?; } self.clear(); - left + first + } + + /// `rtw89_ops_set_key`'s SET_KEY (spec S12, S14.5) of a CCMP-128 key: + /// the pairwise key with `TransmitSeed::host(0)`, a group key + /// receive-only. As `ieee80211_key_link`: an identical key of the same + /// kind and index is not installed again (-EALREADY, which mac80211 + /// takes as success); another replaces it (`ieee80211_key_replace`), + /// the old one deleted first (a flush without drop, then the CAM + /// delete, its failure passed over), then the new one installed. The + /// key counts as installed only once the chip's `add_key` returned its + /// CAM entry, the firmware having acknowledged it; otherwise its slot + /// is never completed and goes. An open port is authorized again on the + /// keys then held. + fn install( + &mut self, + pairwise: bool, + index: u8, + material: &[u8], + receive: ReplaySeed, + ) -> Result { + self.progress.keys.get_or_insert(0); + let temporal: &[u8; 16] = material + .try_into() + .map_err(|_| Error::Unsupported(CCMP_128_ONLY))?; + let peer = self + .station + .pairwise_peer() + .ok_or(Error::Refused("no peer"))?; + if let Some(at) = self + .keys + .iter() + .position(|key| key.pairwise == pairwise && key.index == index) + { + if same_material(&self.keys[at].material, material) + && let Some(identity) = self.keys[at].slot.installed() + { + return Ok(identity); + } + let old = self.keys.remove(at); + // What still waits under the old key goes with it: its CAM + // entry may hold the new key by the time the chip has room. + self.held + .retain(|held| held.key.is_none_or(|(cam, _, _)| cam != old.cam)); + let _ = self.chip.flush(false); + let _ = self.chip.remove_key(old.cam); + } + let scope = if pairwise { + KeyScope::Pairwise(peer) + } else { + KeyScope::Group(peer) + }; + let transmit = if pairwise { + TransmitSeed::host(PacketNumber::new(0).ok_or(Error::Refused("packet number"))?) + } else { + TransmitSeed::RECEIVE_ONLY + }; + // SAFETY: the counter gives each key of the radio its own slot, + // which no other `KeySlot` controls. + let mut slot = unsafe { KeySlot::new(self.next_slot) }.map_err(Error::Key)?; + self.next_slot = self.next_slot.wrapping_add(1); + let ticket = slot + .begin_install(index, Cipher::Ccmp128, material, receive, scope, transmit) + .map_err(Error::Key)?; + let identity = ticket.identity(); + let cam = Self::chip(self.chip.add_key(&HardwareKey { + pairwise, + index, + material: temporal, + }))?; + slot.complete_install(ticket, InstallOutcome::Accepted) + .map_err(Error::Key)?; + self.keys.push(Key { + slot, + pairwise, + index, + cam, + material: Zeroizing::new(material.to_vec()), + }); + if let Some(keys) = &mut self.progress.keys { + bump(keys); + } + // mac80211 keeps the AP's station authorized across a rekey; the + // station layer authorizes one PTK and GTK, which a replaced or + // newer key leaves behind, so the port is authorized again on the + // keys now held. The keeper installs a key only from an + // authenticated handshake. + if self.port_open { + let epoch = self + .station + .association_epoch() + .ok_or(Error::Refused("no association"))?; + self.authorize(epoch)?; + } + Ok(identity) + } + + /// The host's IGTK (spec S1.2), rtw88's `install_management_key` + /// (`station.rs:2236`): BIP under the join's management cipher, beside + /// the GTK, which must be installed first (`Pending` until then). + fn install_integrity( + &mut self, + index: u8, + material: &[u8], + receive: PacketNumber, + ) -> Result, Error> { + let cipher = self + .management_cipher + .ok_or(Error::Refused("no management cipher"))?; + let gtk = self + .keys + .iter() + .rev() + .find(|key| !key.pairwise) + .and_then(|key| key.slot.installed()) + .ok_or(Error::Pending)?; + self.integrity = Some( + BipKey::new(gtk, cipher, index, material, receive) + .map_err(|_| Error::Refused("the IGTK"))?, + ); + Ok(Arc::new(ManagementKey)) + } + + /// rtw88's `authorize_port` (`station.rs:2271`): the PTK and the last + /// GTK, under PMF with the association's protection. + fn authorize(&mut self, epoch: u64) -> Result<(), Error> { + let context = self.context.clone().ok_or(Error::Refused("no context"))?; + let ptk = self + .keys + .iter() + .find(|key| key.pairwise) + .ok_or(Error::Refused("no pairwise key"))?; + let gtk = self + .keys + .iter() + .rev() + .find(|key| !key.pairwise) + .ok_or(Error::Refused("no group key"))?; + let links = [(&ptk.slot, >k.slot)]; + if self.station.requires_protected_management() { + self.station + .authorize_protected_port(&context, epoch, &links) + } else { + self.station.authorize_port(epoch, &links) + } + .map_err(Error::Station)?; + self.port_open = true; + Ok(()) } } @@ -1259,53 +1758,51 @@ impl Radio for Rtl8852c { self.note(sent) } - /// `rtw89_ops_set_key` takes CCMP-128 alone here (spec S1.2); in M3a - /// none reaches the chip (spec S14.5). + /// `rtw89_ops_set_key` of CCMP-128 alone (spec S1.2), into the chip's + /// security CAM (its `install`). fn install_key( &mut self, - _pairwise: bool, - _index: u8, + pairwise: bool, + index: u8, material: &[u8], - _receive: ReplaySeed, + receive: ReplaySeed, ) -> Result { - self.progress.keys.get_or_insert(0); - let refused = if material.len() != Cipher::Ccmp128.key_length() { - Error::Unsupported("a key other than CCMP-128 on an RTL8852C") - } else { - Error::Unsupported(KEYS_BEFORE_M3B) - }; - self.note(Err(refused)) + let installed = self.install(pairwise, index, material, receive); + self.note(installed) } fn install_link_key(&mut self, _: u8, _: u8, _: &[u8], _: ReplaySeed) -> Result<(), Error> { self.note(Err(Error::Unsupported("MLO on an RTL8852C"))) } - /// The IGTK would stay on the host (spec S1.2); M3a has no PTK to - /// hold it beside. + /// The IGTK stays on the host, where mac80211 runs BIP (spec S1.2). unsafe fn install_management_key( &mut self, _: u64, - _: u8, - _: &[u8], - _: PacketNumber, + index: u8, + material: &[u8], + receive: PacketNumber, ) -> Result, Error> { - self.note(Err(Error::Unsupported(KEYS_BEFORE_M3B))) + let installed = self.install_integrity(index, material, receive); + self.note(installed) } + /// A rekeyed IGTK replaces the host's. unsafe fn rotate_management_key( &mut self, _: &Arc, - _: u8, - _: &[u8], - _: PacketNumber, + index: u8, + material: &[u8], + receive: PacketNumber, ) -> Result, Error> { - self.note(Err(Error::Unsupported(KEYS_BEFORE_M3B))) + let installed = self.install_integrity(index, material, receive); + self.note(installed) } - /// The port opens on an installed PTK and GTK, which M3a never has. - fn authorize_port(&mut self, _: u64) -> Result<(), Error> { - self.note(Err(Error::Refused("no pairwise key"))) + /// The port opens on an installed PTK and GTK. + fn authorize_port(&mut self, epoch: u64) -> Result<(), Error> { + let authorized = self.authorize(epoch); + self.note(authorized) } fn deauthenticate(&mut self, reason: u16) -> Result<(), Error> { diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/station/chip.rs b/crates/stela-driver-net/src/wifi/realtek/ax/station/chip.rs index d998d4e780..aa1edbc344 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/station/chip.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/station/chip.rs @@ -17,7 +17,8 @@ //! `BSS_CHANGED_ASSOC` ([`Chip::associate`]), the //! station's way down to NOTEXIST and the channel context's release //! ([`Chip::disassociate`]), `rtw89_ops_set_key` ([`Chip::add_key`], -//! [`Chip::remove_key`]) and `rtw89_ops_ampdu_action`'s RX half +//! [`Chip::remove_key`]), `rtw89_ops_flush` ([`Chip::flush`]) and +//! `rtw89_ops_ampdu_action`'s RX half //! ([`Chip::start_rx_block_ack`], [`Chip::stop_rx_block_ack`]). //! //! The trait grants nothing by itself: a call's success is what its @@ -164,6 +165,12 @@ pub trait Chip { /// Install a key; its security CAM entry (M3 spec S12). fn add_key(&mut self, key: &HardwareKey<'_>) -> Result; fn remove_key(&mut self, cam: u8) -> Result<(), String>; + /// mac80211's `drv_flush`: wait for the frames the chip took to leave + /// its TX rings, then with `drop` drop what it still queues for the AP, + /// or without it wait for its TX queues to empty. Neither wait fails + /// for time, as Linux's only log theirs; nothing is reported for a + /// dropped frame beyond its release report, if any. + fn flush(&mut self, drop: bool) -> Result<(), String>; /// Accept an RX Block Ack agreement for `tid` from `ssn` (M3 spec S13.2). fn start_rx_block_ack(&mut self, tid: u8, ssn: u16) -> Result<(), String>; fn stop_rx_block_ack(&mut self, tid: u8) -> Result<(), String>; diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/station/tests.rs b/crates/stela-driver-net/src/wifi/realtek/ax/station/tests.rs index c3e3526654..5151d92201 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/station/tests.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/station/tests.rs @@ -4,13 +4,17 @@ //! the AP, shaped as rtw88's `station/tests.rs` `Air`: a firmware scan //! hears the AP's beacon on its channel and ends, the AP answers //! authentication and association, and EAPOL runs against the supplicant -//! tests' `Authenticator`. +//! tests' `Authenticator`. The model decrypts nothing: it records the keys +//! the station installs and the key each data frame names, and hands back +//! the AP's protected frames as the hardware leaves them, marked decrypted +//! with their CCMP header and MIC in place. use super::chip::{Association, Chip, Data, HardwareKey, Incoming, Management, Received, Token}; use super::*; use crate::LinkError; use crate::wifi::connection::security::Security; use crate::wifi::intel::policy::tests::regdb; use crate::wifi::network::{Network, Secret}; +use crate::wifi::realtek::ccmp; use crate::wifi::station::phy::AccessCategory; use crate::wifi::supplicant::tests::Authenticator; use alloc::{rc::Rc, vec}; @@ -29,6 +33,16 @@ const SSID: &[u8] = b"test"; const RSN: [u8; 22] = [ 48, 20, 1, 0, 0, 0x0f, 0xac, 4, 1, 0, 0, 0x0f, 0xac, 4, 1, 0, 0, 0x0f, 0xac, 2, 0, 0, ]; +/// [`RSN`] with management frame protection capable (MFPC, b7), so the +/// station protects its management frames (`ieee80211w=1`). +const RSN_PMF: [u8; 22] = [ + 48, 20, 1, 0, 0, 0x0f, 0xac, 4, 1, 0, 0, 0x0f, 0xac, 4, 1, 0, 0, 0x0f, 0xac, 2, 0x80, 0, +]; +/// The IGTK KDE a PMF message 3 carries: key ID 4, IPN 9, the key 0x77s. +const IGTK_KDE: [u8; 30] = [ + 0xdd, 28, 0, 0x0f, 0xac, 9, 4, 0, 9, 0, 0, 0, 0, 0, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, +]; /// An AP's HT capabilities (SGI 20, one RX STBC stream, SM power save /// static) and operation, one stream at 20 MHz. const HT: [u8; 52] = [ @@ -75,6 +89,9 @@ struct Joined { short_slot: bool, } +/// The CAM entry, key ID and PN a data frame goes under, if any. +type FrameKey = Option<(u8, u8, u64)>; + /// One call the chip took, in order. #[derive(Clone, Debug, PartialEq, Eq)] enum Call { @@ -85,15 +102,26 @@ enum Call { Authenticated, /// A management frame and the basic rates it went with. Management(Vec, u16), + /// A data frame, with the CAM entry, key ID and PN it went under. Data { bytes: Vec, tid: u8, eapol: bool, supported: u16, - keyed: bool, + key: FrameKey, }, Associate(Joined), Disassociate, + /// A key the chip installed, in CAM entry `cam`. + AddKey { + pairwise: bool, + index: u8, + material: Vec, + cam: u8, + }, + RemoveKey(u8), + /// mac80211's flush, with drop or without. + Flush(bool), } /// What the chip was told, and what it holds for the host. @@ -121,18 +149,34 @@ struct Air { full_data: bool, /// Frames refused for no room. refused: usize, + /// The AP protects management frames (beacons [`RSN_PMF`]). + pmf: bool, + /// The firmware never acknowledges a key. + refuse_keys: bool, + /// The CAM entries holding a key. + cam: Vec, + /// An authentication's report comes only after the association + /// request has been taken, as the M3a boot saw it. + late_auth_report: bool, + /// Reports held for [`Air::late_auth_report`]. + late: Vec, } impl Air { fn hear(&mut self, bytes: Vec) { + self.hear_as(bytes, false, false); + } + + /// A frame the hardware `decrypted`, or found failing its ICV. + fn hear_as(&mut self, bytes: Vec, decrypted: bool, icv_error: bool) { let channel = self.channel.unwrap(); self.incoming.push_back(Incoming::Frame(Received { bytes, channel, signal_dbm: None, tsf: 0, - decrypted: false, - icv_error: false, + decrypted, + icv_error, fcs_error: false, })); } @@ -141,10 +185,19 @@ impl Air { fn serve(&mut self) { while let Some((token, bytes)) = self.unanswered.pop_front() { let deaf = bytes[0] == 0xb0 && self.deaf_to_auth; - self.incoming.push_back(Incoming::Transmitted { + let report = Incoming::Transmitted { token, acknowledged: !deaf, - }); + }; + if bytes[0] == 0x00 { + let late = core::mem::take(&mut self.late); + self.incoming.extend(late); + } + if bytes[0] == 0xb0 && self.late_auth_report { + self.late.push(report); + } else { + self.incoming.push_back(report); + } if deaf { continue; } @@ -184,6 +237,48 @@ impl Air { .collect() } + /// The data frames the chip took, with the key each named. + fn data(&self) -> Vec<(Vec, FrameKey)> { + self.calls + .iter() + .filter_map(|c| match c { + Call::Data { bytes, key, .. } => Some((bytes.clone(), *key)), + _ => None, + }) + .collect() + } + + /// The keys installed, as (pairwise, index, CAM entry). + fn keys(&self) -> Vec<(bool, u8, u8)> { + self.calls + .iter() + .filter_map(|c| match c { + Call::AddKey { + pairwise, + index, + cam, + .. + } => Some((*pairwise, *index, *cam)), + _ => None, + }) + .collect() + } + + /// The pairwise key's material. + fn ptk(&self) -> [u8; 16] { + self.calls + .iter() + .find_map(|c| match c { + Call::AddKey { + pairwise: true, + material, + .. + } => material[..].try_into().ok(), + _ => None, + }) + .unwrap() + } + /// The management frames of subtype `fc0` the chip took. fn management(&self, fc0: u8) -> Vec> { self.calls @@ -270,12 +365,17 @@ impl Chip for Model { air.refused += 1; return Ok(None); } + if let Some((cam, _, _)) = frame.key + && !air.cam.contains(&cam) + { + return Err("a key the CAM does not hold".into()); + } air.calls.push(Call::Data { bytes: frame.bytes.to_vec(), tid: frame.tid, eapol: frame.eapol, supported: frame.supported_rates, - keyed: frame.key.is_some(), + key: frame.key, }); let token = air.token(); air.unanswered.push_back((token, frame.bytes.to_vec())); @@ -295,15 +395,43 @@ impl Chip for Model { })); Ok(()) } + /// Leaving deletes what keys are left, as `Live::leave` does. fn disassociate(&mut self) -> Result<(), String> { - self.0.borrow_mut().calls.push(Call::Disassociate); + let mut air = self.0.borrow_mut(); + air.calls.push(Call::Disassociate); + air.cam.clear(); Ok(()) } - fn add_key(&mut self, _: &HardwareKey<'_>) -> Result { - Err("the model holds no key".into()) + /// The lowest free CAM entry, unless the firmware never acknowledges. + fn add_key(&mut self, key: &HardwareKey<'_>) -> Result { + let mut air = self.0.borrow_mut(); + if air.refuse_keys { + return Err("the firmware never acknowledged the key".into()); + } + let cam = (0..).find(|cam| !air.cam.contains(cam)).unwrap(); + air.cam.push(cam); + air.calls.push(Call::AddKey { + pairwise: key.pairwise, + index: key.index, + material: key.material.to_vec(), + cam, + }); + Ok(cam) } - fn remove_key(&mut self, _: u8) -> Result<(), String> { - Err("the model holds no key".into()) + fn remove_key(&mut self, cam: u8) -> Result<(), String> { + let mut air = self.0.borrow_mut(); + air.calls.push(Call::RemoveKey(cam)); + let at = air + .cam + .iter() + .position(|&held| held == cam) + .ok_or("no key in that entry")?; + air.cam.remove(at); + Ok(()) + } + fn flush(&mut self, drop: bool) -> Result<(), String> { + self.0.borrow_mut().calls.push(Call::Flush(drop)); + Ok(()) } fn start_rx_block_ack(&mut self, _: u8, _: u16) -> Result<(), String> { Ok(()) @@ -345,7 +473,7 @@ fn beacon(air: &Air) -> Vec { frame.extend(RATES); // DS parameter set, then a TIM with DTIM period 2. frame.extend([3, 1, channel, 5, 4, 0, 2, 0, 0]); - frame.extend(RSN); + frame.extend(if air.pmf { RSN_PMF } else { RSN }); frame.extend(HT); // HT Operation's primary channel. let at = frame.len() - 22; @@ -371,6 +499,38 @@ fn data(receiver: [u8; 6], sequence: u16, kind: [u8; 2], body: &[u8]) -> Vec frame } +/// [`data`] protected under key ID `keyid` at packet number `pn`, as the +/// hardware hands it on decrypted: its CCMP header after the MAC header, +/// the plaintext, then the MIC (zeros here). +fn protected(receiver: [u8; 6], sequence: u16, keyid: u8, pn: u64, body: &[u8]) -> Vec { + let mut frame = data(receiver, sequence, [8, 0], body); + frame[1] |= 0x40; + let [p0, p1, p2, p3, p4, p5, _, _] = pn.to_le_bytes(); + let header = [p0, p1, 0, 0x20 | keyid << 6, p2, p3, p4, p5]; + frame.splice(26..26, header); + frame.extend([0; 8]); + frame +} + +/// An IPv4 frame from the station to the AP, its body `fill`. +fn ip(fill: u8) -> Vec { + let mut ethernet = Vec::from(AP); + ethernet.extend(LOCAL); + ethernet.extend([8, 0, 0x45, 0]); + ethernet.extend([fill; 44]); + ethernet +} + +/// What the station holds for the network, as each frame's first payload +/// byte past its IPv4 type. +fn delivered(wifi: &mut Wifi) -> Vec { + let mut values = Vec::new(); + while let Some(ethernet) = wifi.receive().unwrap() { + values.push(ethernet[14]); + } + values +} + /// What the station sent past `frame`'s header and LLC when it is EAPOL. fn eapol(frame: &[u8]) -> Option<&[u8]> { if frame[0] & 0x0c != 8 { @@ -455,7 +615,12 @@ fn associated() -> (Wifi, Model) { /// The AP's half of the 4-way handshake. fn authenticator() -> Authenticator { - let security = Security::select(&RSN, true).unwrap(); + authenticator_for(&RSN) +} + +/// The AP's half of the 4-way handshake under `rsn`. +fn authenticator_for(rsn: &[u8]) -> Authenticator { + let security = Security::select(rsn, true).unwrap(); Authenticator::between( security.suites(), Zeroizing::new([0; 32]), @@ -469,20 +634,46 @@ fn authenticator() -> Authenticator { /// release report included. fn handshaken() -> (Wifi, Model) { let (mut wifi, model) = associated(); - let mut ap = authenticator(); + shake(&mut wifi, &model, &RSN, &[]); + (wifi, model) +} + +/// Messages 1 to 4 of the 4-way handshake under `rsn`, message 3 carrying +/// `extra` KDEs, m4's release report included. +fn shake(wifi: &mut Wifi, model: &Model, rsn: &[u8], extra: &[u8]) { + let mut ap = authenticator_for(rsn); model .0 .borrow_mut() .hear(data(LOCAL, 0, [0x88, 0x8e], &ap.message_1())); - assert!(run(&mut wifi, &model, |_, air| !air.eapol().is_empty())); + assert!(run(wifi, model, |_, air| !air.eapol().is_empty())); ap.message_2(&model.0.borrow().eapol()[0]); model .0 .borrow_mut() - .hear(data(LOCAL, 1, [0x88, 0x8e], &ap.message_3(&RSN))); - assert!(run(&mut wifi, &model, |wifi, air| { + .hear(data(LOCAL, 1, [0x88, 0x8e], &ap.message_3_with(rsn, extra))); + assert!(run(wifi, model, |wifi, air| { air.eapol().len() > 1 && progress(wifi).contains("acked 2") })); +} + +/// [`handshaken`], the port open. +fn connected() -> (Wifi, Model) { + let (mut wifi, model) = handshaken(); + assert!(wifi.carrier(), "{}", progress(&mut wifi)); + (wifi, model) +} + +/// A join to an AP protecting management frames, through its handshake +/// with an IGTK to an open port. +fn connected_with_pmf() -> (Wifi, Model) { + let (mut wifi, model) = wifi_with(|air| air.pmf = true); + assert!(run(&mut wifi, &model, |wifi, _| { + wifi.radio().station().phase() == Peering::Associated + })); + assert!(wifi.radio().station().requires_protected_management()); + shake(&mut wifi, &model, &RSN_PMF, &IGTK_KDE); + assert!(wifi.carrier(), "{}", progress(&mut wifi)); (wifi, model) } @@ -639,11 +830,12 @@ fn an_ap_without_wmm_leaves_its_edca_to_the_chip() { } #[test] -fn eapol_flows_both_ways_and_m3a_stops_at_the_key() { +fn eapol_flows_both_ways_before_any_key() { let (mut wifi, model) = handshaken(); let air = model.0.borrow(); - // m2 and m4 went as EAPOL on TID 7, without a key, at the peer's rates. - let sent: Vec<(u8, bool, u16, bool)> = air + // m2 and m4 went as EAPOL on TID 7, without a key, at the peer's rates: + // m4 was handed to the chip before wpa_supplicant installs the PTK. + let sent: Vec<(u8, bool, u16, FrameKey)> = air .calls .iter() .filter_map(|c| match c { @@ -652,23 +844,41 @@ fn eapol_flows_both_ways_and_m3a_stops_at_the_key() { tid, eapol: is_eapol, supported, - keyed, - } if eapol(bytes).is_some() => Some((*tid, *is_eapol, *supported, *keyed)), + key, + } if eapol(bytes).is_some() => Some((*tid, *is_eapol, *supported, *key)), _ => None, }) .collect(); - assert_eq!(sent, [(7, true, 0x011, false), (7, true, 0x011, false)]); + assert_eq!(sent, [(7, true, 0x011, None), (7, true, 0x011, None)]); + let data: Vec = (0..air.calls.len()) + .filter(|&at| matches!(air.calls[at], Call::Data { .. })) + .collect(); + let m4 = data[1]; + let ptk = air.position(|c| matches!(c, Call::AddKey { .. })).unwrap(); + assert!(m4 < ptk); drop(air); let line = progress(&mut wifi); assert!(line.contains("eapol rx 2 tx 2 acked 2"), "{line}"); - assert!(line.contains("keys 0, port closed"), "{line}"); - assert!(line.contains("last \"keys before M3b\""), "{line}"); - // The keeper reports the refusal and the port stays closed. - let Err(LinkError::Adapter(failure)) = wifi.receive() else { - panic!("no failure") - }; - assert!(failure.contains("keys before M3b"), "{failure}"); - assert!(!wifi.carrier()); +} + +#[test] +fn the_handshake_installs_ptk_then_gtk_and_opens_the_port() { + let (mut wifi, model) = connected(); + // `rtw89_ops_set_key` for the PTK (entry 0), then the GTK of key ID 1 + // (entry 1), each with its own material (spec S12). + let air = model.0.borrow(); + assert_eq!(air.keys(), [(true, 0, 0), (false, 1, 1)]); + let gtk: Vec = (0x50..0x60).collect(); + assert!(air.calls.iter().any(|c| matches!( + c, + Call::AddKey { pairwise: false, material, .. } if *material == gtk + ))); + drop(air); + assert!(wifi.carrier()); + let line = progress(&mut wifi); + assert!(line.contains("keys 2, port open"), "{line}"); + assert!(!line.contains("last"), "{line}"); + assert_eq!(wifi.receive(), Ok(None)); } #[test] @@ -755,15 +965,14 @@ fn progress_reports_each_stage() { assoc 1/1 status 0 aid 1, eapol rx 0 tx 0 acked 0, keys -, port closed{chip}" ) ); - // The handshake, to M3a's planned stop. + // The handshake, its two keys and the port (M3b's pass). drop((wifi, model)); - let (mut wifi, _model) = handshaken(); + let (mut wifi, _model) = connected(); assert_eq!( progress(&mut wifi), alloc::format!( "scans 1 (1 networks, target found ch 1 -40 dBm), auth 1/1 status 0, \ - assoc 1/1 status 0 aid 1, eapol rx 2 tx 2 acked 2, keys 0, port closed, \ - last \"keys before M3b\"{chip}" + assoc 1/1 status 0 aid 1, eapol rx 2 tx 2 acked 2, keys 2, port open{chip}" ) ); } @@ -786,6 +995,13 @@ fn diagnostic_names_no_address() { .0 .borrow_mut() .hear(data(LOCAL, 1, [0x88, 0x8e], &ap.message_3(&RSN))); + assert!(run(&mut wifi, &model, |wifi, _| { + let line = progress(wifi); + lines.push(line.clone()); + line.contains("port open") + })); + // Then the station leaves. + wifi.radio_mut().deauthenticate(3).unwrap(); assert!(run(&mut wifi, &model, |wifi, air| { lines.push(progress(wifi)); air.count(|c| *c == Call::Disassociate) == 1 @@ -962,3 +1178,452 @@ fn a_frame_the_station_refuses_is_reported_but_is_no_refusal() { "rtw89 unsupported: a management frame the station refuses" ); } + +#[test] +fn no_frame_leaves_encrypted_before_the_key_is_acked() { + // Review Focus 3: the firmware never acknowledges the PTK. The key is + // never completed, nothing goes under it, and the keeper fails the + // handshake and joins again. + let (mut wifi, model) = wifi_with(|air| air.refuse_keys = true); + assert!(run(&mut wifi, &model, |wifi, _| { + wifi.radio().station().phase() == Peering::Associated + })); + shake(&mut wifi, &model, &RSN, &[]); + assert!(run(&mut wifi, &model, |_, air| { + air.count(|c| matches!(c, Call::SetBssid(_))) == 2 + })); + let Err(LinkError::Adapter(failure)) = wifi.receive() else { + panic!("no failure") + }; + assert!(failure.contains("never acknowledged"), "{failure}"); + let air = model.0.borrow(); + assert!(air.keys().is_empty()); + assert!(air.data().iter().all(|(_, key)| key.is_none())); + assert!(air.count(|c| *c == Call::Disassociate) >= 1); + drop(air); + assert!(!wifi.carrier()); + assert!(progress(&mut wifi).contains("keys 0, port closed")); +} + +#[test] +fn data_goes_with_its_pn_and_without_iv() { + let (mut wifi, model) = connected(); + let before = model.0.borrow().data().len(); + wifi.transmit(&ip(1)).unwrap(); + wifi.transmit(&ip(2)).unwrap(); + let air = model.0.borrow(); + let sent = &air.data()[before..]; + // The PTK's CAM entry and key ID 0, under PNs 1 and 2: its + // `TransmitSeed::host(0)`, as `atomic64_inc_return` counts from 0. + let keys: Vec = sent.iter().map(|(_, key)| *key).collect(); + assert_eq!(keys, [Some((0, 0, 1)), Some((0, 0, 2))]); + for (bytes, _) in sent { + // Protected QoS data whose 26-byte header is followed by the LLC: + // the CCMP header is the hardware's to insert (spec S5.4). + assert_eq!(bytes[..2], [0x88, 0x41]); + assert_eq!(bytes[26..34], [0xaa, 0xaa, 3, 0, 0, 0, 8, 0]); + assert_eq!(bytes.len(), 26 + 8 + 46); + } +} + +#[test] +fn pns_strictly_increase_across_a_full_ring() { + // Review Focus 4: a frame the chip has no room for waits in `held` with + // the PN reserved for it; one dropped from `held` still spent its PN. + let (mut wifi, model) = connected(); + let before = model.0.borrow().data().len(); + let fill = |bytes: &[u8]| bytes[36]; + wifi.transmit(&ip(1)).unwrap(); + model.0.borrow_mut().full_data = true; + wifi.transmit(&ip(2)).unwrap(); + wifi.transmit(&ip(3)).unwrap(); + assert_eq!(model.0.borrow().data().len(), before + 1); + model.0.borrow_mut().full_data = false; + assert!(run(&mut wifi, &model, |_, air| air.data().len() == before + 3)); + let sent: Vec<(u8, u64)> = model.0.borrow().data()[before..] + .iter() + .map(|(bytes, key)| (fill(bytes), key.unwrap().2)) + .collect(); + assert_eq!(sent, [(1, 1), (2, 2), (3, 3)]); + // 257 frames wait: the oldest (PN 4) is dropped, the rest leave in + // order, and the next frame takes PN 261, never a PN given before. + model.0.borrow_mut().full_data = true; + for n in 0..257u16 { + wifi.transmit(&ip(n as u8)).unwrap(); + } + model.0.borrow_mut().full_data = false; + assert!(run(&mut wifi, &model, |_, air| air.data().len() == before + 259)); + wifi.transmit(&ip(9)).unwrap(); + let pns: Vec = model.0.borrow().data()[before + 3..] + .iter() + .map(|(_, key)| key.unwrap().2) + .collect(); + assert_eq!(pns, (5..=261).collect::>()); +} + +#[test] +fn received_data_passes_replay_and_reaches_the_link() { + let (mut wifi, model) = connected(); + let hear = |frame: Vec| model.0.borrow_mut().hear_as(frame, true, false); + hear(protected(LOCAL, 10, 0, 1, &[0x45; 46])); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x45]); + // Replayed, then the next packet number. + hear(protected(LOCAL, 10, 0, 1, &[0x45; 46])); + hear(protected(LOCAL, 11, 0, 2, &[0x46; 46])); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x46]); + // A group frame under the GTK of key ID 1, past its RSC of 7. + hear(protected([0xff; 6], 12, 1, 8, &[0x47; 46])); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x47]); + // Unprotected data is refused once the port is controlled. + model + .0 + .borrow_mut() + .hear(data(LOCAL, 13, [8, 0], &[0x48; 46])); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), []); +} + +#[test] +fn an_undecrypted_protected_frame_is_dropped() { + let (mut wifi, model) = connected(); + let body = [0x45; 46]; + let mut air = model.0.borrow_mut(); + // Not decrypted by the hardware, failing its ICV, and under a key ID + // no key has (spec S13.3). + air.hear_as(protected(LOCAL, 10, 0, 1, &body), false, false); + air.hear_as(protected(LOCAL, 11, 0, 2, &body), true, true); + air.hear_as(protected(LOCAL, 12, 2, 3, &body), true, false); + drop(air); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), []); + // None of them spent a packet number. + model + .0 + .borrow_mut() + .hear_as(protected(LOCAL, 13, 0, 1, &body), true, false); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x45]); +} + +#[test] +fn a_robust_management_frame_is_sealed_on_the_host() { + // Spec S1.2: sealed under the PTK with `realtek::ccmp`, handed to the + // chip as any management frame (no hardware key). + let (mut wifi, model) = connected_with_pmf(); + let ptk = model.0.borrow().ptk(); + wifi.radio_mut().deauthenticate(3).unwrap(); + let air = model.0.borrow(); + let deauth = air.management(0xc0); + let [frame] = &deauth[..] else { + panic!("{} deauthentications", deauth.len()) + }; + // Protected, under the PTK's next PN (nothing went under it before), + // its reason sealed and its MIC appended. + assert_eq!(frame[1] & 0x40, 0x40); + assert_eq!(frame[24..32], [1, 0, 0, 0x20, 0, 0, 0, 0]); + assert_eq!(frame.len(), 24 + 8 + 2 + 8); + let opened = ccmp::open(&ptk, frame, PacketNumber::new(1).unwrap()).unwrap(); + assert_eq!(opened[32..34], [3, 0]); +} + +#[test] +fn under_pmf_an_unprotected_departure_is_ignored() { + // `ieee80211_drop_unencrypted_mgmt`: neither a unicast nor a group + // deauthentication without its protection ends a PMF association. + let (mut wifi, model) = connected_with_pmf(); + let mut group = management(0xc0, &[7, 0]); + group[4..10].fill(0xff); + model.0.borrow_mut().hear(management(0xc0, &[7, 0])); + model.0.borrow_mut().hear(group); + for _ in 0..3 { + run(&mut wifi, &model, |_, _| true); + } + assert_eq!(model.0.borrow().count(|c| *c == Call::Disassociate), 0); + assert!(wifi.carrier()); +} + +#[test] +fn a_tkip_or_ccmp256_key_is_unsupported() { + let (mut wifi, model) = associated(); + for (pairwise, index, length) in [(true, 0, 32), (false, 1, 32), (false, 1, 13)] { + let got = wifi + .radio_mut() + .install_key(pairwise, index, &vec![0; length], ReplaySeed::ZERO); + assert!( + matches!( + got, + Err(Error::Unsupported( + "a key other than CCMP-128 on an RTL8852C" + )) + ), + "{got:?}" + ); + } + assert!(model.0.borrow().keys().is_empty()); + let line = progress(&mut wifi); + assert!( + line.contains("last \"a key other than CCMP-128 on an RTL8852C\""), + "{line}" + ); +} + +#[test] +fn an_authentication_reported_late_still_counts_its_ack() { + // The M3a boot read 'auth 1/0' though the chip saw every frame + // acknowledged: the authentication's report came after the association + // request had replaced it as the frame the station awaits. + let (mut wifi, model) = wifi_with(|air| air.late_auth_report = true); + assert!(run(&mut wifi, &model, |wifi, _| { + wifi.radio().station().phase() == Peering::Associated + })); + let line = progress(&mut wifi); + assert!( + line.contains("auth 1/1 status 0, assoc 1/1 status 0"), + "{line}" + ); +} + +/// The flushes, management frames, key calls and the leaving among the +/// chip's calls from `from` to the first disassociation. +fn leaving(air: &Air, from: usize) -> Vec { + let end = from + + air.calls[from..] + .iter() + .position(|c| *c == Call::Disassociate) + .unwrap(); + air.calls[from..=end] + .iter() + .filter_map(|c| match c { + Call::Flush(drop) => Some(alloc::format!("flush {drop}")), + Call::Management(bytes, _) => Some(alloc::format!("mgmt {:02x}", bytes[0])), + Call::RemoveKey(cam) => Some(alloc::format!("remove {cam}")), + Call::Disassociate => Some(String::from("leave")), + Call::AddKey { .. } => Some(String::from("add")), + _ => None, + }) + .collect() +} + +#[test] +fn a_deauthentication_flushes_and_deletes_the_keys_before_leaving() { + // ieee80211_set_disassoc: a flush with drop, the deauthentication, a + // flush without; then sta_info_flush deletes the PTK (DISABLE_KEY: + // rtw89_ops_set_key's flushes, then the CAM delete), the GTK after it + // (spec S14.5), and the AP's station leaves. + let (mut wifi, model) = connected(); + let from = model.0.borrow().calls.len(); + wifi.radio_mut().deauthenticate(3).unwrap(); + assert!(run(&mut wifi, &model, |_, air| { + air.position(|c| *c == Call::Disassociate).is_some() + })); + assert_eq!( + leaving(&model.0.borrow(), from), + [ + "flush true", + "mgmt c0", + "flush false", + "flush false", + "remove 0", + "flush false", + "remove 1", + "leave" + ] + ); + assert!(!wifi.carrier()); +} + +#[test] +fn a_deauthentication_from_the_ap_drops_what_is_queued_and_deletes_the_keys() { + // ieee80211_set_disassoc without a frame of its own: the flush with + // drop alone, then the keys and the leaving. + let (mut wifi, model) = connected(); + let from = model.0.borrow().calls.len(); + model.0.borrow_mut().hear(management(0xc0, &[7, 0])); + assert!(run(&mut wifi, &model, |_, air| { + air.position(|c| *c == Call::Disassociate).is_some() + })); + assert_eq!( + leaving(&model.0.borrow(), from), + [ + "flush true", + "flush false", + "remove 0", + "flush false", + "remove 1", + "leave" + ] + ); +} + +#[test] +fn a_group_rekey_replaces_the_key_of_its_index() { + // ieee80211_key_replace: the old key of the same index goes first + // (DISABLE_KEY), then the new one; a key of another index is added. + // The port stays open on the PTK and the GTK last installed. + let (mut wifi, model) = connected(); + let hear = |frame: Vec| model.0.borrow_mut().hear_as(frame, true, false); + let from = model.0.borrow().calls.len(); + wifi.radio_mut() + .install_key(false, 1, &[0x66; 16], ReplaySeed::ZERO) + .unwrap(); + { + let air = model.0.borrow(); + let calls: Vec<&Call> = air.calls[from..].iter().collect(); + assert_eq!(calls.len(), 3, "{calls:?}"); + assert_eq!(*calls[0], Call::Flush(false)); + assert_eq!(*calls[1], Call::RemoveKey(1)); + assert!(matches!( + calls[2], + Call::AddKey { + pairwise: false, + index: 1, + cam: 1, + .. + } + )); + } + hear(protected([0xff; 6], 20, 1, 1, &[0x51; 46])); + hear(protected(LOCAL, 21, 0, 1, &[0x52; 46])); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x51, 0x52]); + let from = model.0.borrow().calls.len(); + wifi.radio_mut() + .install_key(false, 2, &[0x67; 16], ReplaySeed::ZERO) + .unwrap(); + { + let air = model.0.borrow(); + let calls: Vec<&Call> = air.calls[from..].iter().collect(); + assert_eq!(calls.len(), 1, "{calls:?}"); + assert!(matches!( + calls[0], + Call::AddKey { + pairwise: false, + index: 2, + cam: 2, + .. + } + )); + } + hear(protected([0xff; 6], 22, 2, 1, &[0x53; 46])); + hear(protected(LOCAL, 23, 0, 2, &[0x54; 46])); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x53, 0x54]); + assert!(wifi.carrier()); + // The same key again is no new install (KRACK, ieee80211_key_identical). + let from = model.0.borrow().calls.len(); + wifi.radio_mut() + .install_key(false, 2, &[0x67; 16], ReplaySeed::ZERO) + .unwrap(); + assert_eq!(model.0.borrow().calls.len(), from); + assert!(progress(&mut wifi).contains("keys 4")); +} + +/// Fragment `number` of frame `sequence` under the PTK at packet number +/// `pn`, with `more` to follow. +fn fragment(sequence: u16, number: u8, more: bool, pn: u64, payload: &[u8]) -> Vec { + let mut frame = protected(LOCAL, sequence, 0, pn, &[]); + frame.truncate(34); + frame.extend_from_slice(payload); + frame.extend([0; 8]); + frame[1] |= u8::from(more) << 2; + frame[22] |= number; + frame +} + +#[test] +fn fragments_under_consecutive_numbers_make_one_frame() { + let (mut wifi, model) = connected(); + let first = [&[0xaa, 0xaa, 3, 0, 0, 0, 8, 0][..], &[0x45; 4]].concat(); + let hear = |frame: Vec| model.0.borrow_mut().hear_as(frame, true, false); + hear(fragment(30, 0, true, 1, &first)); + hear(fragment(30, 1, false, 2, &[0x46; 4])); + wifi.carrier(); + let ethernet = wifi.receive().unwrap().unwrap(); + assert_eq!( + ethernet[14..], + [0x45, 0x45, 0x45, 0x45, 0x46, 0x46, 0x46, 0x46] + ); + // Numbers that skip one are dropped. + hear(fragment(31, 0, true, 5, &first)); + hear(fragment(31, 1, false, 7, &[0x46; 4])); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), []); +} + +#[test] +fn an_a_msdu_gives_up_each_of_its_frames() { + let (mut wifi, model) = connected(); + let mut frame = protected(LOCAL, 20, 0, 1, &[]); + frame.truncate(34); + frame[24] = 0x80; + for value in [0x31, 0x32] { + let padding = (4 - frame[34..].len() % 4) % 4; + frame.extend(vec![0; padding]); + frame.extend(LOCAL); + frame.extend(AP); + frame.extend(54u16.to_be_bytes()); + frame.extend([0xaa, 0xaa, 3, 0, 0, 0, 8, 0]); + frame.extend([value; 46]); + } + frame.extend([0; 8]); + model.0.borrow_mut().hear_as(frame, true, false); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x31, 0x32]); +} + +/// An SA Query request at packet number `number` as the hardware leaves +/// it decrypted, its MIC in place. +fn sa_query(number: u8) -> Vec { + let mut frame = management(0xd0, &[number, 0, 0, 0x20, 0, 0, 0, 0, 8, 0, 1, 2]); + frame[1] = 0x40; + frame.extend([0; 8]); + frame +} + +#[test] +fn a_protected_management_frame_is_taken_once_under_its_packet_number() { + let (mut wifi, model) = connected(); + let answers = |air: &Air| air.management(0xd0); + model.0.borrow_mut().hear_as(sa_query(5), true, false); + assert!(run(&mut wifi, &model, |_, air| answers(air).len() == 1)); + model.0.borrow_mut().hear_as(sa_query(5), true, false); + assert!(!run(&mut wifi, &model, |_, air| answers(air).len() > 1)); + model.0.borrow_mut().hear_as(sa_query(6), true, false); + assert!(run(&mut wifi, &model, |_, air| answers(air).len() == 2)); + // Each answer is sealed under the PTK and answers its request's ID. + let air = model.0.borrow(); + let ptk = air.ptk(); + for (n, answer) in answers(&air).iter().enumerate() { + let pn = PacketNumber::new(n as u64 + 1).unwrap(); + let opened = ccmp::open(&ptk, answer, pn).unwrap(); + assert_eq!(opened[32..36], [8, 1, 1, 2]); + } +} + +#[test] +fn a_pairwise_rekey_drops_what_waits_under_the_old_key() { + // The new PTK takes the CAM entry the old one left: a frame held under + // the old key and its PN must not leave under the new one. + let (mut wifi, model) = connected(); + let before = model.0.borrow().data().len(); + model.0.borrow_mut().full_data = true; + wifi.transmit(&ip(1)).unwrap(); + wifi.radio_mut() + .install_key(true, 0, &[0x99; 16], ReplaySeed::ZERO) + .unwrap(); + assert_eq!(model.0.borrow().keys().last(), Some(&(true, 0, 0))); + model.0.borrow_mut().full_data = false; + wifi.transmit(&ip(2)).unwrap(); + assert!(run(&mut wifi, &model, |_, air| air.data().len() > before)); + for _ in 0..3 { + run(&mut wifi, &model, |_, _| true); + } + let sent: Vec<(u8, FrameKey)> = model.0.borrow().data()[before..] + .iter() + .map(|(bytes, key)| (bytes[36], *key)) + .collect(); + assert_eq!(sent, [(2, Some((0, 0, 1)))]); +} diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/txd.rs b/crates/stela-driver-net/src/wifi/realtek/ax/txd.rs index c092a3a35c..79ba59b466 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/txd.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/txd.rs @@ -99,6 +99,8 @@ const SCAM_NUM: u8 = 128; const MAC_ID: u8 = 0; /// `IEEE80211_QOS_CTL_TAG1D_MASK`: `skb->priority`'s TID bits. const QOS_CTL_TAG1D_MASK: u8 = 0x7; +/// `IEEE80211_QOS_CTL_TID_MASK`: the QoS control's TID field. +const QOS_CTL_TID_MASK: u8 = 0xF; /// `IEEE80211_CCMP_HDR_LEN`. const CCMP_HDR_LEN: usize = 8; /// CCMP's 48-bit PN. @@ -262,13 +264,20 @@ pub fn management( /// encrypted as CCMP-128 by the hardware under CAM entry `sec.cam` with /// `sec.pn` in BODY4/5 and `wp_offset` 1. /// +/// `tid` is `skb->priority`, whose TID mac80211 also writes into a QoS +/// frame's QoS control (`ieee80211_set_qos_hdr`, `net/mac80211/wme.c:193-232`) +/// and which it sets to 0 for a peer without WMM, whose frames carry no QoS +/// control (`__ieee80211_select_queue`, `wme.c:167-170`). +/// /// Refused: a frame that is not data or is null data (management, see /// [`management`]), one shorter than its 802.11 header or longer than -/// [`MAX_TX_FRAME`], a Protected frame without `sec` (no data frame is -/// sealed on the host, M3 spec S1.2, so it would leave unencrypted), `sec` -/// for a frame without the Protected bit (mac80211 hands a hardware key -/// only with a Protected frame), and a key the descriptor cannot carry (key -/// ID past 3, PN 0 or past 48 bits, CAM entry past 127). +/// [`MAX_TX_FRAME`], a `tid` whose TID is not the frame's own (its QoS +/// control's four TID bits, 0 without one), a Protected frame without `sec` +/// (no data frame is sealed on the host, M3 spec S1.2, so it would leave +/// unencrypted), `sec` for a frame without the Protected bit (mac80211 +/// hands a hardware key only with a Protected frame), and a key the +/// descriptor cannot carry (key ID past 3, PN 0 or past 48 bits, CAM entry +/// past 127). pub fn data( bytes: &[u8], tid: u8, @@ -290,6 +299,9 @@ pub fn data( } // rtw89_core_tx_update_data_info let tid = tid & QOS_CTL_TAG1D_MASK; + if frame.tid != tid { + return Err(AxError::Tx("a TID other than the frame's own")); + } let ch = TID_CHANNEL[usize::from(tid)]; let mut info = DescInfo { pkt_size: frame.len, @@ -325,16 +337,20 @@ pub fn data( /// The frame keeps its Protected bit; its new length is the `L` of /// [`data`], whose `sec.pn` must be this `pn`. /// -/// Anything else changes nothing in `mpdu`: a frame that is not data or is -/// shorter than its MAC header and 8 bytes, a key ID past 3, a PN of 0 or -/// past 48 bits, and a header that is not the reservation's -/// (`Tx("CCMP header does not match its reservation")`), so no frame is -/// queued under a PN other than the one reserved for it. +/// Anything else changes nothing in `mpdu`: a frame that is not data, one +/// without the Protected bit (the 8 bytes after its header are plaintext, +/// whatever they hold), one shorter than its MAC header and 8 bytes, a key +/// ID past 3, a PN of 0 or past 48 bits, and a header that is not the +/// reservation's (`Tx("CCMP header does not match its reservation")`), so +/// no frame is queued under a PN other than the one reserved for it. pub fn strip_ccmp(mpdu: &mut Vec, pn: u64, keyid: u8) -> Result<(), AxError> { let fc = frame_control(mpdu)?; if !is_data(fc) { return Err(AxError::Tx("not a data frame")); } + if fc & FCTL_PROTECTED == 0 { + return Err(AxError::Tx("not a protected frame")); + } let header = hdrlen(fc); if mpdu.len() < header { return Err(AxError::Tx("frame shorter than its 802.11 header")); @@ -465,6 +481,9 @@ struct Frame { seq: u16, /// `is_broadcast_ether_addr(addr1) || is_multicast_ether_addr(addr1)`. is_bmc: bool, + /// A data frame's QoS control TID (`IEEE80211_QOS_CTL_TID_MASK`), 0 + /// without one, as for a management frame. + tid: u8, } impl Frame { @@ -478,11 +497,23 @@ impl Frame { return Err(AxError::Tx("frame longer than one TX address entry")); } let seq_ctrl = u16::from_le_bytes([bytes[SEQ_CTRL], bytes[SEQ_CTRL + 1]]); + // `ieee80211_get_qos_ctl`: right after the three or four addresses. + let tid = if is_data(fc) && fc & STYPE_QOS_DATA != 0 { + let at = if fc & (FCTL_TODS | FCTL_FROMDS) == FCTL_TODS | FCTL_FROMDS { + HDR_LEN_4ADDR + } else { + HDR_LEN_3ADDR + }; + bytes[at] & QOS_CTL_TID_MASK + } else { + 0 + }; Ok(Self { len: bytes.len() as u16, header, seq: (seq_ctrl & SCTL_SEQ) >> 4, is_bmc: bytes[ADDR1] & 1 != 0, + tid, }) } } diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/txd/tests.rs b/crates/stela-driver-net/src/wifi/realtek/ax/txd/tests.rs index e5d51fd27f..8f085ab148 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/txd/tests.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/txd/tests.rs @@ -550,3 +550,68 @@ fn data_refuses_keys_the_descriptor_cannot_carry() { assert_eq!(w[4..6], [0xFFFF_0000, 0xFFFF_FFFF]); assert_eq!(w[info(2)], 0x0000_017F); } + +#[test] +fn strip_refuses_an_unprotected_frame() { + // Its 8 bytes after the header are plaintext, even when they read as + // the reservation's header. + let mut mpdu = frame(DATA, AP, 0x456, &PN_HEADER); + mpdu.extend_from_slice(&PLAINTEXT); + let before = mpdu.clone(); + assert_eq!( + strip_ccmp(&mut mpdu, PN, 0), + Err(AxError::Tx("not a protected frame")) + ); + assert_eq!(mpdu, before); +} + +#[test] +fn data_takes_the_tid_its_frame_carries() { + const OTHER: Result<(TxChannel, [u8; WD_HEAD_BYTES]), AxError> = + Err(AxError::Tx("a TID other than the frame's own")); + // skb->priority's TID is the QoS control's (ieee80211_set_qos_hdr). + let f = qos(QOS, 5, 1, &PLAINTEXT); + let (ch, _) = data(&f, 5, false, HwBand::G2, 0, NO_CAPS, None).unwrap(); + assert_eq!(ch, TxChannel::Ach2); + assert_eq!(data(&f, 0, false, HwBand::G2, 0, NO_CAPS, None), OTHER); + assert_eq!(data(&f, 6, false, HwBand::G2, 0, NO_CAPS, None), OTHER); + // A frame without QoS goes at priority 0 (__ieee80211_select_queue): + // TID 8 is TID 0, best effort on ACH0; TID 7 is not its own. + let f = frame(DATA, AP, 1, &PLAINTEXT); + let (ch, head) = data(&f, 8, false, HwBand::G2, 0, NO_CAPS, None).unwrap(); + assert_eq!(ch, TxChannel::Ach0); + assert_eq!(words(&head)[2] & 0x00FE_0000, 0); + assert_eq!(data(&f, 7, false, HwBand::G2, 0, NO_CAPS, None), OTHER); + // The QoS control's TID field is four bits: a TSPEC TID 15 is no TID 7. + let f = qos(QOS, 15, 1, &PLAINTEXT); + assert_eq!(data(&f, 7, false, HwBand::G2, 0, NO_CAPS, None), OTHER); +} + +#[test] +fn eapol_under_the_ptk_matches_linux() { + // A group handshake's message 2 under the PTK, as the strip leaves it: + // VO with BK and the TID indication, and the key's dwords. + let f = qos(QOS_PROTECTED, 7, 0x123, &EAPOL_BODY); + let len = f.len() as u32; + let (ch, head) = data(&f, 7, true, HwBand::G2, 0xFFF, NO_CAPS, sec(0, 0, PN)).unwrap(); + assert_eq!(ch, TxChannel::Ach3); + assert_eq!( + words(&head), + [ + 0x0143_6880, // B0: WP_OFFSET 1, WD_INFO_EN, ACH3, HDR_LLC_LEN 13 + 0x0400_0006, // B1: ADDR_INFO_NUM 1, SEC_TYPE CCMP128 + 0x0086_0000 | len, // B2: TID_INDICATE, QSEL VO_0 + 0x2000 | 0x123, // B3: BK, SW_SEQ + 0x0201_0000, // B4: PN1, PN0 + 0x0605_0403, // B5: PN5..PN2 + 0, + 0, + 0, + 0, + 0x0000_0100, // I2: FORCE_KEY_EN, SEC_CAM_IDX 0 + 0, + 0x8800_0000, + 0, + ] + ); +}