From bcffc0edff1ac288fd87dd545de8fb2b3dac6417 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:46:05 +0000 Subject: [PATCH] fix(wifi): reorder an RTL8852CE's protected frames before dropping the ones it cannot open, PN-check each frame as it is drained, and close its port while a replaced key's successor is not installed, as mac80211 and rtw89 do, where an undecryptable frame held its agreement's later frames up to 100 ms, a key install's reset outran the frames its own waits drained, and a refused rekey left the port open without its key --- .../src/wifi/realtek/ax/live.rs | 174 +++++++++--------- .../src/wifi/realtek/ax/live/tests/ba.rs | 47 +++++ .../src/wifi/realtek/ax/station.rs | 87 ++++++--- .../src/wifi/realtek/ax/station/tests.rs | 82 +++++++++ 4 files changed, 282 insertions(+), 108 deletions(-) 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 236b9e2ce4..a4a5b2b4e6 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/live.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/live.rs @@ -113,10 +113,12 @@ //! RX_STOP, a static BA CAM entry and its H2C, sent without a wait as //! Linux's, and the TID's PN check started or stopped; [`Live::leave`] //! stops what is left before the key deletes, as mac80211 tears the -//! agreements down first. Every frame [`Live::service`] hands on passes -//! `rtw89_core_skb_pn_valid` first, as `rtw89_core_rx` runs it before -//! mac80211 (`core.c:4551`), and a pairwise key's install starts the -//! started TIDs' checks over (`mac80211.c:1007-1008`). +//! agreements down first. Every frame the chip drains passes +//! `rtw89_core_skb_pn_valid` as it is drained, by [`Live::drain`] or by an +//! operation that holds it, as `rtw89_core_rx` runs it on reception before +//! mac80211 (`core.c:4551`), and is not checked again when handed on; so a +//! pairwise key's install starts the started TIDs' checks over +//! (`mac80211.c:1007-1008`) after the frames its own waits drained. //! //! The beacon filter the association arms reports the AP's beacons lost //! (M3 spec S15, ruling R2): [`Live::service`] takes each BCNFLTR_RPT as @@ -621,6 +623,19 @@ fn failed(step: &str, error: AxError) -> String { format!("{step}: {error}") } +/// Whether `event` goes on from the drain that brought it: a frame only +/// when `rtw89_core_skb_pn_valid` passes it ([`RxStats::valid`] under +/// `stats`, `associated` saying whether MAC ID 0 is the associated +/// station's), as `rtw89_core_rx` runs it on reception (`core.c:4551`), +/// whichever drain brought it and whatever the operation then changes; +/// every C2H. +fn checked(stats: &mut RxStats, associated: bool, event: &Event<'_>) -> bool { + match event { + Event::Frame(frame) => stats.valid(associated, frame), + Event::C2h(_) => true, + } +} + impl Live { /// What the bring-up reported (M2b2's report, no scan). pub fn running(&self) -> &Running { @@ -789,15 +804,13 @@ impl Live { scan::check_firmware(self.running.firmware)?; let mac = self.running.mac; let budget_us = scan::scan_budget_us(list.len()); - let mut held = core::mem::take(&mut self.held); let mut dig = self.dig; - let started = self.session(|io, session| { + let started = self.holding(|io, session, held| { // SAFETY: the caller's contract is `start`'s, which // `hw_scan_start`'s is, for the live chip's own window and rings. - let edcca = - unsafe { scan::hw_scan_start(io, session, mac, &mut dig, &mut |e| held.keep(e)) }?; + let edcca = unsafe { scan::hw_scan_start(io, session, mac, &mut dig, held) }?; session.rx.set_mode(Mode::Scan); - session.rx.flush(&mut |e| held.keep(e)); + session.rx.flush(held); let mut scan = LiveScan { edcca, deadline_us: u64::MAX, @@ -809,13 +822,12 @@ impl Live { let offloaded = unsafe { scan::offload(io, session, list, &mut |e| { scan.track(&e); - held.keep(e) + held(e) }) } .and_then(|()| io.now_us()); Ok((scan, offloaded)) }); - self.held = held; self.dig = dig; let (mut scan, offloaded) = match started { Ok(Ok(started)) => started, @@ -842,9 +854,11 @@ impl Live { /// One RXQ poll for `sink` (the RXQ step of the radio's poll): first the /// frames and beacon filter reports an operation held, oldest first - /// (see [`Live::service`]), then every RXQ - /// entry through the receiver and the session's ledger, as - /// `rtw89_pci_poll_rxq_dma` hands them to `rtw89_core_rx`. A running + /// (see [`Live::service`]), then every RXQ entry through the receiver, + /// the session's ledger and `rtw89_core_skb_pn_valid` ([`checked`]: a + /// frame it drops is counted, not handed on), as `rtw89_pci_poll_rxq_dma` + /// hands them to `rtw89_core_rx`; a held frame passed that check as it + /// was drained. A running /// scan's first END_SCAN ends it: the same call then drains what /// followed END_SCAN and flushes the receiver into `sink` /// ([`scan::tail`]), so every frame the scan heard is handed on before @@ -860,7 +874,7 @@ impl Live { } self.release(sink); let mut scan = self.scan.take(); - let drained = self.session(|io, session| { + let drained = self.passing(sink, |io, session, sink| { // SAFETY: the caller's contract is `start`'s, which `drain`'s // is, for the live chip's own window and rings. unsafe { @@ -890,8 +904,9 @@ impl Live { /// The scan budget (the radio poll's last step, M3 spec S8.1): a scan /// without END_SCAN at its deadline is stopped as `rtw89_hw_scan_abort` /// does ([`scan::stop`]: SCANOFLD stop, then up to `STOP_WAIT_US` for - /// END_SCAN), what followed drained into `sink` ([`scan::tail`]), after - /// the frames held, and it ends [`ScanEnd::Stopped`], `ended` when + /// END_SCAN), what followed drained into `sink` ([`scan::tail`]) as + /// [`Live::drain`] drains it, after the frames held, and it ends + /// [`ScanEnd::Stopped`], `ended` when /// END_SCAN came in the stop's wait or its tail. A stop or tail that /// fails still ends it so, as Linux completes an abort whatever the /// stop returned (`fw.c:10502-10510`), and returns its error; the stop @@ -914,7 +929,7 @@ impl Live { } self.release(sink); let mut scan = self.scan.take(); - let stopped = self.session(|io, session| { + let stopped = self.passing(sink, |io, session, sink| { let mut track = |e: Event<'_>| { if let Some(scan) = scan.as_mut() { scan.track(&e); @@ -989,12 +1004,9 @@ impl Live { /// # Safety /// [`start`]'s contract, still holding for this chip. unsafe fn abort(&mut self) { - let mut held = core::mem::take(&mut self.held); // SAFETY: the caller's contract is `start`'s, which `stop`'s is, for // the live chip's own window and rings. - let _ = - self.session(|io, session| unsafe { scan::stop(io, session, &mut |e| held.keep(e)) }); - self.held = held; + let _ = self.holding(|io, session, held| unsafe { scan::stop(io, session, held) }); if let Some(scan) = self.scan.take() { // SAFETY: as above, `restore`'s. let _ = unsafe { self.restore(&scan.edcca) }; @@ -1012,16 +1024,12 @@ impl Live { // SAFETY: the caller's contract is `tune`'s, word for word. unsafe { self.tune(&chan) }?; let mac = self.running.mac; - let mut held = core::mem::take(&mut self.held); let mut dig = self.dig; - let completed = self.session(|io, session| { + let completed = self.holding(|io, session, held| { // SAFETY: as above, `hw_scan_complete`'s, for the live chip's own // window and rings. - unsafe { - scan::hw_scan_complete(io, session, mac, edcca, &mut dig, &mut |e| held.keep(e)) - } + unsafe { scan::hw_scan_complete(io, session, mac, edcca, &mut dig, held) } }); - self.held = held; self.dig = dig; match completed { Ok(Ok(())) => Ok(()), @@ -1053,14 +1061,12 @@ impl Live { return Err(AxError::Mac("a new BSSID while associated")); } let mac = self.running.mac; - let mut held = core::mem::take(&mut self.held); let mut dig = self.dig; - let done = self.session(|io, session| { + let done = self.holding(|io, session, held| { // SAFETY: the caller's contract is `start`'s, which `set_bssid`'s // is, for the live chip's own window and rings. - unsafe { assoc::set_bssid(io, session, mac, bssid, &mut dig, &mut |e| held.keep(e)) } + unsafe { assoc::set_bssid(io, session, mac, bssid, &mut dig, held) } }); - self.held = held; self.dig = dig; self.done(done)?; self.bssid = Some(bssid); @@ -1114,18 +1120,12 @@ impl Live { return Err(AxError::Mac("an association on a band not tuned")); } let features = Features::of(self.running.firmware); - let mut held = core::mem::take(&mut self.held); let mut dig = self.dig; - let done = self.session(|io, session| { + let done = self.holding(|io, session, held| { // SAFETY: the caller's contract is `start`'s, which `associate`'s // is, for the live chip's own window and rings. - unsafe { - assoc::associate(io, session, inputs, features, &mut dig, &mut |e| { - held.keep(e) - }) - } + unsafe { assoc::associate(io, session, inputs, features, &mut dig, held) } }); - self.held = held; self.dig = dig; self.done(done)?; self.associated = Some(*inputs); @@ -1171,9 +1171,7 @@ impl Live { let features = Features::of(self.running.firmware); let mac = self.running.mac; let band = self.chan.band; - let mut held = core::mem::take(&mut self.held); - let done = self.session(|io, session| { - let sink = &mut |e: Event<'_>| held.keep(e); + let done = self.holding(|io, session, sink| { match (&associated, bssid) { (Some(inputs), _) => { for tid in agreements.tids() { @@ -1204,7 +1202,6 @@ impl Live { (None, _) => unsafe { assoc::clear_bssid(io, session, mac, cam.keys(), sink) }, } }); - self.held = held; self.done(done) } @@ -1241,8 +1238,7 @@ impl Live { let addr = AddrCam::connected(inputs.mac, inputs.bssid, inputs.aid); keys::check(&self.keys, key.pairwise, key.index)?; let mut cam = self.keys; - let mut held = core::mem::take(&mut self.held); - let done = self.session(|io, session| { + let done = self.holding(|io, session, held| { // SAFETY: the caller's contract is `start`'s, which `install`'s // is, for the live chip's own window and rings. unsafe { @@ -1254,11 +1250,10 @@ impl Live { key.pairwise, key.index, key.material, - &mut |e| held.keep(e), + held, ) } }); - self.held = held; self.keys = cam; let installed = done.and_then(|done| done)?; if key.pairwise { @@ -1286,13 +1281,11 @@ impl Live { }; let addr = AddrCam::connected(inputs.mac, inputs.bssid, inputs.aid); let mut state = self.keys; - let mut held = core::mem::take(&mut self.held); - let done = self.session(|io, session| { + let done = self.holding(|io, session, held| { // SAFETY: the caller's contract is `start`'s, which `delete`'s // is, for the live chip's own window and rings. - unsafe { keys::delete(io, session, &mut state, &addr, cam, &mut |e| held.keep(e)) } + unsafe { keys::delete(io, session, &mut state, &addr, cam, held) } }); - self.held = held; self.keys = state; done.and_then(|done| done) } @@ -1328,17 +1321,11 @@ impl Live { } self.rx_stats.control(tid, true); let mut cam = self.ba; - let mut held = core::mem::take(&mut self.held); - let done = self.session(|io, session| { + let done = self.holding(|io, session, held| { // SAFETY: the caller's contract is `start`'s, which // `ba::start`'s is, for the live chip's own window and rings. - unsafe { - ba::start(io, session, &mut cam, tid, ssn, window, &mut |e| { - held.keep(e) - }) - } + unsafe { ba::start(io, session, &mut cam, tid, ssn, window, held) } }); - self.held = held; self.ba = cam; done.and_then(|done| done)?; bump(&mut self.ba_counts.started); @@ -1364,13 +1351,11 @@ impl Live { } self.rx_stats.control(tid, false); let mut cam = self.ba; - let mut held = core::mem::take(&mut self.held); - let done = self.session(|io, session| { + let done = self.holding(|io, session, held| { // SAFETY: the caller's contract is `start`'s, which `ba::stop`'s // is, for the live chip's own window and rings. - unsafe { ba::stop(io, session, &mut cam, tid, &mut |e| held.keep(e)) } + unsafe { ba::stop(io, session, &mut cam, tid, held) } }); - self.held = held; self.ba = cam; done.and_then(|done| done)?; bump(&mut self.ba_counts.stopped); @@ -1418,21 +1403,19 @@ impl Live { if self.bssid.is_none() { return Ok(()); } - let mut held = core::mem::take(&mut self.held); - let sent = self.session(|io, session| { + let sent = self.holding(|io, session, held| { 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)) }; + let result = unsafe { session.send(io, packet, held) }; if first.is_ok() { first = result.map(|_| ()); } } first }); - self.held = held; sent.and_then(|sent| sent) } @@ -1564,9 +1547,10 @@ impl Live { /// each release report returning its page ([`TxPools::release`]) and /// handed on as [`Incoming::Transmitted`], acknowledged for /// `RTW89_TX_DONE`; the TX reclaim of every channel with TXBDs - /// outstanding; RXQ ([`Live::drain`]), its frames handed on but those - /// `rtw89_core_skb_pn_valid` drops ([`RxStats::valid`], counted); the - /// scan budget ([`Live::expire_scan`]); then each beacon filter report + /// outstanding; RXQ ([`Live::drain`]), its frames handed on, each past + /// `rtw89_core_skb_pn_valid` as it was drained ([`RxStats::valid`], a + /// drop counted); the scan budget ([`Live::expire_scan`]); then each + /// beacon filter report /// the drains brought, held ones first, as `rtw89_mac_bcn_fltr_rpt` /// takes it ([`Live::beacon_filter`]); then, once, /// [`Incoming::ScanEnded`] when the scan begun has ended, after every @@ -1590,15 +1574,9 @@ impl Live { let reclaimed = unsafe { self.rings.txq(&mut self.pools, ch).reclaim(&mut self.io) }; keep(&mut first, reclaimed); } - let associated = self.associated.is_some(); - let mut stats = core::mem::take(&mut self.rx_stats); let mut filter = Vec::new(); let mut frames = |e: Event<'_>| match e { - Event::Frame(frame) => { - if stats.valid(associated, &frame) { - sink(Incoming::Frame(heard(frame))); - } - } + Event::Frame(frame) => sink(Incoming::Frame(heard(frame))), Event::C2h(C2h::BeaconFilter(report)) => filter.push(report), Event::C2h(_) => {} }; @@ -1606,7 +1584,6 @@ impl Live { keep(&mut first, unsafe { self.drain(&mut frames) }); // SAFETY: as above, `expire_scan`'s. keep(&mut first, unsafe { self.expire_scan(&mut frames) }); - self.rx_stats = stats; for report in filter { // SAFETY: as above, `beacon_filter`'s. keep(&mut first, unsafe { self.beacon_filter(report, sink) }); @@ -1708,16 +1685,14 @@ impl Live { if !features.beacon_filter { return Ok(()); } - let mut held = core::mem::take(&mut self.held); - let sent = self.session(|io, session| { + let sent = self.holding(|io, session, held| { let packet = session .h2c .bcn_fltr(vif::MAC_ID, true, features.loss_count_v1); // SAFETY: the caller's contract is `start`'s, which `send`'s is, // for the live chip's own window and rings. - unsafe { session.send(io, packet, &mut |e| held.keep(e)) }.map(|_| ()) + unsafe { session.send(io, packet, held) }.map(|_| ()) }); - self.held = held; sent.and_then(|sent| sent) } @@ -1757,6 +1732,39 @@ impl Live { self.rx_stats.forget(); } + /// [`Live::session`] for an operation's `f`, with a sink that holds what + /// it drains for the next [`Live::drain`] ([`Held`]), each frame past + /// the PN check first ([`Live::passing`]). + fn holding( + &mut self, + f: impl FnOnce(&mut I, &mut Session<'_>, &mut dyn FnMut(Event<'_>)) -> R, + ) -> Result { + let mut held = core::mem::take(&mut self.held); + let result = self.passing(&mut |e| held.keep(e), f); + self.held = held; + result + } + + /// [`Live::session`] for a drain's `f`, with `sink` behind the PN check + /// ([`checked`]). + fn passing( + &mut self, + sink: &mut dyn FnMut(Event<'_>), + f: impl FnOnce(&mut I, &mut Session<'_>, &mut dyn FnMut(Event<'_>)) -> R, + ) -> Result { + let mut stats = core::mem::take(&mut self.rx_stats); + let associated = self.associated.is_some(); + let result = self.session(|io, session| { + f(io, session, &mut |e| { + if checked(&mut stats, associated, &e) { + sink(e); + } + }) + }); + self.rx_stats = stats; + result + } + /// Run `f` on the command session, resumed from where the last one was /// parked, then park it again. Refused with [`POWERED_OFF`] on a chip a /// failure powered off. diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/live/tests/ba.rs b/crates/stela-driver-net/src/wifi/realtek/ax/live/tests/ba.rs index 3293657b65..50ccb1d9a3 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/live/tests/ba.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/live/tests/ba.rs @@ -335,6 +335,53 @@ fn a_pairwise_key_starts_the_checks_over() { assert!(live.pn_valid(&received(7, 8))); } +#[test] +fn a_frame_the_poll_drains_is_checked_as_it_arrives() { + // RXQ's own drain (rtw89_pci_poll_rxq_dma to rtw89_core_rx): the three + // frames right after the agreement's BA CAM H2C reach the next polls. + let (mut live, _m) = live_hearing(&|fw| { + fw.after( + 0xC, + 0, + vec![decrypted(10, 5), decrypted(9, 6), decrypted(11, 7)], + ) + }); + // The core start's dynamic BA CAM H2Cs brought theirs while nothing was + // associated, which the check passes. + heard_sns(&mut live); + heard_sns(&mut live); + // SAFETY: as in `start_on`. + unsafe { live.set_bssid(AP) }.unwrap(); + let a = association(&live); + // SAFETY: as above. + unsafe { live.associate(&a) }.unwrap(); + // SAFETY: as above. + unsafe { live.add_key(&ptk()) }.unwrap(); + // SAFETY: as above. + unsafe { live.start_rx_block_ack(0, 10, 64) }.unwrap(); + assert_eq!(heard_sns(&mut live), [10, 11]); + let d = StationChip::diagnostic(&live); + assert!(d.contains(", pn dropped 1"), "{d}"); +} + +#[test] +fn a_frame_an_install_drains_is_checked_before_the_install_starts_over() { + // rtw89_core_rx runs the PN check as a frame arrives (core.c:4551): one + // that add_key's waits drain is checked before rtw89_ops_set_key's reset + // after the install (mac80211.c:1007-1008), which then forgets it, and + // it is not checked again when the next poll hands it on. + let (mut live, _m) = associated(&|fw| fw.after(0xA, 1, vec![decrypted(20, 5)])); + // SAFETY: as in `start_on`. + unsafe { live.start_rx_block_ack(0, 10, 64) }.unwrap(); + // SAFETY: as above. + unsafe { live.add_key(&ptk()) }.unwrap(); + assert_eq!(heard_sns(&mut live), [20]); + // TID 0 started over after SN 20: an earlier SN under a later PN is the + // first the check sees. + assert!(live.pn_valid(&received(15, 6))); + assert!(!StationChip::diagnostic(&live).contains("pn dropped")); +} + #[test] fn a_powered_off_chip_holds_no_agreement() { let (mut live, _m) = associated(&|_| {}); 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 b5491913dd..83f83062e2 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/station.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/station.rs @@ -45,7 +45,9 @@ //! port opens on both, and under PMF on the IGTK too, which stays on the //! host (`BipKey`, spec S1.2); a rekey while it is open authorizes it //! again on the keys then held, as mac80211's station stays authorized -//! across one. rtw89 puts the IGTK in the CAM as BIP_CCMP128 +//! across one, but a replacement closes it from the old key's delete +//! until the new key is installed, so one the chip refuses leaves it +//! closed. rtw89 puts the IGTK in the CAM as BIP_CCMP128 //! (`cam.c:516-517`), but reads neither BIP bit of the RX descriptor //! (`AX_RXD_BIP_KEYID`, `AX_RXD_BIP_ENC`, `txrx.h:427-428`), and mac80211 //! checks a group robust frame's MIC itself unless the hardware marked it @@ -62,8 +64,11 @@ //! - 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 retried unicast frame +//! split as rtw88 takes them; protected data the station cannot open is +//! dropped where mac80211 decrypts, past the reorder buffer, so it still +//! takes its place in its agreement's window. Protected management +//! frames are opened on the host when the hardware left them sealed. A +//! retried unicast frame //! of the AP's station repeating the last sequence control its counter //! saw is a duplicate, dropped (`ieee80211_rx_h_check_dup`). Frames heard //! after an accepted association response wait until the keeper @@ -109,8 +114,15 @@ //! link, the probe of the AP mac80211 sends on a beacon loss before it //! gives the AP up (`ieee80211_mgd_probe_ap`), 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. Of RX Block Ack it -//! does not grant: an agreement's inactivity timeout +//! following the AP's beacons and channel switches. Under PMF an +//! unprotected deauthentication or disassociation is dropped +//! (`ieee80211_drop_unencrypted_mgmt`), and the SA Query wpa_supplicant +//! then starts for one of reason 6 or 7, to learn whether the AP still +//! knows the station (`sme_event_unprot_disconnect`), is the shared +//! keeper's to send, which sends none for any radio: a station whose AP +//! lost its state keeps a link that carries nothing until the keeper +//! leaves it. Of RX Block Ack it does not grant: an agreement's inactivity +//! timeout //! (`sta_rx_agg_session_timer_expired`); the DELBA mac80211 sends for an //! aggregate on a TID without an agreement (`unexpected_agg`); ending an //! agreement for a fragment under it (fragments are reassembled, never @@ -516,6 +528,9 @@ pub struct Rtl8852c { ap: Option, last_sequence: [u16; SEQUENCES], port_open: bool, + /// The keeper authorized the port in this association; a replaced + /// key's delete closes it until a key is installed again. + authorized: bool, departing: Option, left: bool, reported: Vec<&'static str>, @@ -559,6 +574,7 @@ impl Rtl8852c { ap: None, last_sequence: FRESH_SEQUENCES, port_open: false, + authorized: false, departing: None, left: false, reported: Vec::new(), @@ -679,6 +695,7 @@ impl Rtl8852c { self.keep_earlier(report); } self.port_open = false; + self.authorized = false; self.outbox.clear(); self.held.clear(); self.keys.clear(); @@ -1055,12 +1072,18 @@ impl Rtl8852c { /// scan's beacons and probe responses to the scanner; then a duplicate /// dropped ([`Self::duplicate`]); a Block Ack Request to the agreement it /// names; 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; other data goes through its - /// agreement's reorder buffer ([`Self::order`]). + /// a body to the station. A protected frame failing its ICV is dropped + /// at once, as rtw89 marks it `RX_FLAG_FAILED_FCS_CRC` + /// (`core.c:4396-4397`) and mac80211 drops it before any handler; one + /// the hardware decrypted goes under the key its key ID names + /// (pairwise for unicast, a group key for a group address). One left + /// encrypted (mac80211 would decrypt it in software; no Stela station + /// does), or under a key ID without a key, goes on keyless and is + /// dropped as it is delivered ([`Self::deliver`]): mac80211 decrypts in + /// `ieee80211_rx_h_decrypt`, after `ieee80211_rx_reorder_ampdu`, so such + /// a frame still takes its place in its agreement's window. Fragments + /// are reassembled, a keyless protected one dropped at once; other data + /// goes through its agreement's reorder buffer ([`Self::order`]). fn frame(&mut self, mut frame: Mpdu, now: u64) -> Result<(), Error> { let header = *frame.header(); if let Some(ticket) = self.scanning @@ -1085,22 +1108,23 @@ impl Rtl8852c { return Ok(()); } if header.protected() { + if frame.security.icv_error { + return Ok(()); + } let multicast = header.receiver.is_multicast(); let index = frame.bytes().get(header.length + 3).map(|byte| byte >> 6); - let Some(key) = self + let decrypted = frame.security.decrypted; + frame.security.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); + .filter(|_| decrypted); } if header.fragmented() { + if header.protected() && frame.security.key.is_none() { + return Ok(()); + } self.reassemble(&frame, now); return Ok(()); } @@ -1323,16 +1347,24 @@ impl Rtl8852c { /// 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. + /// checks refuse. EAPOL goes to the keeper. A protected frame without + /// the key that opened it ([`Self::frame`]) is dropped first, as + /// `ieee80211_rx_h_decrypt` drops it once the reorder buffer released + /// it. fn deliver(&mut self, frame: Mpdu) { + if frame.header().protected() && frame.security.key.is_none() { + return; + } 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. + // SAFETY: an A-MSDU is one whole MPDU, one RX queue record, and + // comes here once its agreement's reorder buffer, if any, + // released it in order (`Self::order`); `clear` closes every + // agreement and drops what an older association left, so none + // reaches a newer one. let group = unsafe { OrderedGroup::new(context, alloc::vec![frame], Shape::WholeMpdu, ()) }; let slot = self @@ -2009,7 +2041,10 @@ impl Rtl8852c { /// 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. + /// keys then held. A replacement closes it from the old key's delete + /// on, so it opens again only on the new key installed: where the chip + /// refuses that, mac80211 would go on under a software key, which no + /// Stela station has, and nothing of that kind and index is left. fn install( &mut self, pairwise: bool, @@ -2036,6 +2071,7 @@ impl Rtl8852c { return Ok(identity); } let old = self.keys.remove(at); + self.port_open = false; // 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 @@ -2083,7 +2119,7 @@ impl Rtl8852c { // 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 { + if self.authorized { let epoch = self .station .association_epoch() @@ -2143,6 +2179,7 @@ impl Rtl8852c { } .map_err(Error::Station)?; self.port_open = true; + self.authorized = true; Ok(()) } } 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 016975230f..232ad1d5f2 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 @@ -1594,6 +1594,10 @@ fn under_pmf_an_unprotected_departure_is_ignored() { } assert_eq!(model.0.borrow().count(|c| *c == Call::Disassociate), 0); assert!(wifi.carrier()); + // No SA Query request follows: starting one is wpa_supplicant's + // (`sme_event_unprot_disconnect`), which the shared keeper does not + // port (the module documentation's gap). + assert!(model.0.borrow().management(0xd0).is_empty()); } /// The AP's deauthentication to every station, reason 7, under BIP with @@ -1840,6 +1844,47 @@ fn a_group_rekey_replaces_the_key_of_its_index() { assert!(progress(&mut wifi).contains("keys 4")); } +#[test] +fn a_rekey_the_firmware_refuses_closes_the_port_until_its_key_is_installed() { + // ieee80211_key_replace deletes the old key first: when the chip then + // refuses the new one, no key of that index is left, so the port + // closes, and opens again only on an installed key. + let (mut wifi, model) = connected(); + model.0.borrow_mut().refuse_keys = true; + let got = wifi + .radio_mut() + .install_key(false, 1, &[0x66; 16], ReplaySeed::ZERO); + assert!(matches!(got, Err(Error::Chip(_))), "{got:?}"); + assert!(!wifi.radio_mut().carrier()); + assert_eq!(wifi.radio_mut().transmit(&ip(1)), Err(LinkError::NoCarrier)); + model.0.borrow_mut().refuse_keys = false; + wifi.radio_mut() + .install_key(false, 1, &[0x66; 16], ReplaySeed::ZERO) + .unwrap(); + assert!(wifi.radio_mut().carrier()); + // A key of a new index deletes nothing: refused, the port stays open. + model.0.borrow_mut().refuse_keys = true; + let got = wifi + .radio_mut() + .install_key(false, 2, &[0x67; 16], ReplaySeed::ZERO); + assert!(got.is_err(), "{got:?}"); + assert!(wifi.radio_mut().carrier()); + // A pairwise rekey alike: the old PTK gone, nothing leaves under it. + let got = wifi + .radio_mut() + .install_key(true, 0, &[0x99; 16], ReplaySeed::ZERO); + assert!(got.is_err(), "{got:?}"); + assert!(!wifi.radio_mut().carrier()); + model.0.borrow_mut().refuse_keys = false; + wifi.radio_mut() + .install_key(true, 0, &[0x99; 16], ReplaySeed::ZERO) + .unwrap(); + assert!(wifi.radio_mut().carrier()); + let before = model.0.borrow().data().len(); + wifi.radio_mut().transmit(&ip(2)).unwrap(); + assert_eq!(model.0.borrow().data()[before].1, Some((0, 0, 1))); +} + /// 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 { @@ -2310,6 +2355,43 @@ fn only_the_aps_acknowledged_qos_data_is_reordered() { assert_eq!(delivered(&mut wifi), [0x52]); } +#[test] +fn a_frame_the_station_cannot_open_still_takes_its_place_in_the_window() { + // mac80211 reorders before it decrypts (ieee80211_rx_reorder_ampdu, + // then ieee80211_rx_h_decrypt): an agreement's frame the hardware left + // encrypted, or one under a key ID with no key, fills its slot and is + // dropped as it leaves the buffer, so what follows waits for no hole. + let (mut wifi, model) = aggregating(); + let mut air = model.0.borrow_mut(); + air.hear_as(qos(0, 100, 10, 0x50), false, false); + let mut keyless = qos(0, 101, 11, 0x51); + keyless[29] = 0x20 | 2 << 6; + air.hear_as(keyless, true, false); + air.hear_as(qos(0, 102, 12, 0x52), true, false); + drop(air); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x52]); + // The window moved past them: 104 waits for 103 alone. + let mut air = model.0.borrow_mut(); + air.hear_as(qos(0, 104, 14, 0x54), true, false); + air.hear_as(qos(0, 103, 13, 0x53), true, false); + drop(air); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x53, 0x54]); + // A frame failing its ICV is no frame to mac80211 (rtw89's + // RX_FLAG_FAILED_FCS_CRC, core.c:4396-4397): it leaves a hole, which + // what follows waits behind until the BAR. + let mut air = model.0.borrow_mut(); + air.hear_as(qos(0, 105, 15, 0x55), true, true); + air.hear_as(qos(0, 106, 16, 0x56), true, false); + drop(air); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), []); + model.0.borrow_mut().hear(bar(0, 106)); + wifi.carrier(); + assert_eq!(delivered(&mut wifi), [0x56]); +} + /// The (transaction, status) of each SAE frame the station sent. fn sae_sent(air: &Air) -> Vec<(u16, u16)> { air.management(0xb0)