forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

scanner.rs1945 lines, 76.5 KiBHistoryRawDownload
1//! Passive channel-hopping scanner: discovers APs (beacon/probe-response)
2//! and client stations (probe-request + data frames), live-updating the UI
3//! via [`Event`]s until `stop` flips true. Pure discovery — handshake
4//! correlation happens in [`crate::handshake`].
5
6use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, Instant};
10// `Instant` is still used for dwell timing; timestamps going into shared
11// types are `u64` millis (`crate::common::now_ms`) so they serialize.
12
13use anyhow::{Context, Result};
14use crossbeam_channel::Sender;
15
16use crate::common::{
17 AccessPoint, ChannelStat, ClientInfo, Event, HOP_FREQS_ALL, IdentConfidence, MacAddr,
18 ProbeInfo, now_ms,
19};
20use crate::pcapout::PcapWriter;
21use crate::radiotap::RxMeta;
22use crate::rawsock::RawSocket;
23use crate::{dot11, iface, radiotap};
24
25/// APs go stale (ApLost) after this much silence (ms — `last_seen_ms`).
26const AP_EXPIRE_MS: u64 = 30_000;
27/// Clients go stale after this much silence (ms).
28const CLIENT_EXPIRE_MS: u64 = 60_000;
29/// Probe requests from the same (client, ssid) pair are re-emitted at
30/// most this often — keeps the probe panel from drowning in retries.
31const PROBE_DEDUP_MS: u64 = 60_000;
32/// Sliding window for the foreign-deauth storm detector (ms).
33const DEAUTH_WINDOW_MS: u64 = 10_000;
34/// Deauths inside the window triggering a [`Event::DeauthAlert`].
35const DEAUTH_ALERT_THRESHOLD: u32 = 10;
36/// Per-pair cooldown after an alert fired (ms).
37const DEAUTH_ALERT_COOLDOWN_MS: u64 = 30_000;
38/// Max retained timestamps per (src, dst) pair (hard memory cap; the
39/// window prune keeps it small in practice).
40const DEAUTH_HIST_CAP: usize = 32;
41
42/// Consecutive non-timeout recv failures after which the scanner gives up:
43/// a persistent error (ENODEV — card yanked, EIO — firmware wedged) would
44/// otherwise spin the dwell loop re-emitting the identical event forever.
45const RECV_ERROR_ABORT_THRESHOLD: u32 = 3;
46
47/// EMA weight of each new RSSI sample (~5-sample effective window): a
48/// station walking away visibly decays within a second or two of normal
49/// beacon traffic, while single-frame fades don't reorder the UI.
50const RSSI_EMA_ALPHA: f32 = 0.4;
51
52/// Exponential moving average of RSSI samples; the stored/emitted value is
53/// the rounded i8 so the on-wire event types stay unchanged. Replaces the
54/// earlier peak-hold rule (only-updates-on-improvement) that left stale
55/// inflated signal on stations that moved away.
56fn ema_next(prev: f32, sample: i8) -> f32 {
57 RSSI_EMA_ALPHA * sample as f32 + (1.0 - RSSI_EMA_ALPHA) * prev
58}
59
60fn ema_report(ema: f32) -> i8 {
61 ema.round().clamp(i8::MIN as f32, i8::MAX as f32) as i8
62}
63
64// ---------------------------------------------------------------------------
65// device identity groups (MAC-randomization pairing)
66// ---------------------------------------------------------------------------
67
68/// Pairing state for a single station MAC inside a group.
69struct MacSeen {
70 last_seen_ms: u64,
71 last_seq: Option<u16>,
72 /// Confidence assigned when THIS MAC joined (or first created) the
73 /// group — assignment-time semantics; later frames only refresh times.
74 conf: IdentConfidence,
75}
76
77/// One correlated physical radio: the set of MACs we have witnessed on it,
78/// plus correlation keys (ordered-IE fingerprints it sent, SSIDs it probed
79/// for, its WPS UUID).
80struct IdGroup {
81 id: u64,
82 macs: HashMap<MacAddr, MacSeen>,
83 fps: HashSet<u32>,
84 /// SSIDs any member probed for (capped — a paranoia bound, not a rule).
85 ssids: HashSet<String>,
86 uuid: Option<[u8; 16]>,
87}
88
89/// Correlation book: pairs rotated/randomized MACs that belong to one
90/// physical radio. Witnesses, strongest first: WPS UUID-E (the device
91/// names itself), then shared ordered-IE fingerprint upgraded by a
92/// per-frame witness — a shared probed SSID or uninterrupted 12-bit
93/// sequence numbers across the rotation (seq continuity almost never
94/// happens by chance: 1/4096 per direct successor pair).
95struct GroupBook {
96 groups: Vec<IdGroup>,
97 mac_to_group: HashMap<MacAddr, usize>,
98 fp_to_groups: HashMap<u32, Vec<usize>>,
99 next_id: u64,
100}
101
102/// Group bookkeeping retention: group members and keys outlive the client
103/// row by this long so a rotated MAC that appears *after* the old row
104/// expired still lands in the same group. 15 min covers the typical
105/// rotation cadence (iOS ~24 h per-network, Android on-screen ~10 min during
106/// scanning bursts).
107const GROUP_TTL_MS: u64 = 15 * 60 * 1000;
108
109impl GroupBook {
110 fn new() -> Self {
111 Self {
112 groups: Vec::new(),
113 mac_to_group: HashMap::new(),
114 fp_to_groups: HashMap::new(),
115 next_id: 1,
116 }
117 }
118
119 /// `(group id, assignment confidence)` for an already-assigned MAC.
120 fn id_of(&self, mac: &MacAddr) -> Option<(u64, IdentConfidence)> {
121 let &gi = self.mac_to_group.get(mac)?;
122 let m = self.groups[gi].macs.get(mac)?;
123 Some((self.groups[gi].id, m.conf))
124 }
125
126 /// Record one frame's worth of correlation material for `sta`.
127 /// Returns `Some((group, confidence))` only when the MAC's group
128 /// assignment was newly decided (first assignment or re-assignment
129 /// after expiry) — callers emit [`Event::ClientIdent`] on Some.
130 fn note(
131 &mut self,
132 sta: MacAddr,
133 fp: u32,
134 uuid: Option<[u8; 16]>,
135 ssid: Option<&str>,
136 seq: Option<u16>,
137 now: u64,
138 ) -> Option<(u64, IdentConfidence)> {
139 if let Some(&gi) = self.mac_to_group.get(&sta) {
140 let g = &mut self.groups[gi];
141 if let Some(m) = g.macs.get_mut(&sta) {
142 m.last_seen_ms = now;
143 m.last_seq = seq.or(m.last_seq);
144 }
145 g.fps.insert(fp);
146 if let Some(s) = ssid
147 && !s.is_empty()
148 && g.ssids.len() < 64
149 {
150 g.ssids.insert(s.to_string());
151 }
152 return None;
153 }
154
155 // UUID-E is a certain witness on its own: match it even when the
156 // radio's IE chain changed so much the fingerprint misses (new
157 // driver/firmware between rotations).
158 let mut best: Option<(usize, IdentConfidence)> = uuid.and_then(|u| {
159 self.groups
160 .iter()
161 .position(|g| g.uuid == Some(u) && !g.macs.contains_key(&sta))
162 .map(|gi| (gi, IdentConfidence::Exact))
163 });
164
165 if best.is_none() {
166 let mut hits: Vec<usize> = self.fp_to_groups.get(&fp).cloned().unwrap_or_default();
167 hits.retain(|&gi| gi < self.groups.len());
168 hits.sort_unstable();
169 hits.dedup();
170 for gi in hits {
171 let g = &self.groups[gi];
172 let fresh = g.macs.values().max_by_key(|m| m.last_seen_ms);
173 let ssid_match = ssid.is_some_and(|s| !s.is_empty() && g.ssids.contains(s));
174 let seq_continues =
175 seq.zip(fresh.and_then(|m| m.last_seq))
176 .is_some_and(|(a, b)| {
177 let d = a.wrapping_sub(b);
178 (1..=32).contains(&d)
179 });
180 let conf = if ssid_match || seq_continues {
181 IdentConfidence::Strong
182 } else {
183 IdentConfidence::Probable
184 };
185 if best.is_none_or(|(_, c)| conf > c) {
186 best = Some((gi, conf));
187 }
188 }
189 }
190
191 let (gi, conf) = match best {
192 Some(x) => x,
193 None => {
194 self.groups.push(IdGroup {
195 id: self.next_id,
196 macs: HashMap::new(),
197 fps: HashSet::new(),
198 ssids: HashSet::new(),
199 uuid: None,
200 });
201 self.next_id += 1;
202 (self.groups.len() - 1, IdentConfidence::Probable)
203 }
204 };
205
206 let g = &mut self.groups[gi];
207 g.macs.insert(
208 sta,
209 MacSeen {
210 last_seen_ms: now,
211 last_seq: seq,
212 conf,
213 },
214 );
215 g.fps.insert(fp);
216 if uuid.is_some() {
217 g.uuid = uuid;
218 }
219 if let Some(s) = ssid
220 && !s.is_empty()
221 && g.ssids.len() < 64
222 {
223 g.ssids.insert(s.to_string());
224 }
225 self.mac_to_group.insert(sta, gi);
226 self.fp_to_groups.entry(fp).or_default().push(gi);
227 Some((self.groups[gi].id, conf))
228 }
229
230 /// Reap members — and whole empty groups — past the pairing TTL.
231 fn expire(&mut self, now: u64) {
232 for g in self.groups.iter_mut() {
233 g.macs.retain(|m, seen| {
234 let live = now.saturating_sub(seen.last_seen_ms) <= GROUP_TTL_MS;
235 if !live {
236 self.mac_to_group.remove(m);
237 }
238 live
239 });
240 }
241 // Keep memory bounded against one-off probe storms: a group whose
242 // members all reaped gives up its keys too.
243 self.groups.retain(|g| !g.macs.is_empty());
244 // Rebuild the secondary indexes so integer group positions stay
245 // valid after retain-compaction.
246 self.mac_to_group.clear();
247 self.fp_to_groups.clear();
248 for (gi, g) in self.groups.iter().enumerate() {
249 for m in g.macs.keys() {
250 self.mac_to_group.insert(*m, gi);
251 }
252 for fp in &g.fps {
253 self.fp_to_groups.entry(*fp).or_default().push(gi);
254 }
255 }
256 }
257}
258
259/// Push `now` onto `counts`, prune stamps older than the 10 s window, and
260/// report `Some(n)` when the window holds ≥ [`DEAUTH_ALERT_THRESHOLD`]
261/// stamps. Pure — unit-tested directly.
262pub(crate) fn deauth_alert(counts: &mut VecDeque<u64>, now: u64) -> Option<u32> {
263 counts.push_back(now);
264 while counts.len() > DEAUTH_HIST_CAP {
265 counts.pop_front();
266 }
267 while let Some(&t) = counts.front() {
268 if now.saturating_sub(t) > DEAUTH_WINDOW_MS {
269 counts.pop_front();
270 } else {
271 break;
272 }
273 }
274 (counts.len() >= DEAUTH_ALERT_THRESHOLD as usize).then_some(counts.len() as u32)
275}
276
277pub struct ScannerConfig {
278 pub ifname: String,
279 /// Carrier frequencies (MHz) to hop; empty = [`HOP_FREQS_ALL`]
280 /// (2.4 GHz, full TR-legal 5 GHz span, 6 GHz PSC).
281 pub freqs: Vec<u16>,
282 /// Dwell per channel.
283 pub dwell_ms: u32,
284 /// RSSI below this blocks creation of new AP/client entries (updates to
285 /// already-known entries are always accepted).
286 pub rssi_floor: i8,
287 /// Channel arbitration with attack workers ([`iface::ChannelPin`]):
288 /// nonzero → dwell on the pinned frequency instead of hopping.
289 pub pin: Arc<iface::ChannelPin>,
290 /// Own MAC of the monitor interface — deauth frames sourced from it
291 /// are ours and must not trip the foreign-deauth detector.
292 pub own_mac: MacAddr,
293 /// BSSIDs we are deauthenticating on behalf of the user right now
294 /// (our blasts use the AP as transmitter) — suppressed like `own_mac`.
295 pub deauth_suppress: Arc<Mutex<HashSet<MacAddr>>>,
296 /// Shared pcap spool writer (raw frames WITH radiotap header are
297 /// appended in the recv loop). `None` = no spooling.
298 pub spool: Option<Arc<Mutex<PcapWriter>>>,
299}
300
301/// Channel-frequency → channel number for the bands we hop.
302fn freq_to_channel(freq_mhz: u16) -> Option<u8> {
303 match freq_mhz {
304 // 2.4 GHz: ch 1..14, 2407 + 5*ch (ch14 = 2484).
305 2412..=2472 => Some(((freq_mhz - 2407) / 5) as u8),
306 2484 => Some(14),
307 // 5 GHz: ch = (freq - 5000) / 5.
308 5000..=5900 => Some(((freq_mhz - 5000) / 5) as u8),
309 // 6 GHz (802.11ax): 20 MHz channel center = 5950 + 5·ch for
310 // ch 1..=233 (so 5955 → ch 1). The band-edge outlier 5935 MHz is
311 // ch 2 of the same numbering (iw / IEEE precedent); 5940/5945 are
312 // wide-channel center artifacts, not 20 MHz channels — unmapped.
313 // NB: 5945..5950 must never reach the subtraction arm (u16
314 // underflow → debug panic).
315 5935 => Some(2),
316 5955..=7115 => Some(((freq_mhz - 5950) / 5) as u8),
317 _ => None,
318 }
319}
320
321/// One full parse of a stripped 802.11 frame, shared between the run-loop
322/// stats block and [`Scanner::ingest_classified`] so each frame on the RX
323/// hot path is parsed exactly once. Parser precedence mirrors the
324/// historical ingest order.
325enum FrameClass {
326 /// Beacon or probe-response (AP-producing).
327 Beacon(dot11::MgmtInfo),
328 /// Well-formed probe request carrying client identity material.
329 ProbeIdent(dot11::ProbeIdent),
330 /// Association / reassociation request.
331 Association(dot11::AssocIdent),
332 /// Deauthentication or disassociation.
333 Deauth { from: MacAddr, target: MacAddr },
334 /// Data frame with resolvable (bssid, station) endpoints.
335 Data { bssid: MacAddr, sta: MacAddr },
336 /// Stats-only bucket: probe-request FC (caught by the cheap
337 /// [`dot11::parse_probe_req`]) but the deeper identity walk
338 /// ([`dot11::parse_probe_ident`]) failed on malformed IEs — counts as
339 /// a parsed mgmt frame, carries nothing to ingest.
340 ProbeReqMalformed,
341 /// Anything else (control frames, unknown types, garbage).
342 Other,
343}
344
345impl FrameClass {
346 /// Whether the historical stats block counted this frame as a parsed
347 /// 802.11 management frame (beacon/probe family or deauth/disassoc).
348 fn counts_as_mgmt(&self) -> bool {
349 matches!(
350 self,
351 FrameClass::Beacon(_)
352 | FrameClass::ProbeIdent(_)
353 | FrameClass::ProbeReqMalformed
354 | FrameClass::Deauth { .. }
355 )
356 }
357}
358
359/// Classify + parse a stripped 802.11 frame in one pass. Fallback order
360/// matches ingest semantics exactly: a frame that succeeds an earlier
361/// parser is never offered to a later one.
362fn classify(frame: &[u8]) -> FrameClass {
363 if let Some(m) = dot11::parse_beacon_or_probe(frame) {
364 return FrameClass::Beacon(m);
365 }
366 if let Some(ident) = dot11::parse_probe_ident(frame) {
367 return FrameClass::ProbeIdent(ident);
368 }
369 if let Some(ident) = dot11::parse_assoc_ident(frame) {
370 return FrameClass::Association(ident);
371 }
372 if let Some((from, target)) = dot11::parse_deauth(frame) {
373 return FrameClass::Deauth { from, target };
374 }
375 if let Some((bssid, sta)) = dot11::data_endpoints(frame) {
376 return FrameClass::Data { bssid, sta };
377 }
378 // The stats heartbeat also counted probe requests whose deeper
379 // identity parse failed — cheap FC-level re-check, only reached by
380 // frames every real parser already rejected.
381 if dot11::parse_probe_req(frame).is_some() {
382 return FrameClass::ProbeReqMalformed;
383 }
384 FrameClass::Other
385}
386
387/// One frame's MAC-randomization correlation material (bundle for
388/// [`Scanner::note_ident`]): IE fingerprint, WPS UUID-E, SSID,
389/// sequence number and observation clock.
390struct IdentObs<'a> {
391 fp: u32,
392 uuid: Option<[u8; 16]>,
393 ssid: Option<&'a str>,
394 seq: Option<u16>,
395 now: u64,
396}
397
398/// Stateful discovery engine — owned by `run`, unit-tested via `ingest`.
399struct Scanner {
400 aps: BTreeMap<MacAddr, AccessPoint>,
401 clients: BTreeMap<MacAddr, ClientInfo>,
402 /// RSSI EMA state per AP/client — the emitted `rssi_dbm` is the rounded
403 /// average, so peak-hold can't freeze a stale strong signal on screen.
404 ap_rssi_ema: HashMap<MacAddr, f32>,
405 client_rssi_ema: HashMap<MacAddr, f32>,
406 rssi_floor: i8,
407 /// Own monitor-interface MAC + user-triggered deauth BSSIDs: frames
408 /// sourced from these are suppressed in the storm detector.
409 own_mac: MacAddr,
410 deauth_suppress: Arc<Mutex<HashSet<MacAddr>>>,
411 /// (client, probed-ssid) → last emit; 60 s suppression of repeats.
412 probe_dedup: HashMap<(MacAddr, Option<String>), u64>,
413 /// (deauth src, dst) → ms stamps inside the sliding window.
414 deauth_hist: HashMap<(MacAddr, MacAddr), VecDeque<u64>>,
415 /// (src, dst) → cooldown-until ms after a fired alert.
416 alert_cooldown: HashMap<(MacAddr, MacAddr), u64>,
417 /// MAC-randomization pairing: correlated device groups built from
418 /// probe/assoc frames.
419 groups: GroupBook,
420}
421
422impl Scanner {
423 fn new(
424 rssi_floor: i8,
425 own_mac: MacAddr,
426 deauth_suppress: Arc<Mutex<HashSet<MacAddr>>>,
427 ) -> Self {
428 Self {
429 aps: BTreeMap::new(),
430 clients: BTreeMap::new(),
431 ap_rssi_ema: HashMap::new(),
432 client_rssi_ema: HashMap::new(),
433 rssi_floor,
434 own_mac,
435 deauth_suppress,
436 probe_dedup: HashMap::new(),
437 deauth_hist: HashMap::new(),
438 alert_cooldown: HashMap::new(),
439 groups: GroupBook::new(),
440 }
441 }
442
443 /// Feed one received frame. Radiotap metadata in `meta`, 802.11 bytes in
444 /// `frame` (already stripped), clock in `now` ms since the process-local
445 /// epoch ([`common::now_ms`], test-injectable). Test-only convenience:
446 /// the run loop uses [`Scanner::ingest_classified`] with its own
447 /// single-parse [`classify`] outcome.
448 #[cfg(test)]
449 fn ingest(&mut self, meta: &RxMeta, frame: &[u8], now: u64, tx: &Sender<Event>) {
450 self.ingest_classified(meta, frame, classify(frame), now, tx);
451 }
452
453 /// Ingest with the parse already done by [`classify`] — the run loop
454 /// parses each frame once and hands the same outcome to its stats
455 /// block and to this path (no double walks on the RX hot path).
456 /// `frame` is still needed for the sequence-number pairing witness
457 /// ([`dot11::seq_of`]).
458 fn ingest_classified(
459 &mut self,
460 meta: &RxMeta,
461 frame: &[u8],
462 class: FrameClass,
463 now: u64,
464 tx: &Sender<Event>,
465 ) {
466 // AP from beacon / probe-response.
467 if let FrameClass::Beacon(m) = class {
468 // Trust the DS-parameter IE; fall back to the radiotap carrier
469 // frequency hint when the IE is absent.
470 let channel = m
471 .channel
472 .or_else(|| freq_to_channel(meta.freq_mhz))
473 .unwrap_or(0);
474 let ssid = m.ssid.unwrap_or_default();
475 match self.aps.get_mut(&m.bssid) {
476 Some(ap) => {
477 let mut changed = false;
478 if meta.rssi_dbm != 0 {
479 let ema = self
480 .ap_rssi_ema
481 .entry(m.bssid)
482 .or_insert(ap.rssi_dbm as f32);
483 *ema = ema_next(*ema, meta.rssi_dbm);
484 let r = ema_report(*ema);
485 if r != ap.rssi_dbm {
486 ap.rssi_dbm = r;
487 changed = true;
488 }
489 }
490 if !ssid.is_empty() && ap.ssid != ssid {
491 ap.ssid = ssid.clone();
492 changed = true;
493 }
494 if channel != 0 && ap.channel != channel {
495 ap.channel = channel;
496 changed = true;
497 }
498 if m.security != ap.security {
499 ap.security = m.security;
500 changed = true;
501 }
502 if m.akms != ap.akms {
503 ap.akms = m.akms.clone();
504 changed = true;
505 }
506 ap.beacons += 1;
507 ap.last_seen_ms = now;
508 if changed {
509 let _ = tx.send(Event::ApUpdated(ap.clone()));
510 }
511 }
512 None => {
513 if meta.rssi_dbm != 0 && meta.rssi_dbm < self.rssi_floor {
514 return; // weak signal: don't create the entry
515 }
516 let ap = AccessPoint {
517 bssid: m.bssid,
518 ssid,
519 channel,
520 security: m.security,
521 rssi_dbm: meta.rssi_dbm,
522 beacons: 1,
523 last_seen_ms: now,
524 akms: m.akms.clone(),
525 };
526 if meta.rssi_dbm != 0 {
527 self.ap_rssi_ema.insert(m.bssid, meta.rssi_dbm as f32);
528 }
529 self.aps.insert(m.bssid, ap.clone());
530 let _ = tx.send(Event::ApUpdated(ap));
531 }
532 }
533 return;
534 }
535
536 // Client probing.
537 if let FrameClass::ProbeIdent(ident) = class {
538 let sta = ident.sta;
539 if sta.is_multicast() || sta.is_zero() {
540 return;
541 }
542 // Probe panel: one event per (client, ssid) per 60 s — retries
543 // from reconnect-happy phones would flood the UI otherwise.
544 let key = (sta, ident.ssid.clone());
545 let fresh = match self.probe_dedup.get(&key) {
546 Some(&last) => now.saturating_sub(last) > PROBE_DEDUP_MS,
547 None => true,
548 };
549 if fresh {
550 self.probe_dedup.insert(key, now);
551 let _ = tx.send(Event::ProbeObserved(ProbeInfo {
552 client: sta,
553 ssid: ident.ssid.clone(),
554 rssi_dbm: meta.rssi_dbm,
555 at_ms: now,
556 }));
557 }
558 // Pairing first: the creation event from `note_client` then
559 // already carries the group id (no follow-up stamp needed).
560 self.note_ident(
561 sta,
562 IdentObs {
563 fp: ident.fingerprint,
564 uuid: ident.uuid,
565 ssid: ident.ssid.as_deref(),
566 seq: dot11::seq_of(frame),
567 now,
568 },
569 tx,
570 );
571 self.note_client(sta, None, meta, now, tx);
572 return;
573 }
574
575 // Association/reassociation request: the station names the SSID it
576 // joins — the only on-air witness that reveals a hidden AP's SSID.
577 if let FrameClass::Association(ident) = class {
578 let sta = ident.sta;
579 if !sta.is_multicast() && !sta.is_zero() {
580 // Pairing first: the creation event then already carries
581 // the group id.
582 self.note_ident(
583 sta,
584 IdentObs {
585 fp: ident.fingerprint,
586 uuid: ident.uuid,
587 ssid: ident.ssid.as_deref(),
588 seq: dot11::seq_of(frame),
589 now,
590 },
591 tx,
592 );
593 self.note_client(sta, Some(ident.bssid), meta, now, tx);
594 }
595 if let Some(ssid) = ident.ssid
596 && let Some(ap) = self.aps.get_mut(&ident.bssid)
597 && ap.ssid.is_empty()
598 {
599 ap.ssid = ssid;
600 ap.last_seen_ms = now;
601 let _ = tx.send(Event::ApUpdated(ap.clone()));
602 }
603 return;
604 }
605
606 // Deauth/disassoc: flag the affected station disconnected so the UI
607 // separates it now instead of waiting for 60 s of silence to expire
608 // the row. Either side can be the station: AP → client (target) or
609 // client-initiated (transmitter). Frames between unknown parties are
610 // noise — we only flip state on stations we already track.
611 if let FrameClass::Deauth { from, target } = class {
612 self.track_foreign_deauth(from, target, now, tx);
613 let sta = if !target.is_multicast() && !target.is_zero() {
614 self.clients.contains_key(&target).then_some(target)
615 } else {
616 None
617 }
618 .or_else(|| {
619 (!from.is_multicast() && !from.is_zero())
620 .then(|| self.clients.contains_key(&from).then_some(from))
621 .flatten()
622 });
623 if let Some(sta) = sta
624 && let Some(c) = self.clients.get_mut(&sta)
625 && c.connected
626 {
627 // State change only — repeated deauths against an already
628 // flagged station are silent (no event storm).
629 c.connected = false;
630 let _ = tx.send(Event::ClientUpdated(c.clone()));
631 }
632 return;
633 }
634
635 // Clients talking data: learn station side; the bssid side refreshes
636 // the AP liveness (channel/time) without bumping beacon count.
637 if let FrameClass::Data { bssid, sta } = class {
638 if !sta.is_multicast() && !sta.is_zero() {
639 self.note_client(sta, Some(bssid), meta, now, tx);
640 }
641 if let Some(ap) = self.aps.get_mut(&bssid) {
642 ap.last_seen_ms = now;
643 }
644 }
645 }
646
647 /// Foreign-deauth storm detector: ≥10 deauths/disassocs from one
648 /// (src, dst) pair inside 10 s → one [`Event::DeauthAlert`], then a 30 s
649 /// per-pair cooldown. Frames WE transmitted (monitor MAC as source, or
650 /// an AP we're user-deauthing — our blasts carry its BSSID as addr2)
651 /// never count.
652 fn track_foreign_deauth(
653 &mut self,
654 from: MacAddr,
655 target: MacAddr,
656 now: u64,
657 tx: &Sender<Event>,
658 ) {
659 if from == self.own_mac
660 || self
661 .deauth_suppress
662 .lock()
663 .map(|s| s.contains(&from))
664 .unwrap_or(false)
665 {
666 return;
667 }
668 let key = (from, target);
669 if self
670 .alert_cooldown
671 .get(&key)
672 .is_some_and(|&until| now < until)
673 {
674 return;
675 }
676 let counts = self.deauth_hist.entry(key).or_default();
677 if let Some(n) = deauth_alert(counts, now) {
678 self.alert_cooldown
679 .insert(key, now + DEAUTH_ALERT_COOLDOWN_MS);
680 let _ = tx.send(Event::DeauthAlert {
681 source: from,
682 target,
683 count: n,
684 });
685 }
686 }
687
688 /// MAC-randomization pairing: fold one frame's correlation material
689 /// into the group book; emit [`Event::ClientIdent`] exactly once per
690 /// pairing decision (first assignment or re-entry after expiry).
691 fn note_ident(&mut self, sta: MacAddr, obs: IdentObs<'_>, tx: &Sender<Event>) {
692 let Some((group, confidence)) = self
693 .groups
694 .note(sta, obs.fp, obs.uuid, obs.ssid, obs.seq, obs.now)
695 else {
696 return;
697 };
698 let _ = tx.send(Event::ClientIdent {
699 mac: sta,
700 group,
701 confidence,
702 });
703 // If the station row already exists, stamp it so the ID column
704 // reflects the pairing immediately (UI also overlays from its own
705 // ident map — belt and suspenders for event-order observers).
706 if let Some(c) = self.clients.get_mut(&sta) {
707 c.ident_group = Some(group);
708 c.ident_conf = Some(confidence);
709 let _ = tx.send(Event::ClientUpdated(c.clone()));
710 }
711 }
712
713 fn note_client(
714 &mut self,
715 sta: MacAddr,
716 ap: Option<MacAddr>,
717 meta: &RxMeta,
718 now: u64,
719 tx: &Sender<Event>,
720 ) {
721 match self.clients.get_mut(&sta) {
722 Some(c) => {
723 let mut changed = false;
724 if meta.rssi_dbm != 0 {
725 let ema = self.client_rssi_ema.entry(sta).or_insert(c.rssi_dbm as f32);
726 *ema = ema_next(*ema, meta.rssi_dbm);
727 let r = ema_report(*ema);
728 if r != c.rssi_dbm {
729 c.rssi_dbm = r;
730 changed = true;
731 }
732 }
733 if let Some(b) = ap
734 && c.ap != Some(b)
735 {
736 c.ap = Some(b);
737 changed = true;
738 }
739 // Any frame from the station proves liveness: clear the
740 // deauth-flagged disconnect (the flip rides the normal
741 // `changed` emit below — no separate storm).
742 if !c.connected {
743 c.connected = true;
744 changed = true;
745 }
746 c.frames += 1;
747 c.last_seen_ms = now;
748 if changed {
749 let _ = tx.send(Event::ClientUpdated(c.clone()));
750 }
751 }
752 None => {
753 if meta.rssi_dbm != 0 && meta.rssi_dbm < self.rssi_floor {
754 return;
755 }
756 let ident = self.groups.id_of(&sta);
757 let c = ClientInfo {
758 mac: sta,
759 ap,
760 rssi_dbm: meta.rssi_dbm,
761 frames: 1,
762 last_seen_ms: now,
763 connected: true,
764 ident_group: ident.map(|(g, _)| g),
765 ident_conf: ident.map(|(_, c)| c),
766 };
767 if meta.rssi_dbm != 0 {
768 self.client_rssi_ema.insert(sta, meta.rssi_dbm as f32);
769 }
770 self.clients.insert(sta, c.clone());
771 let _ = tx.send(Event::ClientUpdated(c));
772 }
773 }
774 }
775
776 /// Expire silent entries, emitting ApLost / ClientLost so the UI drops
777 /// the rows too (stale clients must not accumulate on screen).
778 fn expire(&mut self, now: u64, tx: &Sender<Event>) {
779 let gone: Vec<MacAddr> = self
780 .aps
781 .iter()
782 .filter(|(_, ap)| now.saturating_sub(ap.last_seen_ms) > AP_EXPIRE_MS)
783 .map(|(b, _)| *b)
784 .collect();
785 for b in gone {
786 self.aps.remove(&b);
787 self.ap_rssi_ema.remove(&b);
788 let _ = tx.send(Event::ApLost(b));
789 }
790 let gone: Vec<MacAddr> = self
791 .clients
792 .iter()
793 .filter(|(_, c)| now.saturating_sub(c.last_seen_ms) > CLIENT_EXPIRE_MS)
794 .map(|(m, _)| *m)
795 .collect();
796 for m in gone {
797 self.clients.remove(&m);
798 self.client_rssi_ema.remove(&m);
799 let _ = tx.send(Event::ClientLost(m));
800 }
801 // Reap detector/dedup state alongside the row expiry so long
802 // scans don't accumulate dead keys.
803 self.probe_dedup
804 .retain(|_, &mut last| now.saturating_sub(last) <= PROBE_DEDUP_MS);
805 self.deauth_hist.retain(|_, q| {
806 while let Some(&t) = q.front() {
807 if now.saturating_sub(t) > DEAUTH_WINDOW_MS {
808 q.pop_front();
809 } else {
810 break;
811 }
812 }
813 !q.is_empty()
814 });
815 self.alert_cooldown.retain(|_, &mut until| now < until);
816 self.groups.expire(now);
817 }
818}
819
820/// Wall-clock counters for the 10 s `scan: …` diagnostic line — the evidence
821/// channel distinguishing RX-silence from parser-drops when "only my own AP
822/// shows up" is reported.
823#[derive(Default)]
824struct ScanStats {
825 /// Frames returned by `RawSocket::recv` (radiotap included, unparsed).
826 raw_frames_received: u64,
827 /// Frames whose radiotap header parsed (`radiotap::strip` returned Some).
828 radiotap_strip_ok: u64,
829 /// 802.11 payload parsed as SOME mgmt frame (beacon/probe-req/deauth /
830 /// probe-response family recognised by dot11).
831 mgmt_80211_parsed: u64,
832 /// Beacons/probe-responses that ingested an AP row (created or already
833 /// known — i.e. recognised AP-producing frames).
834 beacons_ap_ingested: u64,
835 /// Frames with beacon/probe-response FC byte, REGARDLESS of whether the
836 /// IE walk later succeeded — the parser-independent RX witness.
837 beacon_fc_rx: u64,
838 /// addr3 histogram of beacon_fc frames: answers "are other BSSIDs even
839 /// reaching the card" without trusting any parser.
840 bssid_hist: std::collections::BTreeMap<crate::common::MacAddr, u64>,
841 /// Frames dropped because the kernel reported them longer than the
842 /// receive buffer (MSG_TRUNC) — would otherwise enter the pipeline
843 /// (and the pcap spool) truncated.
844 truncated_dropped: u64,
845}
846
847/// Blocking channel-hop passive scan on an interface the caller already put
848/// into monitor mode. Returns when `stop` flips true.
849pub fn run(cfg: ScannerConfig, tx: Sender<Event>, stop: Arc<AtomicBool>) -> Result<()> {
850 let sock =
851 RawSocket::open(&cfg.ifname).with_context(|| format!("opening {} for scan", cfg.ifname))?;
852 sock.set_timeout(cfg.dwell_ms).context("set_timeout")?;
853
854 let freqs: Vec<u16> = if cfg.freqs.is_empty() {
855 HOP_FREQS_ALL.to_vec()
856 } else {
857 cfg.freqs.clone()
858 };
859 let _ = tx.send(Event::Log(format!(
860 "scanner: {} freqs, {} ms dwell on {}",
861 freqs.len(),
862 cfg.dwell_ms,
863 cfg.ifname
864 )));
865
866 let mut scanner = Scanner::new(cfg.rssi_floor, cfg.own_mac, cfg.deauth_suppress.clone());
867 // 16 KiB covers every real 802.11 frame (max A-MSDU 11454 + radiotap);
868 // anything bigger is a driver/kernel anomaly — recv_msg flags it and
869 // the frame is dropped instead of parsed/spooled truncated.
870 let mut buf = vec![0u8; crate::rawsock::RECV_BUFSZ];
871 let mut ch_idx = 0usize;
872 let mut stats = ScanStats::default();
873 let mut last_stats_log = Instant::now();
874 // Cumulative per-channel counters → Event::ChannelStats every 2 s.
875 let mut chan_hist: BTreeMap<u8, (u64, u64)> = BTreeMap::new();
876 let mut last_chan_emit = Instant::now();
877 // Spool error latch: 3 consecutive append failures → one log, then
878 // the spool is dropped silently for the rest of the scan.
879 let mut spool_failures: u32 = 0;
880 let mut spool_enabled = cfg.spool.is_some();
881 // Last frequency actually tuned — suppresses re-asserting the same
882 // channel every dwell (iw spam) while the pin is steady.
883 let mut last_set: u16 = 0;
884 // Streak of non-timeout recv errors (card yanked / firmware wedged) —
885 // reaching the threshold aborts the scanner instead of storming the UI.
886 let mut recv_err_streak: u32 = 0;
887
888 while !stop.load(Ordering::Relaxed) {
889 // Channel arbitration: a nonzero pin (capture hold or deauth
890 // override) wins over the hop plan for this cycle. While pinned
891 // the hop index stands still — we resume the plan on release.
892 let pinned = cfg.pin.get();
893 let freq = if pinned != 0 {
894 pinned
895 } else {
896 let f = freqs[ch_idx];
897 ch_idx = (ch_idx + 1) % freqs.len();
898 f
899 };
900 // Display channel number (2.4/5 GHz exact; 6 GHz reported as its
901 // own channel number — cosmetic only).
902 let cur_ch = freq_to_channel(freq).map(|c| c as i32).unwrap_or(-1);
903 if freq != last_set {
904 match iface::set_freq(&cfg.ifname, freq) {
905 Ok(()) => last_set = freq,
906 Err(e) => {
907 let _ = tx.send(Event::Log(format!(
908 "scanner: tune to {freq} MHz failed: {e:#}"
909 )));
910 }
911 }
912 }
913
914 // Drain frames until the dwell elapses (recv timeout bounds it).
915 let dwell_start = Instant::now();
916 loop {
917 match sock.recv_msg(&mut buf) {
918 // Over-long frame (>16 KiB — not a real 802.11 frame; a
919 // driver/kernel anomaly): drop it WHOLE — a truncated
920 // prefix is neither parseable nor a complete pcap record.
921 // Separate arm (not `continue`) so the dwell/stop checks at
922 // the loop tail still run under an over-long frame flood.
923 Ok(msg) if msg.truncated() => {
924 recv_err_streak = 0;
925 stats.truncated_dropped += 1;
926 if stats.truncated_dropped == 1 || stats.truncated_dropped % 100 == 0 {
927 let _ = tx.send(Event::Log(format!(
928 "scanner: dropped {} over-long frame(s) (>{} bytes, last {} bytes)",
929 stats.truncated_dropped,
930 buf.len(),
931 msg.orig_len
932 )));
933 }
934 }
935 Ok(msg) => {
936 recv_err_streak = 0;
937 let n = msg.len;
938 stats.raw_frames_received += 1;
939 let now = now_ms();
940 // Pcap spool: the RAW frame straight off the socket,
941 // radiotap header included (linktype 127).
942 if spool_enabled && let Some(w) = &cfg.spool {
943 match w.lock() {
944 Ok(mut w) => match w.append(&buf[..n]) {
945 Ok(()) => spool_failures = 0,
946 Err(e) => {
947 spool_failures += 1;
948 if spool_failures >= 3 {
949 spool_enabled = false;
950 let _ = tx
951 .send(Event::Log(format!("pcap spool disabled: {e}")));
952 }
953 }
954 },
955 Err(e) => {
956 spool_failures += 1;
957 if spool_failures >= 3 {
958 spool_enabled = false;
959 let _ =
960 tx.send(Event::Log(format!("pcap spool disabled: {e}")));
961 }
962 }
963 }
964 }
965 if let Some((meta, frame)) = radiotap::strip(&buf[..n]) {
966 stats.radiotap_strip_ok += 1;
967 // Per-channel attribution: trust the radiotap
968 // carrier frequency; fall back to the channel we
969 // last tuned to (radiotap freq is occasionally 0).
970 let ch =
971 freq_to_channel(meta.freq_mhz).or_else(|| freq_to_channel(last_set));
972 let is_beacon_fc =
973 frame.len() >= 24 && (frame[0] == 0x80 || frame[0] == 0x50);
974 if let Some(ch) = ch {
975 let e = chan_hist.entry(ch).or_insert((0, 0));
976 e.0 += 1;
977 if is_beacon_fc {
978 e.1 += 1;
979 }
980 }
981 // Parser-independent witness: beacon (0x80) and
982 // probe-response (0x50) frames carry the transmitter
983 // BSSID at addr3 (bytes 16..22) before any IE parse.
984 if is_beacon_fc {
985 stats.beacon_fc_rx += 1;
986 let mut mac = [0u8; 6];
987 mac.copy_from_slice(&frame[16..22]);
988 *stats
989 .bssid_hist
990 .entry(crate::common::MacAddr(mac))
991 .or_insert(0) += 1;
992 }
993 // ONE parse per frame: stats and ingest both
994 // consume the classification.
995 let class = classify(frame);
996 if class.counts_as_mgmt() {
997 stats.mgmt_80211_parsed += 1;
998 }
999 if matches!(class, FrameClass::Beacon(_)) {
1000 stats.beacons_ap_ingested += 1;
1001 }
1002 scanner.ingest_classified(&meta, frame, class, now, &tx);
1003 }
1004 }
1005 Err(e)
1006 if e.kind() == std::io::ErrorKind::WouldBlock
1007 || e.kind() == std::io::ErrorKind::TimedOut =>
1008 {
1009 recv_err_streak = 0;
1010 break; // dwell over (set_timeout)
1011 }
1012 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
1013 Err(e) => {
1014 // A persistent error here (ENODEV — card yanked, EIO —
1015 // firmware wedged) repeats identically every dwell;
1016 // without a cap the UI would get the same event ~10/s
1017 // forever. Emit it once per episode, then abort.
1018 recv_err_streak += 1;
1019 if recv_err_streak >= RECV_ERROR_ABORT_THRESHOLD {
1020 let _ = tx.send(Event::Error(format!(
1021 "scanner aborted: recv failing repeatedly on {} (last: {e}) — interface down?",
1022 cfg.ifname
1023 )));
1024 return Err(e).context("scanner recv failing repeatedly");
1025 }
1026 let _ = tx.send(Event::Error(format!("scanner recv: {e}")));
1027 break; // hop to the next channel and let recv retry
1028 }
1029 }
1030 if dwell_start.elapsed() >= Duration::from_millis(cfg.dwell_ms as u64) * 4 {
1031 break; // safety net if timeout doesn't fire
1032 }
1033 if stop.load(Ordering::Relaxed) {
1034 break;
1035 }
1036 }
1037
1038 // 2 s per-channel cumulative snapshot for the channel-activity UI.
1039 if last_chan_emit.elapsed() >= Duration::from_secs(2) {
1040 last_chan_emit = Instant::now();
1041 let snap: Vec<ChannelStat> = chan_hist
1042 .iter()
1043 .map(|(&channel, &(frames, beacons))| ChannelStat {
1044 channel,
1045 frames,
1046 beacons,
1047 })
1048 .collect();
1049 let _ = tx.send(Event::ChannelStats(snap));
1050 }
1051
1052 // 10 s wall-time diagnostic heartbeat: distinguishes RX-silence
1053 // (rx==0) from radiotap/parser drops (rx>0 but beacons==0) when a
1054 // report says "only my own AP shows up".
1055 if last_stats_log.elapsed() >= Duration::from_secs(10) {
1056 last_stats_log = Instant::now();
1057 let top: String = {
1058 let mut v: Vec<(crate::common::MacAddr, u64)> =
1059 stats.bssid_hist.iter().map(|(m, c)| (*m, *c)).collect();
1060 v.sort_unstable_by_key(|a| std::cmp::Reverse(a.1));
1061 v.truncate(4);
1062 v.iter()
1063 .map(|(m, c)| format!("{m}({c})"))
1064 .collect::<Vec<_>>()
1065 .join(", ")
1066 };
1067 let _ = tx.send(Event::Log(format!(
1068 "scan: rx={} strip={} beaconfc={} beacons={} aps={} ch={} trunc={} top=[{}]",
1069 stats.raw_frames_received,
1070 stats.radiotap_strip_ok,
1071 stats.beacon_fc_rx,
1072 stats.beacons_ap_ingested,
1073 scanner.aps.len(),
1074 cur_ch,
1075 stats.truncated_dropped,
1076 top
1077 )));
1078 }
1079
1080 scanner.expire(now_ms(), &tx);
1081 }
1082 Ok(())
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087 use super::*;
1088
1089 fn ap() -> MacAddr {
1090 "aa:bb:cc:dd:ee:ff".parse().unwrap()
1091 }
1092
1093 fn sta() -> MacAddr {
1094 // Unicast (I/G bit clear) — 0x11 would be multicast and filtered.
1095 "12:22:33:44:55:66".parse().unwrap()
1096 }
1097
1098 /// Hand-rolled beacon: radiotap-stripped 802.11 for `dot11` — FC 0x0080,
1099 /// addr1 broadcast, addr2/addr3 bssid, 12 fixed bytes, SSID + DS IEs.
1100 fn beacon_frame(bssid: &MacAddr, ssid: &str, channel: u8) -> Vec<u8> {
1101 let mut f = Vec::new();
1102 f.extend_from_slice(&0x0080u16.to_le_bytes()); // FC beacon
1103 f.extend_from_slice(&0u16.to_le_bytes()); // duration
1104 f.extend_from_slice(&MacAddr::BROADCAST.0); // addr1
1105 f.extend_from_slice(&bssid.0); // addr2 transmitter
1106 f.extend_from_slice(&bssid.0); // addr3 bssid
1107 f.extend_from_slice(&0u16.to_le_bytes()); // seq
1108 f.extend_from_slice(&[0u8; 8]); // timestamp
1109 f.extend_from_slice(&100u16.to_le_bytes()); // beacon interval
1110 f.extend_from_slice(&0x0431u16.to_le_bytes()); // capability (privacy)
1111 f.push(0); // SSID IE
1112 f.push(ssid.len() as u8);
1113 f.extend_from_slice(ssid.as_bytes());
1114 f.push(3); // DS param IE
1115 f.push(1);
1116 f.push(channel);
1117 f
1118 }
1119
1120 /// Probe request (FC 0x0040) from `sta`, broadcast dest, given SSID.
1121 fn probe_req_frame(sta: &MacAddr, ssid: Option<&str>) -> Vec<u8> {
1122 let mut f = Vec::new();
1123 f.extend_from_slice(&0x0040u16.to_le_bytes());
1124 f.extend_from_slice(&0u16.to_le_bytes());
1125 f.extend_from_slice(&MacAddr::BROADCAST.0);
1126 f.extend_from_slice(&sta.0);
1127 f.extend_from_slice(&MacAddr::BROADCAST.0);
1128 f.extend_from_slice(&0u16.to_le_bytes());
1129 let s = ssid.unwrap_or("");
1130 f.push(0);
1131 f.push(s.len() as u8);
1132 f.extend_from_slice(s.as_bytes());
1133 f
1134 }
1135
1136 /// Data frame sta → ap (ToDS): addr1=bssid, addr2=sta, addr3=da.
1137 fn data_frame_tods(bssid: &MacAddr, sta: &MacAddr) -> Vec<u8> {
1138 let mut f = Vec::new();
1139 f.extend_from_slice(&0x0108u16.to_le_bytes()); // data, ToDS
1140 f.extend_from_slice(&0u16.to_le_bytes());
1141 f.extend_from_slice(&bssid.0); // addr1 = bssid
1142 f.extend_from_slice(&sta.0); // addr2 = sta
1143 f.extend_from_slice(&[0u8; 6]); // addr3 = da
1144 f.extend_from_slice(&0u16.to_le_bytes());
1145 f.extend_from_slice(&[0u8; 8]); // llc/payload filler
1146 f
1147 }
1148
1149 fn meta(rssi: i8, freq: u16) -> RxMeta {
1150 RxMeta {
1151 rssi_dbm: rssi,
1152 freq_mhz: freq,
1153 }
1154 }
1155
1156 /// Scanner under test: no suppression, unknown own MAC.
1157 fn test_scanner() -> Scanner {
1158 Scanner::new(-85, MacAddr::ZERO, Arc::new(Mutex::new(HashSet::new())))
1159 }
1160
1161 // -- frames with a caller-picked sequence number (pairing tests) ------
1162
1163 fn ie_bytes(id: u8, body: &[u8]) -> Vec<u8> {
1164 let mut v = vec![id, body.len() as u8];
1165 v.extend_from_slice(body);
1166 v
1167 }
1168
1169 /// Probe request with full control over IEs and sequence number.
1170 fn probe_req_ies(sta: &MacAddr, ssid: Option<&str>, ies: &[Vec<u8>], seq: u16) -> Vec<u8> {
1171 let mut v = Vec::new();
1172 v.extend_from_slice(&0x0040u16.to_le_bytes()); // FC: probe request
1173 v.extend_from_slice(&0u16.to_le_bytes()); // duration
1174 v.extend_from_slice(&MacAddr::BROADCAST.0); // addr1
1175 v.extend_from_slice(&sta.0); // addr2
1176 v.extend_from_slice(&MacAddr::BROADCAST.0); // addr3
1177 v.extend_from_slice(&(seq << 4).to_le_bytes()); // seq<<4 | frag 0
1178 match ssid {
1179 Some(s) => v.extend_from_slice(&ie_bytes(dot11::IE_SSID, s.as_bytes())),
1180 None => v.extend_from_slice(&ie_bytes(dot11::IE_SSID, b"")),
1181 }
1182 for body in ies {
1183 v.extend_from_slice(body);
1184 }
1185 v
1186 }
1187
1188 fn probe_seq(sta: &MacAddr, ssid: Option<&str>, seq: u16) -> Vec<u8> {
1189 let ies = [
1190 ie_bytes(1, &[0x82, 0x84, 0x8b, 0x96]),
1191 ie_bytes(50, &[0x0c, 0x12]),
1192 ];
1193 probe_req_ies(sta, ssid, &ies, seq)
1194 }
1195
1196 /// Minimal WPS UUID-E attribute in a vendor IE.
1197 fn wps_uuid_ie(uuid: &[u8; 16]) -> Vec<u8> {
1198 let mut body = vec![0x00, 0x50, 0xf2, 0x04];
1199 body.extend_from_slice(&0x1047u16.to_be_bytes());
1200 body.extend_from_slice(&16u16.to_be_bytes());
1201 body.extend_from_slice(uuid);
1202 ie_bytes(dot11::IE_VENDOR, &body)
1203 }
1204
1205 /// 6 GHz regression: frequencies just below 5950 must not underflow the
1206 /// (freq - 5950) subtraction (u16 debug panic / garbage channel in
1207 /// release). Grid per 802.11ax: center = 5950 + 5·ch; 5935 = ch 2
1208 /// (band-edge outlier, iw precedent); 5940/5945 aren't 20 MHz channels.
1209 #[test]
1210 fn freq_to_channel_6ghz_edge_freqs() {
1211 assert_eq!(freq_to_channel(5935), Some(2));
1212 assert_eq!(freq_to_channel(5940), None);
1213 assert_eq!(freq_to_channel(5945), None);
1214 assert_eq!(freq_to_channel(5955), Some(1));
1215 assert_eq!(freq_to_channel(5980), Some(6)); // PSC ch 6
1216 assert_eq!(freq_to_channel(6415), Some(93)); // last freq in HOP_FREQS_ALL
1217 assert_eq!(freq_to_channel(7115), Some(233)); // ch 233 = 6 GHz top
1218 assert_eq!(freq_to_channel(7116), None);
1219 // Existing bands untouched.
1220 assert_eq!(freq_to_channel(2412), Some(1));
1221 assert_eq!(freq_to_channel(2484), Some(14));
1222 assert_eq!(freq_to_channel(5180), Some(36));
1223 assert_eq!(freq_to_channel(5920), None); // 5 GHz top edge: not a 5-grid ch
1224 // Every frequency we actually hop maps to SOME channel.
1225 for &f in HOP_FREQS_ALL {
1226 assert!(freq_to_channel(f).is_some(), "hop freq {f} unmapped");
1227 }
1228 }
1229
1230 /// The single-parse classifier: each fixture lands in the bucket the
1231 /// ingest semantics expect, and stats predicates still match the
1232 /// historical definition.
1233 #[test]
1234 fn classify_matches_frame_type() {
1235 assert!(matches!(
1236 classify(&beacon_frame(&ap(), "testnet", 6)),
1237 FrameClass::Beacon(_)
1238 ));
1239 let class = classify(&probe_req_frame(&sta(), Some("net")));
1240 assert!(matches!(class, FrameClass::ProbeIdent(_)));
1241 assert!(class.counts_as_mgmt());
1242 let deauth = dot11::build_deauth(&ap(), &sta(), 7);
1243 let class = classify(&deauth);
1244 assert!(matches!(class, FrameClass::Deauth { .. }));
1245 assert!(class.counts_as_mgmt());
1246 let class = classify(&data_frame_tods(&ap(), &sta()));
1247 assert!(matches!(class, FrameClass::Data { .. }));
1248 assert!(!class.counts_as_mgmt());
1249 assert!(matches!(classify(&[0u8; 4]), FrameClass::Other));
1250 }
1251
1252 #[test]
1253 fn beacon_attached_creates_ap_with_ssid_and_channel() {
1254 let (tx, rx) = crossbeam_channel::unbounded();
1255 let mut sc = test_scanner();
1256 let now: u64 = 0;
1257 sc.ingest(&meta(-42, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1258 match rx.try_recv() {
1259 Ok(Event::ApUpdated(a)) => {
1260 assert_eq!(a.bssid, ap());
1261 assert_eq!(a.ssid, "testnet");
1262 assert_eq!(a.channel, 6);
1263 assert_eq!(a.rssi_dbm, -42);
1264 }
1265 other => panic!("expected ApUpdated, got {other:?}"),
1266 }
1267 }
1268
1269 #[test]
1270 fn beacon_uses_freq_hint_when_no_ds_ie() {
1271 let (tx, rx) = crossbeam_channel::unbounded();
1272 let mut sc = test_scanner();
1273 let now: u64 = 0;
1274 let mut f = beacon_frame(&ap(), "testnet", 6);
1275 f.truncate(f.len() - 3); // drop DS IE
1276 sc.ingest(&meta(-40, 2437), &f, now, &tx);
1277 match rx.try_recv() {
1278 Ok(Event::ApUpdated(a)) => assert_eq!(a.channel, 6),
1279 other => panic!("expected ApUpdated, got {other:?}"),
1280 }
1281 }
1282
1283 #[test]
1284 fn weak_beacon_not_created_but_update_accepted_later() {
1285 let (tx, rx) = crossbeam_channel::unbounded();
1286 let mut sc = test_scanner();
1287 let now: u64 = 0;
1288 // -90 < floor: no event, no entry.
1289 sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1290 assert!(rx.try_recv().is_err());
1291 assert!(sc.aps.is_empty());
1292 // Once created (hit stronger frame), later weak updates are accepted:
1293 // the beacon counter advances and the EMA decay is reported.
1294 sc.ingest(&meta(-60, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1295 assert!(rx.try_recv().is_ok());
1296 sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1297 assert_eq!(sc.aps[&ap()].beacons, 2);
1298 }
1299
1300 /// Peak-hold is gone: sustained weaker samples decay the reported RSSI
1301 /// (station walking away), and it recovers on stronger ones. The EMA
1302 /// keeps single-frame fades from reordering the UI (first -75 sample
1303 /// moves the average only -70 → -72).
1304 #[test]
1305 fn rssi_ema_decays_and_recovers() {
1306 let (tx, rx) = crossbeam_channel::unbounded();
1307 let mut sc = test_scanner();
1308 let now: u64 = 0;
1309 sc.ingest(&meta(-70, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1310 match rx.try_recv() {
1311 Ok(Event::ApUpdated(a)) => assert_eq!(a.rssi_dbm, -70),
1312 other => panic!("expected creation ApUpdated, got {other:?}"),
1313 }
1314 // One weaker sample: EMA -70 → -72 — decay is reported now (the old
1315 // peak-hold rule kept -70 forever).
1316 sc.ingest(&meta(-75, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1317 match rx.try_recv() {
1318 Ok(Event::ApUpdated(a)) => assert_eq!(a.rssi_dbm, -72),
1319 other => panic!("expected decay ApUpdated, got {other:?}"),
1320 }
1321 // Repeated weak samples keep walking the average down (monotonic,
1322 // one rounded dBm per event, skipping no-change steps) until it
1323 // settles on the sample value.
1324 let mut last = -72;
1325 for _ in 0..20 {
1326 sc.ingest(&meta(-75, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1327 match rx.try_recv() {
1328 Ok(Event::ApUpdated(a)) => {
1329 assert!(a.rssi_dbm < last, "decay must be monotonic");
1330 assert!(a.rssi_dbm >= -75, "never overshoots the sample");
1331 last = a.rssi_dbm;
1332 }
1333 Ok(other) => panic!("unexpected event {other:?}"),
1334 Err(_) => {} // sample didn't move the rounded average
1335 }
1336 }
1337 assert_eq!(last, -75, "EMA converges to the repeated sample");
1338 // Settled: identical samples emit nothing (no event storm).
1339 sc.ingest(&meta(-75, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1340 assert!(rx.try_recv().is_err());
1341 // Recovery: one strong sample lifts the average -75 → -65.
1342 sc.ingest(&meta(-50, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1343 match rx.try_recv() {
1344 Ok(Event::ApUpdated(a)) => assert_eq!(a.rssi_dbm, -65),
1345 other => panic!("expected recovery ApUpdated, got {other:?}"),
1346 }
1347 // Frames without an antenna-signal field (rssi 0) leave the
1348 // average untouched.
1349 sc.ingest(&meta(0, 0), &beacon_frame(&ap(), "testnet", 6), now, &tx);
1350 assert!(rx.try_recv().is_err());
1351 assert_eq!(sc.aps[&ap()].rssi_dbm, -65);
1352 }
1353
1354 /// Clients use the same EMA: a station moving away decays instead of
1355 /// pinning its strongest-ever sample.
1356 #[test]
1357 fn client_rssi_ema_decays() {
1358 let (tx, rx) = crossbeam_channel::unbounded();
1359 let mut sc = test_scanner();
1360 let now: u64 = 0;
1361 sc.ingest(
1362 &meta(-60, 0),
1363 &probe_req_frame(&sta(), Some("net")),
1364 now,
1365 &tx,
1366 );
1367 let _ = rx.try_recv(); // ProbeObserved
1368 let _ = rx.try_recv(); // ClientIdent
1369 match rx.try_recv() {
1370 Ok(Event::ClientUpdated(c)) => assert_eq!(c.rssi_dbm, -60),
1371 other => panic!("expected ClientUpdated creation, got {other:?}"),
1372 }
1373 // -60 → 0.4·(-80) + 0.6·(-60) = -68.
1374 sc.ingest(
1375 &meta(-80, 0),
1376 &probe_req_frame(&sta(), Some("net")),
1377 now,
1378 &tx,
1379 );
1380 loop {
1381 match rx.try_recv() {
1382 Ok(Event::ClientUpdated(c)) => {
1383 assert_eq!(c.rssi_dbm, -68);
1384 break;
1385 }
1386 Ok(_) => continue, // ProbeObserved/dedup chatter
1387 other => panic!("expected decayed ClientUpdated, got {other:?}"),
1388 }
1389 }
1390 }
1391
1392 /// The pure EMA helpers: convergence on constant input, alpha weighting,
1393 /// and rounding of the reported value.
1394 #[test]
1395 fn ema_helpers_behave() {
1396 let mut e = -50.0f32;
1397 for _ in 0..50 {
1398 e = ema_next(e, -90);
1399 }
1400 assert_eq!(ema_report(e), -90);
1401 // α=0.4: one step from -70 with -75 lands exactly on -72.
1402 assert_eq!(ema_report(ema_next(-70.0, -75)), -72);
1403 }
1404
1405 #[test]
1406 fn probe_req_creates_client_and_data_freshens() {
1407 let (tx, rx) = crossbeam_channel::unbounded();
1408 let mut sc = test_scanner();
1409 let now: u64 = 0;
1410 sc.ingest(
1411 &meta(-55, 0),
1412 &probe_req_frame(&sta(), Some("testnet")),
1413 now,
1414 &tx,
1415 );
1416 // Novel probe → ProbeObserved first, then the pairing decision,
1417 // then the client creation carrying the group id already.
1418 match rx.try_recv() {
1419 Ok(Event::ProbeObserved(p)) => {
1420 assert_eq!(p.client, sta());
1421 assert_eq!(p.ssid.as_deref(), Some("testnet"));
1422 assert_eq!(p.rssi_dbm, -55);
1423 }
1424 other => panic!("expected ProbeObserved, got {other:?}"),
1425 }
1426 match rx.try_recv() {
1427 Ok(Event::ClientIdent {
1428 mac,
1429 group,
1430 confidence,
1431 }) => {
1432 assert_eq!(mac, sta());
1433 assert_eq!(confidence, IdentConfidence::Probable);
1434 let _ = group;
1435 }
1436 other => panic!("expected ClientIdent, got {other:?}"),
1437 }
1438 match rx.try_recv() {
1439 Ok(Event::ClientUpdated(c)) => {
1440 assert_eq!(c.mac, sta());
1441 assert_eq!(c.ap, None);
1442 assert_eq!(c.ident_group, Some(1), "creation carries the group id");
1443 }
1444 other => panic!("expected ClientUpdated, got {other:?}"),
1445 }
1446 // A repeat of the SAME probe inside 60 s is deduped — no
1447 // ProbeObserved (the client liveness refresh is silent here since
1448 // neither RSSI nor ap changed).
1449 sc.ingest(
1450 &meta(-55, 0),
1451 &probe_req_frame(&sta(), Some("testnet")),
1452 now,
1453 &tx,
1454 );
1455 assert!(rx.try_recv().is_err());
1456 // A different SSID from the same client is a fresh observation.
1457 sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), None), now, &tx);
1458 match rx.try_recv() {
1459 Ok(Event::ProbeObserved(p)) => assert_eq!(p.ssid, None),
1460 other => panic!("expected ProbeObserved(wildcard), got {other:?}"),
1461 }
1462 sc.ingest(&meta(-55, 0), &data_frame_tods(&ap(), &sta()), now, &tx);
1463 match rx.try_recv() {
1464 Ok(Event::ClientUpdated(c)) => assert_eq!(c.ap, Some(ap())),
1465 other => panic!("expected ClientUpdated with ap, got {other:?}"),
1466 }
1467 assert_eq!(sc.clients[&sta()].frames, 4);
1468 }
1469
1470 #[test]
1471 fn deauth_flags_client_disconnected_exactly_once() {
1472 let (tx, rx) = crossbeam_channel::unbounded();
1473 let mut sc = test_scanner();
1474 let now: u64 = 0;
1475 sc.ingest(
1476 &meta(-55, 0),
1477 &probe_req_frame(&sta(), Some("testnet")),
1478 now,
1479 &tx,
1480 );
1481 let _ = rx.try_recv(); // ProbeObserved
1482 let _ = rx.try_recv(); // ClientIdent (pairing decision)
1483 let _ = rx.try_recv(); // creation event
1484 assert!(sc.clients[&sta()].connected);
1485
1486 // AP → client deauth: state flips, one update event.
1487 let f = dot11::build_deauth(&ap(), &sta(), 7);
1488 sc.ingest(&meta(-55, 0), &f, now, &tx);
1489 match rx.try_recv() {
1490 Ok(Event::ClientUpdated(c)) => {
1491 assert_eq!(c.mac, sta());
1492 assert!(!c.connected);
1493 }
1494 other => panic!("expected ClientUpdated(disconnected), got {other:?}"),
1495 }
1496 assert!(!sc.clients[&sta()].connected);
1497
1498 // Repeated deauths against an already-flagged station: silent.
1499 sc.ingest(&meta(-55, 0), &f, now, &tx);
1500 sc.ingest(&meta(-55, 0), &f, now, &tx);
1501 assert!(rx.try_recv().is_err());
1502 assert!(!sc.clients[&sta()].connected);
1503 }
1504
1505 #[test]
1506 fn client_frame_after_deauth_reconnects_it() {
1507 let (tx, rx) = crossbeam_channel::unbounded();
1508 let mut sc = test_scanner();
1509 let now: u64 = 0;
1510 sc.ingest(
1511 &meta(-55, 0),
1512 &probe_req_frame(&sta(), Some("testnet")),
1513 now,
1514 &tx,
1515 );
1516 let _ = rx.try_recv(); // ProbeObserved
1517 let _ = rx.try_recv(); // ClientIdent (pairing decision)
1518 let _ = rx.try_recv(); // creation
1519 sc.ingest(
1520 &meta(-50, 0),
1521 &dot11::build_deauth(&ap(), &sta(), 7),
1522 now,
1523 &tx,
1524 );
1525 let _ = rx.try_recv(); // disconnect flip
1526 assert!(!sc.clients[&sta()].connected);
1527
1528 // Station talks again: connected flips back true and the update
1529 // event fires.
1530 sc.ingest(&meta(-55, 0), &data_frame_tods(&ap(), &sta()), now, &tx);
1531 match rx.try_recv() {
1532 Ok(Event::ClientUpdated(c)) => {
1533 assert_eq!(c.mac, sta());
1534 assert!(c.connected);
1535 }
1536 other => panic!("expected ClientUpdated(reconnected), got {other:?}"),
1537 }
1538 assert!(sc.clients[&sta()].connected);
1539 }
1540
1541 #[test]
1542 fn client_initiated_disassoc_flags_disconnect() {
1543 let (tx, rx) = crossbeam_channel::unbounded();
1544 let mut sc = test_scanner();
1545 let now: u64 = 0;
1546 sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), None), now, &tx);
1547 let _ = rx.try_recv(); // ProbeObserved
1548 let _ = rx.try_recv(); // ClientIdent (pairing decision)
1549 let _ = rx.try_recv(); // creation
1550
1551 // Disassoc (FC 0x00a0) sent BY the station: addr2 = transmitter.
1552 let mut f = Vec::new();
1553 f.extend_from_slice(&0x00a0u16.to_le_bytes());
1554 f.extend_from_slice(&0u16.to_le_bytes());
1555 f.extend_from_slice(&ap().0); // addr1 = ap
1556 f.extend_from_slice(&sta().0); // addr2 = client transmitter
1557 f.extend_from_slice(&ap().0); // addr3 = bssid
1558 f.extend_from_slice(&0u16.to_le_bytes()); // seq
1559 f.extend_from_slice(&8u16.to_le_bytes()); // reason: leaving
1560 sc.ingest(&meta(-55, 0), &f, now, &tx);
1561 match rx.try_recv() {
1562 Ok(Event::ClientUpdated(c)) => assert!(!c.connected),
1563 other => panic!("expected ClientUpdated(disconnected), got {other:?}"),
1564 }
1565 assert!(!sc.clients[&sta()].connected);
1566 }
1567
1568 #[test]
1569 fn deauth_not_touching_a_known_client_is_ignored() {
1570 let (tx, rx) = crossbeam_channel::unbounded();
1571 let mut sc = test_scanner();
1572 let now: u64 = 0;
1573 sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), None), now, &tx);
1574 let _ = rx.try_recv(); // ProbeObserved
1575 let _ = rx.try_recv(); // ClientIdent (pairing decision)
1576 let _ = rx.try_recv(); // creation
1577
1578 // Unknown target: neither side tracked.
1579 let other: MacAddr = "de:ad:be:ef:00:01".parse().unwrap();
1580 sc.ingest(
1581 &meta(-50, 0),
1582 &dot11::build_deauth(&ap(), &other, 7),
1583 now,
1584 &tx,
1585 );
1586 assert!(rx.try_recv().is_err());
1587 assert!(sc.clients[&sta()].connected);
1588
1589 // Broadcast deauth from a tracked AP: broadcast is not a client
1590 // row, and (unless the AP is a client) nothing flips.
1591 sc.ingest(
1592 &meta(-50, 0),
1593 &dot11::build_deauth(&ap(), &MacAddr::BROADCAST, 7),
1594 now,
1595 &tx,
1596 );
1597 assert!(rx.try_recv().is_err());
1598 assert!(sc.clients[&sta()].connected);
1599 }
1600
1601 #[test]
1602 fn multicast_ta_is_ignored() {
1603 let (tx, rx) = crossbeam_channel::unbounded();
1604 let mut sc = test_scanner();
1605 let now: u64 = 0;
1606 let mcast = MacAddr([0x33, 0x33, 0, 0, 0, 1]);
1607 sc.ingest(&meta(-40, 0), &probe_req_frame(&mcast, None), now, &tx);
1608 assert!(rx.try_recv().is_err());
1609 assert!(sc.clients.is_empty());
1610 }
1611
1612 #[test]
1613 fn aging_emits_ap_lost_and_drops_clients() {
1614 let (tx, rx) = crossbeam_channel::unbounded();
1615 let mut sc = test_scanner();
1616 let t0: u64 = 1_000;
1617 sc.ingest(&meta(-40, 0), &beacon_frame(&ap(), "testnet", 6), t0, &tx);
1618 sc.ingest(&meta(-40, 0), &probe_req_frame(&sta(), None), t0, &tx);
1619 let _ = rx.try_recv(); // ApUpdated
1620 let _ = rx.try_recv(); // ProbeObserved
1621 let _ = rx.try_recv(); // ClientIdent (pairing decision)
1622 let _ = rx.try_recv(); // ClientUpdated
1623
1624 // 31 s later: AP expired, client still alive.
1625 let t1 = t0 + 31_000;
1626 sc.expire(t1, &tx);
1627 match rx.try_recv() {
1628 Ok(Event::ApLost(b)) => assert_eq!(b, ap()),
1629 other => panic!("expected ApLost, got {other:?}"),
1630 }
1631 assert!(sc.clients.contains_key(&sta()));
1632
1633 // 61 s: client gone too, with a ClientLost for the UI.
1634 sc.expire(t0 + 61_000, &tx);
1635 assert!(sc.clients.is_empty());
1636 match rx.try_recv() {
1637 Ok(Event::ClientLost(m)) => assert_eq!(m, sta()),
1638 other => panic!("expected ClientLost, got {other:?}"),
1639 }
1640 }
1641
1642 #[test]
1643 fn deauth_alert_window_threshold() {
1644 let mut counts = VecDeque::new();
1645 // 9 stamps inside the window → no alert.
1646 for i in 0..9 {
1647 assert_eq!(deauth_alert(&mut counts, 1_000 + i * 100), None);
1648 }
1649 // The 10th inside 10 s trips it.
1650 assert_eq!(deauth_alert(&mut counts, 2_000), Some(10));
1651 // Stamps older than 10 s are pruned: now = 20_000 drops them all.
1652 assert_eq!(deauth_alert(&mut counts, 20_000), None);
1653 assert_eq!(counts.len(), 1);
1654 }
1655
1656 #[test]
1657 fn deauth_storm_emits_alert_once_per_cooldown() {
1658 let (tx, rx) = crossbeam_channel::unbounded();
1659 let mut sc = test_scanner();
1660 let now: u64 = 100_000;
1661 let evil: MacAddr = "66:77:88:99:aa:bb".parse().unwrap();
1662 // 9 deauths → silent; 10th → one alert.
1663 for i in 0..9u64 {
1664 sc.ingest(
1665 &meta(-40, 0),
1666 &dot11::build_deauth(&evil, &sta(), 7),
1667 now + i,
1668 &tx,
1669 );
1670 }
1671 assert!(rx.try_recv().is_err());
1672 sc.ingest(
1673 &meta(-40, 0),
1674 &dot11::build_deauth(&evil, &sta(), 7),
1675 now + 9,
1676 &tx,
1677 );
1678 match rx.try_recv() {
1679 Ok(Event::DeauthAlert {
1680 source,
1681 target,
1682 count,
1683 }) => {
1684 assert_eq!(source, evil);
1685 assert_eq!(target, sta());
1686 assert_eq!(count, 10);
1687 }
1688 other => panic!("expected DeauthAlert, got {other:?}"),
1689 }
1690 // Cooldown: further deauths inside 30 s stay silent.
1691 for i in 0..15u64 {
1692 sc.ingest(
1693 &meta(-40, 0),
1694 &dot11::build_deauth(&evil, &sta(), 7),
1695 now + 100 + i,
1696 &tx,
1697 );
1698 }
1699 assert!(rx.try_recv().is_err());
1700 }
1701
1702 #[test]
1703 fn own_deauth_sources_are_suppressed() {
1704 let (tx, rx) = crossbeam_channel::unbounded();
1705 let own: MacAddr = "02:11:22:33:44:55".parse().unwrap();
1706 let suppress: Arc<Mutex<HashSet<MacAddr>>> = Arc::new(Mutex::new(HashSet::new()));
1707 suppress.lock().unwrap().insert(ap());
1708 let mut sc = Scanner::new(-85, own, suppress);
1709 let now: u64 = 100_000;
1710 // Blasts from our monitor MAC and from the user-deauthed AP both
1711 // stay silent even past the threshold.
1712 for i in 0..20u64 {
1713 sc.ingest(
1714 &meta(-40, 0),
1715 &dot11::build_deauth(&own, &sta(), 7),
1716 now + i,
1717 &tx,
1718 );
1719 sc.ingest(
1720 &meta(-40, 0),
1721 &dot11::build_deauth(&ap(), &sta(), 7),
1722 now + i,
1723 &tx,
1724 );
1725 }
1726 assert!(rx.try_recv().is_err());
1727 }
1728
1729 /// Hidden-SSID beacon (zero-len SSID IE) followed by an assoc request
1730 /// naming the real SSID: the AP row gains the name.
1731 #[test]
1732 fn assoc_req_reveals_hidden_ssid() {
1733 let (tx, rx) = crossbeam_channel::unbounded();
1734 let mut sc = test_scanner();
1735 let now: u64 = 0;
1736 // Beacon with empty SSID.
1737 sc.ingest(&meta(-45, 0), &beacon_frame(&ap(), "", 6), now, &tx);
1738 match rx.try_recv() {
1739 Ok(Event::ApUpdated(a)) => assert_eq!(a.ssid, ""),
1740 other => panic!("expected ApUpdated(hidden), got {other:?}"),
1741 }
1742 // Assoc request: FC 0x0000, addr1=bssid, addr2=sta, fixed params,
1743 // SSID IE with the real name.
1744 let mut f = Vec::new();
1745 f.extend_from_slice(&0x0000u16.to_le_bytes());
1746 f.extend_from_slice(&0u16.to_le_bytes());
1747 f.extend_from_slice(&ap().0); // addr1 = bssid
1748 f.extend_from_slice(&sta().0); // addr2 = station
1749 f.extend_from_slice(&ap().0); // addr3 = bssid
1750 f.extend_from_slice(&0u16.to_le_bytes()); // seq
1751 f.extend_from_slice(&0u16.to_le_bytes()); // capability
1752 f.extend_from_slice(&10u16.to_le_bytes()); // listen interval
1753 f.push(0); // SSID IE
1754 f.push(7);
1755 f.extend_from_slice(b"testnet");
1756 sc.ingest(&meta(-50, 0), &f, now, &tx);
1757 // Pairing decision first, then client creation, then the ApUpdated
1758 // revealing the ssid.
1759 match rx.try_recv() {
1760 Ok(Event::ClientIdent { mac, .. }) => assert_eq!(mac, sta()),
1761 other => panic!("expected ClientIdent, got {other:?}"),
1762 }
1763 match rx.try_recv() {
1764 Ok(Event::ClientUpdated(c)) => assert_eq!(c.ap, Some(ap())),
1765 other => panic!("expected ClientUpdated, got {other:?}"),
1766 }
1767 match rx.try_recv() {
1768 Ok(Event::ApUpdated(a)) => {
1769 assert_eq!(a.bssid, ap());
1770 assert_eq!(a.ssid, "testnet");
1771 }
1772 other => panic!("expected ApUpdated(revealed), got {other:?}"),
1773 }
1774 assert_eq!(sc.aps[&ap()].ssid, "testnet");
1775 }
1776
1777 // -- MAC-randomization pairing ---------------------------------------
1778
1779 /// Pop events up to and including the next ClientIdent (probe-panel
1780 /// and client-row events are ingestion noise for pairing tests).
1781 fn expect_ident(rx: &crossbeam_channel::Receiver<Event>) -> (MacAddr, u64, IdentConfidence) {
1782 loop {
1783 match rx.try_recv() {
1784 Ok(Event::ClientIdent {
1785 mac,
1786 group,
1787 confidence,
1788 }) => {
1789 return (mac, group, confidence);
1790 }
1791 Ok(_) => continue,
1792 Err(e) => panic!("expected ClientIdent, got {e:?}"),
1793 }
1794 }
1795 }
1796
1797 fn drain(rx: &crossbeam_channel::Receiver<Event>) {
1798 while rx.try_recv().is_ok() {}
1799 }
1800
1801 #[test]
1802 fn pairing_shared_ssid_pairs_rotated_macs() {
1803 let (tx, rx) = crossbeam_channel::unbounded();
1804 let mut sc = test_scanner();
1805 let now: u64 = 0;
1806 let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap();
1807 let m2: MacAddr = "06:bb:bb:bb:bb:02".parse().unwrap();
1808
1809 sc.ingest(&meta(-50, 0), &probe_seq(&m1, Some("testnet"), 7), now, &tx);
1810 let (mac, g1, conf) = expect_ident(&rx);
1811 assert_eq!(mac, m1);
1812 assert_eq!(conf, IdentConfidence::Probable);
1813 sc.ingest(
1814 &meta(-48, 0),
1815 &probe_seq(&m2, Some("testnet"), 8),
1816 now + 1,
1817 &tx,
1818 );
1819 let (mac, g2, conf) = expect_ident(&rx);
1820 // Same IE chain + same probed SSID = same radio, strong witness.
1821 assert_eq!(mac, m2);
1822 assert_eq!(g2, g1, "rotated MAC lands in the same group");
1823 assert_eq!(conf, IdentConfidence::Strong);
1824 // Second frame from m1: no new pairing events.
1825 sc.ingest(&meta(-49, 0), &probe_seq(&m1, None, 9), now + 2, &tx);
1826 drain(&rx);
1827 assert!(rx.try_recv().is_err());
1828 assert!(sc.groups.id_of(&m1).is_some() && sc.groups.id_of(&m2).is_some());
1829 }
1830
1831 #[test]
1832 fn pairing_seq_continuity_witness() {
1833 let (tx, rx) = crossbeam_channel::unbounded();
1834 let mut sc = test_scanner();
1835 let now: u64 = 0;
1836 let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap();
1837 let m2: MacAddr = "06:cc:cc:cc:cc:03".parse().unwrap();
1838
1839 sc.ingest(&meta(-50, 0), &probe_seq(&m1, None, 100), now, &tx);
1840 let _ = expect_ident(&rx);
1841 // Wildcard probes (no shared SSID), but the sequence counter
1842 // continues uninterrupted across the rotation.
1843 sc.ingest(&meta(-50, 0), &probe_seq(&m2, None, 101), now + 1, &tx);
1844 let (_, _, conf) = expect_ident(&rx);
1845 assert_eq!(conf, IdentConfidence::Strong);
1846 // A gap beyond the window is NOT continuity: downgrade.
1847 let m3: MacAddr = "0e:dd:dd:dd:dd:04".parse().unwrap();
1848 sc.ingest(&meta(-50, 0), &probe_seq(&m3, None, 200), now + 2, &tx);
1849 // m3 shares the fingerprint with the group's members, but seq 200
1850 // vs last 101 is 99 away → probable only.
1851 let (_, _, conf) = expect_ident(&rx);
1852 assert_eq!(conf, IdentConfidence::Probable);
1853 }
1854
1855 #[test]
1856 fn pairing_uuid_e_is_exact() {
1857 let (tx, rx) = crossbeam_channel::unbounded();
1858 let mut sc = test_scanner();
1859 let now: u64 = 0;
1860 let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap();
1861 let m2: MacAddr = "06:ee:ee:ee:ee:05".parse().unwrap();
1862 let uuid = [0xABu8; 16];
1863
1864 let f1 = probe_req_ies(&m1, Some("testnet"), &[wps_uuid_ie(&uuid)], 7);
1865 sc.ingest(&meta(-50, 0), &f1, now, &tx);
1866 let _ = expect_ident(&rx);
1867 let f2 = probe_req_ies(&m2, None, &[wps_uuid_ie(&uuid)], 9);
1868 sc.ingest(&meta(-50, 0), &f2, now + 1, &tx);
1869 let (mac, g2, conf) = expect_ident(&rx);
1870 assert_eq!(mac, m2);
1871 assert_eq!(conf, IdentConfidence::Exact, "UUID-E is a certain witness");
1872 // Same UUID but a COMPLETELY different IE chain (firmware update
1873 // between rotations, fingerprint unusable) still pairs.
1874 let m3: MacAddr = "0a:dd:dd:dd:dd:07".parse().unwrap();
1875 let f3 = probe_req_ies(&m3, None, &[ie_bytes(3, &[1u8]), wps_uuid_ie(&uuid)], 40);
1876 sc.ingest(&meta(-50, 0), &f3, now + 2, &tx);
1877 let (mac, g3, conf) = expect_ident(&rx);
1878 assert_eq!(mac, m3);
1879 assert_eq!(g3, g2, "UUID-E pairs across a fingerprint break");
1880 assert_eq!(conf, IdentConfidence::Exact);
1881 }
1882
1883 #[test]
1884 fn pairing_different_fingerprints_stay_separate() {
1885 let (tx, rx) = crossbeam_channel::unbounded();
1886 let mut sc = test_scanner();
1887 let now: u64 = 0;
1888 let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap();
1889 let m2: MacAddr = "06:bb:bb:bb:bb:02".parse().unwrap();
1890
1891 sc.ingest(&meta(-50, 0), &probe_seq(&m1, Some("testnet"), 7), now, &tx);
1892 let (_, g1, _) = expect_ident(&rx);
1893 // Same probed SSID, DIFFERENT IE chain → different device class.
1894 let other = probe_req_ies(
1895 &m2,
1896 Some("testnet"),
1897 &[ie_bytes(1, &[0x82, 0x84]), ie_bytes(3, &[6u8])],
1898 8,
1899 );
1900 sc.ingest(&meta(-50, 0), &other, now + 1, &tx);
1901 let (_, g2, _) = expect_ident(&rx);
1902 assert_ne!(g1, g2, "fingerprint mismatch keeps radios separate");
1903 }
1904
1905 #[test]
1906 fn pairing_groups_outlive_client_rows() {
1907 let (tx, rx) = crossbeam_channel::unbounded();
1908 let mut sc = test_scanner();
1909 let t0: u64 = 100_000;
1910 let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap();
1911 let m2: MacAddr = "06:ff:ff:ff:ff:06".parse().unwrap();
1912
1913 sc.ingest(&meta(-50, 0), &probe_seq(&m1, Some("testnet"), 7), t0, &tx);
1914 let (_, g1, _) = expect_ident(&rx);
1915 // Client row expires (60 s), but the group lives for minutes.
1916 sc.expire(t0 + 61_000, &tx);
1917 drain(&rx);
1918 // The rotated MAC appears late and still pairs (shared SSID).
1919 sc.ingest(
1920 &meta(-46, 0),
1921 &probe_seq(&m2, Some("testnet"), 8),
1922 t0 + 65_000,
1923 &tx,
1924 );
1925 let (_, g2, conf) = expect_ident(&rx);
1926 assert_eq!(g1, g2, "group identity survives the client-row TTL");
1927 assert_eq!(conf, IdentConfidence::Strong);
1928 // Full TTL (15 min) expiry destroys the group.
1929 sc.ingest(&meta(-50, 0), &probe_seq(&m2, None, 9), t0 + 65_000, &tx);
1930 sc.expire(t0 + 65_000 + GROUP_TTL_MS + 1, &tx);
1931 assert!(sc.groups.id_of(&m1).is_none());
1932 assert!(sc.groups.id_of(&m2).is_none());
1933 }
1934
1935 #[test]
1936 fn freq_map_sanity() {
1937 assert_eq!(freq_to_channel(2412), Some(1));
1938 assert_eq!(freq_to_channel(2437), Some(6));
1939 assert_eq!(freq_to_channel(2472), Some(13));
1940 assert_eq!(freq_to_channel(2484), Some(14));
1941 assert_eq!(freq_to_channel(5180), Some(36));
1942 assert_eq!(freq_to_channel(5825), Some(165));
1943 assert_eq!(freq_to_channel(0), None);
1944 }
1945}